code
stringlengths 15
9.96M
| docstring
stringlengths 1
10.1k
| func_name
stringlengths 1
124
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 6
186
| url
stringlengths 50
236
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function attachToObject($phid) {
self::attachFileToObject($this->getPHID(), $phid);
return $this;
} | Write the policy edge between this file and some object.
This method is successful even if the file is already attached.
@param string $phid Object PHID to attach to.
@return $this | attachToObject | php | phorgeit/phorge | src/applications/files/storage/PhabricatorFile.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/storage/PhabricatorFile.php | Apache-2.0 |
public static function attachFileToObject($file_phid, $object_phid) {
// It can be easy to confuse the two arguments. Be strict.
if (phid_get_type($file_phid) !== PhabricatorFileFilePHIDType::TYPECONST) {
throw new Exception(pht('The first argument must be a phid of a file.'));
}
$attachment_table = new PhabricatorFileAttachment();
$attachment_conn = $attachment_table->establishConnection('w');
queryfx(
$attachment_conn,
'INSERT INTO %R (objectPHID, filePHID, attachmentMode,
attacherPHID, dateCreated, dateModified)
VALUES (%s, %s, %s, %ns, %d, %d)
ON DUPLICATE KEY UPDATE
attachmentMode = VALUES(attachmentMode),
attacherPHID = VALUES(attacherPHID),
dateModified = VALUES(dateModified)',
$attachment_table,
$object_phid,
$file_phid,
PhabricatorFileAttachment::MODE_ATTACH,
null,
PhabricatorTime::getNow(),
PhabricatorTime::getNow());
} | Write the policy edge between a file and some object.
This method is successful even if the file is already attached.
NOTE: Please avoid to use this static method directly.
Instead, use PhabricatorFile#attachToObject(phid).
@param string $file_phid File PHID to attach from.
@param string $object_phid Object PHID to attach to.
@return void | attachFileToObject | php | phorgeit/phorge | src/applications/files/storage/PhabricatorFile.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/storage/PhabricatorFile.php | Apache-2.0 |
private function readPropertiesFromParameters(array $params) {
PhutilTypeSpec::checkMap(
$params,
array(
'name' => 'optional string',
'authorPHID' => 'optional string',
'ttl.relative' => 'optional int',
'ttl.absolute' => 'optional int',
'viewPolicy' => 'optional string',
'isExplicitUpload' => 'optional bool',
'canCDN' => 'optional bool',
'profile' => 'optional bool',
'format' => 'optional string|PhabricatorFileStorageFormat',
'mime-type' => 'optional string',
'builtin' => 'optional string',
'storageEngines' => 'optional list<PhabricatorFileStorageEngine>',
'chunk' => 'optional bool',
));
$file_name = idx($params, 'name');
$this->setName($file_name);
$author_phid = idx($params, 'authorPHID');
$this->setAuthorPHID($author_phid);
$absolute_ttl = idx($params, 'ttl.absolute');
$relative_ttl = idx($params, 'ttl.relative');
if ($absolute_ttl !== null && $relative_ttl !== null) {
throw new Exception(
pht(
'Specify an absolute TTL or a relative TTL, but not both.'));
} else if ($absolute_ttl !== null) {
if ($absolute_ttl < PhabricatorTime::getNow()) {
throw new Exception(
pht(
'Absolute TTL must be in the present or future, but TTL "%s" '.
'is in the past.',
$absolute_ttl));
}
$this->setTtl($absolute_ttl);
} else if ($relative_ttl !== null) {
if ($relative_ttl < 0) {
throw new Exception(
pht(
'Relative TTL must be zero or more seconds, but "%s" is '.
'negative.',
$relative_ttl));
}
$max_relative = phutil_units('365 days in seconds');
if ($relative_ttl > $max_relative) {
throw new Exception(
pht(
'Relative TTL must not be more than "%s" seconds, but TTL '.
'"%s" was specified.',
$max_relative,
$relative_ttl));
}
$absolute_ttl = PhabricatorTime::getNow() + $relative_ttl;
$this->setTtl($absolute_ttl);
}
$view_policy = idx($params, 'viewPolicy');
if ($view_policy) {
$this->setViewPolicy($params['viewPolicy']);
}
$is_explicit = (idx($params, 'isExplicitUpload') ? 1 : 0);
$this->setIsExplicitUpload($is_explicit);
$can_cdn = idx($params, 'canCDN');
if ($can_cdn) {
$this->setCanCDN(true);
}
$builtin = idx($params, 'builtin');
if ($builtin) {
$this->setBuiltinName($builtin);
$this->setBuiltinKey($builtin);
}
$profile = idx($params, 'profile');
if ($profile) {
$this->setIsProfileImage(true);
}
$mime_type = idx($params, 'mime-type');
if ($mime_type) {
$this->setMimeType($mime_type);
}
$is_chunk = idx($params, 'chunk');
if ($is_chunk) {
$this->setIsChunk(true);
}
return $this;
} | Configure a newly created file object according to specified parameters.
This method is called both when creating a file from fresh data, and
when creating a new file which reuses existing storage.
@param map<string, wild> $params Bag of parameters, see
@{class:PhabricatorFile} for documentation.
@return $this | readPropertiesFromParameters | php | phorgeit/phorge | src/applications/files/storage/PhabricatorFile.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/storage/PhabricatorFile.php | Apache-2.0 |
public function getTransformedDimensions(PhabricatorFile $file) {
return null;
} | Get an estimate of the transformed dimensions of a file.
@param PhabricatorFile $file File to transform.
@return list<int, int>|null Width and height, if available. | getTransformedDimensions | php | phorgeit/phorge | src/applications/files/transform/PhabricatorFileImageTransform.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/transform/PhabricatorFileImageTransform.php | Apache-2.0 |
protected function newFileFromData($data) {
if ($this->file) {
$name = $this->file->getName();
$inherit_properties = array(
'viewPolicy' => $this->file->getViewPolicy(),
);
} else {
$name = 'default.png';
$inherit_properties = array();
}
$defaults = array(
'canCDN' => true,
'name' => $this->getTransformKey().'-'.$name,
);
$properties = $this->getFileProperties() + $inherit_properties + $defaults;
return PhabricatorFile::newFromFileData($data, $properties);
} | Create a new @{class:PhabricatorFile} from raw data.
@param string $data Raw file data. | newFileFromData | php | phorgeit/phorge | src/applications/files/transform/PhabricatorFileImageTransform.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/transform/PhabricatorFileImageTransform.php | Apache-2.0 |
protected function newEmptyImage($w, $h) {
$w = (int)$w;
$h = (int)$h;
if (($w <= 0) || ($h <= 0)) {
throw new Exception(
pht('Can not create an image with nonpositive dimensions.'));
}
$trap = new PhutilErrorTrap();
$img = @imagecreatetruecolor($w, $h);
$errors = $trap->getErrorsAsString();
$trap->destroy();
if ($img === false) {
throw new Exception(
pht(
'Unable to imagecreatetruecolor() a new empty image: %s',
$errors));
}
$trap = new PhutilErrorTrap();
$ok = @imagesavealpha($img, true);
$errors = $trap->getErrorsAsString();
$trap->destroy();
if ($ok === false) {
throw new Exception(
pht(
'Unable to imagesavealpha() a new empty image: %s',
$errors));
}
$trap = new PhutilErrorTrap();
$color = @imagecolorallocatealpha($img, 255, 255, 255, 127);
$errors = $trap->getErrorsAsString();
$trap->destroy();
if ($color === false) {
throw new Exception(
pht(
'Unable to imagecolorallocatealpha() a new empty image: %s',
$errors));
}
$trap = new PhutilErrorTrap();
$ok = @imagefill($img, 0, 0, $color);
$errors = $trap->getErrorsAsString();
$trap->destroy();
if ($ok === false) {
throw new Exception(
pht(
'Unable to imagefill() a new empty image: %s',
$errors));
}
return $img;
} | Create a new image filled with transparent pixels.
@param int $w Desired image width.
@param int $h Desired image height.
@return resource New image resource. | newEmptyImage | php | phorgeit/phorge | src/applications/files/transform/PhabricatorFileImageTransform.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/transform/PhabricatorFileImageTransform.php | Apache-2.0 |
protected function getImageDimensions() {
if ($this->imageX === null) {
$image = $this->getImage();
$trap = new PhutilErrorTrap();
$x = @imagesx($image);
$y = @imagesy($image);
$errors = $trap->getErrorsAsString();
$trap->destroy();
if (($x === false) || ($y === false) || ($x <= 0) || ($y <= 0)) {
throw new Exception(
pht(
'Unable to determine image dimensions with '.
'imagesx()/imagesy(): %s',
$errors));
}
$this->imageX = $x;
$this->imageY = $y;
}
return array($this->imageX, $this->imageY);
} | Get the pixel dimensions of the image being transformed.
@return list<int, int> Width and height of the image. | getImageDimensions | php | phorgeit/phorge | src/applications/files/transform/PhabricatorFileImageTransform.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/transform/PhabricatorFileImageTransform.php | Apache-2.0 |
protected function getData() {
if ($this->data !== null) {
return $this->data;
}
$file = $this->file;
$max_size = (1024 * 1024 * 16);
$img_size = $file->getByteSize();
if ($img_size > $max_size) {
throw new Exception(
pht(
'This image is too large to transform. The transform limit is %s '.
'bytes, but the image size is %s bytes.',
new PhutilNumber($max_size),
new PhutilNumber($img_size)));
}
$data = $file->loadFileData();
$this->data = $data;
return $this->data;
} | Get the raw file data for the image being transformed.
@return string Raw file data. | getData | php | phorgeit/phorge | src/applications/files/transform/PhabricatorFileImageTransform.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/transform/PhabricatorFileImageTransform.php | Apache-2.0 |
protected function getImage() {
if ($this->image !== null) {
return $this->image;
}
if (!function_exists('imagecreatefromstring')) {
throw new Exception(
pht(
'Unable to transform image: the imagecreatefromstring() function '.
'is not available. Install or enable the "gd" extension for PHP.'));
}
$data = $this->getData();
$data = (string)$data;
// First, we're going to write the file to disk and use getimagesize()
// to determine its dimensions without actually loading the pixel data
// into memory. For very large images, we'll bail out.
// In particular, this defuses a resource exhaustion attack where the
// attacker uploads a 40,000 x 40,000 pixel PNGs of solid white. These
// kinds of files compress extremely well, but require a huge amount
// of memory and CPU to process.
$tmp = new TempFile();
Filesystem::writeFile($tmp, $data);
$tmp_path = (string)$tmp;
$trap = new PhutilErrorTrap();
$info = @getimagesize($tmp_path);
$errors = $trap->getErrorsAsString();
$trap->destroy();
unset($tmp);
if ($info === false) {
throw new Exception(
pht(
'Unable to get image information with getimagesize(): %s',
$errors));
}
list($width, $height) = $info;
if (($width <= 0) || ($height <= 0)) {
throw new Exception(
pht(
'Unable to determine image width and height with getimagesize().'));
}
$max_pixels_array = $this->getMaxTransformDimensions();
$max_pixels = ($max_pixels_array[0] * $max_pixels_array[1]);
$img_pixels = ($width * $height);
if ($img_pixels > $max_pixels) {
throw new Exception(
pht(
'This image (with dimensions %spx x %spx) is too large to '.
'transform. The image has %s pixels, but transforms are limited '.
'to images with %s or fewer pixels.',
new PhutilNumber($width),
new PhutilNumber($height),
new PhutilNumber($img_pixels),
new PhutilNumber($max_pixels)));
}
$trap = new PhutilErrorTrap();
$image = @imagecreatefromstring($data);
$errors = $trap->getErrorsAsString();
$trap->destroy();
if ($image === false) {
throw new Exception(
pht(
'Unable to load image data with imagecreatefromstring(): %s',
$errors));
}
$this->image = $image;
return $this->image;
} | Get the GD image resource for the image being transformed.
@return resource GD image resource. | getImage | php | phorgeit/phorge | src/applications/files/transform/PhabricatorFileImageTransform.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/transform/PhabricatorFileImageTransform.php | Apache-2.0 |
public function getMaxTransformDimensions() {
return array(4096, 4096);
} | Get maximum supported image dimensions in pixels for transforming
@return array<int> Maximum width and height | getMaxTransformDimensions | php | phorgeit/phorge | src/applications/files/transform/PhabricatorFileImageTransform.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/transform/PhabricatorFileImageTransform.php | Apache-2.0 |
public function getEngineIdentifier() {
return 'blob';
} | For historical reasons, this engine identifies as "blob". | getEngineIdentifier | php | phorgeit/phorge | src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | Apache-2.0 |
public function writeFile($data, array $params) {
$blob = new PhabricatorFileStorageBlob();
$blob->setData($data);
$blob->save();
return $blob->getID();
} | Write file data into the big blob store table in MySQL. Returns the row
ID as the file data handle. | writeFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | Apache-2.0 |
public function readFile($handle) {
return $this->loadFromMySQLFileStorage($handle)->getData();
} | Load a stored blob from MySQL. | readFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | Apache-2.0 |
public function deleteFile($handle) {
$this->loadFromMySQLFileStorage($handle)->delete();
} | Delete a blob from MySQL. | deleteFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | Apache-2.0 |
private function loadFromMySQLFileStorage($handle) {
$blob = id(new PhabricatorFileStorageBlob())->load($handle);
if (!$blob) {
throw new Exception(pht("Unable to load MySQL blob file '%s'!", $handle));
}
return $blob;
} | Load the Lisk object that stores the file data for a handle.
@param string $handle File data handle.
@return PhabricatorFileStorageBlob Data DAO.
@task internal | loadFromMySQLFileStorage | php | phorgeit/phorge | src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | Apache-2.0 |
public function getEngineIdentifier() {
return 'amazon-s3';
} | This engine identifies as `amazon-s3`. | getEngineIdentifier | php | phorgeit/phorge | src/applications/files/engine/PhabricatorS3FileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorS3FileStorageEngine.php | Apache-2.0 |
public function writeFile($data, array $params) {
$s3 = $this->newS3API();
// Generate a random name for this file. We add some directories to it
// (e.g. 'abcdef123456' becomes 'ab/cd/ef123456') to make large numbers of
// files more browsable with web/debugging tools like the S3 administration
// tool.
$seed = Filesystem::readRandomCharacters(20);
$parts = array();
$parts[] = 'phabricator';
$instance_name = PhabricatorEnv::getEnvConfig('cluster.instance');
if (phutil_nonempty_string($instance_name)) {
$parts[] = $instance_name;
}
$parts[] = substr($seed, 0, 2);
$parts[] = substr($seed, 2, 2);
$parts[] = substr($seed, 4);
$name = implode('/', $parts);
AphrontWriteGuard::willWrite();
$profiler = PhutilServiceProfiler::getInstance();
$call_id = $profiler->beginServiceCall(
array(
'type' => 's3',
'method' => 'putObject',
));
$s3
->setParametersForPutObject($name, $data)
->resolve();
$profiler->endServiceCall($call_id, array());
return $name;
} | Writes file data into Amazon S3. | writeFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorS3FileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorS3FileStorageEngine.php | Apache-2.0 |
public function readFile($handle) {
$s3 = $this->newS3API();
$profiler = PhutilServiceProfiler::getInstance();
$call_id = $profiler->beginServiceCall(
array(
'type' => 's3',
'method' => 'getObject',
));
$result = $s3
->setParametersForGetObject($handle)
->resolve();
$profiler->endServiceCall($call_id, array());
return $result;
} | Load a stored blob from Amazon S3. | readFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorS3FileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorS3FileStorageEngine.php | Apache-2.0 |
public function deleteFile($handle) {
$s3 = $this->newS3API();
AphrontWriteGuard::willWrite();
$profiler = PhutilServiceProfiler::getInstance();
$call_id = $profiler->beginServiceCall(
array(
'type' => 's3',
'method' => 'deleteObject',
));
$s3
->setParametersForDeleteObject($handle)
->resolve();
$profiler->endServiceCall($call_id, array());
} | Delete a blob from Amazon S3. | deleteFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorS3FileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorS3FileStorageEngine.php | Apache-2.0 |
private function getBucketName() {
$bucket = PhabricatorEnv::getEnvConfig('storage.s3.bucket');
if (!$bucket) {
throw new PhabricatorFileStorageConfigurationException(
pht(
"No '%s' specified!",
'storage.s3.bucket'));
}
return $bucket;
} | Retrieve the S3 bucket name.
@task internal | getBucketName | php | phorgeit/phorge | src/applications/files/engine/PhabricatorS3FileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorS3FileStorageEngine.php | Apache-2.0 |
private function newS3API() {
$access_key = PhabricatorEnv::getEnvConfig('amazon-s3.access-key');
$secret_key = PhabricatorEnv::getEnvConfig('amazon-s3.secret-key');
$region = PhabricatorEnv::getEnvConfig('amazon-s3.region');
$endpoint = PhabricatorEnv::getEnvConfig('amazon-s3.endpoint');
return id(new PhutilAWSS3Future())
->setAccessKey($access_key)
->setSecretKey(new PhutilOpaqueEnvelope($secret_key))
->setRegion($region)
->setEndpoint($endpoint)
->setBucket($this->getBucketName());
} | Create a new S3 API object.
@task internal | newS3API | php | phorgeit/phorge | src/applications/files/engine/PhabricatorS3FileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorS3FileStorageEngine.php | Apache-2.0 |
public function canWriteFiles() {
return (bool)$this->getWritableEngine();
} | We can write chunks if we have at least one valid storage engine
underneath us. | canWriteFiles | php | phorgeit/phorge | src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | Apache-2.0 |
public static function getChunkedHash(PhabricatorUser $viewer, $hash) {
if (!$viewer->getPHID()) {
throw new Exception(
pht('Unable to compute chunked hash without real viewer!'));
}
$input = $viewer->getAccountSecret().':'.$hash.':'.$viewer->getPHID();
return self::getChunkedHashForInput($input);
} | Compute a chunked file hash for the viewer.
We can not currently compute a real hash for chunked file uploads (because
no process sees all of the file data).
We also can not trust the hash that the user claims to have computed. If
we trust the user, they can upload some `evil.exe` and claim it has the
same file hash as `good.exe`. When another user later uploads the real
`good.exe`, we'll just create a reference to the existing `evil.exe`. Users
who download `good.exe` will then receive `evil.exe`.
Instead, we rehash the user's claimed hash with account secrets. This
allows users to resume file uploads, but not collide with other users.
Ideally, we'd like to be able to verify hashes, but this is complicated
and time consuming and gives us a fairly small benefit.
@param PhabricatorUser $viewer Viewing user.
@param string $hash Claimed file hash.
@return string Rehashed file hash. | getChunkedHash | php | phorgeit/phorge | src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | Apache-2.0 |
private function getWritableEngine() {
// NOTE: We can't just load writable engines or we'll loop forever.
$engines = parent::loadAllEngines();
foreach ($engines as $engine) {
if ($engine->isChunkEngine()) {
continue;
}
if ($engine->isTestEngine()) {
continue;
}
if (!$engine->canWriteFiles()) {
continue;
}
if ($engine->hasFilesizeLimit()) {
if ($engine->getFilesizeLimit() < $this->getChunkSize()) {
continue;
}
}
return true;
}
return false;
} | Find a storage engine which is suitable for storing chunks.
This engine must be a writable engine, have a filesize limit larger than
the chunk limit, and must not be a chunk engine itself. | getWritableEngine | php | phorgeit/phorge | src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | Apache-2.0 |
final public function __construct() {
// <empty>
} | Construct a new storage engine.
@task construct | __construct | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public function hasFilesizeLimit() {
return true;
} | Return `true` if the engine has a filesize limit on storable files.
The @{method:getFilesizeLimit} method can retrieve the actual limit. This
method just removes the ambiguity around the meaning of a `0` limit.
@return bool `true` if the engine has a filesize limit.
@task meta | hasFilesizeLimit | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public function getFilesizeLimit() {
// NOTE: This 8MB limit is selected to be larger than the 4MB chunk size,
// but not much larger. Files between 0MB and 8MB will be stored normally;
// files larger than 8MB will be chunked.
return (1024 * 1024 * 8);
} | Return maximum storable file size, in bytes.
Not all engines have a limit; use @{method:getFilesizeLimit} to check if
an engine has a limit. Engines without a limit can store files of any
size.
By default, engines define a limit which supports chunked storage of
large files. In most cases, you should not change this limit, even if an
engine has vast storage capacity: chunked storage makes large files more
manageable and enables features like resumable uploads.
@return int Maximum storable file size, in bytes.
@task meta | getFilesizeLimit | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public function isTestEngine() {
return false;
} | Identifies storage engines that support unit tests.
These engines are not used for production writes.
@return bool True if this is a test engine.
@task meta | isTestEngine | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public function isChunkEngine() {
return false;
} | Identifies chunking storage engines.
If this is a storage engine which splits files into chunks and stores the
chunks in other engines, it can return `true` to signal that other
chunking engines should not try to store data here.
@return bool True if this is a chunk engine.
@task meta | isChunkEngine | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public static function loadStorageEngines($length) {
$engines = self::loadWritableEngines();
$writable = array();
foreach ($engines as $key => $engine) {
if ($engine->hasFilesizeLimit()) {
$limit = $engine->getFilesizeLimit();
if ($limit < $length) {
continue;
}
}
$writable[$key] = $engine;
}
return $writable;
} | Select viable default storage engines according to configuration. We'll
select the MySQL and Local Disk storage engines if they are configured
to allow a given file.
@param int $length File size in bytes.
@task load | loadStorageEngines | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public static function loadAllEngines() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getEngineIdentifier')
->setSortMethod('getEnginePriority')
->execute();
} | @task load | loadAllEngines | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
private static function loadProductionEngines() {
$engines = self::loadAllEngines();
$active = array();
foreach ($engines as $key => $engine) {
if ($engine->isTestEngine()) {
continue;
}
$active[$key] = $engine;
}
return $active;
} | @task load | loadProductionEngines | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public static function loadWritableEngines() {
$engines = self::loadProductionEngines();
$writable = array();
foreach ($engines as $key => $engine) {
if (!$engine->canWriteFiles()) {
continue;
}
if ($engine->isChunkEngine()) {
// Don't select chunk engines as writable.
continue;
}
$writable[$key] = $engine;
}
return $writable;
} | @task load | loadWritableEngines | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public static function loadWritableChunkEngines() {
$engines = self::loadProductionEngines();
$chunk = array();
foreach ($engines as $key => $engine) {
if (!$engine->canWriteFiles()) {
continue;
}
if (!$engine->isChunkEngine()) {
continue;
}
$chunk[$key] = $engine;
}
return $chunk;
} | @task load | loadWritableChunkEngines | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public static function getChunkThreshold() {
$engines = self::loadWritableChunkEngines();
$min = null;
foreach ($engines as $engine) {
if (!$min) {
$min = $engine;
continue;
}
if ($min->getChunkSize() > $engine->getChunkSize()) {
$min = $engine->getChunkSize();
}
}
if (!$min) {
return null;
}
return $engine->getChunkSize();
} | Return the largest file size which can not be uploaded in chunks.
Files smaller than this will always upload in one request, so clients
can safely skip the allocation step.
@return int|null Byte size, or `null` if there is no chunk support. | getChunkThreshold | php | phorgeit/phorge | src/applications/files/engine/PhabricatorFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorFileStorageEngine.php | Apache-2.0 |
public function getEngineIdentifier() {
return 'local-disk';
} | This engine identifies as "local-disk". | getEngineIdentifier | php | phorgeit/phorge | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
public function writeFile($data, array $params) {
$root = $this->getLocalDiskFileStorageRoot();
// Generate a random, unique file path like "ab/29/1f918a9ac39201ff". We
// put a couple of subdirectories up front to avoid a situation where we
// have one directory with a zillion files in it, since this is generally
// bad news.
do {
$name = md5(mt_rand());
$name = preg_replace('/^(..)(..)(.*)$/', '\\1/\\2/\\3', $name);
if (!Filesystem::pathExists($root.'/'.$name)) {
break;
}
} while (true);
$parent = $root.'/'.dirname($name);
if (!Filesystem::pathExists($parent)) {
execx('mkdir -p %s', $parent);
}
AphrontWriteGuard::willWrite();
Filesystem::writeFile($root.'/'.$name, $data);
return $name;
} | Write the file data to local disk. Returns the relative path as the
file data handle.
@task impl | writeFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
public function readFile($handle) {
$path = $this->getLocalDiskFileStorageFullPath($handle);
return Filesystem::readFile($path);
} | Read the file data off local disk.
@task impl | readFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
public function deleteFile($handle) {
$path = $this->getLocalDiskFileStorageFullPath($handle);
if (Filesystem::pathExists($path)) {
AphrontWriteGuard::willWrite();
Filesystem::remove($path);
}
} | Deletes the file from local disk, if it exists.
@task impl | deleteFile | php | phorgeit/phorge | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
private function getLocalDiskFileStorageRoot() {
$root = PhabricatorEnv::getEnvConfig('storage.local-disk.path');
if (!$root || $root == '/' || $root[0] != '/') {
throw new PhabricatorFileStorageConfigurationException(
pht(
"Malformed local disk storage root. You must provide an absolute ".
"path, and can not use '%s' as the root.",
'/'));
}
return rtrim($root, '/');
} | Get the configured local disk path for file storage.
@return string Absolute path to somewhere that files can be stored.
@task internal | getLocalDiskFileStorageRoot | php | phorgeit/phorge | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
private function getLocalDiskFileStorageFullPath($handle) {
// Make sure there's no funny business going on here. Users normally have
// no ability to affect the content of handles, but double-check that
// we're only accessing local storage just in case.
if (!preg_match('@^[a-f0-9]{2}/[a-f0-9]{2}/[a-f0-9]{28}\z@', $handle)) {
throw new Exception(
pht(
"Local disk filesystem handle '%s' is malformed!",
$handle));
}
$root = $this->getLocalDiskFileStorageRoot();
return $root.'/'.$handle;
} | Convert a handle into an absolute local disk path.
@param string $handle File data handle.
@return string Absolute path to the corresponding file.
@task internal | getLocalDiskFileStorageFullPath | php | phorgeit/phorge | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
// NOTE: Throws if valid CSRF token is not present in the request.
$request->validateCSRF();
$name = $request->getStr('name');
$file_phid = $request->getStr('phid');
// If there's no explicit view policy, make it very restrictive by default.
// This is the correct policy for files dropped onto objects during
// creation, comment and edit flows.
$view_policy = $request->getStr('viewPolicy');
if (!$view_policy) {
$view_policy = $viewer->getPHID();
}
$is_chunks = $request->getBool('querychunks');
if ($is_chunks) {
$params = array(
'filePHID' => $file_phid,
);
$result = id(new ConduitCall('file.querychunks', $params))
->setUser($viewer)
->execute();
return id(new AphrontAjaxResponse())->setContent($result);
}
$is_allocate = $request->getBool('allocate');
if ($is_allocate) {
$params = array(
'name' => $name,
'contentLength' => $request->getInt('length'),
'viewPolicy' => $view_policy,
);
$result = id(new ConduitCall('file.allocate', $params))
->setUser($viewer)
->execute();
$file_phid = $result['filePHID'];
if ($file_phid) {
$file = $this->loadFile($file_phid);
$result += $file->getDragAndDropDictionary();
}
return id(new AphrontAjaxResponse())->setContent($result);
}
// Read the raw request data. We're either doing a chunk upload or a
// vanilla upload, so we need it.
$data = PhabricatorStartup::getRawInput();
$is_chunk_upload = $request->getBool('uploadchunk');
if ($is_chunk_upload) {
$params = array(
'filePHID' => $file_phid,
'byteStart' => $request->getInt('byteStart'),
'data' => $data,
);
$result = id(new ConduitCall('file.uploadchunk', $params))
->setUser($viewer)
->execute();
$file = $this->loadFile($file_phid);
if ($file->getIsPartial()) {
$result = array();
} else {
$result = array(
'complete' => true,
) + $file->getDragAndDropDictionary();
}
return id(new AphrontAjaxResponse())->setContent($result);
}
$file = PhabricatorFile::newFromXHRUpload(
$data,
array(
'name' => $request->getStr('name'),
'authorPHID' => $viewer->getPHID(),
'viewPolicy' => $view_policy,
'isExplicitUpload' => true,
));
$result = $file->getDragAndDropDictionary();
return id(new AphrontAjaxResponse())->setContent($result);
} | @phutil-external-symbol class PhabricatorStartup | handleRequest | php | phorgeit/phorge | src/applications/files/controller/PhabricatorFileDropUploadController.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/controller/PhabricatorFileDropUploadController.php | Apache-2.0 |
public function withTransforms(array $specs) {
foreach ($specs as $spec) {
if (!is_array($spec) ||
empty($spec['originalPHID']) ||
empty($spec['transform'])) {
throw new Exception(
pht(
"Transform specification must be a dictionary with keys ".
"'%s' and '%s'!",
'originalPHID',
'transform'));
}
}
$this->transforms = $specs;
return $this;
} | Select files which are transformations of some other file. For example,
you can use this query to find previously generated thumbnails of an image
file.
As a parameter, provide a list of transformation specifications. Each
specification is a dictionary with the keys `originalPHID` and `transform`.
The `originalPHID` is the PHID of the original file (the file which was
transformed) and the `transform` is the name of the transform to query
for. If you pass `true` as the `transform`, all transformations of the
file will be selected.
For example:
array(
array(
'originalPHID' => 'PHID-FILE-aaaa',
'transform' => 'sepia',
),
array(
'originalPHID' => 'PHID-FILE-bbbb',
'transform' => true,
),
)
This selects the `"sepia"` transformation of the file with PHID
`PHID-FILE-aaaa` and all transformations of the file with PHID
`PHID-FILE-bbbb`.
@param list<dict> $specs List of transform specifications, described
above.
@return $this | withTransforms | php | phorgeit/phorge | src/applications/files/query/PhabricatorFileQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/query/PhabricatorFileQuery.php | Apache-2.0 |
private static function rgba2gd($rgba) {
// When working with a truecolor image, we can use bitwise operations
// https://www.php.net/manual/en/function.imagecolorallocate.php#49168
$r = $rgba[0];
$g = $rgba[1];
$b = $rgba[2];
$a = $rgba[3];
$a = round(((1 - $a) * 255), 0);
return ($a << 24) | ($r << 16) | ($g << 8) | $b;
} | Convert a color from RGBA to a value usable in PHP-GD.
Each RGB color should be expressed as an integer from 0 to 255.
The Alpha Channel should be expressed as a float from 0 to 1.
@param array $rgba array( int Red, int Green, int Blue, float Alpha )
@return int | rgba2gd | php | phorgeit/phorge | src/applications/files/builtin/PhabricatorFilesComposeAvatarBuiltinFile.php | https://github.com/phorgeit/phorge/blob/master/src/applications/files/builtin/PhabricatorFilesComposeAvatarBuiltinFile.php | Apache-2.0 |
final public static function newFromDictionary(array $data) {
$repository_key = 'repository';
$identifier_key = 'callsign';
$viewer_key = 'user';
$repository = idx($data, $repository_key);
$identifier = idx($data, $identifier_key);
$have_repository = ($repository !== null);
$have_identifier = ($identifier !== null);
if ($have_repository && $have_identifier) {
throw new Exception(
pht(
'Specify "%s" or "%s", but not both.',
$repository_key,
$identifier_key));
}
if (!$have_repository && !$have_identifier) {
throw new Exception(
pht(
'One of "%s" and "%s" is required.',
$repository_key,
$identifier_key));
}
if ($have_repository) {
if (!($repository instanceof PhabricatorRepository)) {
if (empty($data[$viewer_key])) {
throw new Exception(
pht(
'Parameter "%s" is required if "%s" is provided.',
$viewer_key,
$identifier_key));
}
$identifier = $repository;
$repository = null;
}
}
if ($identifier !== null) {
$object = self::newFromIdentifier(
$identifier,
$data[$viewer_key],
idx($data, 'edit'));
} else {
$object = self::newFromRepository($repository);
}
if (!$object) {
return null;
}
$object->initializeFromDictionary($data);
return $object;
} | Create a new synthetic request from a parameter dictionary. If you need
a @{class:DiffusionRequest} object in order to issue a DiffusionQuery, you
can use this method to build one.
Parameters are:
- `repository` Repository object or identifier.
- `user` Viewing user. Required if `repository` is an identifier.
- `branch` Optional, branch name.
- `path` Optional, file path.
- `commit` Optional, commit identifier.
- `line` Optional, line range.
@param map $data See documentation.
@return DiffusionRequest|null New request object, or null if none is
found.
@task new | newFromDictionary | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
private function __construct() {
// <private>
} | Internal.
@task new | __construct | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
private static function newFromIdentifier(
$identifier,
PhabricatorUser $viewer,
$need_edit = false) {
$query = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withIdentifiers(array($identifier))
->needProfileImage(true)
->needURIs(true);
if ($need_edit) {
$query->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
));
}
$repository = $query->executeOne();
if (!$repository) {
return null;
}
return self::newFromRepository($repository);
} | Internal. Use @{method:newFromDictionary}, not this method.
@param string $identifier Repository identifier.
@param PhabricatorUser $viewer Viewing user.
@param bool $need_edit (optional)
@return DiffusionRequest New request object, or null if no repository is
found.
@task new | newFromIdentifier | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
private static function newFromRepository(
PhabricatorRepository $repository) {
$map = array(
PhabricatorRepositoryType::REPOSITORY_TYPE_GIT => 'DiffusionGitRequest',
PhabricatorRepositoryType::REPOSITORY_TYPE_SVN => 'DiffusionSvnRequest',
PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL =>
'DiffusionMercurialRequest',
);
$class = idx($map, $repository->getVersionControlSystem());
if (!$class) {
throw new Exception(pht('Unknown version control system!'));
}
$object = new $class();
$object->repository = $repository;
return $object;
} | Internal. Use @{method:newFromDictionary}, not this method.
@param PhabricatorRepository $repository Repository object.
@return DiffusionRequest New request object.
@task new | newFromRepository | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
private function initializeFromDictionary(array $data) {
$blob = idx($data, 'blob');
if (phutil_nonempty_string($blob)) {
$blob = self::parseRequestBlob($blob, $this->supportsBranches());
$data = $blob + $data;
}
$this->path = idx($data, 'path');
$this->line = idx($data, 'line');
$this->initFromConduit = idx($data, 'initFromConduit', true);
$this->lint = idx($data, 'lint');
$this->symbolicCommit = idx($data, 'commit');
if ($this->supportsBranches()) {
$this->branch = idx($data, 'branch');
}
if (!$this->getUser()) {
$user = idx($data, 'user');
if (!$user) {
throw new Exception(
pht(
'You must provide a %s in the dictionary!',
'PhabricatorUser'));
}
$this->setUser($user);
}
$this->didInitialize();
} | Internal. Use @{method:newFromDictionary}, not this method.
@param map $data Map of parsed data.
@return void
@task new | initializeFromDictionary | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
public function getSymbolicCommit() {
return $this->symbolicCommit;
} | Get the symbolic commit associated with this request.
A symbolic commit may be a commit hash, an abbreviated commit hash, a
branch name, a tag name, or an expression like "HEAD^^^". The symbolic
commit may also be absent.
This method always returns the symbol present in the original request,
in unmodified form.
See also @{method:getStableCommit}.
@return string|null Symbolic commit, if one was present in the request. | getSymbolicCommit | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
public function updateSymbolicCommit($symbol) {
$this->symbolicCommit = $symbol;
$this->symbolicType = null;
$this->stableCommit = null;
return $this;
} | Modify the request to move the symbolic commit elsewhere.
@param string $symbol New symbolic commit.
@return $this | updateSymbolicCommit | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
public function getSymbolicType() {
if ($this->symbolicType === null) {
// As a side effect, this resolves the symbolic type.
$this->getStableCommit();
}
return $this->symbolicType;
} | Get the ref type (`commit` or `tag`) of the location associated with this
request.
If a symbolic commit is present in the request, this method identifies
the type of the symbol. Otherwise, it identifies the type of symbol of
the location the request is implicitly associated with. This will probably
always be `commit`.
@return string Symbolic commit type (`commit` or `tag`). | getSymbolicType | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
public function getStableCommit() {
if (!$this->stableCommit) {
if ($this->isStableCommit($this->symbolicCommit)) {
$this->stableCommit = $this->symbolicCommit;
$this->symbolicType = 'commit';
} else {
$this->queryStableCommit();
}
}
return $this->stableCommit;
} | Retrieve the stable, permanent commit name identifying the repository
location associated with this request.
This returns a non-symbolic identifier for the current commit: in Git and
Mercurial, a 40-character SHA1; in SVN, a revision number.
See also @{method:getSymbolicCommit}.
@return string Stable commit name, like a git hash or SVN revision. Not
a symbolic commit reference. | getStableCommit | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
public static function parseRequestBlob($blob, $supports_branches) {
$result = array(
'branch' => null,
'path' => null,
'commit' => null,
'line' => null,
);
$matches = null;
if ($supports_branches) {
// Consume the front part of the URI, up to the first "/". This is the
// path-component encoded branch name.
if (preg_match('@^([^/]+)/@', $blob, $matches)) {
$result['branch'] = phutil_unescape_uri_path_component($matches[1]);
$blob = substr($blob, strlen($matches[1]) + 1);
}
}
// Consume the back part of the URI, up to the first "$". Use a negative
// lookbehind to prevent matching '$$'. We double the '$' symbol when
// encoding so that files with names like "money/$100" will survive.
$pattern = '@(?:(?:^|[^$])(?:[$][$])*)[$]([\d,-]+)$@';
if (preg_match($pattern, $blob, $matches)) {
$result['line'] = $matches[1];
$blob = substr($blob, 0, -(strlen($matches[1]) + 1));
}
// We've consumed the line number if it exists, so unescape "$" in the
// rest of the string.
$blob = str_replace('$$', '$', $blob);
// Consume the commit name, stopping on ';;'. We allow any character to
// appear in commits names, as they can sometimes be symbolic names (like
// tag names or refs).
if (preg_match('@(?:(?:^|[^;])(?:;;)*);([^;].*)$@', $blob, $matches)) {
$result['commit'] = $matches[1];
$blob = substr($blob, 0, -(strlen($matches[1]) + 1));
}
// We've consumed the commit if it exists, so unescape ";" in the rest
// of the string.
$blob = str_replace(';;', ';', $blob);
if (strlen($blob)) {
$result['path'] = $blob;
}
if ($result['path'] !== null) {
$parts = explode('/', $result['path']);
foreach ($parts as $part) {
// Prevent any hyjinx since we're ultimately shipping this to the
// filesystem under a lot of workflows.
if ($part == '..') {
throw new Exception(pht('Invalid path URI.'));
}
}
}
return $result;
} | Internal. Public only for unit tests.
Parse the request URI into components.
@param string $blob URI blob.
@param bool $supports_branches True if this VCS supports branches.
@return map Parsed URI.
@task uri | parseRequestBlob | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
protected function validateWorkingCopy($path) {
if (!is_readable(dirname($path))) {
$this->raisePermissionException();
}
if (!Filesystem::pathExists($path)) {
$this->raiseCloneException();
}
} | Check that the working copy of the repository is present and readable.
@param string $path Path to the working copy. | validateWorkingCopy | php | phorgeit/phorge | src/applications/diffusion/request/DiffusionRequest.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/request/DiffusionRequest.php | Apache-2.0 |
public function synchronizeWorkingCopyAfterWrite() {
if (!$this->shouldEnableSynchronization(true)) {
return;
}
if (!$this->clusterWriteLock) {
throw new Exception(
pht(
'Trying to synchronize after write, but not holding a write '.
'lock!'));
}
$repository = $this->getRepository();
$repository_phid = $repository->getPHID();
$device = AlmanacKeys::getLiveDevice();
$device_phid = $device->getPHID();
// It is possible that we've lost the global lock while receiving the push.
// For example, the master database may have been restarted between the
// time we acquired the global lock and now, when the push has finished.
// We wrote a durable lock while we were holding the the global lock,
// essentially upgrading our lock. We can still safely release this upgraded
// lock even if we're no longer holding the global lock.
// If we fail to release the lock, the repository will be frozen until
// an operator can figure out what happened, so we try pretty hard to
// reconnect to the database and release the lock.
$now = PhabricatorTime::getNow();
$duration = phutil_units('5 minutes in seconds');
$try_until = $now + $duration;
$did_release = false;
$already_failed = false;
while (PhabricatorTime::getNow() <= $try_until) {
try {
// NOTE: This means we're still bumping the version when pushes fail. We
// could select only un-rejected events instead to bump a little less
// often.
$new_log = id(new PhabricatorRepositoryPushEventQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withRepositoryPHIDs(array($repository_phid))
->setLimit(1)
->executeOne();
$old_version = $this->clusterWriteVersion;
if ($new_log) {
$new_version = $new_log->getID();
} else {
$new_version = $old_version;
}
PhabricatorRepositoryWorkingCopyVersion::didWrite(
$repository_phid,
$device_phid,
$this->clusterWriteVersion,
$new_version,
$this->clusterWriteOwner);
$did_release = true;
break;
} catch (AphrontConnectionQueryException $ex) {
$connection_exception = $ex;
} catch (AphrontConnectionLostQueryException $ex) {
$connection_exception = $ex;
}
if (!$already_failed) {
$already_failed = true;
$this->logLine(
pht('CRITICAL. Failed to release cluster write lock!'));
$this->logLine(
pht(
'The connection to the master database was lost while receiving '.
'the write.'));
$this->logLine(
pht(
'This process will spend %s more second(s) attempting to '.
'recover, then give up.',
new PhutilNumber($duration)));
}
sleep(1);
}
if ($did_release) {
if ($already_failed) {
$this->logLine(
pht('RECOVERED. Link to master database was restored.'));
}
$this->logLine(pht('Released cluster write lock.'));
} else {
throw new Exception(
pht(
'Failed to reconnect to master database and release held write '.
'lock ("%s") on device "%s" for repository "%s" after trying '.
'for %s seconds(s). This repository will be frozen.',
$this->clusterWriteOwner,
$device->getName(),
$repository->getDisplayName(),
new PhutilNumber($duration)));
}
// We can continue even if we've lost this lock, everything is still
// consistent.
try {
$this->clusterWriteLock->unlock();
} catch (Exception $ex) {
// Ignore.
}
$this->clusterWriteLock = null;
$this->clusterWriteOwner = null;
} | @task sync | synchronizeWorkingCopyAfterWrite | php | phorgeit/phorge | src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | Apache-2.0 |
private function shouldEnableSynchronization($require_device) {
$repository = $this->getRepository();
$service_phid = $repository->getAlmanacServicePHID();
if (!$service_phid) {
return false;
}
if (!$repository->supportsSynchronization()) {
return false;
}
if ($require_device) {
$device = AlmanacKeys::getLiveDevice();
if (!$device) {
return false;
}
}
return true;
} | @task internal | shouldEnableSynchronization | php | phorgeit/phorge | src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | Apache-2.0 |
private function synchronizeWorkingCopyFromRemote() {
$repository = $this->getRepository();
$device = AlmanacKeys::getLiveDevice();
$local_path = $repository->getLocalPath();
$fetch_uri = $repository->getRemoteURIEnvelope();
if ($repository->isGit()) {
$this->requireWorkingCopy();
$argv = array(
'fetch --prune -- %P %s',
$fetch_uri,
'+refs/*:refs/*',
);
} else {
throw new Exception(pht('Remote sync only supported for git!'));
}
$future = DiffusionCommandEngine::newCommandEngine($repository)
->setArgv($argv)
->setSudoAsDaemon(true)
->setCredentialPHID($repository->getCredentialPHID())
->setURI($repository->getRemoteURIObject())
->newFuture();
$future->setCWD($local_path);
try {
$future->resolvex();
} catch (Exception $ex) {
$this->logLine(
pht(
'Synchronization of "%s" from remote failed: %s',
$device->getName(),
$ex->getMessage()));
throw $ex;
}
} | @task internal | synchronizeWorkingCopyFromRemote | php | phorgeit/phorge | src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | Apache-2.0 |
private function synchronizeWorkingCopyFromBinding(
AlmanacBinding $binding,
$local_version,
$remote_version) {
$repository = $this->getRepository();
$device = AlmanacKeys::getLiveDevice();
$this->logLine(
pht(
'Synchronizing this device ("%s") from cluster leader ("%s").',
$device->getName(),
$binding->getDevice()->getName()));
$fetch_uri = $repository->getClusterRepositoryURIFromBinding($binding);
$local_path = $repository->getLocalPath();
if ($repository->isGit()) {
$this->requireWorkingCopy();
$argv = array(
'fetch --prune -- %s %s',
$fetch_uri,
'+refs/*:refs/*',
);
} else {
throw new Exception(pht('Binding sync only supported for git!'));
}
$future = DiffusionCommandEngine::newCommandEngine($repository)
->setArgv($argv)
->setConnectAsDevice(true)
->setSudoAsDaemon(true)
->setURI($fetch_uri)
->newFuture();
$future->setCWD($local_path);
$log = PhabricatorRepositorySyncEvent::initializeNewEvent()
->setRepositoryPHID($repository->getPHID())
->setEpoch(PhabricatorTime::getNow())
->setDevicePHID($device->getPHID())
->setFromDevicePHID($binding->getDevice()->getPHID())
->setDeviceVersion($local_version)
->setFromDeviceVersion($remote_version);
$sync_start = microtime(true);
try {
$future->resolvex();
} catch (Exception $ex) {
$log->setSyncWait(phutil_microseconds_since($sync_start));
if ($ex instanceof CommandException) {
if ($future->getWasKilledByTimeout()) {
$result_type = PhabricatorRepositorySyncEvent::RESULT_TIMEOUT;
} else {
$result_type = PhabricatorRepositorySyncEvent::RESULT_ERROR;
}
$log
->setResultCode($ex->getError())
->setResultType($result_type)
->setProperty('stdout', $ex->getStdout())
->setProperty('stderr', $ex->getStderr());
} else {
$log
->setResultCode(1)
->setResultType(PhabricatorRepositorySyncEvent::RESULT_EXCEPTION)
->setProperty('message', $ex->getMessage());
}
$log->save();
$this->logLine(
pht(
'Synchronization of "%s" from leader "%s" failed: %s',
$device->getName(),
$binding->getDevice()->getName(),
$ex->getMessage()));
throw $ex;
}
$log
->setSyncWait(phutil_microseconds_since($sync_start))
->setResultCode(0)
->setResultType(PhabricatorRepositorySyncEvent::RESULT_SYNC)
->save();
} | @task internal | synchronizeWorkingCopyFromBinding | php | phorgeit/phorge | src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | Apache-2.0 |
private function logLine($message) {
return $this->logText("# {$message}\n");
} | @task internal | logLine | php | phorgeit/phorge | src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | Apache-2.0 |
private function logText($message) {
$log = $this->logger;
if ($log) {
$log->writeClusterEngineLogMessage($message);
}
return $this;
} | @task internal | logText | php | phorgeit/phorge | src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/protocol/DiffusionRepositoryClusterEngine.php | Apache-2.0 |
public static function filterBundle2Capability($capabilities) {
$parts = explode(' ', $capabilities);
foreach ($parts as $key => $part) {
if (preg_match('/^bundle2=/', $part)) {
unset($parts[$key]);
break;
}
}
return implode(' ', $parts);
} | If the server version is running 3.4+ it will respond
with 'bundle2' capability in the format of "bundle2=(url-encoding)".
Until we manage to properly package up bundles to send back we
disallow the client from knowing we speak bundle2 by removing it
from the capabilities listing.
The format of the capabilities string is: "a space separated list
of strings representing what commands the server supports"
@link https://www.mercurial-scm.org/wiki/CommandServer#Protocol
@param string $capabilities - The string of capabilities to
strip the bundle2 capability from. This is expected to be
the space-separated list of strings resulting from the
querying the 'capabilities' command.
@return string The resulting space-separated list of capabilities
which no longer contains the 'bundle2' capability. This is meant
to replace the original $body to send back to client. | filterBundle2Capability | php | phorgeit/phorge | src/applications/diffusion/protocol/DiffusionMercurialWireProtocol.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/protocol/DiffusionMercurialWireProtocol.php | Apache-2.0 |
public function serializeStruct(array $struct) {
$out = array();
$out[] = '( ';
foreach ($struct as $item) {
$value = $item['value'];
$type = $item['type'];
switch ($type) {
case 'word':
$out[] = $value;
break;
case 'number':
$out[] = $value;
break;
case 'string':
$out[] = strlen($value).':'.$value;
break;
case 'list':
$out[] = self::serializeStruct($value);
break;
default:
throw new Exception(
pht(
"Unknown SVN wire protocol structure '%s'!",
$type));
}
if ($type != 'list') {
$out[] = ' ';
}
}
$out[] = ') ';
return implode('', $out);
} | Convert a parsed command struct into a wire protocol string. | serializeStruct | php | phorgeit/phorge | src/applications/diffusion/protocol/DiffusionSubversionWireProtocol.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/protocol/DiffusionSubversionWireProtocol.php | Apache-2.0 |
public function supportsObject($object) {
if (id(new PhabricatorAuditApplication())->isInstalled()) {
return ($object instanceof PhabricatorRepositoryCommit);
} else {
return false;
}
} | hide "Auditors" Herald condition if Audit not installed | supportsObject | php | phorgeit/phorge | src/applications/diffusion/herald/DiffusionCommitAuditorsHeraldField.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/herald/DiffusionCommitAuditorsHeraldField.php | Apache-2.0 |
public function supportsRuleType($rule_type) {
if (id(new PhabricatorAuditApplication())->isInstalled()) {
return ($rule_type == HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
} else {
return false;
}
} | hide "Add me as an auditor" Herald action if Audit not installed | supportsRuleType | php | phorgeit/phorge | src/applications/diffusion/herald/DiffusionAuditorsAddSelfHeraldAction.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/herald/DiffusionAuditorsAddSelfHeraldAction.php | Apache-2.0 |
public function supportsObject($object) {
if (id(new PhabricatorAuditApplication())->isInstalled()) {
return ($object instanceof PhabricatorRepositoryCommit);
} else {
return false;
}
} | hide "Affected packages that need audit" Herald condition
if Audit not installed | supportsObject | php | phorgeit/phorge | src/applications/diffusion/herald/DiffusionCommitPackageAuditHeraldField.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/herald/DiffusionCommitPackageAuditHeraldField.php | Apache-2.0 |
public function supportsRuleType($rule_type) {
if (id(new PhabricatorAuditApplication())->isInstalled()) {
return ($rule_type != HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
} else {
return false;
}
} | hide "Add auditors" Herald action if Audit not installed | supportsRuleType | php | phorgeit/phorge | src/applications/diffusion/herald/DiffusionAuditorsAddAuditorsHeraldAction.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/herald/DiffusionAuditorsAddAuditorsHeraldAction.php | Apache-2.0 |
protected function defineCustomErrorTypes() {
return array();
} | Subclasses should override this to specify custom error types. | defineCustomErrorTypes | php | phorgeit/phorge | src/applications/diffusion/conduit/DiffusionQueryConduitAPIMethod.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/conduit/DiffusionQueryConduitAPIMethod.php | Apache-2.0 |
protected function defineCustomParamTypes() {
return array();
} | Subclasses should override this to specify custom param types. | defineCustomParamTypes | php | phorgeit/phorge | src/applications/diffusion/conduit/DiffusionQueryConduitAPIMethod.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/conduit/DiffusionQueryConduitAPIMethod.php | Apache-2.0 |
protected function getGitResult(ConduitAPIRequest $request) {
throw new ConduitException('ERR-UNSUPPORTED-VCS');
} | Subclasses should override these methods with the proper result for the
pertinent version control system, e.g. getGitResult for Git.
If the result is not supported for that VCS, do not implement it. e.g.
Subversion (SVN) does not support branches. | getGitResult | php | phorgeit/phorge | src/applications/diffusion/conduit/DiffusionQueryConduitAPIMethod.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/conduit/DiffusionQueryConduitAPIMethod.php | Apache-2.0 |
final protected function execute(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
// We pass this flag on to prevent proxying of any other Conduit calls
// which we need to make in order to respond to this one. Although we
// could safely proxy them, we take a big performance hit in the common
// case, and doing more proxying wouldn't exercise any additional code so
// we wouldn't gain a testability/predictability benefit.
$is_cluster_request = $request->getIsClusterRequest();
$drequest->setIsClusterRequest($is_cluster_request);
$viewer = $request->getViewer();
$repository = $drequest->getRepository();
// TODO: Allow web UI queries opt out of this if they don't care about
// fetching the most up-to-date data? Synchronization can be slow, and a
// lot of web reads are probably fine if they're a few seconds out of
// date.
id(new DiffusionRepositoryClusterEngine())
->setViewer($viewer)
->setRepository($repository)
->synchronizeWorkingCopyBeforeRead();
return $this->getResult($request);
} | This method is final because most queries will need to construct a
@{class:DiffusionRequest} and use it. Consolidating this codepath and
enforcing @{method:getDiffusionRequest} works when we need it is good.
@{method:getResult} should be overridden by subclasses as necessary, e.g.
there is a common operation across all version control systems that
should occur after @{method:getResult}, like formatting a timestamp. | execute | php | phorgeit/phorge | src/applications/diffusion/conduit/DiffusionQueryConduitAPIMethod.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/conduit/DiffusionQueryConduitAPIMethod.php | Apache-2.0 |
protected function getSVNResult(ConduitAPIRequest $request) {
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$effective_commit = $this->getEffectiveCommit($request);
if (!$effective_commit) {
return $this->getEmptyResult();
}
$drequest = clone $drequest;
$drequest->updateSymbolicCommit($effective_commit);
$path_change_query = DiffusionPathChangeQuery::newFromDiffusionRequest(
$drequest);
$path_changes = $path_change_query->loadChanges();
$path = null;
foreach ($path_changes as $change) {
if ($change->getPath() == $drequest->getPath()) {
$path = $change;
}
}
if (!$path) {
return $this->getEmptyResult();
}
$change_type = $path->getChangeType();
switch ($change_type) {
case DifferentialChangeType::TYPE_MULTICOPY:
case DifferentialChangeType::TYPE_DELETE:
if ($path->getTargetPath()) {
$old = array(
$path->getTargetPath(),
$path->getTargetCommitIdentifier(),
);
} else {
$old = array($path->getPath(), $path->getCommitIdentifier() - 1);
}
$old_name = $path->getPath();
$new_name = '';
$new = null;
break;
case DifferentialChangeType::TYPE_ADD:
$old = null;
$new = array($path->getPath(), $path->getCommitIdentifier());
$old_name = '';
$new_name = $path->getPath();
break;
case DifferentialChangeType::TYPE_MOVE_HERE:
case DifferentialChangeType::TYPE_COPY_HERE:
$old = array(
$path->getTargetPath(),
$path->getTargetCommitIdentifier(),
);
$new = array($path->getPath(), $path->getCommitIdentifier());
$old_name = $path->getTargetPath();
$new_name = $path->getPath();
break;
case DifferentialChangeType::TYPE_MOVE_AWAY:
$old = array(
$path->getPath(),
$path->getCommitIdentifier() - 1,
);
$old_name = $path->getPath();
$new_name = null;
$new = null;
break;
default:
$old = array($path->getPath(), $path->getCommitIdentifier() - 1);
$new = array($path->getPath(), $path->getCommitIdentifier());
$old_name = $path->getPath();
$new_name = $path->getPath();
break;
}
$futures = array(
'old' => $this->buildSVNContentFuture($old),
'new' => $this->buildSVNContentFuture($new),
);
$futures = array_filter($futures);
foreach (new FutureIterator($futures) as $key => $future) {
$stdout = '';
try {
list($stdout) = $future->resolvex();
} catch (CommandException $e) {
if ($path->getFileType() != DifferentialChangeType::FILE_DIRECTORY) {
throw $e;
}
}
$futures[$key] = $stdout;
}
$old_data = idx($futures, 'old', '');
$new_data = idx($futures, 'new', '');
$engine = new PhabricatorDifferenceEngine();
$engine->setOldName($old_name);
$engine->setNewName($new_name);
$raw_diff = $engine->generateRawDiffFromFileContent($old_data, $new_data);
$arcanist_changes = DiffusionPathChange::convertToArcanistChanges(
$path_changes);
$parser = $this->getDefaultParser($request);
$parser->setChanges($arcanist_changes);
$parser->forcePath($path->getPath());
$changes = $parser->parseDiff($raw_diff);
$change = $changes[$path->getPath()];
return array($change);
} | NOTE: We have to work particularly hard for SVN as compared to other VCS.
That's okay but means this shares little code with the other VCS. | getSVNResult | php | phorgeit/phorge | src/applications/diffusion/conduit/DiffusionDiffQueryConduitAPIMethod.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/conduit/DiffusionDiffQueryConduitAPIMethod.php | Apache-2.0 |
private function getReadmeLanguage($path) {
$path = phutil_utf8_strtolower($path);
if ($path == 'readme') {
return 'remarkup';
}
$ext = last(explode('.', $path));
switch ($ext) {
case 'remarkup':
case 'md':
return 'remarkup';
case 'rainbow':
return 'rainbow';
case 'txt':
default:
return 'text';
}
} | Get the markup language a README should be interpreted as.
@param string $path Local README path, like "README.txt".
@return string Best markup interpreter (like "remarkup") for this file. | getReadmeLanguage | php | phorgeit/phorge | src/applications/diffusion/view/DiffusionReadmeView.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/view/DiffusionReadmeView.php | Apache-2.0 |
private function isReadOnlyRequest(
PhabricatorRepository $repository) {
$request = $this->getRequest();
$method = $_SERVER['REQUEST_METHOD'];
// TODO: This implementation is safe by default, but very incomplete.
if ($this->getIsGitLFSRequest()) {
return $this->isGitLFSReadOnlyRequest($repository);
}
switch ($repository->getVersionControlSystem()) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
$service = $request->getStr('service');
$path = $this->getRequestDirectoryPath($repository);
// NOTE: Service names are the reverse of what you might expect, as they
// are from the point of view of the server. The main read service is
// "git-upload-pack", and the main write service is "git-receive-pack".
if ($method == 'GET' &&
$path == '/info/refs' &&
$service == 'git-upload-pack') {
return true;
}
if ($path == '/git-upload-pack') {
return true;
}
break;
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
$cmd = $request->getStr('cmd');
if ($cmd == 'batch') {
$cmds = idx($this->getMercurialArguments(), 'cmds');
return DiffusionMercurialWireProtocol::isReadOnlyBatchCommand($cmds);
}
return DiffusionMercurialWireProtocol::isReadOnlyCommand($cmd);
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
break;
}
return false;
} | @return bool | isReadOnlyRequest | php | phorgeit/phorge | src/applications/diffusion/controller/DiffusionServeController.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/controller/DiffusionServeController.php | Apache-2.0 |
private function serveGitRequest(
PhabricatorRepository $repository,
PhabricatorUser $viewer) {
$request = $this->getRequest();
$request_path = $this->getRequestDirectoryPath($repository);
$repository_root = $repository->getLocalPath();
// Rebuild the query string to strip `__magic__` parameters and prevent
// issues where we might interpret inputs like "service=read&service=write"
// differently than the server does and pass it an unsafe command.
// NOTE: This does not use getPassthroughRequestParameters() because
// that code is HTTP-method agnostic and will encode POST data.
$query_data = $_GET;
foreach ($query_data as $key => $value) {
if (!strncmp($key, '__', 2)) {
unset($query_data[$key]);
}
}
$query_string = phutil_build_http_querystring($query_data);
// We're about to wipe out PATH with the rest of the environment, so
// resolve the binary first.
$bin = Filesystem::resolveBinary('git-http-backend');
if (!$bin) {
throw new Exception(
pht(
'Unable to find `%s` in %s!',
'git-http-backend',
'$PATH'));
}
// NOTE: We do not set HTTP_CONTENT_ENCODING here, because we already
// decompressed the request when we read the request body, so the body is
// just plain data with no encoding.
$env = array(
'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'],
'QUERY_STRING' => $query_string,
'CONTENT_TYPE' => $request->getHTTPHeader('Content-Type'),
'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'],
'GIT_PROJECT_ROOT' => $repository_root,
'GIT_HTTP_EXPORT_ALL' => '1',
'PATH_INFO' => $request_path,
'REMOTE_USER' => $viewer->getUsername(),
// TODO: Set these correctly.
// GIT_COMMITTER_NAME
// GIT_COMMITTER_EMAIL
) + $this->getCommonEnvironment($viewer);
$input = PhabricatorStartup::getRawInput();
$command = csprintf('%s', $bin);
$command = PhabricatorDaemon::sudoCommandAsDaemonUser($command);
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$cluster_engine = id(new DiffusionRepositoryClusterEngine())
->setViewer($viewer)
->setRepository($repository);
$did_write_lock = false;
if ($this->isReadOnlyRequest($repository)) {
$cluster_engine->synchronizeWorkingCopyBeforeRead();
} else {
$did_write_lock = true;
$cluster_engine->synchronizeWorkingCopyBeforeWrite();
}
$caught = null;
try {
list($err, $stdout, $stderr) = id(new ExecFuture('%C', $command))
->setEnv($env, true)
->write($input)
->resolve();
} catch (Exception $ex) {
$caught = $ex;
}
if ($did_write_lock) {
$cluster_engine->synchronizeWorkingCopyAfterWrite();
}
unset($unguarded);
if ($caught) {
throw $caught;
}
if ($err) {
if ($this->isValidGitShallowCloneResponse($stdout, $stderr)) {
// Ignore the error if the response passes this special check for
// validity.
$err = 0;
}
}
if ($err) {
return new PhabricatorVCSResponse(
500,
pht(
'Error %d: %s',
$err,
phutil_utf8ize($stderr)));
}
return id(new DiffusionGitResponse())->setGitData($stdout);
} | @phutil-external-symbol class PhabricatorStartup | serveGitRequest | php | phorgeit/phorge | src/applications/diffusion/controller/DiffusionServeController.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/controller/DiffusionServeController.php | Apache-2.0 |
protected function buildLocateFile() {
$request = $this->getRequest();
$viewer = $request->getUser();
$drequest = $this->getDiffusionRequest();
$repository = $drequest->getRepository();
$form_box = null;
if ($repository->canUsePathTree()) {
Javelin::initBehavior(
'diffusion-locate-file',
array(
'controlID' => 'locate-control',
'inputID' => 'locate-input',
'symbolicCommit' => $drequest->getSymbolicCommit(),
'browseBaseURI' => (string)$drequest->generateURI(
array(
'action' => 'browse',
'commit' => '',
'path' => '',
)),
'uri' => (string)$drequest->generateURI(
array(
'action' => 'pathtree',
)),
));
$form = id(new AphrontFormView())
->setUser($viewer)
->appendChild(
id(new AphrontFormTypeaheadControl())
->setHardpointID('locate-control')
->setID('locate-input')
->setPlaceholder(pht('Locate File')));
$form_box = id(new PHUIBoxView())
->appendChild($form->buildLayoutView())
->addClass('diffusion-profile-locate');
}
return $form_box;
} | @return PHUIBoxView|null | buildLocateFile | php | phorgeit/phorge | src/applications/diffusion/controller/DiffusionController.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/controller/DiffusionController.php | Apache-2.0 |
public function withIdentifiers(array $identifiers) {
// Some workflows (like blame lookups) can pass in large numbers of
// duplicate identifiers. We only care about unique identifiers, so
// get rid of duplicates immediately.
$identifiers = array_fuse($identifiers);
$this->identifiers = $identifiers;
return $this;
} | Load commits by partial or full identifiers, e.g. "rXab82393", "rX1234",
or "a9caf12". When an identifier matches multiple commits, they will all
be returned; callers should be prepared to deal with more results than
they queried for. | withIdentifiers | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionCommitQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionCommitQuery.php | Apache-2.0 |
public function withRepository(PhabricatorRepository $repository) {
$this->withDefaultRepository($repository);
$this->withRepositoryIDs(array($repository->getID()));
return $this;
} | Look up commits in a specific repository. This is a shorthand for calling
@{method:withDefaultRepository} and @{method:withRepositoryIDs}. | withRepository | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionCommitQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionCommitQuery.php | Apache-2.0 |
public function withRepositoryPHIDs(array $phids) {
$this->repositoryPHIDs = $phids;
return $this;
} | Look up commits in a specific repository. Prefer
@{method:withRepositoryIDs}; the underlying table is keyed by ID such
that this method requires a separate initial query to map PHID to ID. | withRepositoryPHIDs | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionCommitQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionCommitQuery.php | Apache-2.0 |
public function withDefaultRepository(PhabricatorRepository $repository) {
$this->defaultRepository = $repository;
return $this;
} | If a default repository is provided, ambiguous commit identifiers will
be assumed to belong to the default repository.
For example, "r123" appearing in a commit message in repository X is
likely to be unambiguously "rX123". Normally the reference would be
considered ambiguous, but if you provide a default repository it will
be correctly resolved. | withDefaultRepository | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionCommitQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionCommitQuery.php | Apache-2.0 |
private function resolveSubversionRefs() {
$repository = $this->getRepository();
$max_commit = id(new PhabricatorRepositoryCommit())
->loadOneWhere(
'repositoryID = %d ORDER BY epoch DESC, id DESC LIMIT 1',
$repository->getID());
if (!$max_commit) {
// This repository is empty or hasn't parsed yet, so none of the refs are
// going to resolve.
return array();
}
$max_commit_id = (int)$max_commit->getCommitIdentifier();
$results = array();
foreach ($this->refs as $ref) {
if ($ref == 'HEAD') {
// Resolve "HEAD" to mean "the most recent commit".
$results[$ref][] = array(
'type' => 'commit',
'identifier' => $max_commit_id,
);
continue;
}
if (!preg_match('/^\d+$/', $ref)) {
// This ref is non-numeric, so it doesn't resolve to anything.
continue;
}
// Resolve other commits if we can deduce their existence.
// TODO: When we import only part of a repository, we won't necessarily
// have all of the smaller commits. Should we fail to resolve them here
// for repositories with a subpath? It might let us simplify other things
// elsewhere.
if ((int)$ref <= $max_commit_id) {
$results[$ref][] = array(
'type' => 'commit',
'identifier' => (int)$ref,
);
}
}
return $results;
} | Resolve refs in Subversion repositories.
We can resolve all numeric identifiers and the keyword `HEAD`. | resolveSubversionRefs | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionCachedResolveRefsQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionCachedResolveRefsQuery.php | Apache-2.0 |
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
} | @task config | setViewer | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function getViewer() {
return $this->viewer;
} | @task config | getViewer | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function setContext($context) {
$this->context = $context;
return $this;
} | @task config | setContext | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function setName($name) {
$this->name = $name;
return $this;
} | @task config | setName | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function setNamePrefix($name_prefix) {
$this->namePrefix = $name_prefix;
return $this;
} | @task config | setNamePrefix | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
} | @task config | withRepositoryPHIDs | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function setLanguage($language) {
$this->language = $language;
return $this;
} | @task config | setLanguage | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function setType($type) {
$this->type = $type;
return $this;
} | @task config | setType | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function needPaths($need_paths) {
$this->needPaths = $need_paths;
return $this;
} | @task config | needPaths | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function needRepositories($need_repositories) {
$this->needRepositories = $need_repositories;
return $this;
} | @task config | needRepositories | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
public function execute() {
if ($this->name && $this->namePrefix) {
throw new Exception(
pht('You can not set both a name and a name prefix!'));
} else if (!$this->name && !$this->namePrefix) {
throw new Exception(
pht('You must set a name or a name prefix!'));
}
$symbol = new PhabricatorRepositorySymbol();
$conn_r = $symbol->establishConnection('r');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T %Q %Q %Q',
$symbol->getTableName(),
$this->buildWhereClause($conn_r),
$this->buildOrderClause($conn_r),
$this->buildLimitClause($conn_r));
$symbols = $symbol->loadAllFromArray($data);
if ($symbols) {
if ($this->needPaths) {
$this->loadPaths($symbols);
}
if ($this->needRepositories) {
$symbols = $this->loadRepositories($symbols);
}
}
return $symbols;
} | @task exec | execute | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
private function buildOrderClause($conn_r) {
return qsprintf(
$conn_r,
'ORDER BY symbolName ASC');
} | @task internal | buildOrderClause | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$where = array();
if (isset($this->context)) {
$where[] = qsprintf(
$conn,
'symbolContext = %s',
$this->context);
}
if ($this->name) {
$where[] = qsprintf(
$conn,
'symbolName = %s',
$this->name);
}
if ($this->namePrefix) {
$where[] = qsprintf(
$conn,
'symbolName LIKE %>',
$this->namePrefix);
}
if ($this->repositoryPHIDs) {
$where[] = qsprintf(
$conn,
'repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
if ($this->language) {
$where[] = qsprintf(
$conn,
'symbolLanguage = %s',
$this->language);
}
if ($this->type) {
$where[] = qsprintf(
$conn,
'symbolType = %s',
$this->type);
}
return $this->formatWhereClause($conn, $where);
} | @task internal | buildWhereClause | php | phorgeit/phorge | src/applications/diffusion/query/DiffusionSymbolQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/DiffusionSymbolQuery.php | Apache-2.0 |
private function getFields() {
return array(
'objectname',
'objecttype',
'refname',
'*objectname',
'*objecttype',
'subject',
'creator',
);
} | List of git `--format` fields we want to grab. | getFields | php | phorgeit/phorge | src/applications/diffusion/query/lowlevel/DiffusionLowLevelGitRefQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/lowlevel/DiffusionLowLevelGitRefQuery.php | Apache-2.0 |
private function getFormatString() {
$fields = $this->getFields();
foreach ($fields as $key => $field) {
$fields[$key] = '%('.$field.')';
}
return implode('%01', $fields);
} | Get a string for `--format` which enumerates all the fields we want. | getFormatString | php | phorgeit/phorge | src/applications/diffusion/query/lowlevel/DiffusionLowLevelGitRefQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/lowlevel/DiffusionLowLevelGitRefQuery.php | Apache-2.0 |
private function pickBestRevision(array $revisions) {
assert_instances_of($revisions, 'DifferentialRevision');
// If we have more than one revision of a given status, choose the most
// recently updated one.
$revisions = msort($revisions, 'getDateModified');
$revisions = array_reverse($revisions);
// Try to find an accepted revision first.
foreach ($revisions as $revision) {
if ($revision->isAccepted()) {
return $revision;
}
}
// Try to find an open revision.
foreach ($revisions as $revision) {
if (!$revision->isClosed()) {
return $revision;
}
}
// Settle for whatever's left.
return head($revisions);
} | When querying for revisions by hash, more than one revision may be found.
This function identifies the "best" revision from such a set. Typically,
there is only one revision found. Otherwise, we try to pick an accepted
revision first, followed by an open revision, and otherwise we go with a
closed or abandoned revision as a last resort. | pickBestRevision | php | phorgeit/phorge | src/applications/diffusion/query/lowlevel/DiffusionLowLevelCommitFieldsQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/lowlevel/DiffusionLowLevelCommitFieldsQuery.php | Apache-2.0 |
public static function normalizePath($path) {
// Ensure we have a string, not a null.
$path = coalesce($path, '');
// Normalize to single slashes, e.g. "///" => "/".
$path = preg_replace('@[/]{2,}@', '/', $path);
return '/'.trim($path, '/');
} | Convert a path to the canonical, absolute representation used by Diffusion.
@param string $path Some repository path.
@return string Canonicalized Diffusion path.
@task pathutil | normalizePath | php | phorgeit/phorge | src/applications/diffusion/query/pathid/DiffusionPathIDQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/pathid/DiffusionPathIDQuery.php | Apache-2.0 |
public static function getParentPath($path) {
$path = self::normalizePath($path);
$path = dirname($path);
if (phutil_is_windows() && $path == '\\') {
$path = '/';
}
return $path;
} | Return the canonical parent directory for a path. Note, returns "/" when
passed "/".
@param string $path Some repository path.
@return string That path's canonical parent directory.
@task pathutil | getParentPath | php | phorgeit/phorge | src/applications/diffusion/query/pathid/DiffusionPathIDQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/pathid/DiffusionPathIDQuery.php | Apache-2.0 |
public static function expandPathToRoot($path) {
$path = self::normalizePath($path);
$parents = array($path);
$parts = explode('/', trim($path, '/'));
while (count($parts) >= 1) {
if (array_pop($parts)) {
$parents[] = '/'.implode('/', $parts);
}
}
return $parents;
} | Generate a list of parents for a repository path. The path itself is
included.
@param string $path Some repository path.
@return list List of canonical paths between the path and the root.
@task pathutil | expandPathToRoot | php | phorgeit/phorge | src/applications/diffusion/query/pathid/DiffusionPathIDQuery.php | https://github.com/phorgeit/phorge/blob/master/src/applications/diffusion/query/pathid/DiffusionPathIDQuery.php | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.