repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/application/PhabricatorFilesApplication.php | src/applications/files/application/PhabricatorFilesApplication.php | <?php
final class PhabricatorFilesApplication extends PhabricatorApplication {
public function getBaseURI() {
return '/file/';
}
public function getName() {
return pht('Files');
}
public function getShortDescription() {
return pht('Store and Share Files');
}
public function getIcon() {
return 'fa-file';
}
public function getTitleGlyph() {
return "\xE2\x87\xAA";
}
public function getFlavorText() {
return pht('Blob store for Pokemon pictures.');
}
public function getApplicationGroup() {
return self::GROUP_UTILITIES;
}
public function canUninstall() {
return false;
}
public function getRemarkupRules() {
return array(
new PhabricatorEmbedFileRemarkupRule(),
new PhabricatorImageRemarkupRule(),
);
}
public function supportsEmailIntegration() {
return true;
}
public function getAppEmailBlurb() {
return pht(
'Send emails with file attachments to these addresses to upload '.
'files. %s',
phutil_tag(
'a',
array(
'href' => $this->getInboundEmailSupportLink(),
),
pht('Learn More')));
}
protected function getCustomCapabilities() {
return array(
FilesDefaultViewCapability::CAPABILITY => array(
'caption' => pht('Default view policy for newly created files.'),
'template' => PhabricatorFileFilePHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_VIEW,
),
);
}
public function getRoutes() {
return array(
'/F(?P<id>[1-9]\d*)(?:\$(?P<lines>\d+(?:-\d+)?))?'
=> 'PhabricatorFileViewController',
'/file/' => array(
'(query/(?P<queryKey>[^/]+)/)?' => 'PhabricatorFileListController',
'view/(?P<id>[1-9]\d*)/'.
'(?:(?P<engineKey>[^/]+)/)?'.
'(?:\$(?P<lines>\d+(?:-\d+)?))?'
=> 'PhabricatorFileViewController',
'info/(?P<phid>[^/]+)/' => 'PhabricatorFileViewController',
'upload/' => 'PhabricatorFileUploadController',
'dropupload/' => 'PhabricatorFileDropUploadController',
'compose/' => 'PhabricatorFileComposeController',
'thread/(?P<phid>[^/]+)/' => 'PhabricatorFileLightboxController',
'delete/(?P<id>[1-9]\d*)/' => 'PhabricatorFileDeleteController',
$this->getEditRoutePattern('edit/')
=> 'PhabricatorFileEditController',
'imageproxy/' => 'PhabricatorFileImageProxyController',
'transforms/(?P<id>[1-9]\d*)/' =>
'PhabricatorFileTransformListController',
'uploaddialog/(?P<single>single/)?'
=> 'PhabricatorFileUploadDialogController',
'iconset/(?P<key>[^/]+)/' => array(
'select/' => 'PhabricatorFileIconSetSelectController',
),
'document/(?P<engineKey>[^/]+)/(?P<phid>[^/]+)/'
=> 'PhabricatorFileDocumentController',
'ui/' => array(
'detach/(?P<objectPHID>[^/]+)/(?P<filePHID>[^/]+)/'
=> 'PhabricatorFileDetachController',
'curtain/' => array(
'list/(?P<phid>[^/]+)/'
=> 'PhabricatorFileUICurtainListController',
'attach/(?P<objectPHID>[^/]+)/(?P<filePHID>[^/]+)/'
=> 'PhabricatorFileUICurtainAttachController',
),
),
) + $this->getResourceSubroutes(),
);
}
public function getResourceRoutes() {
return array(
'/file/' => $this->getResourceSubroutes(),
);
}
private function getResourceSubroutes() {
return array(
'(?P<kind>data|download)/'.
'(?:@(?P<instance>[^/]+)/)?'.
'(?P<key>[^/]+)/'.
'(?P<phid>[^/]+)/'.
'(?:(?P<token>[^/]+)/)?'.
'.*'
=> 'PhabricatorFileDataController',
'xform/'.
'(?:@(?P<instance>[^/]+)/)?'.
'(?P<transform>[^/]+)/'.
'(?P<phid>[^/]+)/'.
'(?P<key>[^/]+)/'
=> 'PhabricatorFileTransformController',
);
}
public function getMailCommandObjects() {
return array(
'file' => array(
'name' => pht('Email Commands: Files'),
'header' => pht('Interacting with Files'),
'object' => new PhabricatorFile(),
'summary' => pht(
'This page documents the commands you can use to interact with '.
'files.'),
),
);
}
public function getQuicksandURIPatternBlacklist() {
return array(
'/file/(data|download)/.*',
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/diff/PhabricatorDocumentEngineBlocks.php | src/applications/files/diff/PhabricatorDocumentEngineBlocks.php | <?php
final class PhabricatorDocumentEngineBlocks
extends Phobject {
private $lists = array();
private $messages = array();
private $rangeMin;
private $rangeMax;
private $revealedIndexes;
private $layoutAvailableRowCount;
public function setRange($min, $max) {
$this->rangeMin = $min;
$this->rangeMax = $max;
return $this;
}
public function setRevealedIndexes(array $indexes) {
$this->revealedIndexes = $indexes;
return $this;
}
public function getLayoutAvailableRowCount() {
if ($this->layoutAvailableRowCount === null) {
throw new PhutilInvalidStateException('new...Layout');
}
return $this->layoutAvailableRowCount;
}
public function addMessage($message) {
$this->messages[] = $message;
return $this;
}
public function getMessages() {
return $this->messages;
}
public function addBlockList(
PhabricatorDocumentRef $ref = null,
array $blocks = array()) {
assert_instances_of($blocks, 'PhabricatorDocumentEngineBlock');
$this->lists[] = array(
'ref' => $ref,
'blocks' => array_values($blocks),
);
return $this;
}
public function getDocumentRefs() {
return ipull($this->lists, 'ref');
}
public function newTwoUpLayout() {
$rows = array();
$lists = $this->lists;
if (count($lists) != 2) {
$this->layoutAvailableRowCount = 0;
return array();
}
$specs = array();
foreach ($this->lists as $list) {
$specs[] = $this->newDiffSpec($list['blocks']);
}
$old_map = $specs[0]['map'];
$new_map = $specs[1]['map'];
$old_list = $specs[0]['list'];
$new_list = $specs[1]['list'];
$changeset = id(new PhabricatorDifferenceEngine())
->generateChangesetFromFileContent($old_list, $new_list);
$hunk_parser = id(new DifferentialHunkParser())
->parseHunksForLineData($changeset->getHunks())
->reparseHunksForSpecialAttributes();
$hunk_parser->generateVisibleBlocksMask(2);
$mask = $hunk_parser->getVisibleLinesMask();
$old_lines = $hunk_parser->getOldLines();
$new_lines = $hunk_parser->getNewLines();
$rows = array();
$count = count($old_lines);
for ($ii = 0; $ii < $count; $ii++) {
$old_line = idx($old_lines, $ii);
$new_line = idx($new_lines, $ii);
$is_visible = !empty($mask[$ii]);
if ($old_line) {
$old_hash = rtrim($old_line['text'], "\n");
if (!strlen($old_hash)) {
// This can happen when one of the sources has no blocks.
$old_block = null;
} else {
$old_block = array_shift($old_map[$old_hash]);
$old_block
->setDifferenceType($old_line['type'])
->setIsVisible($is_visible);
}
} else {
$old_block = null;
}
if ($new_line) {
$new_hash = rtrim($new_line['text'], "\n");
if (!strlen($new_hash)) {
$new_block = null;
} else {
$new_block = array_shift($new_map[$new_hash]);
$new_block
->setDifferenceType($new_line['type'])
->setIsVisible($is_visible);
}
} else {
$new_block = null;
}
// If both lists are empty, we may generate a row which has two empty
// blocks.
if (!$old_block && !$new_block) {
continue;
}
$rows[] = array(
$old_block,
$new_block,
);
}
$this->layoutAvailableRowCount = count($rows);
$rows = $this->revealIndexes($rows, true);
$rows = $this->sliceRows($rows);
return $rows;
}
public function newOneUpLayout() {
$rows = array();
$lists = $this->lists;
$idx = 0;
while (true) {
$found_any = false;
$row = array();
foreach ($lists as $list) {
$blocks = $list['blocks'];
$cell = idx($blocks, $idx);
if ($cell !== null) {
$found_any = true;
}
if ($cell) {
$rows[] = $cell;
}
}
if (!$found_any) {
break;
}
$idx++;
}
$this->layoutAvailableRowCount = count($rows);
$rows = $this->revealIndexes($rows, false);
$rows = $this->sliceRows($rows);
return $rows;
}
private function newDiffSpec(array $blocks) {
$map = array();
$list = array();
foreach ($blocks as $block) {
$hash = $block->getDifferenceHash();
if (!isset($map[$hash])) {
$map[$hash] = array();
}
$map[$hash][] = $block;
$list[] = $hash;
}
return array(
'map' => $map,
'list' => implode("\n", $list)."\n",
);
}
private function sliceRows(array $rows) {
$min = $this->rangeMin;
$max = $this->rangeMax;
if ($min === null && $max === null) {
return $rows;
}
if ($max === null) {
return array_slice($rows, $min, null, true);
}
if ($min === null) {
$min = 0;
}
return array_slice($rows, $min, $max - $min, true);
}
private function revealIndexes(array $rows, $is_vector) {
if ($this->revealedIndexes === null) {
return $rows;
}
foreach ($this->revealedIndexes as $index) {
if (!isset($rows[$index])) {
continue;
}
if ($is_vector) {
foreach ($rows[$index] as $block) {
if ($block !== null) {
$block->setIsVisible(true);
}
}
} else {
$rows[$index]->setIsVisible(true);
}
}
return $rows;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/diff/PhabricatorDocumentEngineBlockDiff.php | src/applications/files/diff/PhabricatorDocumentEngineBlockDiff.php | <?php
final class PhabricatorDocumentEngineBlockDiff
extends Phobject {
private $oldContent;
private $newContent;
private $oldClasses = array();
private $newClasses = array();
public function setOldContent($old_content) {
$this->oldContent = $old_content;
return $this;
}
public function getOldContent() {
return $this->oldContent;
}
public function setNewContent($new_content) {
$this->newContent = $new_content;
return $this;
}
public function getNewContent() {
return $this->newContent;
}
public function addOldClass($class) {
$this->oldClasses[] = $class;
return $this;
}
public function getOldClasses() {
return $this->oldClasses;
}
public function addNewClass($class) {
$this->newClasses[] = $class;
return $this;
}
public function getNewClasses() {
return $this->newClasses;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/diff/PhabricatorDocumentEngineBlock.php | src/applications/files/diff/PhabricatorDocumentEngineBlock.php | <?php
final class PhabricatorDocumentEngineBlock
extends Phobject {
private $blockKey;
private $content;
private $differenceHash;
private $differenceType;
private $isVisible;
public function setContent($content) {
$this->content = $content;
return $this;
}
public function getContent() {
return $this->content;
}
public function setBlockKey($block_key) {
$this->blockKey = $block_key;
return $this;
}
public function getBlockKey() {
return $this->blockKey;
}
public function setDifferenceHash($difference_hash) {
$this->differenceHash = $difference_hash;
return $this;
}
public function getDifferenceHash() {
return $this->differenceHash;
}
public function setDifferenceType($difference_type) {
$this->differenceType = $difference_type;
return $this;
}
public function getDifferenceType() {
return $this->differenceType;
}
public function setIsVisible($is_visible) {
$this->isVisible = $is_visible;
return $this;
}
public function getIsVisible() {
return $this->isVisible;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/transform/PhabricatorFileImageTransform.php | src/applications/files/transform/PhabricatorFileImageTransform.php | <?php
abstract class PhabricatorFileImageTransform extends PhabricatorFileTransform {
private $file;
private $data;
private $image;
private $imageX;
private $imageY;
/**
* Get an estimate of the transformed dimensions of a file.
*
* @param PhabricatorFile File to transform.
* @return list<int, int>|null Width and height, if available.
*/
public function getTransformedDimensions(PhabricatorFile $file) {
return null;
}
public function canApplyTransform(PhabricatorFile $file) {
if (!$file->isViewableImage()) {
return false;
}
if (!$file->isTransformableImage()) {
return false;
}
return true;
}
protected function willTransformFile(PhabricatorFile $file) {
$this->file = $file;
$this->data = null;
$this->image = null;
$this->imageX = null;
$this->imageY = null;
}
protected function getFileProperties() {
return array();
}
protected function applyCropAndScale(
$dst_w, $dst_h,
$src_x, $src_y,
$src_w, $src_h,
$use_w, $use_h,
$scale_up) {
// Figure out the effective destination width, height, and offsets.
$cpy_w = min($dst_w, $use_w);
$cpy_h = min($dst_h, $use_h);
// If we aren't scaling up, and are copying a very small source image,
// we're just going to center it in the destination image.
if (!$scale_up) {
$cpy_w = min($cpy_w, $src_w);
$cpy_h = min($cpy_h, $src_h);
}
$off_x = ($dst_w - $cpy_w) / 2;
$off_y = ($dst_h - $cpy_h) / 2;
if ($this->shouldUseImagemagick()) {
$argv = array();
$argv[] = '-coalesce';
$argv[] = '-shave';
$argv[] = $src_x.'x'.$src_y;
$argv[] = '-resize';
if ($scale_up) {
$argv[] = $dst_w.'x'.$dst_h;
} else {
$argv[] = $dst_w.'x'.$dst_h.'>';
}
$argv[] = '-bordercolor';
$argv[] = 'rgba(255, 255, 255, 0)';
$argv[] = '-border';
$argv[] = $off_x.'x'.$off_y;
return $this->applyImagemagick($argv);
}
$src = $this->getImage();
$dst = $this->newEmptyImage($dst_w, $dst_h);
$trap = new PhutilErrorTrap();
$ok = @imagecopyresampled(
$dst,
$src,
$off_x, $off_y,
$src_x, $src_y,
$cpy_w, $cpy_h,
$src_w, $src_h);
$errors = $trap->getErrorsAsString();
$trap->destroy();
if ($ok === false) {
throw new Exception(
pht(
'Failed to imagecopyresampled() image: %s',
$errors));
}
$data = PhabricatorImageTransformer::saveImageDataInAnyFormat(
$dst,
$this->file->getMimeType());
return $this->newFileFromData($data);
}
protected function applyImagemagick(array $argv) {
$tmp = new TempFile();
Filesystem::writeFile($tmp, $this->getData());
$out = new TempFile();
$future = new ExecFuture('convert %s %Ls %s', $tmp, $argv, $out);
// Don't spend more than 60 seconds resizing; just fail if it takes longer
// than that.
$future->setTimeout(60)->resolvex();
$data = Filesystem::readFile($out);
return $this->newFileFromData($data);
}
/**
* Create a new @{class:PhabricatorFile} from raw data.
*
* @param string Raw file data.
*/
protected function newFileFromData($data) {
if ($this->file) {
$name = $this->file->getName();
} else {
$name = 'default.png';
}
$defaults = array(
'canCDN' => true,
'name' => $this->getTransformKey().'-'.$name,
);
$properties = $this->getFileProperties() + $defaults;
return PhabricatorFile::newFromFileData($data, $properties);
}
/**
* Create a new image filled with transparent pixels.
*
* @param int Desired image width.
* @param int Desired image height.
* @return resource New image resource.
*/
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;
}
/**
* Get the pixel dimensions of the image being transformed.
*
* @return list<int, int> Width and height of the image.
*/
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 raw file data for the image being transformed.
*
* @return string Raw file data.
*/
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 GD image resource for the image being transformed.
*
* @return resource GD image resource.
*/
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 = (4096 * 4096);
$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;
}
private function shouldUseImagemagick() {
if (!PhabricatorEnv::getEnvConfig('files.enable-imagemagick')) {
return false;
}
if ($this->file->getMimeType() != 'image/gif') {
return false;
}
// Don't try to preserve the animation in huge GIFs.
list($x, $y) = $this->getImageDimensions();
if (($x * $y) > (512 * 512)) {
return false;
}
return true;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/transform/PhabricatorFileTransform.php | src/applications/files/transform/PhabricatorFileTransform.php | <?php
abstract class PhabricatorFileTransform extends Phobject {
abstract public function getTransformName();
abstract public function getTransformKey();
abstract public function canApplyTransform(PhabricatorFile $file);
abstract public function applyTransform(PhabricatorFile $file);
public function getDefaultTransform(PhabricatorFile $file) {
return null;
}
public function generateTransforms() {
return array($this);
}
public function executeTransform(PhabricatorFile $file) {
if ($this->canApplyTransform($file)) {
try {
return $this->applyTransform($file);
} catch (Exception $ex) {
// Ignore.
}
}
return $this->getDefaultTransform($file);
}
public static function getAllTransforms() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setExpandMethod('generateTransforms')
->setUniqueMethod('getTransformKey')
->execute();
}
public static function getTransformByKey($key) {
$all = self::getAllTransforms();
$xform = idx($all, $key);
if (!$xform) {
throw new Exception(
pht(
'No file transform with key "%s" exists.',
$key));
}
return $xform;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/transform/PhabricatorFileThumbnailTransform.php | src/applications/files/transform/PhabricatorFileThumbnailTransform.php | <?php
final class PhabricatorFileThumbnailTransform
extends PhabricatorFileImageTransform {
const TRANSFORM_PROFILE = 'profile';
const TRANSFORM_PINBOARD = 'pinboard';
const TRANSFORM_THUMBGRID = 'thumbgrid';
const TRANSFORM_PREVIEW = 'preview';
const TRANSFORM_WORKCARD = 'workcard';
private $name;
private $key;
private $dstX;
private $dstY;
private $scaleUp;
public function setName($name) {
$this->name = $name;
return $this;
}
public function setKey($key) {
$this->key = $key;
return $this;
}
public function setDimensions($x, $y) {
$this->dstX = $x;
$this->dstY = $y;
return $this;
}
public function setScaleUp($scale) {
$this->scaleUp = $scale;
return $this;
}
public function getTransformName() {
return $this->name;
}
public function getTransformKey() {
return $this->key;
}
protected function getFileProperties() {
$properties = array();
switch ($this->key) {
case self::TRANSFORM_PROFILE:
$properties['profile'] = true;
$properties['name'] = 'profile';
break;
}
return $properties;
}
public function generateTransforms() {
return array(
id(new PhabricatorFileThumbnailTransform())
->setName(pht("Profile (400px \xC3\x97 400px)"))
->setKey(self::TRANSFORM_PROFILE)
->setDimensions(400, 400)
->setScaleUp(true),
id(new PhabricatorFileThumbnailTransform())
->setName(pht("Pinboard (280px \xC3\x97 210px)"))
->setKey(self::TRANSFORM_PINBOARD)
->setDimensions(280, 210),
id(new PhabricatorFileThumbnailTransform())
->setName(pht('Thumbgrid (100px)'))
->setKey(self::TRANSFORM_THUMBGRID)
->setDimensions(100, null),
id(new PhabricatorFileThumbnailTransform())
->setName(pht('Preview (220px)'))
->setKey(self::TRANSFORM_PREVIEW)
->setDimensions(220, null),
id(new self())
->setName(pht('Workcard (526px)'))
->setKey(self::TRANSFORM_WORKCARD)
->setScaleUp(true)
->setDimensions(526, null),
);
}
public function applyTransform(PhabricatorFile $file) {
$this->willTransformFile($file);
list($src_x, $src_y) = $this->getImageDimensions();
$dst_x = $this->dstX;
$dst_y = $this->dstY;
$dimensions = $this->computeDimensions(
$src_x,
$src_y,
$dst_x,
$dst_y);
$copy_x = $dimensions['copy_x'];
$copy_y = $dimensions['copy_y'];
$use_x = $dimensions['use_x'];
$use_y = $dimensions['use_y'];
$dst_x = $dimensions['dst_x'];
$dst_y = $dimensions['dst_y'];
return $this->applyCropAndScale(
$dst_x,
$dst_y,
($src_x - $copy_x) / 2,
($src_y - $copy_y) / 2,
$copy_x,
$copy_y,
$use_x,
$use_y,
$this->scaleUp);
}
public function getTransformedDimensions(PhabricatorFile $file) {
$dst_x = $this->dstX;
$dst_y = $this->dstY;
// If this is transform has fixed dimensions, we can trivially predict
// the dimensions of the transformed file.
if ($dst_y !== null) {
return array($dst_x, $dst_y);
}
$src_x = $file->getImageWidth();
$src_y = $file->getImageHeight();
if (!$src_x || !$src_y) {
return null;
}
$dimensions = $this->computeDimensions(
$src_x,
$src_y,
$dst_x,
$dst_y);
return array($dimensions['dst_x'], $dimensions['dst_y']);
}
private function computeDimensions($src_x, $src_y, $dst_x, $dst_y) {
if ($dst_y === null) {
// If we only have one dimension, it represents a maximum dimension.
// The other dimension of the transform is scaled appropriately, except
// that we never generate images with crazily extreme aspect ratios.
if ($src_x < $src_y) {
// This is a tall, narrow image. Use the maximum dimension for the
// height and scale the width.
$use_y = $dst_x;
$dst_y = $dst_x;
$use_x = $dst_y * ($src_x / $src_y);
$dst_x = max($dst_y / 4, $use_x);
} else {
// This is a short, wide image. Use the maximum dimension for the width
// and scale the height.
$use_x = $dst_x;
$use_y = $dst_x * ($src_y / $src_x);
$dst_y = max($dst_x / 4, $use_y);
}
// In this mode, we always copy the entire source image. We may generate
// margins in the output.
$copy_x = $src_x;
$copy_y = $src_y;
} else {
$scale_up = $this->scaleUp;
// Otherwise, both dimensions are fixed. Figure out how much we'd have to
// scale the image down along each dimension to get the entire thing to
// fit.
$scale_x = ($dst_x / $src_x);
$scale_y = ($dst_y / $src_y);
if (!$scale_up) {
$scale_x = min($scale_x, 1);
$scale_y = min($scale_y, 1);
}
if ($scale_x > $scale_y) {
// This image is relatively tall and narrow. We're going to crop off the
// top and bottom.
$scale = $scale_x;
} else {
// This image is relatively short and wide. We're going to crop off the
// left and right.
$scale = $scale_y;
}
$copy_x = $dst_x / $scale;
$copy_y = $dst_y / $scale;
if (!$scale_up) {
$copy_x = min($src_x, $copy_x);
$copy_y = min($src_y, $copy_y);
}
// In this mode, we always use the entire destination image. We may
// crop the source input.
$use_x = $dst_x;
$use_y = $dst_y;
}
return array(
'copy_x' => $copy_x,
'copy_y' => $copy_y,
'use_x' => $use_x,
'use_y' => $use_y,
'dst_x' => $dst_x,
'dst_y' => $dst_y,
);
}
public function getDefaultTransform(PhabricatorFile $file) {
$x = (int)$this->dstX;
$y = (int)$this->dstY;
$name = 'image-'.$x.'x'.nonempty($y, $x).'.png';
$root = dirname(phutil_get_library_root('phabricator'));
$data = Filesystem::readFile($root.'/resources/builtin/'.$name);
return $this->newFileFromData($data);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/transform/__tests__/PhabricatorFileTransformTestCase.php | src/applications/files/transform/__tests__/PhabricatorFileTransformTestCase.php | <?php
final class PhabricatorFileTransformTestCase extends PhabricatorTestCase {
protected function getPhabricatorTestCaseConfiguration() {
return array(
self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
);
}
public function testGetAllTransforms() {
PhabricatorFileTransform::getAllTransforms();
$this->assertTrue(true);
}
public function testThumbTransformDefaults() {
$xforms = PhabricatorFileTransform::getAllTransforms();
$file = new PhabricatorFile();
foreach ($xforms as $xform) {
if (!($xform instanceof PhabricatorFileThumbnailTransform)) {
continue;
}
// For thumbnails, generate the default thumbnail. This should be able
// to generate something rather than throwing an exception because we
// forgot to add a default file to the builtin resources. See T12614.
$xform->getDefaultTransform($file);
$this->assertTrue(true);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/uploadsource/PhabricatorExecFutureFileUploadSource.php | src/applications/files/uploadsource/PhabricatorExecFutureFileUploadSource.php | <?php
final class PhabricatorExecFutureFileUploadSource
extends PhabricatorFileUploadSource {
private $future;
public function setExecFuture(ExecFuture $future) {
$this->future = $future;
return $this;
}
public function getExecFuture() {
return $this->future;
}
protected function newDataIterator() {
$future = $this->getExecFuture();
return id(new LinesOfALargeExecFuture($future))
->setDelimiter(null);
}
protected function getDataLength() {
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/uploadsource/PhabricatorFileUploadSource.php | src/applications/files/uploadsource/PhabricatorFileUploadSource.php | <?php
abstract class PhabricatorFileUploadSource
extends Phobject {
private $name;
private $relativeTTL;
private $viewPolicy;
private $mimeType;
private $authorPHID;
private $rope;
private $data;
private $shouldChunk;
private $didRewind;
private $totalBytesWritten = 0;
private $totalBytesRead = 0;
private $byteLimit = 0;
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function setRelativeTTL($relative_ttl) {
$this->relativeTTL = $relative_ttl;
return $this;
}
public function getRelativeTTL() {
return $this->relativeTTL;
}
public function setViewPolicy($view_policy) {
$this->viewPolicy = $view_policy;
return $this;
}
public function getViewPolicy() {
return $this->viewPolicy;
}
public function setByteLimit($byte_limit) {
$this->byteLimit = $byte_limit;
return $this;
}
public function getByteLimit() {
return $this->byteLimit;
}
public function setMIMEType($mime_type) {
$this->mimeType = $mime_type;
return $this;
}
public function getMIMEType() {
return $this->mimeType;
}
public function setAuthorPHID($author_phid) {
$this->authorPHID = $author_phid;
return $this;
}
public function getAuthorPHID() {
return $this->authorPHID;
}
public function uploadFile() {
if (!$this->shouldChunkFile()) {
return $this->writeSingleFile();
} else {
return $this->writeChunkedFile();
}
}
private function getDataIterator() {
if (!$this->data) {
$this->data = $this->newDataIterator();
}
return $this->data;
}
private function getRope() {
if (!$this->rope) {
$this->rope = new PhutilRope();
}
return $this->rope;
}
abstract protected function newDataIterator();
abstract protected function getDataLength();
private function readFileData() {
$data = $this->getDataIterator();
if (!$this->didRewind) {
$data->rewind();
$this->didRewind = true;
} else {
if ($data->valid()) {
$data->next();
}
}
if (!$data->valid()) {
return false;
}
$read_bytes = $data->current();
$this->totalBytesRead += strlen($read_bytes);
if ($this->byteLimit && ($this->totalBytesRead > $this->byteLimit)) {
throw new PhabricatorFileUploadSourceByteLimitException();
}
$rope = $this->getRope();
$rope->append($read_bytes);
return true;
}
private function shouldChunkFile() {
if ($this->shouldChunk !== null) {
return $this->shouldChunk;
}
$threshold = PhabricatorFileStorageEngine::getChunkThreshold();
if ($threshold === null) {
// If there are no chunk engines available, we clearly can't chunk the
// file.
$this->shouldChunk = false;
} else {
// If we don't know how large the file is, we're going to read some data
// from it until we know whether it's a small file or not. This will give
// us enough information to make a decision about chunking.
$length = $this->getDataLength();
if ($length === null) {
$rope = $this->getRope();
while ($this->readFileData()) {
$length = $rope->getByteLength();
if ($length > $threshold) {
break;
}
}
}
$this->shouldChunk = ($length > $threshold);
}
return $this->shouldChunk;
}
private function writeSingleFile() {
while ($this->readFileData()) {
// Read the entire file.
}
$rope = $this->getRope();
$data = $rope->getAsString();
$parameters = $this->getNewFileParameters();
return PhabricatorFile::newFromFileData($data, $parameters);
}
private function writeChunkedFile() {
$engine = $this->getChunkEngine();
$parameters = $this->getNewFileParameters();
$data_length = $this->getDataLength();
if ($data_length !== null) {
$length = $data_length;
} else {
$length = 0;
}
$file = PhabricatorFile::newChunkedFile($engine, $length, $parameters);
$file->saveAndIndex();
$rope = $this->getRope();
// Read the source, writing chunks as we get enough data.
while ($this->readFileData()) {
while (true) {
$rope_length = $rope->getByteLength();
if ($rope_length < $engine->getChunkSize()) {
break;
}
$this->writeChunk($file, $engine);
}
}
// If we have extra bytes at the end, write them. Note that it's possible
// that we have more than one chunk of bytes left if the read was very
// fast.
while ($rope->getByteLength()) {
$this->writeChunk($file, $engine);
}
$file->setIsPartial(0);
if ($data_length === null) {
$file->setByteSize($this->getTotalBytesWritten());
}
$file->save();
return $file;
}
private function writeChunk(
PhabricatorFile $file,
PhabricatorFileStorageEngine $engine) {
$offset = $this->getTotalBytesWritten();
$max_length = $engine->getChunkSize();
$rope = $this->getRope();
$data = $rope->getPrefixBytes($max_length);
$actual_length = strlen($data);
$rope->removeBytesFromHead($actual_length);
$params = array(
'name' => $file->getMonogram().'.chunk-'.$offset,
'viewPolicy' => PhabricatorPolicies::POLICY_NOONE,
'chunk' => true,
);
// If this isn't the initial chunk, provide a dummy MIME type so we do not
// try to detect it. See T12857.
if ($offset > 0) {
$params['mime-type'] = 'application/octet-stream';
}
$chunk_data = PhabricatorFile::newFromFileData($data, $params);
$chunk = PhabricatorFileChunk::initializeNewChunk(
$file->getStorageHandle(),
$offset,
$offset + $actual_length);
$chunk
->setDataFilePHID($chunk_data->getPHID())
->save();
$this->setTotalBytesWritten($offset + $actual_length);
return $chunk;
}
private function getNewFileParameters() {
$parameters = array(
'name' => $this->getName(),
'viewPolicy' => $this->getViewPolicy(),
);
$ttl = $this->getRelativeTTL();
if ($ttl !== null) {
$parameters['ttl.relative'] = $ttl;
}
$mime_type = $this->getMimeType();
if ($mime_type !== null) {
$parameters['mime-type'] = $mime_type;
}
$author_phid = $this->getAuthorPHID();
if ($author_phid !== null) {
$parameters['authorPHID'] = $author_phid;
}
return $parameters;
}
private function getChunkEngine() {
$chunk_engines = PhabricatorFileStorageEngine::loadWritableChunkEngines();
if (!$chunk_engines) {
throw new Exception(
pht(
'Unable to upload file: this server is not configured with any '.
'storage engine which can store large files.'));
}
return head($chunk_engines);
}
private function setTotalBytesWritten($total_bytes_written) {
$this->totalBytesWritten = $total_bytes_written;
return $this;
}
private function getTotalBytesWritten() {
return $this->totalBytesWritten;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/uploadsource/PhabricatorFileUploadSourceByteLimitException.php | src/applications/files/uploadsource/PhabricatorFileUploadSourceByteLimitException.php | <?php
final class PhabricatorFileUploadSourceByteLimitException
extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/uploadsource/PhabricatorIteratorFileUploadSource.php | src/applications/files/uploadsource/PhabricatorIteratorFileUploadSource.php | <?php
final class PhabricatorIteratorFileUploadSource
extends PhabricatorFileUploadSource {
private $iterator;
public function setIterator(Iterator $iterator) {
$this->iterator = $iterator;
return $this;
}
public function getIterator() {
return $this->iterator;
}
protected function newDataIterator() {
return $this->getIterator();
}
protected function getDataLength() {
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/lipsum/PhabricatorFileTestDataGenerator.php | src/applications/files/lipsum/PhabricatorFileTestDataGenerator.php | <?php
final class PhabricatorFileTestDataGenerator
extends PhabricatorTestDataGenerator {
const GENERATORKEY = 'files';
public function getGeneratorName() {
return pht('Files');
}
public function generateObject() {
$author_phid = $this->loadPhabricatorUserPHID();
$dimension = 1 << rand(5, 12);
$image = id(new PhabricatorLipsumMondrianArtist())
->generate($dimension, $dimension);
$file = PhabricatorFile::newFromFileData(
$image,
array(
'name' => 'rand-'.rand(1000, 9999),
));
$file->setAuthorPHID($author_phid);
$file->setMimeType('image/jpeg');
return $file->save();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/garbagecollector/PhabricatorFileExternalRequestGarbageCollector.php | src/applications/files/garbagecollector/PhabricatorFileExternalRequestGarbageCollector.php | <?php
final class PhabricatorFileExternalRequestGarbageCollector
extends PhabricatorGarbageCollector {
const COLLECTORCONST = 'files.externalttl';
public function getCollectorName() {
return pht('External Requests (TTL)');
}
public function hasAutomaticPolicy() {
return true;
}
protected function collectGarbage() {
$file_requests = id(new PhabricatorFileExternalRequest())->loadAllWhere(
'ttl < %d LIMIT 100',
PhabricatorTime::getNow());
$engine = new PhabricatorDestructionEngine();
foreach ($file_requests as $request) {
$engine->destroyObject($request);
}
return (count($file_requests) == 100);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/garbagecollector/PhabricatorFileTemporaryGarbageCollector.php | src/applications/files/garbagecollector/PhabricatorFileTemporaryGarbageCollector.php | <?php
final class PhabricatorFileTemporaryGarbageCollector
extends PhabricatorGarbageCollector {
const COLLECTORCONST = 'files.ttl';
public function getCollectorName() {
return pht('Files (TTL)');
}
public function hasAutomaticPolicy() {
return true;
}
protected function collectGarbage() {
$files = id(new PhabricatorFile())->loadAllWhere(
'ttl < %d LIMIT 100',
PhabricatorTime::getNow());
$engine = new PhabricatorDestructionEngine();
foreach ($files as $file) {
$engine->destroyObject($file);
}
return (count($files) == 100);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/view/PhabricatorGlobalUploadTargetView.php | src/applications/files/view/PhabricatorGlobalUploadTargetView.php | <?php
/**
* IMPORTANT: If you use this, make sure to implement
*
* public function isGlobalDragAndDropUploadEnabled() {
* return true;
* }
*
* on the controller(s) that render this class...! This is necessary
* to make sure Quicksand works properly with the javascript in this
* UI.
*/
final class PhabricatorGlobalUploadTargetView extends AphrontView {
private $showIfSupportedID;
private $hintText;
private $viewPolicy;
private $submitURI;
public function setShowIfSupportedID($show_if_supported_id) {
$this->showIfSupportedID = $show_if_supported_id;
return $this;
}
public function getShowIfSupportedID() {
return $this->showIfSupportedID;
}
public function setHintText($hint_text) {
$this->hintText = $hint_text;
return $this;
}
public function getHintText() {
return $this->hintText;
}
public function setViewPolicy($view_policy) {
$this->viewPolicy = $view_policy;
return $this;
}
public function getViewPolicy() {
return $this->viewPolicy;
}
public function setSubmitURI($submit_uri) {
$this->submitURI = $submit_uri;
return $this;
}
public function getSubmitURI() {
return $this->submitURI;
}
public function render() {
$viewer = $this->getViewer();
if (!$viewer->isLoggedIn()) {
return null;
}
$instructions_id = 'phabricator-global-drag-and-drop-upload-instructions';
require_celerity_resource('global-drag-and-drop-css');
$hint_text = $this->getHintText();
if ($hint_text === null || !strlen($hint_text)) {
$hint_text = "\xE2\x87\xAA ".pht('Drop Files to Upload');
}
// Use the configured default view policy. Drag and drop uploads use
// a more restrictive view policy if we don't specify a policy explicitly,
// as the more restrictive policy is correct for most drop targets (like
// Pholio uploads and Remarkup text areas).
$view_policy = $this->getViewPolicy();
if ($view_policy === null) {
$view_policy = PhabricatorFile::initializeNewFile()->getViewPolicy();
}
$submit_uri = $this->getSubmitURI();
$done_uri = '/file/query/authored/';
Javelin::initBehavior('global-drag-and-drop', array(
'ifSupported' => $this->showIfSupportedID,
'instructions' => $instructions_id,
'uploadURI' => '/file/dropupload/',
'submitURI' => $submit_uri,
'browseURI' => $done_uri,
'viewPolicy' => $view_policy,
'chunkThreshold' => PhabricatorFileStorageEngine::getChunkThreshold(),
));
return phutil_tag(
'div',
array(
'id' => $instructions_id,
'class' => 'phabricator-global-upload-instructions',
'style' => 'display: none;',
),
$hint_text);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/applicationpanel/PhabricatorFilesApplicationStorageEnginePanel.php | src/applications/files/applicationpanel/PhabricatorFilesApplicationStorageEnginePanel.php | <?php
final class PhabricatorFilesApplicationStorageEnginePanel
extends PhabricatorApplicationConfigurationPanel {
public function getPanelKey() {
return 'storage';
}
public function shouldShowForApplication(
PhabricatorApplication $application) {
return ($application instanceof PhabricatorFilesApplication);
}
public function buildConfigurationPagePanel() {
$viewer = $this->getViewer();
$application = $this->getApplication();
$engines = PhabricatorFileStorageEngine::loadAllEngines();
$writable_engines = PhabricatorFileStorageEngine::loadWritableEngines();
$chunk_engines = PhabricatorFileStorageEngine::loadWritableChunkEngines();
$yes = pht('Yes');
$no = pht('No');
$rows = array();
$rowc = array();
foreach ($engines as $key => $engine) {
if ($engine->isTestEngine()) {
continue;
}
$limit = null;
if ($engine->hasFilesizeLimit()) {
$limit = phutil_format_bytes($engine->getFilesizeLimit());
} else {
$limit = pht('Unlimited');
}
if ($engine->canWriteFiles()) {
$writable = $yes;
} else {
$writable = $no;
}
if (isset($writable_engines[$key]) || isset($chunk_engines[$key])) {
$rowc[] = 'highlighted';
} else {
$rowc[] = null;
}
$rows[] = array(
$key,
get_class($engine),
$writable,
$limit,
);
}
$table = id(new AphrontTableView($rows))
->setNoDataString(pht('No storage engines available.'))
->setHeaders(
array(
pht('Key'),
pht('Class'),
pht('Writable'),
pht('Limit'),
))
->setRowClasses($rowc)
->setColumnClasses(
array(
'',
'wide',
'',
'n',
));
$box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Storage Engines'))
->setTable($table);
return $box;
}
public function handlePanelRequest(
AphrontRequest $request,
PhabricatorController $controller) {
return new Aphront404Response();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/phid/PhabricatorFileFilePHIDType.php | src/applications/files/phid/PhabricatorFileFilePHIDType.php | <?php
final class PhabricatorFileFilePHIDType extends PhabricatorPHIDType {
const TYPECONST = 'FILE';
public function getTypeName() {
return pht('File');
}
public function newObject() {
return new PhabricatorFile();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorFilesApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorFileQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$file = $objects[$phid];
$id = $file->getID();
$name = $file->getName();
$uri = $file->getInfoURI();
$handle->setName("F{$id}");
$handle->setFullName("F{$id}: {$name}");
$handle->setURI($uri);
$icon = FileTypeIcon::getFileIcon($name);
$handle->setIcon($icon);
}
}
public function canLoadNamedObject($name) {
return preg_match('/^F\d*[1-9]\d*$/', $name);
}
public function loadNamedObjects(
PhabricatorObjectQuery $query,
array $names) {
$id_map = array();
foreach ($names as $name) {
$id = (int)substr($name, 1);
$id_map[$id][] = $name;
}
$objects = id(new PhabricatorFileQuery())
->setViewer($query->getViewer())
->withIDs(array_keys($id_map))
->execute();
$results = array();
foreach ($objects as $id => $object) {
foreach (idx($id_map, $id, array()) as $name) {
$results[$name] = $object;
}
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/config/PhabricatorFilesConfigOptions.php | src/applications/files/config/PhabricatorFilesConfigOptions.php | <?php
final class PhabricatorFilesConfigOptions
extends PhabricatorApplicationConfigOptions {
public function getName() {
return pht('Files');
}
public function getDescription() {
return pht('Configure files and file storage.');
}
public function getIcon() {
return 'fa-file';
}
public function getGroup() {
return 'apps';
}
public function getOptions() {
$viewable_default = array(
'image/jpeg' => 'image/jpeg',
'image/jpg' => 'image/jpg',
'image/png' => 'image/png',
'image/gif' => 'image/gif',
'text/plain' => 'text/plain; charset=utf-8',
'text/x-diff' => 'text/plain; charset=utf-8',
// ".ico" favicon files, which have mime type diversity. See:
// http://en.wikipedia.org/wiki/ICO_(file_format)#MIME_type
'image/x-ico' => 'image/x-icon',
'image/x-icon' => 'image/x-icon',
'image/vnd.microsoft.icon' => 'image/x-icon',
// This is a generic type for both OGG video and OGG audio.
'application/ogg' => 'application/ogg',
'audio/x-wav' => 'audio/x-wav',
'audio/mpeg' => 'audio/mpeg',
'audio/ogg' => 'audio/ogg',
'video/mp4' => 'video/mp4',
'video/ogg' => 'video/ogg',
'video/webm' => 'video/webm',
'video/quicktime' => 'video/quicktime',
'application/pdf' => 'application/pdf',
);
$image_default = array(
'image/jpeg' => true,
'image/jpg' => true,
'image/png' => true,
'image/gif' => true,
'image/x-ico' => true,
'image/x-icon' => true,
'image/vnd.microsoft.icon' => true,
);
// The "application/ogg" type is listed as both an audio and video type,
// because it may contain either type of content.
$audio_default = array(
'audio/x-wav' => true,
'audio/mpeg' => true,
'audio/ogg' => true,
// These are video or ambiguous types, but can be forced to render as
// audio with `media=audio`, which seems to work properly in browsers.
// (For example, you can embed a music video as audio if you just want
// to set the mood for your task without distracting viewers.)
'video/mp4' => true,
'video/ogg' => true,
'video/quicktime' => true,
'application/ogg' => true,
);
$video_default = array(
'video/mp4' => true,
'video/ogg' => true,
'video/webm' => true,
'video/quicktime' => true,
'application/ogg' => true,
);
// largely lifted from http://en.wikipedia.org/wiki/Internet_media_type
$icon_default = array(
// audio file icon
'audio/basic' => 'fa-file-audio-o',
'audio/L24' => 'fa-file-audio-o',
'audio/mp4' => 'fa-file-audio-o',
'audio/mpeg' => 'fa-file-audio-o',
'audio/ogg' => 'fa-file-audio-o',
'audio/vorbis' => 'fa-file-audio-o',
'audio/vnd.rn-realaudio' => 'fa-file-audio-o',
'audio/vnd.wave' => 'fa-file-audio-o',
'audio/webm' => 'fa-file-audio-o',
// movie file icon
'video/mpeg' => 'fa-file-movie-o',
'video/mp4' => 'fa-file-movie-o',
'application/ogg' => 'fa-file-movie-o',
'video/ogg' => 'fa-file-movie-o',
'video/quicktime' => 'fa-file-movie-o',
'video/webm' => 'fa-file-movie-o',
'video/x-matroska' => 'fa-file-movie-o',
'video/x-ms-wmv' => 'fa-file-movie-o',
'video/x-flv' => 'fa-file-movie-o',
// pdf file icon
'application/pdf' => 'fa-file-pdf-o',
// zip file icon
'application/zip' => 'fa-file-zip-o',
// msword icon
'application/msword' => 'fa-file-word-o',
// msexcel
'application/vnd.ms-excel' => 'fa-file-excel-o',
// mspowerpoint
'application/vnd.ms-powerpoint' => 'fa-file-powerpoint-o',
) + array_fill_keys(array_keys($image_default), 'fa-file-image-o');
// NOTE: These options are locked primarily because adding "text/plain"
// as an image MIME type increases SSRF vulnerability by allowing users
// to load text files from remote servers as "images" (see T6755 for
// discussion).
return array(
$this->newOption('files.viewable-mime-types', 'wild', $viewable_default)
->setLocked(true)
->setSummary(
pht('Configure which MIME types are viewable in the browser.'))
->setDescription(
pht(
"Configure which uploaded file types may be viewed directly ".
"in the browser. Other file types will be downloaded instead ".
"of displayed. This is mainly a usability consideration, since ".
"browsers tend to freak out when viewing very large binary files.".
"\n\n".
"The keys in this map are viewable MIME types; the values are ".
"the MIME types they are delivered as when they are viewed in ".
"the browser.")),
$this->newOption('files.image-mime-types', 'set', $image_default)
->setLocked(true)
->setSummary(pht('Configure which MIME types are images.'))
->setDescription(
pht(
'List of MIME types which can be used as the `%s` for an `%s` tag.',
'src',
'<img />')),
$this->newOption('files.audio-mime-types', 'set', $audio_default)
->setLocked(true)
->setSummary(pht('Configure which MIME types are audio.'))
->setDescription(
pht(
'List of MIME types which can be rendered with an `%s` tag.',
'<audio />')),
$this->newOption('files.video-mime-types', 'set', $video_default)
->setLocked(true)
->setSummary(pht('Configure which MIME types are video.'))
->setDescription(
pht(
'List of MIME types which can be rendered with a `%s` tag.',
'<video />')),
$this->newOption('files.icon-mime-types', 'wild', $icon_default)
->setLocked(true)
->setSummary(pht('Configure which MIME types map to which icons.'))
->setDescription(
pht(
'Map of MIME type to icon name. MIME types which can not be '.
'found default to icon `%s`.',
'doc_files')),
$this->newOption('storage.mysql-engine.max-size', 'int', 1000000)
->setSummary(
pht(
'Configure the largest file which will be put into the MySQL '.
'storage engine.')),
$this->newOption('storage.local-disk.path', 'string', null)
->setLocked(true)
->setSummary(pht('Local storage disk path.'))
->setDescription(
pht(
"This software provides a local disk storage engine, which just ".
"writes files to some directory on local disk. The webserver ".
"must have read/write permissions on this directory. This is ".
"straightforward and suitable for most installs, but will not ".
"scale past one web frontend unless the path is actually an NFS ".
"mount, since you'll end up with some of the files written to ".
"each web frontend and no way for them to share. To use the ".
"local disk storage engine, specify the path to a directory ".
"here. To disable it, specify null.")),
$this->newOption('storage.s3.bucket', 'string', null)
->setSummary(pht('Amazon S3 bucket.'))
->setDescription(
pht(
"Set this to a valid Amazon S3 bucket to store files there. You ".
"must also configure S3 access keys in the 'Amazon Web Services' ".
"group.")),
$this->newOption('files.enable-imagemagick', 'bool', false)
->setBoolOptions(
array(
pht('Enable'),
pht('Disable'),
))
->setDescription(
pht(
'This option will use Imagemagick to rescale images, so animated '.
'GIFs can be thumbnailed and set as profile pictures. Imagemagick '.
'must be installed and the "%s" binary must be available to '.
'the webserver for this to work.',
'convert')),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/FileQueryChunksConduitAPIMethod.php | src/applications/files/conduit/FileQueryChunksConduitAPIMethod.php | <?php
final class FileQueryChunksConduitAPIMethod
extends FileConduitAPIMethod {
public function getAPIMethodName() {
return 'file.querychunks';
}
public function getMethodDescription() {
return pht('Get information about file chunks.');
}
protected function defineParamTypes() {
return array(
'filePHID' => 'phid',
);
}
protected function defineReturnType() {
return 'list<wild>';
}
protected function execute(ConduitAPIRequest $request) {
$viewer = $request->getUser();
$file_phid = $request->getValue('filePHID');
$file = $this->loadFileByPHID($viewer, $file_phid);
$chunks = $this->loadFileChunks($viewer, $file);
$results = array();
foreach ($chunks as $chunk) {
$results[] = array(
'byteStart' => $chunk->getByteStart(),
'byteEnd' => $chunk->getByteEnd(),
'complete' => (bool)$chunk->getDataFilePHID(),
);
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/FileUploadChunkConduitAPIMethod.php | src/applications/files/conduit/FileUploadChunkConduitAPIMethod.php | <?php
final class FileUploadChunkConduitAPIMethod
extends FileConduitAPIMethod {
public function getAPIMethodName() {
return 'file.uploadchunk';
}
public function getMethodDescription() {
return pht('Upload a chunk of file data to the server.');
}
protected function defineParamTypes() {
return array(
'filePHID' => 'phid',
'byteStart' => 'int',
'data' => 'string',
'dataEncoding' => 'string',
);
}
protected function defineReturnType() {
return 'void';
}
protected function execute(ConduitAPIRequest $request) {
$viewer = $request->getUser();
$file_phid = $request->getValue('filePHID');
$file = $this->loadFileByPHID($viewer, $file_phid);
$start = $request->getValue('byteStart');
$data = $request->getValue('data');
$encoding = $request->getValue('dataEncoding');
switch ($encoding) {
case 'base64':
$data = $this->decodeBase64($data);
break;
case null:
break;
default:
throw new Exception(pht('Unsupported data encoding.'));
}
$length = strlen($data);
$chunk = $this->loadFileChunkForUpload(
$viewer,
$file,
$start,
$start + $length);
// If this is the initial chunk, leave the MIME type unset so we detect
// it and can update the parent file. If this is any other chunk, it has
// no meaningful MIME type. Provide a default type so we can avoid writing
// it to disk to perform MIME type detection.
if (!$start) {
$mime_type = null;
} else {
$mime_type = 'application/octet-stream';
}
$params = array(
'name' => $file->getMonogram().'.chunk-'.$chunk->getID(),
'viewPolicy' => PhabricatorPolicies::POLICY_NOONE,
'chunk' => true,
);
if ($mime_type !== null) {
$params['mime-type'] = 'application/octet-stream';
}
// NOTE: These files have a view policy which prevents normal access. They
// are only accessed through the storage engine.
$chunk_data = PhabricatorFile::newFromFileData(
$data,
$params);
$chunk->setDataFilePHID($chunk_data->getPHID())->save();
$needs_update = false;
$missing = $this->loadAnyMissingChunk($viewer, $file);
if (!$missing) {
$file->setIsPartial(0);
$needs_update = true;
}
if (!$start) {
$file->setMimeType($chunk_data->getMimeType());
$needs_update = true;
}
if ($needs_update) {
$file->save();
}
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/FileDownloadConduitAPIMethod.php | src/applications/files/conduit/FileDownloadConduitAPIMethod.php | <?php
final class FileDownloadConduitAPIMethod extends FileConduitAPIMethod {
public function getAPIMethodName() {
return 'file.download';
}
public function getMethodDescription() {
return pht('Download a file from the server.');
}
protected function defineParamTypes() {
return array(
'phid' => 'required phid',
);
}
protected function defineReturnType() {
return 'nonempty base64-bytes';
}
protected function defineErrorTypes() {
return array(
'ERR-BAD-PHID' => pht('No such file exists.'),
);
}
protected function execute(ConduitAPIRequest $request) {
$phid = $request->getValue('phid');
$file = id(new PhabricatorFileQuery())
->setViewer($request->getUser())
->withPHIDs(array($phid))
->executeOne();
if (!$file) {
throw new ConduitException('ERR-BAD-PHID');
}
return base64_encode($file->loadFileData());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/FileAllocateConduitAPIMethod.php | src/applications/files/conduit/FileAllocateConduitAPIMethod.php | <?php
final class FileAllocateConduitAPIMethod
extends FileConduitAPIMethod {
public function getAPIMethodName() {
return 'file.allocate';
}
public function getMethodDescription() {
return pht('Prepare to upload a file.');
}
protected function defineParamTypes() {
return array(
'name' => 'string',
'contentLength' => 'int',
'contentHash' => 'optional string',
'viewPolicy' => 'optional string',
'deleteAfterEpoch' => 'optional int',
);
}
protected function defineReturnType() {
return 'map<string, wild>';
}
protected function execute(ConduitAPIRequest $request) {
$viewer = $request->getUser();
$hash = $request->getValue('contentHash');
$name = $request->getValue('name');
$view_policy = $request->getValue('viewPolicy');
$length = $request->getValue('contentLength');
$properties = array(
'name' => $name,
'authorPHID' => $viewer->getPHID(),
'isExplicitUpload' => true,
);
if ($view_policy !== null) {
$properties['viewPolicy'] = $view_policy;
}
$ttl = $request->getValue('deleteAfterEpoch');
if ($ttl) {
$properties['ttl.absolute'] = $ttl;
}
$file = null;
if ($hash !== null) {
$file = PhabricatorFile::newFileFromContentHash(
$hash,
$properties);
}
if ($hash !== null && !$file) {
$chunked_hash = PhabricatorChunkedFileStorageEngine::getChunkedHash(
$viewer,
$hash);
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withContentHashes(array($chunked_hash))
->executeOne();
}
if ($name !== null && strlen($name) && !$hash && !$file) {
if ($length > PhabricatorFileStorageEngine::getChunkThreshold()) {
// If we don't have a hash, but this file is large enough to store in
// chunks and thus may be resumable, try to find a partially uploaded
// file by the same author with the same name and same length. This
// allows us to resume uploads in Javascript where we can't efficiently
// compute file hashes.
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withAuthorPHIDs(array($viewer->getPHID()))
->withNames(array($name))
->withLengthBetween($length, $length)
->withIsPartial(true)
->setLimit(1)
->executeOne();
}
}
if ($file) {
return array(
'upload' => (bool)$file->getIsPartial(),
'filePHID' => $file->getPHID(),
);
}
// If there are any non-chunk engines which this file can fit into,
// just tell the client to upload the file.
$engines = PhabricatorFileStorageEngine::loadStorageEngines($length);
if ($engines) {
return array(
'upload' => true,
'filePHID' => null,
);
}
// Otherwise, this is a large file and we want to perform a chunked
// upload if we have a chunk engine available.
$chunk_engines = PhabricatorFileStorageEngine::loadWritableChunkEngines();
if ($chunk_engines) {
$chunk_properties = $properties;
if ($hash !== null) {
$chunk_properties += array(
'chunkedHash' => $chunked_hash,
);
}
$chunk_engine = head($chunk_engines);
$file = $chunk_engine->allocateChunks($length, $chunk_properties);
return array(
'upload' => true,
'filePHID' => $file->getPHID(),
);
}
// None of the storage engines can accept this file.
if (PhabricatorFileStorageEngine::loadWritableEngines()) {
$error = pht(
'Unable to upload file: this file is too large for any '.
'configured storage engine.');
} else {
$error = pht(
'Unable to upload file: the server is not configured with any '.
'writable storage engines.');
}
return array(
'upload' => false,
'filePHID' => null,
'error' => $error,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/FileUploadHashConduitAPIMethod.php | src/applications/files/conduit/FileUploadHashConduitAPIMethod.php | <?php
final class FileUploadHashConduitAPIMethod extends FileConduitAPIMethod {
public function getAPIMethodName() {
return 'file.uploadhash';
}
public function getMethodStatus() {
return self::METHOD_STATUS_DEPRECATED;
}
public function getMethodStatusDescription() {
return pht(
'This method is deprecated. Callers should use "file.allocate" '.
'instead.');
}
public function getMethodDescription() {
return pht('Obsolete. Has no effect.');
}
protected function defineParamTypes() {
return array(
'hash' => 'required nonempty string',
'name' => 'required nonempty string',
);
}
protected function defineReturnType() {
return 'null';
}
protected function execute(ConduitAPIRequest $request) {
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/PhabricatorFileSearchConduitAPIMethod.php | src/applications/files/conduit/PhabricatorFileSearchConduitAPIMethod.php | <?php
final class PhabricatorFileSearchConduitAPIMethod
extends PhabricatorSearchEngineAPIMethod {
public function getAPIMethodName() {
return 'file.search';
}
public function newSearchEngine() {
return new PhabricatorFileSearchEngine();
}
public function getMethodSummary() {
return pht('Read information about files.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/FileInfoConduitAPIMethod.php | src/applications/files/conduit/FileInfoConduitAPIMethod.php | <?php
final class FileInfoConduitAPIMethod extends FileConduitAPIMethod {
public function getAPIMethodName() {
return 'file.info';
}
public function getMethodDescription() {
return pht('Get information about a file.');
}
public function getMethodStatus() {
return self::METHOD_STATUS_FROZEN;
}
public function getMethodStatusDescription() {
return pht(
'This method is frozen and will eventually be deprecated. New code '.
'should use "file.search" instead.');
}
protected function defineParamTypes() {
return array(
'phid' => 'optional phid',
'id' => 'optional id',
);
}
protected function defineReturnType() {
return 'nonempty dict';
}
protected function defineErrorTypes() {
return array(
'ERR-NOT-FOUND' => pht('No such file exists.'),
);
}
protected function execute(ConduitAPIRequest $request) {
$phid = $request->getValue('phid');
$id = $request->getValue('id');
$query = id(new PhabricatorFileQuery())
->setViewer($request->getUser());
if ($id) {
$query->withIDs(array($id));
} else {
$query->withPHIDs(array($phid));
}
$file = $query->executeOne();
if (!$file) {
throw new ConduitException('ERR-NOT-FOUND');
}
$uri = $file->getInfoURI();
return array(
'id' => $file->getID(),
'phid' => $file->getPHID(),
'objectName' => 'F'.$file->getID(),
'name' => $file->getName(),
'mimeType' => $file->getMimeType(),
'byteSize' => $file->getByteSize(),
'authorPHID' => $file->getAuthorPHID(),
'dateCreated' => $file->getDateCreated(),
'dateModified' => $file->getDateModified(),
'uri' => PhabricatorEnv::getProductionURI($uri),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/FileUploadConduitAPIMethod.php | src/applications/files/conduit/FileUploadConduitAPIMethod.php | <?php
final class FileUploadConduitAPIMethod extends FileConduitAPIMethod {
public function getAPIMethodName() {
return 'file.upload';
}
public function getMethodDescription() {
return pht('Upload a file to the server.');
}
protected function defineParamTypes() {
return array(
'data_base64' => 'required nonempty base64-bytes',
'name' => 'optional string',
'viewPolicy' => 'optional valid policy string or <phid>',
'canCDN' => 'optional bool',
);
}
protected function defineReturnType() {
return 'nonempty guid';
}
protected function execute(ConduitAPIRequest $request) {
$viewer = $request->getUser();
$name = $request->getValue('name');
$can_cdn = (bool)$request->getValue('canCDN');
$view_policy = $request->getValue('viewPolicy');
$data = $request->getValue('data_base64');
if ($data === null) {
throw new Exception(pht('Field "data_base64" must be non-empty.'));
}
$data = $this->decodeBase64($data);
$params = array(
'authorPHID' => $viewer->getPHID(),
'canCDN' => $can_cdn,
'isExplicitUpload' => true,
);
if ($name !== null) {
$params['name'] = $name;
}
if ($view_policy !== null) {
$params['viewPolicy'] = $view_policy;
}
$file = PhabricatorFile::newFromFileData($data, $params);
return $file->getPHID();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/conduit/FileConduitAPIMethod.php | src/applications/files/conduit/FileConduitAPIMethod.php | <?php
abstract class FileConduitAPIMethod extends ConduitAPIMethod {
final public function getApplication() {
return PhabricatorApplication::getByClass('PhabricatorFilesApplication');
}
protected function loadFileByPHID(PhabricatorUser $viewer, $file_phid) {
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($file_phid))
->executeOne();
if (!$file) {
throw new Exception(pht('No such file "%s"!', $file_phid));
}
return $file;
}
protected function loadFileChunks(
PhabricatorUser $viewer,
PhabricatorFile $file) {
return $this->newChunkQuery($viewer, $file)
->execute();
}
protected function loadFileChunkForUpload(
PhabricatorUser $viewer,
PhabricatorFile $file,
$start,
$end) {
$start = (int)$start;
$end = (int)$end;
$chunks = $this->newChunkQuery($viewer, $file)
->withByteRange($start, $end)
->execute();
if (!$chunks) {
throw new Exception(
pht(
'There are no file data chunks in byte range %d - %d.',
$start,
$end));
}
if (count($chunks) !== 1) {
phlog($chunks);
throw new Exception(
pht(
'There are multiple chunks in byte range %d - %d.',
$start,
$end));
}
$chunk = head($chunks);
if ($chunk->getByteStart() != $start) {
throw new Exception(
pht(
'Chunk start byte is %d, not %d.',
$chunk->getByteStart(),
$start));
}
if ($chunk->getByteEnd() != $end) {
throw new Exception(
pht(
'Chunk end byte is %d, not %d.',
$chunk->getByteEnd(),
$end));
}
if ($chunk->getDataFilePHID()) {
throw new Exception(
pht('Chunk has already been uploaded.'));
}
return $chunk;
}
protected function decodeBase64($data) {
$data = base64_decode($data, $strict = true);
if ($data === false) {
throw new Exception(pht('Unable to decode base64 data!'));
}
return $data;
}
protected function loadAnyMissingChunk(
PhabricatorUser $viewer,
PhabricatorFile $file) {
return $this->newChunkQuery($viewer, $file)
->withIsComplete(false)
->setLimit(1)
->execute();
}
private function newChunkQuery(
PhabricatorUser $viewer,
PhabricatorFile $file) {
$engine = $file->instantiateStorageEngine();
if (!$engine->isChunkEngine()) {
throw new Exception(
pht(
'File "%s" does not have chunks!',
$file->getPHID()));
}
return id(new PhabricatorFileChunkQuery())
->setViewer($viewer)
->withChunkHandles(array($file->getStorageHandle()));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/format/PhabricatorFileRawStorageFormat.php | src/applications/files/format/PhabricatorFileRawStorageFormat.php | <?php
final class PhabricatorFileRawStorageFormat
extends PhabricatorFileStorageFormat {
const FORMATKEY = 'raw';
public function getStorageFormatName() {
return pht('Raw Data');
}
public function newReadIterator($raw_iterator) {
return $raw_iterator;
}
public function newWriteIterator($raw_iterator) {
return $raw_iterator;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/format/PhabricatorFileROT13StorageFormat.php | src/applications/files/format/PhabricatorFileROT13StorageFormat.php | <?php
/**
* Trivial example of a file storage format for at-rest encryption.
*
* This format applies ROT13 encoding to file data as it is stored and
* reverses it on the way out. This encoding is trivially reversible. This
* format is for testing, developing, and understanding encoding formats and
* is not intended for production use.
*/
final class PhabricatorFileROT13StorageFormat
extends PhabricatorFileStorageFormat {
const FORMATKEY = 'rot13';
public function getStorageFormatName() {
return pht('Encoded (ROT13)');
}
public function newReadIterator($raw_iterator) {
$file = $this->getFile();
$iterations = $file->getStorageProperty('iterations', 1);
$value = $file->loadDataFromIterator($raw_iterator);
for ($ii = 0; $ii < $iterations; $ii++) {
$value = str_rot13($value);
}
return array($value);
}
public function newWriteIterator($raw_iterator) {
return $this->newReadIterator($raw_iterator);
}
public function newStorageProperties() {
// For extreme security, repeatedly encode the data using a random (odd)
// number of iterations.
return array(
'iterations' => (mt_rand(1, 3) * 2) - 1,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/format/PhabricatorFileAES256StorageFormat.php | src/applications/files/format/PhabricatorFileAES256StorageFormat.php | <?php
/**
* At-rest encryption format using AES256 CBC.
*/
final class PhabricatorFileAES256StorageFormat
extends PhabricatorFileStorageFormat {
const FORMATKEY = 'aes-256-cbc';
private $keyName;
public function getStorageFormatName() {
return pht('Encrypted (AES-256-CBC)');
}
public function canGenerateNewKeyMaterial() {
return true;
}
public function generateNewKeyMaterial() {
$envelope = self::newAES256Key();
$material = $envelope->openEnvelope();
return base64_encode($material);
}
public function canCycleMasterKey() {
return true;
}
public function cycleStorageProperties() {
$file = $this->getFile();
list($key, $iv) = $this->extractKeyAndIV($file);
return $this->formatStorageProperties($key, $iv);
}
public function newReadIterator($raw_iterator) {
$file = $this->getFile();
$data = $file->loadDataFromIterator($raw_iterator);
list($key, $iv) = $this->extractKeyAndIV($file);
$data = $this->decryptData($data, $key, $iv);
return array($data);
}
public function newWriteIterator($raw_iterator) {
$file = $this->getFile();
$data = $file->loadDataFromIterator($raw_iterator);
list($key, $iv) = $this->extractKeyAndIV($file);
$data = $this->encryptData($data, $key, $iv);
return array($data);
}
public function newFormatIntegrityHash() {
$file = $this->getFile();
list($key_envelope, $iv_envelope) = $this->extractKeyAndIV($file);
// NOTE: We include the IV in the format integrity hash. If we do not,
// attackers can potentially forge the first block of decrypted data
// in CBC mode if they are able to substitute a chosen IV and predict
// the plaintext. (Normally, they can not tamper with the IV.)
$input = self::FORMATKEY.'/iv:'.$iv_envelope->openEnvelope();
return PhabricatorHash::digestWithNamedKey(
$input,
PhabricatorFileStorageEngine::HMAC_INTEGRITY);
}
public function newStorageProperties() {
// Generate a unique key and IV for this block of data.
$key_envelope = self::newAES256Key();
$iv_envelope = self::newAES256IV();
return $this->formatStorageProperties($key_envelope, $iv_envelope);
}
private function formatStorageProperties(
PhutilOpaqueEnvelope $key_envelope,
PhutilOpaqueEnvelope $iv_envelope) {
// Encode the raw binary data with base64 so we can wrap it in JSON.
$data = array(
'iv.base64' => base64_encode($iv_envelope->openEnvelope()),
'key.base64' => base64_encode($key_envelope->openEnvelope()),
);
// Encode the base64 data with JSON.
$data_clear = phutil_json_encode($data);
// Encrypt the block key with the master key, using a unique IV.
$data_iv = self::newAES256IV();
$key_name = $this->getMasterKeyName();
$master_key = $this->getMasterKeyMaterial($key_name);
$data_cipher = $this->encryptData($data_clear, $master_key, $data_iv);
return array(
'key.name' => $key_name,
'iv.base64' => base64_encode($data_iv->openEnvelope()),
'payload.base64' => base64_encode($data_cipher),
);
}
private function extractKeyAndIV(PhabricatorFile $file) {
$outer_iv = $file->getStorageProperty('iv.base64');
$outer_iv = base64_decode($outer_iv);
$outer_iv = new PhutilOpaqueEnvelope($outer_iv);
$outer_payload = $file->getStorageProperty('payload.base64');
$outer_payload = base64_decode($outer_payload);
$outer_key_name = $file->getStorageProperty('key.name');
$outer_key = $this->getMasterKeyMaterial($outer_key_name);
$payload = $this->decryptData($outer_payload, $outer_key, $outer_iv);
$payload = phutil_json_decode($payload);
$inner_iv = $payload['iv.base64'];
$inner_iv = base64_decode($inner_iv);
$inner_iv = new PhutilOpaqueEnvelope($inner_iv);
$inner_key = $payload['key.base64'];
$inner_key = base64_decode($inner_key);
$inner_key = new PhutilOpaqueEnvelope($inner_key);
return array($inner_key, $inner_iv);
}
private function encryptData(
$data,
PhutilOpaqueEnvelope $key,
PhutilOpaqueEnvelope $iv) {
$method = 'aes-256-cbc';
$key = $key->openEnvelope();
$iv = $iv->openEnvelope();
$result = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
if ($result === false) {
throw new Exception(
pht(
'Failed to openssl_encrypt() data: %s',
openssl_error_string()));
}
return $result;
}
private function decryptData(
$data,
PhutilOpaqueEnvelope $key,
PhutilOpaqueEnvelope $iv) {
$method = 'aes-256-cbc';
$key = $key->openEnvelope();
$iv = $iv->openEnvelope();
$result = openssl_decrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
if ($result === false) {
throw new Exception(
pht(
'Failed to openssl_decrypt() data: %s',
openssl_error_string()));
}
return $result;
}
public static function newAES256Key() {
// Unsurprisingly, AES256 uses a 256 bit key.
$key = Filesystem::readRandomBytes(phutil_units('256 bits in bytes'));
return new PhutilOpaqueEnvelope($key);
}
public static function newAES256IV() {
// AES256 uses a 256 bit key, but the initialization vector length is
// only 128 bits.
$iv = Filesystem::readRandomBytes(phutil_units('128 bits in bytes'));
return new PhutilOpaqueEnvelope($iv);
}
public function selectMasterKey($key_name) {
// Require that the key exist on the key ring.
$this->getMasterKeyMaterial($key_name);
$this->keyName = $key_name;
return $this;
}
private function getMasterKeyName() {
if ($this->keyName !== null) {
return $this->keyName;
}
$default = PhabricatorKeyring::getDefaultKeyName(self::FORMATKEY);
if ($default !== null) {
return $default;
}
throw new Exception(
pht(
'No AES256 key is specified in the keyring as a default encryption '.
'key, and no encryption key has been explicitly selected.'));
}
private function getMasterKeyMaterial($key_name) {
return PhabricatorKeyring::getKey($key_name, self::FORMATKEY);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/format/PhabricatorFileStorageFormat.php | src/applications/files/format/PhabricatorFileStorageFormat.php | <?php
abstract class PhabricatorFileStorageFormat
extends Phobject {
private $file;
final public function setFile(PhabricatorFile $file) {
$this->file = $file;
return $this;
}
final public function getFile() {
if (!$this->file) {
throw new PhutilInvalidStateException('setFile');
}
return $this->file;
}
abstract public function getStorageFormatName();
abstract public function newReadIterator($raw_iterator);
abstract public function newWriteIterator($raw_iterator);
public function newFormatIntegrityHash() {
return null;
}
public function newStorageProperties() {
return array();
}
public function canGenerateNewKeyMaterial() {
return false;
}
public function generateNewKeyMaterial() {
throw new PhutilMethodNotImplementedException();
}
public function canCycleMasterKey() {
return false;
}
public function cycleStorageProperties() {
throw new PhutilMethodNotImplementedException();
}
public function selectMasterKey($key_name) {
throw new Exception(
pht(
'This storage format ("%s") does not support key selection.',
$this->getStorageFormatName()));
}
final public function getStorageFormatKey() {
return $this->getPhobjectClassConstant('FORMATKEY');
}
final public static function getAllFormats() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getStorageFormatKey')
->execute();
}
final public static function getFormat($key) {
$formats = self::getAllFormats();
return idx($formats, $key);
}
final public static function requireFormat($key) {
$format = self::getFormat($key);
if (!$format) {
throw new Exception(
pht(
'No file storage format with key "%s" exists.',
$key));
}
return $format;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/format/__tests__/PhabricatorFileStorageFormatTestCase.php | src/applications/files/format/__tests__/PhabricatorFileStorageFormatTestCase.php | <?php
final class PhabricatorFileStorageFormatTestCase extends PhabricatorTestCase {
protected function getPhabricatorTestCaseConfiguration() {
return array(
self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
);
}
public function testRot13Storage() {
$engine = new PhabricatorTestStorageEngine();
$rot13_format = PhabricatorFileROT13StorageFormat::FORMATKEY;
$data = 'The cow jumped over the full moon.';
$expect = 'Gur pbj whzcrq bire gur shyy zbba.';
$params = array(
'name' => 'test.dat',
'storageEngines' => array(
$engine,
),
'format' => $rot13_format,
);
$file = PhabricatorFile::newFromFileData($data, $params);
// We should have a file stored as rot13, which reads back the input
// data correctly.
$this->assertEqual($rot13_format, $file->getStorageFormat());
$this->assertEqual($data, $file->loadFileData());
// The actual raw data in the storage engine should be encoded.
$raw_data = $engine->readFile($file->getStorageHandle());
$this->assertEqual($expect, $raw_data);
// If we generate an iterator over a slice of the file, it should return
// the decrypted file.
$iterator = $file->getFileDataIterator(4, 14);
$raw_data = '';
foreach ($iterator as $data_chunk) {
$raw_data .= $data_chunk;
}
$this->assertEqual('cow jumped', $raw_data);
}
public function testAES256Storage() {
if (!function_exists('openssl_encrypt')) {
$this->assertSkipped(pht('No OpenSSL extension available.'));
}
$engine = new PhabricatorTestStorageEngine();
$key_name = 'test.abcd';
$key_text = 'abcdefghijklmnopABCDEFGHIJKLMNOP';
PhabricatorKeyring::addKey(
array(
'name' => $key_name,
'type' => 'aes-256-cbc',
'material.base64' => base64_encode($key_text),
));
$format = id(new PhabricatorFileAES256StorageFormat())
->selectMasterKey($key_name);
$data = 'The cow jumped over the full moon.';
$params = array(
'name' => 'test.dat',
'storageEngines' => array(
$engine,
),
'format' => $format,
);
$file = PhabricatorFile::newFromFileData($data, $params);
// We should have a file stored as AES256.
$format_key = $format->getStorageFormatKey();
$this->assertEqual($format_key, $file->getStorageFormat());
$this->assertEqual($data, $file->loadFileData());
// The actual raw data in the storage engine should be encrypted. We
// can't really test this, but we can make sure it's not the same as the
// input data.
$raw_data = $engine->readFile($file->getStorageHandle());
$this->assertTrue($data !== $raw_data);
// If we generate an iterator over a slice of the file, it should return
// the decrypted file.
$iterator = $file->getFileDataIterator(4, 14);
$raw_data = '';
foreach ($iterator as $data_chunk) {
$raw_data .= $data_chunk;
}
$this->assertEqual('cow jumped', $raw_data);
$iterator = $file->getFileDataIterator(4, null);
$raw_data = '';
foreach ($iterator as $data_chunk) {
$raw_data .= $data_chunk;
}
$this->assertEqual('cow jumped over the full moon.', $raw_data);
}
public function testStorageTampering() {
$engine = new PhabricatorTestStorageEngine();
$good = 'The cow jumped over the full moon.';
$evil = 'The cow slept quietly, honoring the glorious dictator.';
$params = array(
'name' => 'message.txt',
'storageEngines' => array(
$engine,
),
);
// First, write the file normally.
$file = PhabricatorFile::newFromFileData($good, $params);
$this->assertEqual($good, $file->loadFileData());
// As an adversary, tamper with the file.
$engine->tamperWithFile($file->getStorageHandle(), $evil);
// Attempts to read the file data should now fail the integrity check.
$caught = null;
try {
$file->loadFileData();
} catch (PhabricatorFileIntegrityException $ex) {
$caught = $ex;
}
$this->assertTrue($caught instanceof PhabricatorFileIntegrityException);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorHexdumpDocumentEngine.php | src/applications/files/document/PhabricatorHexdumpDocumentEngine.php | <?php
final class PhabricatorHexdumpDocumentEngine
extends PhabricatorDocumentEngine {
const ENGINEKEY = 'hexdump';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as Hexdump');
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-microchip';
}
protected function getByteLengthLimit() {
return (1024 * 1024 * 1);
}
protected function getContentScore(PhabricatorDocumentRef $ref) {
return 500;
}
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
return true;
}
protected function canRenderPartialDocument(PhabricatorDocumentRef $ref) {
return true;
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$limit = $this->getByteLengthLimit();
$length = $ref->getByteLength();
$is_partial = false;
if ($limit) {
if ($length > $limit) {
$is_partial = true;
$length = $limit;
}
}
$content = $ref->loadData(null, $length);
$output = array();
$offset = 0;
$lines = str_split($content, 16);
foreach ($lines as $line) {
$output[] = sprintf(
'%08x %- 23s %- 23s %- 16s',
$offset,
$this->renderHex(substr($line, 0, 8)),
$this->renderHex(substr($line, 8)),
$this->renderBytes($line));
$offset += 16;
}
$output = implode("\n", $output);
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-hexdump PhabricatorMonospaced',
),
$output);
$message = null;
if ($is_partial) {
$message = $this->newMessage(
pht(
'This document is too large to be completely rendered inline. The '.
'first %s bytes are shown.',
new PhutilNumber($limit)));
}
return array(
$message,
$container,
);
}
private function renderHex($bytes) {
$length = strlen($bytes);
$output = array();
for ($ii = 0; $ii < $length; $ii++) {
$output[] = sprintf('%02x', ord($bytes[$ii]));
}
return implode(' ', $output);
}
private function renderBytes($bytes) {
$length = strlen($bytes);
$output = array();
for ($ii = 0; $ii < $length; $ii++) {
$chr = $bytes[$ii];
$ord = ord($chr);
if ($ord < 0x20 || $ord >= 0x7F) {
$chr = '.';
}
$output[] = $chr;
}
return implode('', $output);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorImageDocumentEngine.php | src/applications/files/document/PhabricatorImageDocumentEngine.php | <?php
final class PhabricatorImageDocumentEngine
extends PhabricatorDocumentEngine {
const ENGINEKEY = 'image';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as Image');
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-file-image-o';
}
protected function getByteLengthLimit() {
return (1024 * 1024 * 64);
}
public function canDiffDocuments(
PhabricatorDocumentRef $uref = null,
PhabricatorDocumentRef $vref = null) {
// For now, we can only render a rich image diff if the documents have
// their data stored in Files already.
if ($uref && !$uref->getFile()) {
return false;
}
if ($vref && !$vref->getFile()) {
return false;
}
return true;
}
public function newEngineBlocks(
PhabricatorDocumentRef $uref = null,
PhabricatorDocumentRef $vref = null) {
if ($uref) {
$u_blocks = $this->newDiffBlocks($uref);
} else {
$u_blocks = array();
}
if ($vref) {
$v_blocks = $this->newDiffBlocks($vref);
} else {
$v_blocks = array();
}
return id(new PhabricatorDocumentEngineBlocks())
->addBlockList($uref, $u_blocks)
->addBlockList($vref, $v_blocks);
}
public function newBlockDiffViews(
PhabricatorDocumentRef $uref,
PhabricatorDocumentEngineBlock $ublock,
PhabricatorDocumentRef $vref,
PhabricatorDocumentEngineBlock $vblock) {
$u_content = $this->newBlockContentView($uref, $ublock);
$v_content = $this->newBlockContentView($vref, $vblock);
return id(new PhabricatorDocumentEngineBlockDiff())
->setOldContent($u_content)
->addOldClass('diff-image-cell')
->setNewContent($v_content)
->addNewClass('diff-image-cell');
}
private function newDiffBlocks(PhabricatorDocumentRef $ref) {
$blocks = array();
$file = $ref->getFile();
$image_view = phutil_tag(
'div',
array(
'class' => 'differential-image-stage',
),
phutil_tag(
'img',
array(
'alt' => $file->getAltText(),
'src' => $file->getBestURI(),
)));
$hash = $file->getContentHash();
$blocks[] = id(new PhabricatorDocumentEngineBlock())
->setBlockKey('1')
->setDifferenceHash($hash)
->setContent($image_view);
return $blocks;
}
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
$file = $ref->getFile();
if ($file) {
return $file->isViewableImage();
}
$viewable_types = PhabricatorEnv::getEnvConfig('files.viewable-mime-types');
$viewable_types = array_keys($viewable_types);
$image_types = PhabricatorEnv::getEnvConfig('files.image-mime-types');
$image_types = array_keys($image_types);
return
$ref->hasAnyMimeType($viewable_types) &&
$ref->hasAnyMimeType($image_types);
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$file = $ref->getFile();
if ($file) {
$source_uri = $file->getViewURI();
} else {
// We could use a "data:" URI here. It's not yet clear if or when we'll
// have a ref but no backing file.
throw new PhutilMethodNotImplementedException();
}
$image = phutil_tag(
'img',
array(
'alt' => $file->getAltText(),
'src' => $source_uri,
));
$linked_image = phutil_tag(
'a',
array(
'href' => $source_uri,
'rel' => 'noreferrer',
),
$image);
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-image',
),
$linked_image);
return $container;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorDocumentEngine.php | src/applications/files/document/PhabricatorDocumentEngine.php | <?php
abstract class PhabricatorDocumentEngine
extends Phobject {
private $viewer;
private $highlightedLines = array();
private $encodingConfiguration;
private $highlightingConfiguration;
private $blameConfiguration = true;
final public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
final public function getViewer() {
return $this->viewer;
}
final public function setHighlightedLines(array $highlighted_lines) {
$this->highlightedLines = $highlighted_lines;
return $this;
}
final public function getHighlightedLines() {
return $this->highlightedLines;
}
final public function canRenderDocument(PhabricatorDocumentRef $ref) {
return $this->canRenderDocumentType($ref);
}
public function canDiffDocuments(
PhabricatorDocumentRef $uref = null,
PhabricatorDocumentRef $vref = null) {
return false;
}
public function newBlockDiffViews(
PhabricatorDocumentRef $uref,
PhabricatorDocumentEngineBlock $ublock,
PhabricatorDocumentRef $vref,
PhabricatorDocumentEngineBlock $vblock) {
$u_content = $this->newBlockContentView($uref, $ublock);
$v_content = $this->newBlockContentView($vref, $vblock);
return id(new PhabricatorDocumentEngineBlockDiff())
->setOldContent($u_content)
->addOldClass('old')
->addOldClass('old-full')
->setNewContent($v_content)
->addNewClass('new')
->addNewClass('new-full');
}
public function newBlockContentView(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngineBlock $block) {
return $block->getContent();
}
public function newEngineBlocks(
PhabricatorDocumentRef $uref,
PhabricatorDocumentRef $vref) {
throw new PhutilMethodNotImplementedException();
}
public function canConfigureEncoding(PhabricatorDocumentRef $ref) {
return false;
}
public function canConfigureHighlighting(PhabricatorDocumentRef $ref) {
return false;
}
public function canBlame(PhabricatorDocumentRef $ref) {
return false;
}
final public function setEncodingConfiguration($config) {
$this->encodingConfiguration = $config;
return $this;
}
final public function getEncodingConfiguration() {
return $this->encodingConfiguration;
}
final public function setHighlightingConfiguration($config) {
$this->highlightingConfiguration = $config;
return $this;
}
final public function getHighlightingConfiguration() {
return $this->highlightingConfiguration;
}
final public function setBlameConfiguration($blame_configuration) {
$this->blameConfiguration = $blame_configuration;
return $this;
}
final public function getBlameConfiguration() {
return $this->blameConfiguration;
}
final protected function getBlameEnabled() {
return $this->blameConfiguration;
}
public function shouldRenderAsync(PhabricatorDocumentRef $ref) {
return false;
}
abstract protected function canRenderDocumentType(
PhabricatorDocumentRef $ref);
final public function newDocument(PhabricatorDocumentRef $ref) {
$can_complete = $this->canRenderCompleteDocument($ref);
$can_partial = $this->canRenderPartialDocument($ref);
if (!$can_complete && !$can_partial) {
return $this->newMessage(
pht(
'This document is too large to be rendered inline. (The document '.
'is %s bytes, the limit for this engine is %s bytes.)',
new PhutilNumber($ref->getByteLength()),
new PhutilNumber($this->getByteLengthLimit())));
}
return $this->newDocumentContent($ref);
}
final public function newDocumentIcon(PhabricatorDocumentRef $ref) {
return id(new PHUIIconView())
->setIcon($this->getDocumentIconIcon($ref));
}
abstract protected function newDocumentContent(
PhabricatorDocumentRef $ref);
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-file-o';
}
protected function getDocumentRenderingText(PhabricatorDocumentRef $ref) {
return pht('Loading...');
}
final public function getDocumentEngineKey() {
return $this->getPhobjectClassConstant('ENGINEKEY');
}
final public static function getAllEngines() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getDocumentEngineKey')
->execute();
}
final public function newSortVector(PhabricatorDocumentRef $ref) {
$content_score = $this->getContentScore($ref);
// Prefer engines which can render the entire file over engines which
// can only render a header, and engines which can render a header over
// engines which can't render anything.
if ($this->canRenderCompleteDocument($ref)) {
$limit_score = 0;
} else if ($this->canRenderPartialDocument($ref)) {
$limit_score = 1;
} else {
$limit_score = 2;
}
return id(new PhutilSortVector())
->addInt($limit_score)
->addInt(-$content_score);
}
protected function getContentScore(PhabricatorDocumentRef $ref) {
return 2000;
}
abstract public function getViewAsLabel(PhabricatorDocumentRef $ref);
public function getViewAsIconIcon(PhabricatorDocumentRef $ref) {
$can_complete = $this->canRenderCompleteDocument($ref);
$can_partial = $this->canRenderPartialDocument($ref);
if (!$can_complete && !$can_partial) {
return 'fa-times';
}
return $this->getDocumentIconIcon($ref);
}
public function getViewAsIconColor(PhabricatorDocumentRef $ref) {
$can_complete = $this->canRenderCompleteDocument($ref);
if (!$can_complete) {
return 'grey';
}
return null;
}
final public static function getEnginesForRef(
PhabricatorUser $viewer,
PhabricatorDocumentRef $ref) {
$engines = self::getAllEngines();
foreach ($engines as $key => $engine) {
$engine = id(clone $engine)
->setViewer($viewer);
if (!$engine->canRenderDocument($ref)) {
unset($engines[$key]);
continue;
}
$engines[$key] = $engine;
}
if (!$engines) {
throw new Exception(pht('No content engine can render this document.'));
}
$vectors = array();
foreach ($engines as $key => $usable_engine) {
$vectors[$key] = $usable_engine->newSortVector($ref);
}
$vectors = msortv($vectors, 'getSelf');
return array_select_keys($engines, array_keys($vectors));
}
protected function getByteLengthLimit() {
return (1024 * 1024 * 8);
}
protected function canRenderCompleteDocument(PhabricatorDocumentRef $ref) {
$limit = $this->getByteLengthLimit();
if ($limit) {
$length = $ref->getByteLength();
if ($length > $limit) {
return false;
}
}
return true;
}
protected function canRenderPartialDocument(PhabricatorDocumentRef $ref) {
return false;
}
protected function newMessage($message) {
return phutil_tag(
'div',
array(
'class' => 'document-engine-error',
),
$message);
}
final public function newLoadingContent(PhabricatorDocumentRef $ref) {
$spinner = id(new PHUIIconView())
->setIcon('fa-gear')
->addClass('ph-spin');
return phutil_tag(
'div',
array(
'class' => 'document-engine-loading',
),
array(
$spinner,
$this->getDocumentRenderingText($ref),
));
}
public function shouldSuggestEngine(PhabricatorDocumentRef $ref) {
return false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorRemarkupDocumentEngine.php | src/applications/files/document/PhabricatorRemarkupDocumentEngine.php | <?php
final class PhabricatorRemarkupDocumentEngine
extends PhabricatorDocumentEngine {
const ENGINEKEY = 'remarkup';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as Remarkup');
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-file-text-o';
}
protected function getContentScore(PhabricatorDocumentRef $ref) {
$name = $ref->getName();
if ($name !== null) {
if (preg_match('/\\.remarkup\z/i', $name)) {
return 2000;
}
}
return 500;
}
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
return $ref->isProbablyText();
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$viewer = $this->getViewer();
$content = $ref->loadData();
$content = phutil_utf8ize($content);
$remarkup = new PHUIRemarkupView($viewer, $content);
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-remarkup',
),
$remarkup);
return $container;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorSourceDocumentEngine.php | src/applications/files/document/PhabricatorSourceDocumentEngine.php | <?php
final class PhabricatorSourceDocumentEngine
extends PhabricatorTextDocumentEngine {
const ENGINEKEY = 'source';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as Source');
}
public function canConfigureHighlighting(PhabricatorDocumentRef $ref) {
return true;
}
public function canBlame(PhabricatorDocumentRef $ref) {
return true;
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-code';
}
protected function getContentScore(PhabricatorDocumentRef $ref) {
return 1500;
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$content = $this->loadTextData($ref);
$messages = array();
$highlighting = $this->getHighlightingConfiguration();
if ($highlighting !== null) {
$content = PhabricatorSyntaxHighlighter::highlightWithLanguage(
$highlighting,
$content);
} else {
$highlight_limit = DifferentialChangesetParser::HIGHLIGHT_BYTE_LIMIT;
if (strlen($content) > $highlight_limit) {
$messages[] = $this->newMessage(
pht(
'This file is larger than %s, so syntax highlighting was skipped.',
phutil_format_bytes($highlight_limit)));
} else {
$content = PhabricatorSyntaxHighlighter::highlightWithFilename(
$ref->getName(),
$content);
}
}
$options = array();
if ($ref->getBlameURI() && $this->getBlameEnabled()) {
$content = phutil_split_lines($content);
$blame = range(1, count($content));
$blame = array_fuse($blame);
$options['blame'] = $blame;
}
if ($ref->getCoverage()) {
$options['coverage'] = $ref->getCoverage();
}
return array(
$messages,
$this->newTextDocumentContent($ref, $content, $options),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorPDFDocumentEngine.php | src/applications/files/document/PhabricatorPDFDocumentEngine.php | <?php
final class PhabricatorPDFDocumentEngine
extends PhabricatorDocumentEngine {
const ENGINEKEY = 'pdf';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as PDF');
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-file-pdf-o';
}
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
// Since we just render a link to the document anyway, we don't need to
// check anything fancy in config to see if the MIME type is actually
// viewable.
return $ref->hasAnyMimeType(
array(
'application/pdf',
));
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$viewer = $this->getViewer();
$file = $ref->getFile();
if ($file) {
$source_uri = $file->getViewURI();
} else {
throw new PhutilMethodNotImplementedException();
}
$name = $ref->getName();
$length = $ref->getByteLength();
$link = id(new PhabricatorFileLinkView())
->setViewer($viewer)
->setFileName($name)
->setFileViewURI($source_uri)
->setFileViewable(true)
->setFileSize(phutil_format_bytes($length));
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-pdf',
),
$link);
return $container;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorAudioDocumentEngine.php | src/applications/files/document/PhabricatorAudioDocumentEngine.php | <?php
final class PhabricatorAudioDocumentEngine
extends PhabricatorDocumentEngine {
const ENGINEKEY = 'audio';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as Audio');
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-file-sound-o';
}
protected function getByteLengthLimit() {
return null;
}
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
$file = $ref->getFile();
if ($file) {
return $file->isAudio();
}
$viewable_types = PhabricatorEnv::getEnvConfig('files.viewable-mime-types');
$viewable_types = array_keys($viewable_types);
$audio_types = PhabricatorEnv::getEnvConfig('files.audio-mime-types');
$audio_types = array_keys($audio_types);
return
$ref->hasAnyMimeType($viewable_types) &&
$ref->hasAnyMimeType($audio_types);
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$file = $ref->getFile();
if ($file) {
$source_uri = $file->getViewURI();
} else {
throw new PhutilMethodNotImplementedException();
}
$mime_type = $ref->getMimeType();
$audio = phutil_tag(
'audio',
array(
'controls' => 'controls',
),
phutil_tag(
'source',
array(
'src' => $source_uri,
'type' => $mime_type,
)));
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-audio',
),
$audio);
return $container;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorJSONDocumentEngine.php | src/applications/files/document/PhabricatorJSONDocumentEngine.php | <?php
final class PhabricatorJSONDocumentEngine
extends PhabricatorTextDocumentEngine {
const ENGINEKEY = 'json';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as JSON');
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-database';
}
protected function getContentScore(PhabricatorDocumentRef $ref) {
$name = $ref->getName();
if ($name !== null) {
if (preg_match('/\.json\z/', $name)) {
return 2000;
}
}
if ($ref->isProbablyJSON()) {
return 1750;
}
return 500;
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$raw_data = $this->loadTextData($ref);
try {
$data = phutil_json_decode($raw_data);
// See T13635. "phutil_json_decode()" always turns JSON into a PHP array,
// and we lose the distinction between "{}" and "[]". This distinction is
// important when rendering a document.
$data = json_decode($raw_data, false);
if (!$data) {
throw new PhabricatorDocumentEngineParserException(
pht(
'Failed to "json_decode(...)" JSON document after successfully '.
'decoding it with "phutil_json_decode(...).'));
}
if (preg_match('/^\s*\[/', $raw_data)) {
$content = id(new PhutilJSON())->encodeAsList($data);
} else {
$content = id(new PhutilJSON())->encodeFormatted($data);
}
$message = null;
$content = PhabricatorSyntaxHighlighter::highlightWithLanguage(
'json',
$content);
} catch (PhutilJSONParserException $ex) {
$message = $this->newMessage(
pht(
'This document is not valid JSON: %s',
$ex->getMessage()));
$content = $raw_data;
} catch (PhabricatorDocumentEngineParserException $ex) {
$message = $this->newMessage(
pht(
'Unable to parse this document as JSON: %s',
$ex->getMessage()));
$content = $raw_data;
}
return array(
$message,
$this->newTextDocumentContent($ref, $content),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorVideoDocumentEngine.php | src/applications/files/document/PhabricatorVideoDocumentEngine.php | <?php
final class PhabricatorVideoDocumentEngine
extends PhabricatorDocumentEngine {
const ENGINEKEY = 'video';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as Video');
}
protected function getContentScore(PhabricatorDocumentRef $ref) {
// Some video documents can be rendered as either video or audio, but we
// want to prefer video.
return 2500;
}
protected function getByteLengthLimit() {
return null;
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-film';
}
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
$file = $ref->getFile();
if ($file) {
return $file->isVideo();
}
$viewable_types = PhabricatorEnv::getEnvConfig('files.viewable-mime-types');
$viewable_types = array_keys($viewable_types);
$video_types = PhabricatorEnv::getEnvConfig('files.video-mime-types');
$video_types = array_keys($video_types);
return
$ref->hasAnyMimeType($viewable_types) &&
$ref->hasAnyMimeType($video_types);
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$file = $ref->getFile();
if ($file) {
$source_uri = $file->getViewURI();
} else {
throw new PhutilMethodNotImplementedException();
}
$mime_type = $ref->getMimeType();
$video = phutil_tag(
'video',
array(
'controls' => 'controls',
),
phutil_tag(
'source',
array(
'src' => $source_uri,
'type' => $mime_type,
)));
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-video',
),
$video);
return $container;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorVoidDocumentEngine.php | src/applications/files/document/PhabricatorVoidDocumentEngine.php | <?php
final class PhabricatorVoidDocumentEngine
extends PhabricatorDocumentEngine {
const ENGINEKEY = 'void';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return null;
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-file';
}
protected function getContentScore(PhabricatorDocumentRef $ref) {
return 1000;
}
protected function getByteLengthLimit() {
return null;
}
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
return true;
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$message = pht(
'No document engine can render the contents of this file.');
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-message',
),
$message);
return $container;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorJupyterDocumentEngine.php | src/applications/files/document/PhabricatorJupyterDocumentEngine.php | <?php
final class PhabricatorJupyterDocumentEngine
extends PhabricatorDocumentEngine {
const ENGINEKEY = 'jupyter';
public function getViewAsLabel(PhabricatorDocumentRef $ref) {
return pht('View as Jupyter Notebook');
}
protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) {
return 'fa-sun-o';
}
protected function getDocumentRenderingText(PhabricatorDocumentRef $ref) {
return pht('Rendering Jupyter Notebook...');
}
public function shouldRenderAsync(PhabricatorDocumentRef $ref) {
return true;
}
protected function getContentScore(PhabricatorDocumentRef $ref) {
$name = $ref->getName();
if (preg_match('/\\.ipynb\z/i', $name)) {
return 2000;
}
return 500;
}
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
return $ref->isProbablyJSON();
}
public function canDiffDocuments(
PhabricatorDocumentRef $uref = null,
PhabricatorDocumentRef $vref = null) {
return true;
}
public function newEngineBlocks(
PhabricatorDocumentRef $uref = null,
PhabricatorDocumentRef $vref = null) {
$blocks = new PhabricatorDocumentEngineBlocks();
try {
if ($uref) {
$u_blocks = $this->newDiffBlocks($uref);
} else {
$u_blocks = array();
}
if ($vref) {
$v_blocks = $this->newDiffBlocks($vref);
} else {
$v_blocks = array();
}
$blocks->addBlockList($uref, $u_blocks);
$blocks->addBlockList($vref, $v_blocks);
} catch (Exception $ex) {
phlog($ex);
$blocks->addMessage($ex->getMessage());
}
return $blocks;
}
public function newBlockDiffViews(
PhabricatorDocumentRef $uref,
PhabricatorDocumentEngineBlock $ublock,
PhabricatorDocumentRef $vref,
PhabricatorDocumentEngineBlock $vblock) {
$ucell = $ublock->getContent();
$vcell = $vblock->getContent();
$utype = idx($ucell, 'cell_type');
$vtype = idx($vcell, 'cell_type');
if ($utype === $vtype) {
switch ($utype) {
case 'markdown':
$usource = $this->readString($ucell, 'source');
$vsource = $this->readString($vcell, 'source');
$diff = id(new PhutilProseDifferenceEngine())
->getDiff($usource, $vsource);
$u_content = $this->newProseDiffCell($diff, array('=', '-'));
$v_content = $this->newProseDiffCell($diff, array('=', '+'));
$u_content = $this->newJupyterCell(null, $u_content, null);
$v_content = $this->newJupyterCell(null, $v_content, null);
$u_content = $this->newCellContainer($u_content);
$v_content = $this->newCellContainer($v_content);
return id(new PhabricatorDocumentEngineBlockDiff())
->setOldContent($u_content)
->addOldClass('old')
->setNewContent($v_content)
->addNewClass('new');
case 'code/line':
$usource = idx($ucell, 'raw');
$vsource = idx($vcell, 'raw');
$udisplay = idx($ucell, 'display');
$vdisplay = idx($vcell, 'display');
$intraline_segments = ArcanistDiffUtils::generateIntralineDiff(
$usource,
$vsource);
$u_segments = array();
foreach ($intraline_segments[0] as $u_segment) {
$u_segments[] = $u_segment;
}
$v_segments = array();
foreach ($intraline_segments[1] as $v_segment) {
$v_segments[] = $v_segment;
}
$usource = PhabricatorDifferenceEngine::applyIntralineDiff(
$udisplay,
$u_segments);
$vsource = PhabricatorDifferenceEngine::applyIntralineDiff(
$vdisplay,
$v_segments);
list($u_label, $u_content) = $this->newCodeLineCell($ucell, $usource);
list($v_label, $v_content) = $this->newCodeLineCell($vcell, $vsource);
$classes = array(
'jupyter-cell-flush',
);
$u_content = $this->newJupyterCell($u_label, $u_content, $classes);
$v_content = $this->newJupyterCell($v_label, $v_content, $classes);
$u_content = $this->newCellContainer($u_content);
$v_content = $this->newCellContainer($v_content);
return id(new PhabricatorDocumentEngineBlockDiff())
->setOldContent($u_content)
->addOldClass('old')
->setNewContent($v_content)
->addNewClass('new');
}
}
return parent::newBlockDiffViews($uref, $ublock, $vref, $vblock);
}
public function newBlockContentView(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngineBlock $block) {
$viewer = $this->getViewer();
$cell = $block->getContent();
$cell_content = $this->renderJupyterCell($viewer, $cell);
return $this->newCellContainer($cell_content);
}
private function newCellContainer($cell_content) {
$notebook_table = phutil_tag(
'table',
array(
'class' => 'jupyter-notebook',
),
$cell_content);
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-jupyter document-engine-diff',
),
$notebook_table);
return $container;
}
private function newProseDiffCell(PhutilProseDiff $diff, array $mask) {
$mask = array_fuse($mask);
$result = array();
foreach ($diff->getParts() as $part) {
$type = $part['type'];
$text = $part['text'];
if (!isset($mask[$type])) {
continue;
}
switch ($type) {
case '-':
$result[] = phutil_tag(
'span',
array(
'class' => 'bright',
),
$text);
break;
case '+':
$result[] = phutil_tag(
'span',
array(
'class' => 'bright',
),
$text);
break;
case '=':
$result[] = $text;
break;
}
}
return array(
null,
phutil_tag(
'div',
array(
'class' => 'jupyter-cell-markdown',
),
$result),
);
}
private function newDiffBlocks(PhabricatorDocumentRef $ref) {
$viewer = $this->getViewer();
$content = $ref->loadData();
$cells = $this->newCells($content, true);
$idx = 1;
$blocks = array();
foreach ($cells as $cell) {
// When the cell is a source code line, we can hash just the raw
// input rather than all the cell metadata.
switch (idx($cell, 'cell_type')) {
case 'code/line':
$hash_input = $cell['raw'];
break;
case 'markdown':
$hash_input = $this->readString($cell, 'source');
break;
default:
$hash_input = serialize($cell);
break;
}
$hash = PhabricatorHash::digestWithNamedKey(
$hash_input,
'document-engine.content-digest');
$blocks[] = id(new PhabricatorDocumentEngineBlock())
->setBlockKey($idx)
->setDifferenceHash($hash)
->setContent($cell);
$idx++;
}
return $blocks;
}
protected function newDocumentContent(PhabricatorDocumentRef $ref) {
$viewer = $this->getViewer();
$content = $ref->loadData();
try {
$cells = $this->newCells($content, false);
} catch (Exception $ex) {
return $this->newMessage($ex->getMessage());
}
$rows = array();
foreach ($cells as $cell) {
$rows[] = $this->renderJupyterCell($viewer, $cell);
}
$notebook_table = phutil_tag(
'table',
array(
'class' => 'jupyter-notebook',
),
$rows);
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-jupyter',
),
$notebook_table);
return $container;
}
private function newCells($content, $for_diff) {
try {
$data = phutil_json_decode($content);
} catch (PhutilJSONParserException $ex) {
throw new Exception(
pht(
'This is not a valid JSON document and can not be rendered as '.
'a Jupyter notebook: %s.',
$ex->getMessage()));
}
if (!is_array($data)) {
throw new Exception(
pht(
'This document does not encode a valid JSON object and can not '.
'be rendered as a Jupyter notebook.'));
}
$nbformat = idx($data, 'nbformat');
if ($nbformat == null || !strlen($nbformat)) {
throw new Exception(
pht(
'This document is missing an "nbformat" field. Jupyter notebooks '.
'must have this field.'));
}
if ($nbformat !== 4) {
throw new Exception(
pht(
'This Jupyter notebook uses an unsupported version of the file '.
'format (found version %s, expected version 4).',
$nbformat));
}
$cells = idx($data, 'cells');
if (!is_array($cells)) {
throw new Exception(
pht(
'This Jupyter notebook does not specify a list of "cells".'));
}
if (!$cells) {
throw new Exception(
pht(
'This Jupyter notebook does not specify any notebook cells.'));
}
if (!$for_diff) {
return $cells;
}
// If we're extracting cells to build a diff view, split code cells into
// individual lines and individual outputs. We want users to be able to
// add inline comments to each line and each output block.
$results = array();
foreach ($cells as $cell) {
$cell_type = idx($cell, 'cell_type');
if ($cell_type === 'markdown') {
$source = $this->readString($cell, 'source');
// Attempt to split contiguous blocks of markdown into smaller
// pieces.
$chunks = preg_split(
'/\n\n+/',
$source);
foreach ($chunks as $chunk) {
$result = $cell;
$result['source'] = array($chunk);
$results[] = $result;
}
continue;
}
if ($cell_type !== 'code') {
$results[] = $cell;
continue;
}
$label = $this->newCellLabel($cell);
$lines = $this->readStringList($cell, 'source');
$content = $this->highlightLines($lines);
$count = count($lines);
for ($ii = 0; $ii < $count; $ii++) {
$is_head = ($ii === 0);
$is_last = ($ii === ($count - 1));
if ($is_head) {
$line_label = $label;
} else {
$line_label = null;
}
$results[] = array(
'cell_type' => 'code/line',
'label' => $line_label,
'raw' => $lines[$ii],
'display' => idx($content, $ii),
'head' => $is_head,
'last' => $is_last,
);
}
$outputs = array();
$output_list = idx($cell, 'outputs');
if (is_array($output_list)) {
foreach ($output_list as $output) {
$results[] = array(
'cell_type' => 'code/output',
'output' => $output,
);
}
}
}
return $results;
}
private function renderJupyterCell(
PhabricatorUser $viewer,
array $cell) {
list($label, $content) = $this->renderJupyterCellContent($viewer, $cell);
$classes = null;
switch (idx($cell, 'cell_type')) {
case 'code/line':
$classes = 'jupyter-cell-flush';
break;
}
return $this->newJupyterCell(
$label,
$content,
$classes);
}
private function newJupyterCell($label, $content, $classes) {
$label_cell = phutil_tag(
'td',
array(
'class' => 'jupyter-label',
),
$label);
$content_cell = phutil_tag(
'td',
array(
'class' => $classes,
),
$content);
return phutil_tag(
'tr',
array(),
array(
$label_cell,
$content_cell,
));
}
private function renderJupyterCellContent(
PhabricatorUser $viewer,
array $cell) {
$cell_type = idx($cell, 'cell_type');
switch ($cell_type) {
case 'markdown':
return $this->newMarkdownCell($cell);
case 'code':
return $this->newCodeCell($cell);
case 'code/line':
return $this->newCodeLineCell($cell);
case 'code/output':
return $this->newCodeOutputCell($cell);
}
$json_content = id(new PhutilJSON())
->encodeFormatted($cell);
return $this->newRawCell($json_content);
}
private function newRawCell($content) {
return array(
null,
phutil_tag(
'div',
array(
'class' => 'jupyter-cell-raw PhabricatorMonospaced',
),
$content),
);
}
private function newMarkdownCell(array $cell) {
$content = $this->readStringList($cell, 'source');
// TODO: This should ideally highlight as Markdown, but the "md"
// highlighter in Pygments is painfully slow and not terribly useful.
$content = $this->highlightLines($content, 'txt');
return array(
null,
phutil_tag(
'div',
array(
'class' => 'jupyter-cell-markdown',
),
$content),
);
}
private function newCodeCell(array $cell) {
$label = $this->newCellLabel($cell);
$content = $this->readStringList($cell, 'source');
$content = $this->highlightLines($content);
$outputs = array();
$output_list = idx($cell, 'outputs');
if (is_array($output_list)) {
foreach ($output_list as $output) {
$outputs[] = $this->newOutput($output);
}
}
return array(
$label,
array(
phutil_tag(
'div',
array(
'class' =>
'jupyter-cell-code jupyter-cell-code-block '.
'PhabricatorMonospaced remarkup-code',
),
array(
$content,
)),
$outputs,
),
);
}
private function newCodeLineCell(array $cell, $content = null) {
$classes = array();
$classes[] = 'PhabricatorMonospaced';
$classes[] = 'remarkup-code';
$classes[] = 'jupyter-cell-code';
$classes[] = 'jupyter-cell-code-line';
if ($cell['head']) {
$classes[] = 'jupyter-cell-code-head';
}
if ($cell['last']) {
$classes[] = 'jupyter-cell-code-last';
}
$classes = implode(' ', $classes);
if ($content === null) {
$content = $cell['display'];
}
return array(
$cell['label'],
array(
phutil_tag(
'div',
array(
'class' => $classes,
),
array(
$content,
)),
),
);
}
private function newCodeOutputCell(array $cell) {
return array(
null,
$this->newOutput($cell['output']),
);
}
private function newOutput(array $output) {
if (!is_array($output)) {
return pht('<Invalid Output>');
}
$classes = array(
'jupyter-output',
'PhabricatorMonospaced',
);
$output_name = idx($output, 'name');
switch ($output_name) {
case 'stderr':
$classes[] = 'jupyter-output-stderr';
break;
}
$output_type = idx($output, 'output_type');
switch ($output_type) {
case 'execute_result':
case 'display_data':
$data = idx($output, 'data');
$image_formats = array(
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
);
foreach ($image_formats as $image_format) {
if (!isset($data[$image_format])) {
continue;
}
$raw_data = $this->readString($data, $image_format);
$content = phutil_tag(
'img',
array(
'src' => 'data:'.$image_format.';base64,'.$raw_data,
));
break 2;
}
if (isset($data['text/html'])) {
$content = $data['text/html'];
$classes[] = 'jupyter-output-html';
break;
}
if (isset($data['application/javascript'])) {
$content = $data['application/javascript'];
$classes[] = 'jupyter-output-html';
break;
}
if (isset($data['text/plain'])) {
$content = $data['text/plain'];
break;
}
break;
case 'stream':
default:
$content = $this->readString($output, 'text');
break;
}
return phutil_tag(
'div',
array(
'class' => implode(' ', $classes),
),
$content);
}
private function newCellLabel(array $cell) {
$execution_count = idx($cell, 'execution_count');
if ($execution_count) {
$label = 'In ['.$execution_count.']:';
} else {
$label = null;
}
return $label;
}
private function highlightLines(array $lines, $force_language = null) {
if ($force_language === null) {
$head = head($lines);
$matches = null;
if (preg_match('/^%%(.*)$/', $head, $matches)) {
$restore = array_shift($lines);
$lang = $matches[1];
} else {
$restore = null;
$lang = 'py';
}
} else {
$restore = null;
$lang = $force_language;
}
$content = PhabricatorSyntaxHighlighter::highlightWithLanguage(
$lang,
implode('', $lines));
$content = phutil_split_lines($content);
if ($restore !== null) {
$language_tag = phutil_tag(
'span',
array(
'class' => 'language-tag',
),
$restore);
array_unshift($content, $language_tag);
}
return $content;
}
public function shouldSuggestEngine(PhabricatorDocumentRef $ref) {
return true;
}
private function readString(array $src, $key) {
$list = $this->readStringList($src, $key);
return implode('', $list);
}
private function readStringList(array $src, $key) {
$list = idx($src, $key);
if (is_array($list)) {
$list = $list;
} else if (is_string($list)) {
$list = array($list);
} else {
$list = array();
}
return $list;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorTextDocumentEngine.php | src/applications/files/document/PhabricatorTextDocumentEngine.php | <?php
abstract class PhabricatorTextDocumentEngine
extends PhabricatorDocumentEngine {
private $encodingMessage = null;
protected function canRenderDocumentType(PhabricatorDocumentRef $ref) {
return $ref->isProbablyText();
}
public function canConfigureEncoding(PhabricatorDocumentRef $ref) {
return true;
}
protected function newTextDocumentContent(
PhabricatorDocumentRef $ref,
$content,
array $options = array()) {
PhutilTypeSpec::checkMap(
$options,
array(
'blame' => 'optional wild',
'coverage' => 'optional list<wild>',
));
if (is_array($content)) {
$lines = $content;
} else {
$lines = phutil_split_lines($content);
}
$view = id(new PhabricatorSourceCodeView())
->setHighlights($this->getHighlightedLines())
->setLines($lines)
->setSymbolMetadata($ref->getSymbolMetadata());
$blame = idx($options, 'blame');
if ($blame !== null) {
$view->setBlameMap($blame);
}
$coverage = idx($options, 'coverage');
if ($coverage !== null) {
$view->setCoverage($coverage);
}
$message = null;
if ($this->encodingMessage !== null) {
$message = $this->newMessage($this->encodingMessage);
}
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-text',
),
array(
$message,
$view,
));
return $container;
}
protected function loadTextData(PhabricatorDocumentRef $ref) {
$content = $ref->loadData();
$encoding = $this->getEncodingConfiguration();
if ($encoding !== null) {
if (function_exists('mb_convert_encoding')) {
$content = mb_convert_encoding($content, 'UTF-8', $encoding);
$this->encodingMessage = pht(
'This document was converted from %s to UTF8 for display.',
$encoding);
} else {
$this->encodingMessage = pht(
'Unable to perform text encoding conversion: mbstring extension '.
'is not available.');
}
} else {
if (!phutil_is_utf8($content)) {
if (function_exists('mb_detect_encoding')) {
$try_encodings = array(
'JIS' => pht('JIS'),
'EUC-JP' => pht('EUC-JP'),
'SJIS' => pht('Shift JIS'),
'ISO-8859-1' => pht('ISO-8859-1 (Latin 1)'),
);
$guess = mb_detect_encoding($content, array_keys($try_encodings));
if ($guess) {
$content = mb_convert_encoding($content, 'UTF-8', $guess);
$this->encodingMessage = pht(
'This document is not UTF8. It was detected as %s and '.
'converted to UTF8 for display.',
idx($try_encodings, $guess, $guess));
}
}
}
}
if (!phutil_is_utf8($content)) {
$content = phutil_utf8ize($content);
$this->encodingMessage = pht(
'This document is not UTF8 and its text encoding could not be '.
'detected automatically. Use "Change Text Encoding..." to choose '.
'an encoding.');
}
return $content;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/PhabricatorDocumentRef.php | src/applications/files/document/PhabricatorDocumentRef.php | <?php
final class PhabricatorDocumentRef
extends Phobject {
private $name;
private $mimeType;
private $file;
private $byteLength;
private $snippet;
private $symbolMetadata = array();
private $blameURI;
private $coverage = array();
private $data;
public function setFile(PhabricatorFile $file) {
$this->file = $file;
return $this;
}
public function getFile() {
return $this->file;
}
public function setMimeType($mime_type) {
$this->mimeType = $mime_type;
return $this;
}
public function getMimeType() {
if ($this->mimeType !== null) {
return $this->mimeType;
}
if ($this->file) {
return $this->file->getMimeType();
}
return null;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
if ($this->name !== null) {
return $this->name;
}
if ($this->file) {
return $this->file->getName();
}
return null;
}
public function setByteLength($length) {
$this->byteLength = $length;
return $this;
}
public function getByteLength() {
if ($this->byteLength !== null) {
return $this->byteLength;
}
if ($this->data !== null) {
return strlen($this->data);
}
if ($this->file) {
return (int)$this->file->getByteSize();
}
return null;
}
public function setData($data) {
$this->data = $data;
return $this;
}
public function loadData($begin = null, $end = null) {
if ($this->data !== null) {
$data = $this->data;
if ($begin !== null && $end !== null) {
$data = substr($data, $begin, $end - $begin);
} else if ($begin !== null) {
$data = substr($data, $begin);
} else if ($end !== null) {
$data = substr($data, 0, $end);
}
return $data;
}
if ($this->file) {
$iterator = $this->file->getFileDataIterator($begin, $end);
$result = '';
foreach ($iterator as $chunk) {
$result .= $chunk;
}
return $result;
}
throw new PhutilMethodNotImplementedException();
}
public function hasAnyMimeType(array $candidate_types) {
$mime_full = $this->getMimeType();
if (!phutil_nonempty_string($mime_full)) {
return false;
}
$mime_parts = explode(';', $mime_full);
$mime_type = head($mime_parts);
$mime_type = $this->normalizeMimeType($mime_type);
foreach ($candidate_types as $candidate_type) {
if ($this->normalizeMimeType($candidate_type) === $mime_type) {
return true;
}
}
return false;
}
private function normalizeMimeType($mime_type) {
$mime_type = trim($mime_type);
$mime_type = phutil_utf8_strtolower($mime_type);
return $mime_type;
}
public function isProbablyText() {
$snippet = $this->getSnippet();
return (strpos($snippet, "\0") === false);
}
public function isProbablyJSON() {
if (!$this->isProbablyText()) {
return false;
}
$snippet = $this->getSnippet();
// If the file is longer than the snippet, we don't detect the content
// as JSON. We could use some kind of heuristic here if we wanted, but
// see PHI749 for a false positive.
if (strlen($snippet) < $this->getByteLength()) {
return false;
}
// If the snippet is the whole file, just check if the snippet is valid
// JSON. Note that `phutil_json_decode()` only accepts arrays and objects
// as JSON, so this won't misfire on files with content like "3".
try {
phutil_json_decode($snippet);
return true;
} catch (Exception $ex) {
return false;
}
}
public function getSnippet() {
if ($this->snippet === null) {
$this->snippet = $this->loadData(null, (1024 * 1024 * 1));
}
return $this->snippet;
}
public function setSymbolMetadata(array $metadata) {
$this->symbolMetadata = $metadata;
return $this;
}
public function getSymbolMetadata() {
return $this->symbolMetadata;
}
public function setBlameURI($blame_uri) {
$this->blameURI = $blame_uri;
return $this;
}
public function getBlameURI() {
return $this->blameURI;
}
public function addCoverage($coverage) {
$this->coverage[] = array(
'data' => $coverage,
);
return $this;
}
public function getCoverage() {
return $this->coverage;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/exception/PhabricatorDocumentEngineParserException.php | src/applications/files/document/exception/PhabricatorDocumentEngineParserException.php | <?php
final class PhabricatorDocumentEngineParserException
extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/render/PhabricatorDocumentRenderingEngine.php | src/applications/files/document/render/PhabricatorDocumentRenderingEngine.php | <?php
abstract class PhabricatorDocumentRenderingEngine
extends Phobject {
private $request;
private $controller;
private $activeEngine;
private $ref;
final public function setRequest(AphrontRequest $request) {
$this->request = $request;
return $this;
}
final public function getRequest() {
if (!$this->request) {
throw new PhutilInvalidStateException('setRequest');
}
return $this->request;
}
final public function setController(PhabricatorController $controller) {
$this->controller = $controller;
return $this;
}
final public function getController() {
if (!$this->controller) {
throw new PhutilInvalidStateException('setController');
}
return $this->controller;
}
final protected function getActiveEngine() {
return $this->activeEngine;
}
final protected function getRef() {
return $this->ref;
}
final public function newDocumentView(PhabricatorDocumentRef $ref) {
$request = $this->getRequest();
$viewer = $request->getViewer();
$engines = PhabricatorDocumentEngine::getEnginesForRef($viewer, $ref);
$engine_key = $this->getSelectedDocumentEngineKey();
if (!isset($engines[$engine_key])) {
$engine_key = head_key($engines);
}
$engine = $engines[$engine_key];
$lines = $this->getSelectedLineRange();
if ($lines) {
$engine->setHighlightedLines(range($lines[0], $lines[1]));
}
$encode_setting = $request->getStr('encode');
if (phutil_nonempty_string($encode_setting)) {
$engine->setEncodingConfiguration($encode_setting);
}
$highlight_setting = $request->getStr('highlight');
if (phutil_nonempty_string($highlight_setting)) {
$engine->setHighlightingConfiguration($highlight_setting);
}
$blame_setting = ($request->getStr('blame') !== 'off');
$engine->setBlameConfiguration($blame_setting);
$views = array();
foreach ($engines as $candidate_key => $candidate_engine) {
$label = $candidate_engine->getViewAsLabel($ref);
if ($label === null) {
continue;
}
$view_uri = $this->newRefViewURI($ref, $candidate_engine);
$view_icon = $candidate_engine->getViewAsIconIcon($ref);
$view_color = $candidate_engine->getViewAsIconColor($ref);
$loading = $candidate_engine->newLoadingContent($ref);
$views[] = array(
'viewKey' => $candidate_engine->getDocumentEngineKey(),
'icon' => $view_icon,
'color' => $view_color,
'name' => $label,
'engineURI' => $this->newRefRenderURI($ref, $candidate_engine),
'viewURI' => $view_uri,
'loadingMarkup' => hsprintf('%s', $loading),
'canEncode' => $candidate_engine->canConfigureEncoding($ref),
'canHighlight' => $candidate_engine->canConfigureHighlighting($ref),
'canBlame' => $candidate_engine->canBlame($ref),
);
}
$viewport_id = celerity_generate_unique_node_id();
$control_id = celerity_generate_unique_node_id();
$icon = $engine->newDocumentIcon($ref);
$config = array(
'controlID' => $control_id,
);
$this->willStageRef($ref);
if ($engine->shouldRenderAsync($ref)) {
$content = $engine->newLoadingContent($ref);
$config['next'] = 'render';
} else {
$this->willRenderRef($ref);
$content = $engine->newDocument($ref);
if ($engine->canBlame($ref)) {
$config['next'] = 'blame';
}
}
Javelin::initBehavior('document-engine', $config);
$viewport = phutil_tag(
'div',
array(
'id' => $viewport_id,
),
$content);
$meta = array(
'viewportID' => $viewport_id,
'viewKey' => $engine->getDocumentEngineKey(),
'views' => $views,
'encode' => array(
'icon' => 'fa-font',
'name' => pht('Change Text Encoding...'),
'uri' => '/services/encoding/',
'value' => $encode_setting,
),
'highlight' => array(
'icon' => 'fa-lightbulb-o',
'name' => pht('Highlight As...'),
'uri' => '/services/highlight/',
'value' => $highlight_setting,
),
'blame' => array(
'icon' => 'fa-backward',
'hide' => pht('Hide Blame'),
'show' => pht('Show Blame'),
'uri' => $ref->getBlameURI(),
'enabled' => $blame_setting,
'value' => null,
),
'coverage' => array(
'labels' => array(
// TODO: Modularize this properly, see T13125.
array(
'C' => pht('Covered'),
'U' => pht('Not Covered'),
'N' => pht('Not Executable'),
'X' => pht('Not Reachable'),
),
),
),
);
$view_button = id(new PHUIButtonView())
->setTag('a')
->setText(pht('View Options'))
->setIcon('fa-file-image-o')
->setColor(PHUIButtonView::GREY)
->setID($control_id)
->setMetadata($meta)
->setDropdown(true)
->addSigil('document-engine-view-dropdown');
$header = id(new PHUIHeaderView())
->setHeaderIcon($icon)
->setHeader($ref->getName())
->addActionLink($view_button);
return id(new PHUIObjectBoxView())
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setHeader($header)
->appendChild($viewport);
}
final public function newRenderResponse(PhabricatorDocumentRef $ref) {
$this->willStageRef($ref);
$this->willRenderRef($ref);
$request = $this->getRequest();
$viewer = $request->getViewer();
$engines = PhabricatorDocumentEngine::getEnginesForRef($viewer, $ref);
$engine_key = $this->getSelectedDocumentEngineKey();
if (!isset($engines[$engine_key])) {
return $this->newErrorResponse(
pht(
'The engine ("%s") is unknown, or unable to render this document.',
$engine_key));
}
$engine = $engines[$engine_key];
$this->activeEngine = $engine;
$encode_setting = $request->getStr('encode');
if (phutil_nonempty_string($encode_setting)) {
$engine->setEncodingConfiguration($encode_setting);
}
$highlight_setting = $request->getStr('highlight');
if (phutil_nonempty_string($highlight_setting)) {
$engine->setHighlightingConfiguration($highlight_setting);
}
$blame_setting = ($request->getStr('blame') !== 'off');
$engine->setBlameConfiguration($blame_setting);
try {
$content = $engine->newDocument($ref);
} catch (Exception $ex) {
return $this->newErrorResponse($ex->getMessage());
}
return $this->newContentResponse($content);
}
public function newErrorResponse($message) {
$container = phutil_tag(
'div',
array(
'class' => 'document-engine-error',
),
array(
id(new PHUIIconView())
->setIcon('fa-exclamation-triangle red'),
' ',
$message,
));
return $this->newContentResponse($container);
}
private function newContentResponse($content) {
$request = $this->getRequest();
$viewer = $request->getViewer();
$controller = $this->getController();
if ($request->isAjax()) {
return id(new AphrontAjaxResponse())
->setContent(
array(
'markup' => hsprintf('%s', $content),
));
}
$crumbs = $this->newCrumbs();
$crumbs->setBorder(true);
$content_frame = id(new PHUIObjectBoxView())
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($content);
$page_frame = id(new PHUITwoColumnView())
->setFooter($content_frame);
$title = array();
$ref = $this->getRef();
if ($ref) {
$title = array(
$ref->getName(),
pht('Standalone'),
);
} else {
$title = pht('Document');
}
return $controller->newPage()
->setCrumbs($crumbs)
->setTitle($title)
->appendChild($page_frame);
}
protected function newCrumbs() {
$engine = $this->getActiveEngine();
$controller = $this->getController();
$crumbs = $controller->buildApplicationCrumbsForEditEngine();
$ref = $this->getRef();
$this->addApplicationCrumbs($crumbs, $ref);
if ($ref) {
$label = $engine->getViewAsLabel($ref);
if ($label) {
$crumbs->addTextCrumb($label);
}
}
return $crumbs;
}
public function getRefViewURI(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngine $engine) {
return $this->newRefViewURI($ref, $engine);
}
abstract protected function newRefViewURI(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngine $engine);
abstract protected function newRefRenderURI(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngine $engine);
protected function getSelectedDocumentEngineKey() {
return $this->getRequest()->getURIData('engineKey');
}
protected function getSelectedLineRange() {
return $this->getRequest()->getURILineRange('lines', 1000);
}
protected function addApplicationCrumbs(
PHUICrumbsView $crumbs,
PhabricatorDocumentRef $ref = null) {
return;
}
protected function willStageRef(PhabricatorDocumentRef $ref) {
return;
}
protected function willRenderRef(PhabricatorDocumentRef $ref) {
return;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/document/render/PhabricatorFileDocumentRenderingEngine.php | src/applications/files/document/render/PhabricatorFileDocumentRenderingEngine.php | <?php
final class PhabricatorFileDocumentRenderingEngine
extends PhabricatorDocumentRenderingEngine {
protected function newRefViewURI(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngine $engine) {
$file = $ref->getFile();
$engine_key = $engine->getDocumentEngineKey();
return urisprintf(
'/file/view/%d/%s/',
$file->getID(),
$engine_key);
}
protected function newRefRenderURI(
PhabricatorDocumentRef $ref,
PhabricatorDocumentEngine $engine) {
$file = $ref->getFile();
if (!$file) {
throw new PhutilMethodNotImplementedException();
}
$engine_key = $engine->getDocumentEngineKey();
$file_phid = $file->getPHID();
return urisprintf(
'/file/document/%s/%s/',
$engine_key,
$file_phid);
}
protected function addApplicationCrumbs(
PHUICrumbsView $crumbs,
PhabricatorDocumentRef $ref = null) {
if ($ref) {
$file = $ref->getFile();
if ($file) {
$crumbs->addTextCrumb($file->getMonogram(), $file->getInfoURI());
}
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | <?php
/**
* Local disk storage engine. Keeps files on local disk. This engine is easy
* to set up, but it doesn't work if you have multiple web frontends!
*
* @task internal Internals
*/
final class PhabricatorLocalDiskFileStorageEngine
extends PhabricatorFileStorageEngine {
/* -( Engine Metadata )---------------------------------------------------- */
/**
* This engine identifies as "local-disk".
*/
public function getEngineIdentifier() {
return 'local-disk';
}
public function getEnginePriority() {
return 5;
}
public function canWriteFiles() {
$path = PhabricatorEnv::getEnvConfig('storage.local-disk.path');
$path = phutil_string_cast($path);
return (bool)strlen($path);
}
/* -( Managing File Data )------------------------------------------------- */
/**
* Write the file data to local disk. Returns the relative path as the
* file data handle.
* @task impl
*/
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;
}
/**
* Read the file data off local disk.
* @task impl
*/
public function readFile($handle) {
$path = $this->getLocalDiskFileStorageFullPath($handle);
return Filesystem::readFile($path);
}
/**
* Deletes the file from local disk, if it exists.
* @task impl
*/
public function deleteFile($handle) {
$path = $this->getLocalDiskFileStorageFullPath($handle);
if (Filesystem::pathExists($path)) {
AphrontWriteGuard::willWrite();
Filesystem::remove($path);
}
}
/* -( Internals )---------------------------------------------------------- */
/**
* Get the configured local disk path for file storage.
*
* @return string Absolute path to somewhere that files can be stored.
* @task internal
*/
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, '/');
}
/**
* Convert a handle into an absolute local disk path.
*
* @param string File data handle.
* @return string Absolute path to the corresponding file.
* @task internal
*/
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;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | <?php
final class PhabricatorChunkedFileStorageEngine
extends PhabricatorFileStorageEngine {
public function getEngineIdentifier() {
return 'chunks';
}
public function getEnginePriority() {
return 60000;
}
/**
* We can write chunks if we have at least one valid storage engine
* underneath us.
*/
public function canWriteFiles() {
return (bool)$this->getWritableEngine();
}
public function hasFilesizeLimit() {
return false;
}
public function isChunkEngine() {
return true;
}
public function writeFile($data, array $params) {
// The chunk engine does not support direct writes.
throw new PhutilMethodNotImplementedException();
}
public function readFile($handle) {
// This is inefficient, but makes the API work as expected.
$chunks = $this->loadAllChunks($handle, true);
$buffer = '';
foreach ($chunks as $chunk) {
$data_file = $chunk->getDataFile();
if (!$data_file) {
throw new Exception(pht('This file data is incomplete!'));
}
$buffer .= $chunk->getDataFile()->loadFileData();
}
return $buffer;
}
public function deleteFile($handle) {
$engine = new PhabricatorDestructionEngine();
$chunks = $this->loadAllChunks($handle, true);
foreach ($chunks as $chunk) {
$engine->destroyObject($chunk);
}
}
private function loadAllChunks($handle, $need_files) {
$chunks = id(new PhabricatorFileChunkQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withChunkHandles(array($handle))
->needDataFiles($need_files)
->execute();
$chunks = msort($chunks, 'getByteStart');
return $chunks;
}
/**
* 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 Viewing user.
* @param string Claimed file hash.
* @return string Rehashed file hash.
*/
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);
}
public static function getChunkedHashForInput($input) {
$rehash = PhabricatorHash::weakDigest($input);
// Add a suffix to identify this as a chunk hash.
$rehash = substr($rehash, 0, -2).'-C';
return $rehash;
}
public function allocateChunks($length, array $properties) {
$file = PhabricatorFile::newChunkedFile($this, $length, $properties);
$chunk_size = $this->getChunkSize();
$handle = $file->getStorageHandle();
$chunks = array();
for ($ii = 0; $ii < $length; $ii += $chunk_size) {
$chunks[] = PhabricatorFileChunk::initializeNewChunk(
$handle,
$ii,
min($ii + $chunk_size, $length));
}
$file->openTransaction();
foreach ($chunks as $chunk) {
$chunk->save();
}
$file->saveAndIndex();
$file->saveTransaction();
return $file;
}
/**
* 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.
*/
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;
}
public function getChunkSize() {
return (4 * 1024 * 1024);
}
public function getRawFileDataIterator(
PhabricatorFile $file,
$begin,
$end,
PhabricatorFileStorageFormat $format) {
// NOTE: It is currently impossible for files stored with the chunk
// engine to have their own formatting (instead, the individual chunks
// are formatted), so we ignore the format object.
$chunks = id(new PhabricatorFileChunkQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withChunkHandles(array($file->getStorageHandle()))
->withByteRange($begin, $end)
->needDataFiles(true)
->execute();
return new PhabricatorFileChunkIterator($chunks, $begin, $end);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engine/PhabricatorTestStorageEngine.php | src/applications/files/engine/PhabricatorTestStorageEngine.php | <?php
/**
* Test storage engine. Does not actually store files. Used for unit tests.
*/
final class PhabricatorTestStorageEngine
extends PhabricatorFileStorageEngine {
private static $storage = array();
private static $nextHandle = 1;
public function getEngineIdentifier() {
return 'unit-test';
}
public function getEnginePriority() {
return 1000;
}
public function isTestEngine() {
return true;
}
public function canWriteFiles() {
return true;
}
public function hasFilesizeLimit() {
return false;
}
public function writeFile($data, array $params) {
AphrontWriteGuard::willWrite();
self::$storage[self::$nextHandle] = $data;
return (string)self::$nextHandle++;
}
public function readFile($handle) {
if (isset(self::$storage[$handle])) {
return self::$storage[$handle];
}
throw new Exception(pht("No such file with handle '%s'!", $handle));
}
public function deleteFile($handle) {
AphrontWriteGuard::willWrite();
unset(self::$storage[$handle]);
}
public function tamperWithFile($handle, $data) {
self::$storage[$handle] = $data;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engine/PhabricatorFileChunkIterator.php | src/applications/files/engine/PhabricatorFileChunkIterator.php | <?php
final class PhabricatorFileChunkIterator
extends Phobject
implements Iterator {
private $chunks;
private $cursor;
private $begin;
private $end;
private $data;
public function __construct(array $chunks, $begin = null, $end = null) {
$chunks = msort($chunks, 'getByteStart');
$this->chunks = $chunks;
if ($begin !== null) {
foreach ($chunks as $key => $chunk) {
if ($chunk->getByteEnd() >= $begin) {
unset($chunks[$key]);
}
break;
}
$this->begin = $begin;
}
if ($end !== null) {
foreach ($chunks as $key => $chunk) {
if ($chunk->getByteStart() <= $end) {
unset($chunks[$key]);
}
}
$this->end = $end;
}
}
public function current() {
$chunk = head($this->chunks);
$data = $chunk->getDataFile()->loadFileData();
if ($this->end !== null) {
if ($chunk->getByteEnd() > $this->end) {
$data = substr($data, 0, ($this->end - $chunk->getByteStart()));
}
}
if ($this->begin !== null) {
if ($chunk->getByteStart() < $this->begin) {
$data = substr($data, ($this->begin - $chunk->getByteStart()));
}
}
return $data;
}
public function key() {
return head_key($this->chunks);
}
public function next() {
unset($this->chunks[$this->key()]);
}
public function rewind() {
return;
}
public function valid() {
return (count($this->chunks) > 0);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engine/PhabricatorS3FileStorageEngine.php | src/applications/files/engine/PhabricatorS3FileStorageEngine.php | <?php
/**
* Amazon S3 file storage engine. This engine scales well but is relatively
* high-latency since data has to be pulled off S3.
*
* @task internal Internals
*/
final class PhabricatorS3FileStorageEngine
extends PhabricatorFileStorageEngine {
/* -( Engine Metadata )---------------------------------------------------- */
/**
* This engine identifies as `amazon-s3`.
*/
public function getEngineIdentifier() {
return 'amazon-s3';
}
public function getEnginePriority() {
return 100;
}
public function canWriteFiles() {
$bucket = PhabricatorEnv::getEnvConfig('storage.s3.bucket');
$access_key = PhabricatorEnv::getEnvConfig('amazon-s3.access-key');
$secret_key = PhabricatorEnv::getEnvConfig('amazon-s3.secret-key');
$endpoint = PhabricatorEnv::getEnvConfig('amazon-s3.endpoint');
$region = PhabricatorEnv::getEnvConfig('amazon-s3.region');
return ($bucket !== null && strlen($bucket) &&
$access_key !== null && strlen($access_key) &&
$secret_key !== null && strlen($secret_key) &&
$endpoint !== null && strlen($endpoint) &&
$region !== null && strlen($region));
}
/* -( Managing File Data )------------------------------------------------- */
/**
* Writes file data into Amazon S3.
*/
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 ($instance_name !== null && strlen($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;
}
/**
* Load a stored blob from Amazon S3.
*/
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;
}
/**
* Delete a blob from Amazon S3.
*/
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());
}
/* -( Internals )---------------------------------------------------------- */
/**
* Retrieve the S3 bucket name.
*
* @task internal
*/
private function getBucketName() {
$bucket = PhabricatorEnv::getEnvConfig('storage.s3.bucket');
if (!$bucket) {
throw new PhabricatorFileStorageConfigurationException(
pht(
"No '%s' specified!",
'storage.s3.bucket'));
}
return $bucket;
}
/**
* Create a new S3 API object.
*
* @task internal
*/
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());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | src/applications/files/engine/PhabricatorMySQLFileStorageEngine.php | <?php
/**
* MySQL blob storage engine. This engine is the easiest to set up but doesn't
* scale very well.
*
* It uses the @{class:PhabricatorFileStorageBlob} to actually access the
* underlying database table.
*
* @task internal Internals
*/
final class PhabricatorMySQLFileStorageEngine
extends PhabricatorFileStorageEngine {
/* -( Engine Metadata )---------------------------------------------------- */
/**
* For historical reasons, this engine identifies as "blob".
*/
public function getEngineIdentifier() {
return 'blob';
}
public function getEnginePriority() {
return 1;
}
public function canWriteFiles() {
return ($this->getFilesizeLimit() > 0);
}
public function hasFilesizeLimit() {
return true;
}
public function getFilesizeLimit() {
return PhabricatorEnv::getEnvConfig('storage.mysql-engine.max-size');
}
/* -( Managing File Data )------------------------------------------------- */
/**
* Write file data into the big blob store table in MySQL. Returns the row
* ID as the file data handle.
*/
public function writeFile($data, array $params) {
$blob = new PhabricatorFileStorageBlob();
$blob->setData($data);
$blob->save();
return $blob->getID();
}
/**
* Load a stored blob from MySQL.
*/
public function readFile($handle) {
return $this->loadFromMySQLFileStorage($handle)->getData();
}
/**
* Delete a blob from MySQL.
*/
public function deleteFile($handle) {
$this->loadFromMySQLFileStorage($handle)->delete();
}
/* -( Internals )---------------------------------------------------------- */
/**
* Load the Lisk object that stores the file data for a handle.
*
* @param string File data handle.
* @return PhabricatorFileStorageBlob Data DAO.
* @task internal
*/
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;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engine/PhabricatorFileStorageEngine.php | src/applications/files/engine/PhabricatorFileStorageEngine.php | <?php
/**
* Defines a storage engine which can write file data somewhere (like a
* database, local disk, Amazon S3, the A:\ drive, or a custom filer) and
* retrieve it later.
*
* You can extend this class to provide new file storage backends.
*
* For more information, see @{article:File Storage Technical Documentation}.
*
* @task construct Constructing an Engine
* @task meta Engine Metadata
* @task file Managing File Data
* @task load Loading Storage Engines
*/
abstract class PhabricatorFileStorageEngine extends Phobject {
const HMAC_INTEGRITY = 'file.integrity';
/**
* Construct a new storage engine.
*
* @task construct
*/
final public function __construct() {
// <empty>
}
/* -( Engine Metadata )---------------------------------------------------- */
/**
* Return a unique, nonempty string which identifies this storage engine.
* This is used to look up the storage engine when files needs to be read or
* deleted. For instance, if you store files by giving them to a duck for
* safe keeping in his nest down by the pond, you might return 'duck' from
* this method.
*
* @return string Unique string for this engine, max length 32.
* @task meta
*/
abstract public function getEngineIdentifier();
/**
* Prioritize this engine relative to other engines.
*
* Engines with a smaller priority number get an opportunity to write files
* first. Generally, lower-latency filestores should have lower priority
* numbers, and higher-latency filestores should have higher priority
* numbers. Setting priority to approximately the number of milliseconds of
* read latency will generally produce reasonable results.
*
* In conjunction with filesize limits, the goal is to store small files like
* profile images, thumbnails, and text snippets in lower-latency engines,
* and store large files in higher-capacity engines.
*
* @return float Engine priority.
* @task meta
*/
abstract public function getEnginePriority();
/**
* Return `true` if the engine is currently writable.
*
* Engines that are disabled or missing configuration should return `false`
* to prevent new writes. If writes were made with this engine in the past,
* the application may still try to perform reads.
*
* @return bool True if this engine can support new writes.
* @task meta
*/
abstract public function canWriteFiles();
/**
* 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
*/
public function hasFilesizeLimit() {
return true;
}
/**
* 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
*/
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);
}
/**
* 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
*/
public function isTestEngine() {
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
*/
public function isChunkEngine() {
return false;
}
/* -( Managing File Data )------------------------------------------------- */
/**
* Write file data to the backing storage and return a handle which can later
* be used to read or delete it. For example, if the backing storage is local
* disk, the handle could be the path to the file.
*
* The caller will provide a $params array, which may be empty or may have
* some metadata keys (like "name" and "author") in it. You should be prepared
* to handle writes which specify no metadata, but might want to optionally
* use some keys in this array for debugging or logging purposes. This is
* the same dictionary passed to @{method:PhabricatorFile::newFromFileData},
* so you could conceivably do custom things with it.
*
* If you are unable to write for whatever reason (e.g., the disk is full),
* throw an exception. If there are other satisfactory but less-preferred
* storage engines available, they will be tried.
*
* @param string The file data to write.
* @param array File metadata (name, author), if available.
* @return string Unique string which identifies the stored file, max length
* 255.
* @task file
*/
abstract public function writeFile($data, array $params);
/**
* Read the contents of a file previously written by @{method:writeFile}.
*
* @param string The handle returned from @{method:writeFile} when the
* file was written.
* @return string File contents.
* @task file
*/
abstract public function readFile($handle);
/**
* Delete the data for a file previously written by @{method:writeFile}.
*
* @param string The handle returned from @{method:writeFile} when the
* file was written.
* @return void
* @task file
*/
abstract public function deleteFile($handle);
/* -( Loading Storage Engines )-------------------------------------------- */
/**
* 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 File size in bytes.
* @task load
*/
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;
}
/**
* @task load
*/
public static function loadAllEngines() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getEngineIdentifier')
->setSortMethod('getEnginePriority')
->execute();
}
/**
* @task load
*/
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
*/
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
*/
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;
}
/**
* 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.
*/
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();
}
public function getRawFileDataIterator(
PhabricatorFile $file,
$begin,
$end,
PhabricatorFileStorageFormat $format) {
$formatted_data = $this->readFile($file->getStorageHandle());
$known_integrity = $file->getIntegrityHash();
if ($known_integrity !== null) {
$new_integrity = $this->newIntegrityHash($formatted_data, $format);
if (!phutil_hashes_are_identical($known_integrity, $new_integrity)) {
throw new PhabricatorFileIntegrityException(
pht(
'File data integrity check failed. Dark forces have corrupted '.
'or tampered with this file. The file data can not be read.'));
}
}
$formatted_data = array($formatted_data);
$data = '';
$format_iterator = $format->newReadIterator($formatted_data);
foreach ($format_iterator as $raw_chunk) {
$data .= $raw_chunk;
}
if ($begin !== null && $end !== null) {
$data = substr($data, $begin, ($end - $begin));
} else if ($begin !== null) {
$data = substr($data, $begin);
} else if ($end !== null) {
$data = substr($data, 0, $end);
}
return array($data);
}
public function newIntegrityHash(
$data,
PhabricatorFileStorageFormat $format) {
$hmac_name = self::HMAC_INTEGRITY;
$data_hash = PhabricatorHash::digestWithNamedKey($data, $hmac_name);
$format_hash = $format->newFormatIntegrityHash();
$full_hash = "{$data_hash}/{$format_hash}";
return PhabricatorHash::digestWithNamedKey($full_hash, $hmac_name);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engine/__tests__/PhabricatorFileStorageEngineTestCase.php | src/applications/files/engine/__tests__/PhabricatorFileStorageEngineTestCase.php | <?php
final class PhabricatorFileStorageEngineTestCase extends PhabricatorTestCase {
public function testLoadAllEngines() {
PhabricatorFileStorageEngine::loadAllEngines();
$this->assertTrue(true);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/typeahead/PhabricatorIconDatasource.php | src/applications/files/typeahead/PhabricatorIconDatasource.php | <?php
final class PhabricatorIconDatasource extends PhabricatorTypeaheadDatasource {
public function getPlaceholderText() {
return pht('Type an icon name...');
}
public function getBrowseTitle() {
return pht('Browse Icons');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorFilesApplication';
}
public function loadResults() {
$results = $this->buildResults();
return $this->filterResultsAgainstTokens($results);
}
protected function renderSpecialTokens(array $values) {
return $this->renderTokensFromResults($this->buildResults(), $values);
}
private function buildResults() {
$raw_query = $this->getRawQuery();
$icons = id(new PHUIIconView())->getIcons();
$results = array();
foreach ($icons as $icon) {
$display_name = str_replace('fa-', '', $icon);
$result = id(new PhabricatorTypeaheadResult())
->setPHID($icon)
->setName($icon)
->setIcon($icon)
->setDisplayname($display_name)
->addAttribute($icon);
$results[$icon] = $result;
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/capability/FilesDefaultViewCapability.php | src/applications/files/capability/FilesDefaultViewCapability.php | <?php
final class FilesDefaultViewCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'files.default.view';
public function getCapabilityName() {
return pht('Default View Policy');
}
public function shouldAllowPublicPolicySetting() {
return true;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/constants/FileTypeIcon.php | src/applications/files/constants/FileTypeIcon.php | <?php
final class FileTypeIcon extends Phobject {
public static function getFileIcon($filename) {
$path_info = pathinfo($filename);
$extension = idx($path_info, 'extension');
switch ($extension) {
case 'psd':
case 'ai':
$icon = 'fa-file-image-o';
break;
case 'conf':
$icon = 'fa-wrench';
break;
case 'wav':
case 'mp3':
case 'aiff':
$icon = 'fa-file-sound-o';
break;
case 'm4v':
case 'mov':
$icon = 'fa-file-movie-o';
break;
case 'sql':
case 'db':
$icon = 'fa-database';
break;
case 'xls':
case 'csv':
$icon = 'fa-file-excel-o';
break;
case 'ics':
$icon = 'fa-calendar';
break;
case 'zip':
case 'tar':
case 'bz':
case 'tgz':
case 'gz':
$icon = 'fa-file-archive-o';
break;
case 'png':
case 'jpg':
case 'bmp':
case 'gif':
$icon = 'fa-file-picture-o';
break;
case 'txt':
$icon = 'fa-file-text-o';
break;
case 'doc':
case 'docx':
$icon = 'fa-file-word-o';
break;
case 'pdf':
$icon = 'fa-file-pdf-o';
break;
default:
$icon = 'fa-file-text-o';
break;
}
return $icon;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/markup/PhabricatorEmbedFileRemarkupRule.php | src/applications/files/markup/PhabricatorEmbedFileRemarkupRule.php | <?php
final class PhabricatorEmbedFileRemarkupRule
extends PhabricatorObjectRemarkupRule {
private $viewer;
const KEY_ATTACH_INTENT_FILE_PHIDS = 'files.attach-intent';
protected function getObjectNamePrefix() {
return 'F';
}
protected function loadObjects(array $ids) {
$engine = $this->getEngine();
$this->viewer = $engine->getConfig('viewer');
$objects = id(new PhabricatorFileQuery())
->setViewer($this->viewer)
->withIDs($ids)
->needTransforms(
array(
PhabricatorFileThumbnailTransform::TRANSFORM_PREVIEW,
))
->execute();
$objects = mpull($objects, null, 'getID');
// Identify files embedded in the block with "attachment intent", i.e.
// those files which the user appears to want to attach to the object.
// Files referenced inside quoted blocks are not considered to have this
// attachment intent.
$metadata_key = self::KEY_RULE_OBJECT.'.'.$this->getObjectNamePrefix();
$metadata = $engine->getTextMetadata($metadata_key, array());
$attach_key = self::KEY_ATTACH_INTENT_FILE_PHIDS;
$attach_phids = $engine->getTextMetadata($attach_key, array());
foreach ($metadata as $item) {
// If this reference was inside a quoted block, don't count it. Quoting
// someone else doesn't establish an intent to attach a file.
$depth = idx($item, 'quote.depth');
if ($depth > 0) {
continue;
}
$id = $item['id'];
$file = idx($objects, $id);
if (!$file) {
continue;
}
$attach_phids[] = $file->getPHID();
}
$attach_phids = array_fuse($attach_phids);
$attach_phids = array_keys($attach_phids);
$engine->setTextMetadata($attach_key, $attach_phids);
return $objects;
}
protected function renderObjectEmbed(
$object,
PhabricatorObjectHandle $handle,
$options) {
$options = $this->getFileOptions($options) + array(
'name' => $object->getName(),
);
$is_viewable_image = $object->isViewableImage();
$is_audio = $object->isAudio();
$is_video = $object->isVideo();
$force_link = ($options['layout'] == 'link');
// If a file is both audio and video, as with "application/ogg" by default,
// render it as video but allow the user to specify `media=audio` if they
// want to force it to render as audio.
if ($is_audio && $is_video) {
$media = $options['media'];
if ($media == 'audio') {
$is_video = false;
} else {
$is_audio = false;
}
}
$options['viewable'] = ($is_viewable_image || $is_audio || $is_video);
if ($is_viewable_image && !$force_link) {
return $this->renderImageFile($object, $handle, $options);
} else if ($is_video && !$force_link) {
return $this->renderVideoFile($object, $handle, $options);
} else if ($is_audio && !$force_link) {
return $this->renderAudioFile($object, $handle, $options);
} else {
return $this->renderFileLink($object, $handle, $options);
}
}
private function getFileOptions($option_string) {
$options = array(
'size' => null,
'layout' => 'left',
'float' => false,
'width' => null,
'height' => null,
'alt' => null,
'media' => null,
'autoplay' => null,
'loop' => null,
);
if ($option_string) {
$option_string = trim($option_string, ', ');
$parser = new PhutilSimpleOptions();
$options = $parser->parse($option_string) + $options;
}
return $options;
}
private function renderImageFile(
PhabricatorFile $file,
PhabricatorObjectHandle $handle,
array $options) {
require_celerity_resource('phui-lightbox-css');
$attrs = array();
$image_class = 'phabricator-remarkup-embed-image';
$use_size = true;
if (!$options['size']) {
$width = $this->parseDimension($options['width']);
$height = $this->parseDimension($options['height']);
if ($width || $height) {
$use_size = false;
$attrs += array(
'src' => $file->getBestURI(),
'width' => $width,
'height' => $height,
);
}
}
if ($use_size) {
switch ((string)$options['size']) {
case 'full':
$attrs += array(
'src' => $file->getBestURI(),
'height' => $file->getImageHeight(),
'width' => $file->getImageWidth(),
);
$image_class = 'phabricator-remarkup-embed-image-full';
break;
// Displays "full" in normal Remarkup, "wide" in Documents
case 'wide':
$attrs += array(
'src' => $file->getBestURI(),
'width' => $file->getImageWidth(),
);
$image_class = 'phabricator-remarkup-embed-image-wide';
break;
case 'thumb':
default:
$preview_key = PhabricatorFileThumbnailTransform::TRANSFORM_PREVIEW;
$xform = PhabricatorFileTransform::getTransformByKey($preview_key);
$existing_xform = $file->getTransform($preview_key);
if ($existing_xform) {
$xform_uri = $existing_xform->getCDNURI('data');
} else {
$xform_uri = $file->getURIForTransform($xform);
}
$attrs['src'] = $xform_uri;
$dimensions = $xform->getTransformedDimensions($file);
if ($dimensions) {
list($x, $y) = $dimensions;
$attrs['width'] = $x;
$attrs['height'] = $y;
}
break;
}
}
$alt = null;
if (isset($options['alt'])) {
$alt = $options['alt'];
}
if ($alt === null || !strlen($alt)) {
$alt = $file->getAltText();
}
$attrs['alt'] = $alt;
$img = phutil_tag('img', $attrs);
$embed = javelin_tag(
'a',
array(
'href' => $file->getBestURI(),
'class' => $image_class,
'sigil' => 'lightboxable',
'meta' => array(
'phid' => $file->getPHID(),
'uri' => $file->getBestURI(),
'dUri' => $file->getDownloadURI(),
'alt' => $alt,
'viewable' => true,
'monogram' => $file->getMonogram(),
),
),
$img);
switch ($options['layout']) {
case 'right':
case 'center':
case 'inline':
case 'left':
$layout_class = 'phabricator-remarkup-embed-layout-'.$options['layout'];
break;
default:
$layout_class = 'phabricator-remarkup-embed-layout-left';
break;
}
if ($options['float']) {
switch ($options['layout']) {
case 'center':
case 'inline':
break;
case 'right':
$layout_class .= ' phabricator-remarkup-embed-float-right';
break;
case 'left':
default:
$layout_class .= ' phabricator-remarkup-embed-float-left';
break;
}
}
return phutil_tag(
($options['layout'] == 'inline' ? 'span' : 'div'),
array(
'class' => $layout_class,
),
$embed);
}
private function renderAudioFile(
PhabricatorFile $file,
PhabricatorObjectHandle $handle,
array $options) {
return $this->renderMediaFile('audio', $file, $handle, $options);
}
private function renderVideoFile(
PhabricatorFile $file,
PhabricatorObjectHandle $handle,
array $options) {
return $this->renderMediaFile('video', $file, $handle, $options);
}
private function renderMediaFile(
$tag,
PhabricatorFile $file,
PhabricatorObjectHandle $handle,
array $options) {
$is_video = ($tag == 'video');
if (idx($options, 'autoplay')) {
$preload = 'auto';
$autoplay = 'autoplay';
} else {
// If we don't preload video, the user can't see the first frame and
// has no clue what they're looking at, so always preload.
if ($is_video) {
$preload = 'auto';
} else {
$preload = 'none';
}
$autoplay = null;
}
// Rendering contexts like feed can disable autoplay.
$engine = $this->getEngine();
if ($engine->getConfig('autoplay.disable')) {
$autoplay = null;
}
if ($is_video) {
// See T13135. Chrome refuses to play videos with type "video/quicktime",
// even though it may actually be able to play them. The least awful fix
// based on available information is to simply omit the "type" attribute
// from `<source />` tags. This causes Chrome to try to play the video
// and realize it can, and does not appear to produce any bad behavior in
// any other browser.
$mime_type = null;
} else {
$mime_type = $file->getMimeType();
}
return $this->newTag(
$tag,
array(
'controls' => 'controls',
'preload' => $preload,
'autoplay' => $autoplay,
'loop' => idx($options, 'loop') ? 'loop' : null,
'alt' => $options['alt'],
'class' => 'phabricator-media',
),
$this->newTag(
'source',
array(
'src' => $file->getBestURI(),
'type' => $mime_type,
)));
}
private function renderFileLink(
PhabricatorFile $file,
PhabricatorObjectHandle $handle,
array $options) {
return id(new PhabricatorFileLinkView())
->setViewer($this->viewer)
->setFilePHID($file->getPHID())
->setFileName($this->assertFlatText($options['name']))
->setFileDownloadURI($file->getDownloadURI())
->setFileViewURI($file->getBestURI())
->setFileViewable((bool)$options['viewable'])
->setFileSize(phutil_format_bytes($file->getByteSize()))
->setFileMonogram($file->getMonogram());
}
private function parseDimension($string) {
if ($string === null || !strlen($string)) {
return null;
}
$string = trim($string);
if (preg_match('/^(?:\d*\\.)?\d+%?$/', $string)) {
return $string;
}
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/markup/PhabricatorImageRemarkupRule.php | src/applications/files/markup/PhabricatorImageRemarkupRule.php | <?php
final class PhabricatorImageRemarkupRule extends PhutilRemarkupRule {
const KEY_RULE_EXTERNAL_IMAGE = 'rule.external-image';
public function getPriority() {
return 200.0;
}
public function apply($text) {
return preg_replace_callback(
'@{(image|img) ((?:[^}\\\\]+|\\\\.)*)}@m',
array($this, 'markupImage'),
$text);
}
public function markupImage(array $matches) {
if (!$this->isFlatText($matches[0])) {
return $matches[0];
}
$args = array();
$defaults = array(
'uri' => null,
'alt' => null,
'width' => null,
'height' => null,
);
$trimmed_match = trim($matches[2]);
if ($this->isURI($trimmed_match)) {
$args['uri'] = $trimmed_match;
} else {
$parser = new PhutilSimpleOptions();
$keys = $parser->parse($trimmed_match);
$uri_key = '';
foreach (array('src', 'uri', 'url') as $key) {
if (array_key_exists($key, $keys)) {
$uri_key = $key;
}
}
if ($uri_key) {
$args['uri'] = $keys[$uri_key];
}
$args += $keys;
}
$args += $defaults;
$uri_arg = $args['uri'];
if ($uri_arg === null || !strlen($uri_arg)) {
return $matches[0];
}
// Make sure this is something that looks roughly like a real URI. We'll
// validate it more carefully before proxying it, but if whatever the user
// has typed isn't even close, just decline to activate the rule behavior.
try {
$uri = new PhutilURI($uri_arg);
if ($uri->getProtocol() === null || !strlen($uri->getProtocol())) {
return $matches[0];
}
$args['uri'] = (string)$uri;
} catch (Exception $ex) {
return $matches[0];
}
$engine = $this->getEngine();
$metadata_key = self::KEY_RULE_EXTERNAL_IMAGE;
$metadata = $engine->getTextMetadata($metadata_key, array());
$token = $engine->storeText('<img>');
$metadata[] = array(
'token' => $token,
'args' => $args,
);
$engine->setTextMetadata($metadata_key, $metadata);
return $token;
}
public function didMarkupText() {
$engine = $this->getEngine();
$metadata_key = self::KEY_RULE_EXTERNAL_IMAGE;
$images = $engine->getTextMetadata($metadata_key, array());
$engine->setTextMetadata($metadata_key, array());
if (!$images) {
return;
}
// Look for images we've already successfully fetched that aren't about
// to get eaten by the GC. For any we find, we can just emit a normal
// "<img />" tag pointing directly to the file.
// For files which we don't hit in the cache, we emit a placeholder
// instead and use AJAX to actually perform the fetch.
$digests = array();
foreach ($images as $image) {
$uri = $image['args']['uri'];
$digests[] = PhabricatorHash::digestForIndex($uri);
}
$caches = id(new PhabricatorFileExternalRequest())->loadAllWhere(
'uriIndex IN (%Ls) AND isSuccessful = 1 AND ttl > %d',
$digests,
PhabricatorTime::getNow() + phutil_units('1 hour in seconds'));
$file_phids = array();
foreach ($caches as $cache) {
$file_phids[$cache->getFilePHID()] = $cache->getURI();
}
$file_map = array();
if ($file_phids) {
$files = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs(array_keys($file_phids))
->execute();
foreach ($files as $file) {
$phid = $file->getPHID();
$file_remote_uri = $file_phids[$phid];
$file_view_uri = $file->getViewURI();
$file_map[$file_remote_uri] = $file_view_uri;
}
}
foreach ($images as $image) {
$args = $image['args'];
$uri = $args['uri'];
$direct_uri = idx($file_map, $uri);
if ($direct_uri) {
$img = phutil_tag(
'img',
array(
'src' => $direct_uri,
'alt' => $args['alt'],
'width' => $args['width'],
'height' => $args['height'],
));
} else {
$src_uri = id(new PhutilURI('/file/imageproxy/'))
->replaceQueryParam('uri', $uri);
$img = id(new PHUIRemarkupImageView())
->setURI($src_uri)
->setAlt($args['alt'])
->setWidth($args['width'])
->setHeight($args['height']);
}
$engine->overwriteStoredText($image['token'], $img);
}
}
private function isURI($uri_string) {
// Very simple check to make sure it starts with either http or https.
// If it does, we'll try to treat it like a valid URI
return preg_match('~^https?\:\/\/.*\z~i', $uri_string);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/PhabricatorOAuthServer.php | src/applications/oauthserver/PhabricatorOAuthServer.php | <?php
/**
* Implements core OAuth 2.0 Server logic.
*
* This class should be used behind business logic that parses input to
* determine pertinent @{class:PhabricatorUser} $user,
* @{class:PhabricatorOAuthServerClient} $client(s),
* @{class:PhabricatorOAuthServerAuthorizationCode} $code(s), and.
* @{class:PhabricatorOAuthServerAccessToken} $token(s).
*
* For an OAuth 2.0 server, there are two main steps:
*
* 1) Authorization - the user authorizes a given client to access the data
* the OAuth 2.0 server protects. Once this is achieved / if it has
* been achived already, the OAuth server sends the client an authorization
* code.
* 2) Access Token - the client should send the authorization code received in
* step 1 along with its id and secret to the OAuth server to receive an
* access token. This access token can later be used to access Phabricator
* data on behalf of the user.
*
* @task auth Authorizing @{class:PhabricatorOAuthServerClient}s and
* generating @{class:PhabricatorOAuthServerAuthorizationCode}s
* @task token Validating @{class:PhabricatorOAuthServerAuthorizationCode}s
* and generating @{class:PhabricatorOAuthServerAccessToken}s
* @task internal Internals
*/
final class PhabricatorOAuthServer extends Phobject {
const AUTHORIZATION_CODE_TIMEOUT = 300;
private $user;
private $client;
private function getUser() {
if (!$this->user) {
throw new PhutilInvalidStateException('setUser');
}
return $this->user;
}
public function setUser(PhabricatorUser $user) {
$this->user = $user;
return $this;
}
private function getClient() {
if (!$this->client) {
throw new PhutilInvalidStateException('setClient');
}
return $this->client;
}
public function setClient(PhabricatorOAuthServerClient $client) {
$this->client = $client;
return $this;
}
/**
* @task auth
* @return tuple <bool hasAuthorized, ClientAuthorization or null>
*/
public function userHasAuthorizedClient(array $scope) {
$authorization = id(new PhabricatorOAuthClientAuthorization())
->loadOneWhere(
'userPHID = %s AND clientPHID = %s',
$this->getUser()->getPHID(),
$this->getClient()->getPHID());
if (empty($authorization)) {
return array(false, null);
}
if ($scope) {
$missing_scope = array_diff_key($scope, $authorization->getScope());
} else {
$missing_scope = false;
}
if ($missing_scope) {
return array(false, $authorization);
}
return array(true, $authorization);
}
/**
* @task auth
*/
public function authorizeClient(array $scope) {
$authorization = new PhabricatorOAuthClientAuthorization();
$authorization->setUserPHID($this->getUser()->getPHID());
$authorization->setClientPHID($this->getClient()->getPHID());
$authorization->setScope($scope);
$authorization->save();
return $authorization;
}
/**
* @task auth
*/
public function generateAuthorizationCode(PhutilURI $redirect_uri) {
$code = Filesystem::readRandomCharacters(32);
$client = $this->getClient();
$authorization_code = new PhabricatorOAuthServerAuthorizationCode();
$authorization_code->setCode($code);
$authorization_code->setClientPHID($client->getPHID());
$authorization_code->setClientSecret($client->getSecret());
$authorization_code->setUserPHID($this->getUser()->getPHID());
$authorization_code->setRedirectURI((string)$redirect_uri);
$authorization_code->save();
return $authorization_code;
}
/**
* @task token
*/
public function generateAccessToken() {
$token = Filesystem::readRandomCharacters(32);
$access_token = new PhabricatorOAuthServerAccessToken();
$access_token->setToken($token);
$access_token->setUserPHID($this->getUser()->getPHID());
$access_token->setClientPHID($this->getClient()->getPHID());
$access_token->save();
return $access_token;
}
/**
* @task token
*/
public function validateAuthorizationCode(
PhabricatorOAuthServerAuthorizationCode $test_code,
PhabricatorOAuthServerAuthorizationCode $valid_code) {
// check that all the meta data matches
if ($test_code->getClientPHID() != $valid_code->getClientPHID()) {
return false;
}
if ($test_code->getClientSecret() != $valid_code->getClientSecret()) {
return false;
}
// check that the authorization code hasn't timed out
$created_time = $test_code->getDateCreated();
$must_be_used_by = $created_time + self::AUTHORIZATION_CODE_TIMEOUT;
return (time() < $must_be_used_by);
}
/**
* @task token
*/
public function authorizeToken(
PhabricatorOAuthServerAccessToken $token) {
$user_phid = $token->getUserPHID();
$client_phid = $token->getClientPHID();
$authorization = id(new PhabricatorOAuthClientAuthorizationQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withUserPHIDs(array($user_phid))
->withClientPHIDs(array($client_phid))
->executeOne();
if (!$authorization) {
return null;
}
$application = $authorization->getClient();
if ($application->getIsDisabled()) {
return null;
}
return $authorization;
}
public function validateRedirectURI($uri) {
try {
$this->assertValidRedirectURI($uri);
return true;
} catch (Exception $ex) {
return false;
}
}
/**
* See http://tools.ietf.org/html/draft-ietf-oauth-v2-23#section-3.1.2
* for details on what makes a given redirect URI "valid".
*/
public function assertValidRedirectURI($raw_uri) {
// This covers basics like reasonable formatting and the existence of a
// protocol.
PhabricatorEnv::requireValidRemoteURIForLink($raw_uri);
$uri = new PhutilURI($raw_uri);
$fragment = $uri->getFragment();
if (strlen($fragment)) {
throw new Exception(
pht(
'OAuth application redirect URIs must not contain URI '.
'fragments, but the URI "%s" has a fragment ("%s").',
$raw_uri,
$fragment));
}
$protocol = $uri->getProtocol();
switch ($protocol) {
case 'http':
case 'https':
break;
default:
throw new Exception(
pht(
'OAuth application redirect URIs must only use the "http" or '.
'"https" protocols, but the URI "%s" uses the "%s" protocol.',
$raw_uri,
$protocol));
}
}
/**
* If there's a URI specified in an OAuth request, it must be validated in
* its own right. Further, it must have the same domain, the same path, the
* same port, and (at least) the same query parameters as the primary URI.
*/
public function validateSecondaryRedirectURI(
PhutilURI $secondary_uri,
PhutilURI $primary_uri) {
// The secondary URI must be valid.
if (!$this->validateRedirectURI($secondary_uri)) {
return false;
}
// Both URIs must point at the same domain.
if ($secondary_uri->getDomain() != $primary_uri->getDomain()) {
return false;
}
// Both URIs must have the same path
if ($secondary_uri->getPath() != $primary_uri->getPath()) {
return false;
}
// Both URIs must have the same port
if ($secondary_uri->getPort() != $primary_uri->getPort()) {
return false;
}
// Any query parameters present in the first URI must be exactly present
// in the second URI.
$need_params = $primary_uri->getQueryParamsAsMap();
$have_params = $secondary_uri->getQueryParamsAsMap();
foreach ($need_params as $key => $value) {
if (!array_key_exists($key, $have_params)) {
return false;
}
if ((string)$have_params[$key] != (string)$value) {
return false;
}
}
// If the first URI is HTTPS, the second URI must also be HTTPS. This
// defuses an attack where a third party with control over the network
// tricks you into using HTTP to authenticate over a link which is supposed
// to be HTTPS only and sniffs all your token cookies.
if (strtolower($primary_uri->getProtocol()) == 'https') {
if (strtolower($secondary_uri->getProtocol()) != 'https') {
return false;
}
}
return true;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/PhabricatorOAuthServerScope.php | src/applications/oauthserver/PhabricatorOAuthServerScope.php | <?php
final class PhabricatorOAuthServerScope extends Phobject {
public static function getScopeMap() {
return array();
}
public static function filterScope(array $scope) {
$valid_scopes = self::getScopeMap();
foreach ($scope as $key => $scope_item) {
if (!isset($valid_scopes[$scope_item])) {
unset($scope[$key]);
}
}
return $scope;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/PhabricatorOAuthResponse.php | src/applications/oauthserver/PhabricatorOAuthResponse.php | <?php
final class PhabricatorOAuthResponse extends AphrontResponse {
private $state;
private $content;
private $clientURI;
private $error;
private $errorDescription;
private function getState() {
return $this->state;
}
public function setState($state) {
$this->state = $state;
return $this;
}
private function getContent() {
return $this->content;
}
public function setContent($content) {
$this->content = $content;
return $this;
}
private function getClientURI() {
return $this->clientURI;
}
public function setClientURI(PhutilURI $uri) {
$this->setHTTPResponseCode(302);
$this->clientURI = $uri;
return $this;
}
private function getFullURI() {
$base_uri = $this->getClientURI();
$query_params = $this->buildResponseDict();
foreach ($query_params as $key => $value) {
$base_uri->replaceQueryParam($key, $value);
}
return $base_uri;
}
private function getError() {
return $this->error;
}
public function setError($error) {
// errors sometimes redirect to the client (302) but otherwise
// the spec says all code 400
if (!$this->getClientURI()) {
$this->setHTTPResponseCode(400);
}
$this->error = $error;
return $this;
}
private function getErrorDescription() {
return $this->errorDescription;
}
public function setErrorDescription($error_description) {
$this->errorDescription = $error_description;
return $this;
}
public function __construct() {
$this->setHTTPResponseCode(200); // assume the best
}
public function getHeaders() {
$headers = array(
array('Content-Type', 'application/json'),
);
if ($this->getClientURI()) {
$headers[] = array('Location', $this->getFullURI());
}
// TODO -- T844 set headers with X-Auth-Scopes, etc
$headers = array_merge(parent::getHeaders(), $headers);
return $headers;
}
private function buildResponseDict() {
if ($this->getError()) {
$content = array(
'error' => $this->getError(),
'error_description' => $this->getErrorDescription(),
);
$this->setContent($content);
}
$content = $this->getContent();
if (!$content) {
return '';
}
if ($this->getState()) {
$content['state'] = $this->getState();
}
return $content;
}
public function buildResponseString() {
return $this->encodeJSONForHTTPResponse($this->buildResponseDict());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/PhabricatorOAuthServerController.php | src/applications/oauthserver/controller/PhabricatorOAuthServerController.php | <?php
abstract class PhabricatorOAuthServerController
extends PhabricatorController {
const CONTEXT_AUTHORIZE = 'oauthserver.authorize';
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/PhabricatorOAuthServerTokenController.php | src/applications/oauthserver/controller/PhabricatorOAuthServerTokenController.php | <?php
final class PhabricatorOAuthServerTokenController
extends PhabricatorOAuthServerController {
public function shouldRequireLogin() {
return false;
}
public function shouldAllowRestrictedParameter($parameter_name) {
if ($parameter_name == 'code') {
return true;
}
return parent::shouldAllowRestrictedParameter($parameter_name);
}
public function handleRequest(AphrontRequest $request) {
$grant_type = $request->getStr('grant_type');
$code = $request->getStr('code');
$redirect_uri = $request->getStr('redirect_uri');
$response = new PhabricatorOAuthResponse();
$server = new PhabricatorOAuthServer();
$client_id_parameter = $request->getStr('client_id');
$client_id_header = idx($_SERVER, 'PHP_AUTH_USER');
if (strlen($client_id_parameter) && strlen($client_id_header)) {
if ($client_id_parameter !== $client_id_header) {
throw new Exception(
pht(
'Request included a client_id parameter and an "Authorization" '.
'header with a username, but the values "%s" and "%s") disagree. '.
'The values must match.',
$client_id_parameter,
$client_id_header));
}
}
$client_secret_parameter = $request->getStr('client_secret');
$client_secret_header = idx($_SERVER, 'PHP_AUTH_PW');
if (strlen($client_secret_parameter)) {
// If the `client_secret` parameter is present, prefer parameters.
$client_phid = $client_id_parameter;
$client_secret = $client_secret_parameter;
} else {
// Otherwise, read values from the "Authorization" header.
$client_phid = $client_id_header;
$client_secret = $client_secret_header;
}
if ($grant_type != 'authorization_code') {
$response->setError('unsupported_grant_type');
$response->setErrorDescription(
pht(
'Only %s %s is supported.',
'grant_type',
'authorization_code'));
return $response;
}
if (!$code) {
$response->setError('invalid_request');
$response->setErrorDescription(pht('Required parameter code missing.'));
return $response;
}
if (!$client_phid) {
$response->setError('invalid_request');
$response->setErrorDescription(
pht(
'Required parameter %s missing.',
'client_id'));
return $response;
}
if (!$client_secret) {
$response->setError('invalid_request');
$response->setErrorDescription(
pht(
'Required parameter %s missing.',
'client_secret'));
return $response;
}
// one giant try / catch around all the exciting database stuff so we
// can return a 'server_error' response if something goes wrong!
try {
$auth_code = id(new PhabricatorOAuthServerAuthorizationCode())
->loadOneWhere('code = %s',
$code);
if (!$auth_code) {
$response->setError('invalid_grant');
$response->setErrorDescription(
pht(
'Authorization code %s not found.',
$code));
return $response;
}
// if we have an auth code redirect URI, there must be a redirect_uri
// in the request and it must match the auth code redirect uri *exactly*
$auth_code_redirect_uri = $auth_code->getRedirectURI();
if ($auth_code_redirect_uri) {
$auth_code_redirect_uri = new PhutilURI($auth_code_redirect_uri);
$redirect_uri = new PhutilURI($redirect_uri);
if (!$redirect_uri->getDomain() ||
$redirect_uri != $auth_code_redirect_uri) {
$response->setError('invalid_grant');
$response->setErrorDescription(
pht(
'Redirect URI in request must exactly match redirect URI '.
'from authorization code.'));
return $response;
}
} else if ($redirect_uri) {
$response->setError('invalid_grant');
$response->setErrorDescription(
pht(
'Redirect URI in request and no redirect URI in authorization '.
'code. The two must exactly match.'));
return $response;
}
$client = id(new PhabricatorOAuthServerClient())
->loadOneWhere('phid = %s', $client_phid);
if (!$client) {
$response->setError('invalid_client');
$response->setErrorDescription(
pht(
'Client with %s %s not found.',
'client_id',
$client_phid));
return $response;
}
if ($client->getIsDisabled()) {
$response->setError('invalid_client');
$response->setErrorDescription(
pht(
'OAuth application "%s" has been disabled.',
$client->getName()));
return $response;
}
$server->setClient($client);
$user_phid = $auth_code->getUserPHID();
$user = id(new PhabricatorUser())
->loadOneWhere('phid = %s', $user_phid);
if (!$user) {
$response->setError('invalid_grant');
$response->setErrorDescription(
pht(
'User with PHID %s not found.',
$user_phid));
return $response;
}
$server->setUser($user);
$test_code = new PhabricatorOAuthServerAuthorizationCode();
$test_code->setClientSecret($client_secret);
$test_code->setClientPHID($client_phid);
$is_good_code = $server->validateAuthorizationCode(
$auth_code,
$test_code);
if (!$is_good_code) {
$response->setError('invalid_grant');
$response->setErrorDescription(
pht(
'Invalid authorization code %s.',
$code));
return $response;
}
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$access_token = $server->generateAccessToken();
$auth_code->delete();
unset($unguarded);
$result = array(
'access_token' => $access_token->getToken(),
'token_type' => 'Bearer',
);
return $response->setContent($result);
} catch (Exception $e) {
$response->setError('server_error');
$response->setErrorDescription(
pht(
'The authorization server encountered an unexpected condition '.
'which prevented it from fulfilling the request.'));
return $response;
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/PhabricatorOAuthServerAuthController.php | src/applications/oauthserver/controller/PhabricatorOAuthServerAuthController.php | <?php
final class PhabricatorOAuthServerAuthController
extends PhabricatorOAuthServerController {
protected function buildApplicationCrumbs() {
// We're specifically not putting an "OAuth Server" application crumb
// on the auth pages because it doesn't make sense to send users there.
return new PHUICrumbsView();
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$server = new PhabricatorOAuthServer();
$client_phid = $request->getStr('client_id');
$redirect_uri = $request->getStr('redirect_uri');
$response_type = $request->getStr('response_type');
// state is an opaque value the client sent us for their own purposes
// we just need to send it right back to them in the response!
$state = $request->getStr('state');
if (!$client_phid) {
return $this->buildErrorResponse(
'invalid_request',
pht('Malformed Request'),
pht(
'Required parameter %s was not present in the request.',
phutil_tag('strong', array(), 'client_id')));
}
// We require that users must be able to see an OAuth application
// in order to authorize it. This allows an application's visibility
// policy to be used to restrict authorized users.
try {
$client = id(new PhabricatorOAuthServerClientQuery())
->setViewer($viewer)
->withPHIDs(array($client_phid))
->executeOne();
} catch (PhabricatorPolicyException $ex) {
$ex->setContext(self::CONTEXT_AUTHORIZE);
throw $ex;
}
$server->setUser($viewer);
$is_authorized = false;
$authorization = null;
$uri = null;
$name = null;
// one giant try / catch around all the exciting database stuff so we
// can return a 'server_error' response if something goes wrong!
try {
if (!$client) {
return $this->buildErrorResponse(
'invalid_request',
pht('Invalid Client Application'),
pht(
'Request parameter %s does not specify a valid client application.',
phutil_tag('strong', array(), 'client_id')));
}
if ($client->getIsDisabled()) {
return $this->buildErrorResponse(
'invalid_request',
pht('Application Disabled'),
pht(
'The %s OAuth application has been disabled.',
phutil_tag('strong', array(), 'client_id')));
}
$name = $client->getName();
$server->setClient($client);
if ($redirect_uri) {
$client_uri = new PhutilURI($client->getRedirectURI());
$redirect_uri = new PhutilURI($redirect_uri);
if (!($server->validateSecondaryRedirectURI($redirect_uri,
$client_uri))) {
return $this->buildErrorResponse(
'invalid_request',
pht('Invalid Redirect URI'),
pht(
'Request parameter %s specifies an invalid redirect URI. '.
'The redirect URI must be a fully-qualified domain with no '.
'fragments, and must have the same domain and at least '.
'the same query parameters as the redirect URI the client '.
'registered.',
phutil_tag('strong', array(), 'redirect_uri')));
}
$uri = $redirect_uri;
} else {
$uri = new PhutilURI($client->getRedirectURI());
}
if (empty($response_type)) {
return $this->buildErrorResponse(
'invalid_request',
pht('Invalid Response Type'),
pht(
'Required request parameter %s is missing.',
phutil_tag('strong', array(), 'response_type')));
}
if ($response_type != 'code') {
return $this->buildErrorResponse(
'unsupported_response_type',
pht('Unsupported Response Type'),
pht(
'Request parameter %s specifies an unsupported response type. '.
'Valid response types are: %s.',
phutil_tag('strong', array(), 'response_type'),
implode(', ', array('code'))));
}
$requested_scope = $request->getStrList('scope');
$requested_scope = array_fuse($requested_scope);
$scope = PhabricatorOAuthServerScope::filterScope($requested_scope);
// NOTE: We're always requiring a confirmation dialog to redirect.
// Partly this is a general defense against redirect attacks, and
// partly this shakes off anchors in the URI (which are not shaken
// by 302'ing).
$auth_info = $server->userHasAuthorizedClient($scope);
list($is_authorized, $authorization) = $auth_info;
if ($request->isFormPost()) {
if ($authorization) {
$authorization->setScope($scope)->save();
} else {
$authorization = $server->authorizeClient($scope);
}
$is_authorized = true;
}
} catch (Exception $e) {
return $this->buildErrorResponse(
'server_error',
pht('Server Error'),
pht(
'The authorization server encountered an unexpected condition '.
'which prevented it from fulfilling the request.'));
}
// When we reach this part of the controller, we can be in two states:
//
// 1. The user has not authorized the application yet. We want to
// give them an "Authorize this application?" dialog.
// 2. The user has authorized the application. We want to give them
// a "Confirm Login" dialog.
if ($is_authorized) {
// The second case is simpler, so handle it first. The user either
// authorized the application previously, or has just authorized the
// application. Show them a confirm dialog with a normal link back to
// the application. This shakes anchors from the URI.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$auth_code = $server->generateAuthorizationCode($uri);
unset($unguarded);
$full_uri = $this->addQueryParams(
$uri,
array(
'code' => $auth_code->getCode(),
'scope' => $authorization->getScopeString(),
'state' => $state,
));
if ($client->getIsTrusted()) {
// NOTE: See T13099. We currently emit a "Content-Security-Policy"
// which includes a narrow "form-action". At the time of writing,
// Chrome applies "form-action" to redirects following form submission.
// This can lead to a situation where a user enters the OAuth workflow
// and is prompted for MFA. When they submit an MFA response, the form
// can redirect here, and Chrome will block the "Location" redirect.
// To avoid this, render an interstitial. We only actually need to do
// this in Chrome (but do it everywhere for consistency) and only need
// to do it if the request is a redirect after a form submission (but
// we can't tell if it is or not).
Javelin::initBehavior(
'redirect',
array(
'uri' => (string)$full_uri,
));
return $this->newDialog()
->setTitle(pht('Authenticate: %s', $name))
->appendParagraph(
pht(
'Authorization for "%s" confirmed, redirecting...',
phutil_tag('strong', array(), $name)))
->addCancelButton((string)$full_uri, pht('Continue'));
}
// TODO: It would be nice to give the user more options here, like
// reviewing permissions, canceling the authorization, or aborting
// the workflow.
$dialog = id(new AphrontDialogView())
->setUser($viewer)
->setTitle(pht('Authenticate: %s', $name))
->appendParagraph(
pht(
'This application ("%s") is authorized to use your %s '.
'credentials. Continue to complete the authentication workflow.',
phutil_tag('strong', array(), $name),
PlatformSymbols::getPlatformServerName()))
->addCancelButton((string)$full_uri, pht('Continue to Application'));
return id(new AphrontDialogResponse())->setDialog($dialog);
}
// Here, we're confirming authorization for the application.
if ($authorization) {
$missing_scope = array_diff_key($scope, $authorization->getScope());
} else {
$missing_scope = $scope;
}
$form = id(new AphrontFormView())
->addHiddenInput('client_id', $client_phid)
->addHiddenInput('redirect_uri', $redirect_uri)
->addHiddenInput('response_type', $response_type)
->addHiddenInput('state', $state)
->addHiddenInput('scope', $request->getStr('scope'))
->setUser($viewer);
$cancel_msg = pht('The user declined to authorize this application.');
$cancel_uri = $this->addQueryParams(
$uri,
array(
'error' => 'access_denied',
'error_description' => $cancel_msg,
));
$dialog = $this->newDialog()
->setShortTitle(pht('Authorize Access'))
->setTitle(pht('Authorize "%s"?', $name))
->setSubmitURI($request->getRequestURI()->getPath())
->setWidth(AphrontDialogView::WIDTH_FORM)
->appendParagraph(
pht(
'Do you want to authorize the external application "%s" to '.
'access your %s account data, including your primary '.
'email address?',
phutil_tag('strong', array(), $name),
PlatformSymbols::getPlatformServerName()))
->appendForm($form)
->addSubmitButton(pht('Authorize Access'))
->addCancelButton((string)$cancel_uri, pht('Do Not Authorize'));
if ($missing_scope) {
$dialog->appendParagraph(
pht(
'This application has requested these additional permissions. '.
'Authorizing it will grant it the permissions it requests:'));
foreach ($missing_scope as $scope_key => $ignored) {
// TODO: Once we introduce more scopes, explain them here.
}
}
$unknown_scope = array_diff_key($requested_scope, $scope);
if ($unknown_scope) {
$dialog->appendParagraph(
pht(
'This application also requested additional unrecognized '.
'permissions. These permissions may have existed in an older '.
'version of the software, or may be from a future version of '.
'the software. They will not be granted.'));
$unknown_form = id(new AphrontFormView())
->setViewer($viewer)
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Unknown Scope'))
->setValue(implode(', ', array_keys($unknown_scope)))
->setDisabled(true));
$dialog->appendForm($unknown_form);
}
return $dialog;
}
private function buildErrorResponse($code, $title, $message) {
$viewer = $this->getRequest()->getUser();
return $this->newDialog()
->setTitle(pht('OAuth: %s', $title))
->appendParagraph($message)
->appendParagraph(
pht('OAuth Error Code: %s', phutil_tag('tt', array(), $code)))
->addCancelButton('/', pht('Alas!'));
}
private function addQueryParams(PhutilURI $uri, array $params) {
$full_uri = clone $uri;
foreach ($params as $key => $value) {
if (strlen($value)) {
$full_uri->replaceQueryParam($key, $value);
}
}
return $full_uri;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/client/PhabricatorOAuthClientViewController.php | src/applications/oauthserver/controller/client/PhabricatorOAuthClientViewController.php | <?php
final class PhabricatorOAuthClientViewController
extends PhabricatorOAuthClientController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$client = id(new PhabricatorOAuthServerClientQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->executeOne();
if (!$client) {
return new Aphront404Response();
}
$header = $this->buildHeaderView($client);
$properties = $this->buildPropertyListView($client);
$crumbs = $this->buildApplicationCrumbs()
->addTextCrumb($client->getName())
->setBorder(true);
$timeline = $this->buildTransactionTimeline(
$client,
new PhabricatorOAuthServerTransactionQuery());
$timeline->setShouldTerminate(true);
$box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Details'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->addPropertyList($properties);
$title = pht('OAuth Application: %s', $client->getName());
$curtain = $this->buildCurtain($client);
$columns = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(
array(
$box,
$timeline,
));
return $this->newPage()
->setCrumbs($crumbs)
->setTitle($title)
->appendChild($columns);
}
private function buildHeaderView(PhabricatorOAuthServerClient $client) {
$viewer = $this->getViewer();
$header = id(new PHUIHeaderView())
->setUser($viewer)
->setHeader(pht('OAuth Application: %s', $client->getName()))
->setPolicyObject($client);
if ($client->getIsDisabled()) {
$header->setStatus('fa-ban', 'indigo', pht('Disabled'));
} else {
$header->setStatus('fa-check', 'green', pht('Enabled'));
}
return $header;
}
private function buildCurtain(PhabricatorOAuthServerClient $client) {
$viewer = $this->getViewer();
$actions = array();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$client,
PhabricatorPolicyCapability::CAN_EDIT);
$id = $client->getID();
$actions[] = id(new PhabricatorActionView())
->setName(pht('Edit Application'))
->setIcon('fa-pencil')
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit)
->setHref($client->getEditURI());
$actions[] = id(new PhabricatorActionView())
->setName(pht('Show Application Secret'))
->setIcon('fa-eye')
->setHref($this->getApplicationURI("client/secret/{$id}/"))
->setDisabled(!$can_edit)
->setWorkflow(true);
$is_disabled = $client->getIsDisabled();
if ($is_disabled) {
$disable_text = pht('Enable Application');
$disable_icon = 'fa-check';
} else {
$disable_text = pht('Disable Application');
$disable_icon = 'fa-ban';
}
$disable_uri = $this->getApplicationURI("client/disable/{$id}/");
$actions[] = id(new PhabricatorActionView())
->setName($disable_text)
->setIcon($disable_icon)
->setWorkflow(true)
->setDisabled(!$can_edit)
->setHref($disable_uri);
$actions[] = id(new PhabricatorActionView())
->setName(pht('Generate Test Token'))
->setIcon('fa-plus')
->setWorkflow(true)
->setHref($this->getApplicationURI("client/test/{$id}/"));
$curtain = $this->newCurtainView($client);
foreach ($actions as $action) {
$curtain->addAction($action);
}
return $curtain;
}
private function buildPropertyListView(PhabricatorOAuthServerClient $client) {
$viewer = $this->getRequest()->getUser();
$view = id(new PHUIPropertyListView())
->setUser($viewer);
$view->addProperty(
pht('Client PHID'),
$client->getPHID());
$view->addProperty(
pht('Redirect URI'),
$client->getRedirectURI());
return $view;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/client/PhabricatorOAuthClientListController.php | src/applications/oauthserver/controller/client/PhabricatorOAuthClientListController.php | <?php
final class PhabricatorOAuthClientListController
extends PhabricatorOAuthClientController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new PhabricatorOAuthServerClientSearchEngine())
->setController($this)
->buildResponse();
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
id(new PhabricatorOAuthServerEditEngine())
->setViewer($this->getViewer())
->addActionToCrumbs($crumbs);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/client/PhabricatorOAuthClientSecretController.php | src/applications/oauthserver/controller/client/PhabricatorOAuthClientSecretController.php | <?php
final class PhabricatorOAuthClientSecretController
extends PhabricatorOAuthClientController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getUser();
$client = id(new PhabricatorOAuthServerClientQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$client) {
return new Aphront404Response();
}
$view_uri = $client->getViewURI();
$token = id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession(
$viewer,
$request,
$view_uri);
if ($request->isFormPost()) {
$secret = $client->getSecret();
$body = id(new PHUIFormLayoutView())
->appendChild(
id(new AphrontFormTextAreaControl())
->setLabel(pht('Plaintext'))
->setReadOnly(true)
->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_SHORT)
->setValue($secret));
return $this->newDialog()
->setWidth(AphrontDialogView::WIDTH_FORM)
->setTitle(pht('Application Secret'))
->appendChild($body)
->addCancelButton($view_uri, pht('Done'));
}
$is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');
if ($is_serious) {
$body = pht(
'The secret associated with this OAuth application will be shown in '.
'plain text on your screen.');
} else {
$body = pht(
'The secret associated with this OAuth application will be shown in '.
'plain text on your screen. Before continuing, wrap your arms around '.
'your monitor to create a human shield, keeping it safe from prying '.
'eyes. Protect company secrets!');
}
return $this->newDialog()
->setTitle(pht('Really show application secret?'))
->appendChild($body)
->addSubmitButton(pht('Show Application Secret'))
->addCancelButton($view_uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/client/PhabricatorOAuthClientEditController.php | src/applications/oauthserver/controller/client/PhabricatorOAuthClientEditController.php | <?php
final class PhabricatorOAuthClientEditController
extends PhabricatorOAuthClientController {
public function handleRequest(AphrontRequest $request) {
return id(new PhabricatorOAuthServerEditEngine())
->setController($this)
->buildResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/client/PhabricatorOAuthClientTestController.php | src/applications/oauthserver/controller/client/PhabricatorOAuthClientTestController.php | <?php
final class PhabricatorOAuthClientTestController
extends PhabricatorOAuthClientController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$client = id(new PhabricatorOAuthServerClientQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$client) {
return new Aphront404Response();
}
$done_uri = $client->getViewURI();
if ($request->isFormPost()) {
$server = id(new PhabricatorOAuthServer())
->setUser($viewer)
->setClient($client);
// Create an authorization if we don't already have one.
$authorization = id(new PhabricatorOAuthClientAuthorizationQuery())
->setViewer($viewer)
->withUserPHIDs(array($viewer->getPHID()))
->withClientPHIDs(array($client->getPHID()))
->executeOne();
if (!$authorization) {
$scope = array();
$authorization = $server->authorizeClient($scope);
}
$access_token = $server->generateAccessToken();
$form = id(new AphrontFormView())
->setViewer($viewer)
->appendInstructions(
pht(
'Keep this token private, it allows any bearer to access '.
'your account on behalf of this application.'))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Token'))
->setValue($access_token->getToken()));
return $this->newDialog()
->setTitle(pht('OAuth Access Token'))
->appendForm($form)
->addCancelButton($done_uri, pht('Close'));
}
// TODO: It would be nice to put scope options in this dialog, maybe?
return $this->newDialog()
->setTitle(pht('Authorize Application?'))
->appendParagraph(
pht(
'This will create an authorization and OAuth token, permitting %s '.
'to access your account.',
phutil_tag('strong', array(), $client->getName())))
->addCancelButton($done_uri)
->addSubmitButton(pht('Authorize Application'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/client/PhabricatorOAuthClientController.php | src/applications/oauthserver/controller/client/PhabricatorOAuthClientController.php | <?php
abstract class PhabricatorOAuthClientController
extends PhabricatorOAuthServerController {
private $clientPHID;
protected function getClientPHID() {
return $this->clientPHID;
}
private function setClientPHID($phid) {
$this->clientPHID = $phid;
return $this;
}
public function shouldRequireLogin() {
return true;
}
public function willProcessRequest(array $data) {
$this->setClientPHID(idx($data, 'phid'));
}
public function buildSideNavView($for_app = false) {
$user = $this->getRequest()->getUser();
$nav = new AphrontSideNavFilterView();
$nav->setBaseURI(new PhutilURI($this->getApplicationURI()));
id(new PhabricatorOAuthServerClientSearchEngine())
->setViewer($user)
->addNavigationItems($nav->getMenu());
$nav->selectFilter(null);
return $nav;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/controller/client/PhabricatorOAuthClientDisableController.php | src/applications/oauthserver/controller/client/PhabricatorOAuthClientDisableController.php | <?php
final class PhabricatorOAuthClientDisableController
extends PhabricatorOAuthClientController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$client = id(new PhabricatorOAuthServerClientQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$client) {
return new Aphront404Response();
}
$done_uri = $client->getViewURI();
$is_disable = !$client->getIsDisabled();
if ($request->isFormPost()) {
$xactions = array();
$xactions[] = id(new PhabricatorOAuthServerTransaction())
->setTransactionType(PhabricatorOAuthServerTransaction::TYPE_DISABLED)
->setNewValue((int)$is_disable);
$editor = id(new PhabricatorOAuthServerEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true)
->applyTransactions($client, $xactions);
return id(new AphrontRedirectResponse())->setURI($done_uri);
}
if ($is_disable) {
$title = pht('Disable OAuth Application');
$body = pht(
'Really disable the %s OAuth application? Users will no longer be '.
'able to authenticate against it, nor access this server using '.
'tokens generated by this application.',
phutil_tag('strong', array(), $client->getName()));
$button = pht('Disable Application');
} else {
$title = pht('Enable OAuth Application');
$body = pht(
'Really enable the %s OAuth application? Users will be able to '.
'authenticate against it, and existing tokens will become usable '.
'again.',
phutil_tag('strong', array(), $client->getName()));
$button = pht('Enable Application');
}
return $this->newDialog()
->setTitle($title)
->appendParagraph($body)
->addCancelButton($done_uri)
->addSubmitButton($button);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/storage/PhabricatorOAuthServerAuthorizationCode.php | src/applications/oauthserver/storage/PhabricatorOAuthServerAuthorizationCode.php | <?php
final class PhabricatorOAuthServerAuthorizationCode
extends PhabricatorOAuthServerDAO {
protected $id;
protected $code;
protected $clientPHID;
protected $clientSecret;
protected $userPHID;
protected $redirectURI;
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'code' => 'text32',
'clientSecret' => 'text32',
'redirectURI' => 'text255',
),
self::CONFIG_KEY_SCHEMA => array(
'code' => array(
'columns' => array('code'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/storage/PhabricatorOAuthServerTransaction.php | src/applications/oauthserver/storage/PhabricatorOAuthServerTransaction.php | <?php
final class PhabricatorOAuthServerTransaction
extends PhabricatorApplicationTransaction {
const TYPE_NAME = 'oauthserver.name';
const TYPE_REDIRECT_URI = 'oauthserver.redirect-uri';
const TYPE_DISABLED = 'oauthserver.disabled';
public function getApplicationName() {
return 'oauth_server';
}
public function getTableName() {
return 'oauth_server_transaction';
}
public function getApplicationTransactionType() {
return PhabricatorOAuthServerClientPHIDType::TYPECONST;
}
public function getTitle() {
$author_phid = $this->getAuthorPHID();
$old = $this->getOldValue();
$new = $this->getNewValue();
switch ($this->getTransactionType()) {
case PhabricatorTransactions::TYPE_CREATE:
return pht(
'%s created this OAuth application.',
$this->renderHandleLink($author_phid));
case self::TYPE_NAME:
return pht(
'%s renamed this application from "%s" to "%s".',
$this->renderHandleLink($author_phid),
$old,
$new);
case self::TYPE_REDIRECT_URI:
return pht(
'%s changed the application redirect URI from "%s" to "%s".',
$this->renderHandleLink($author_phid),
$old,
$new);
case self::TYPE_DISABLED:
if ($new) {
return pht(
'%s disabled this application.',
$this->renderHandleLink($author_phid));
} else {
return pht(
'%s enabled this application.',
$this->renderHandleLink($author_phid));
}
}
return parent::getTitle();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/storage/PhabricatorOAuthClientAuthorization.php | src/applications/oauthserver/storage/PhabricatorOAuthClientAuthorization.php | <?php
final class PhabricatorOAuthClientAuthorization
extends PhabricatorOAuthServerDAO
implements PhabricatorPolicyInterface {
protected $userPHID;
protected $clientPHID;
protected $scope;
private $client = self::ATTACHABLE;
public function getScopeString() {
$scope = $this->getScope();
$scopes = array_keys($scope);
sort($scopes);
return implode(' ', $scopes);
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'scope' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'scope' => 'text',
),
self::CONFIG_KEY_SCHEMA => array(
'key_phid' => null,
'phid' => array(
'columns' => array('phid'),
'unique' => true,
),
'userPHID' => array(
'columns' => array('userPHID', 'clientPHID'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorOAuthServerClientAuthorizationPHIDType::TYPECONST);
}
public function getClient() {
return $this->assertAttached($this->client);
}
public function attachClient(PhabricatorOAuthServerClient $client) {
$this->client = $client;
return $this;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return PhabricatorPolicies::POLICY_NOONE;
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return ($viewer->getPHID() == $this->getUserPHID());
}
public function describeAutomaticCapability($capability) {
return pht('Authorizations can only be viewed by the authorizing user.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/storage/PhabricatorOAuthServerClient.php | src/applications/oauthserver/storage/PhabricatorOAuthServerClient.php | <?php
final class PhabricatorOAuthServerClient
extends PhabricatorOAuthServerDAO
implements
PhabricatorPolicyInterface,
PhabricatorApplicationTransactionInterface,
PhabricatorDestructibleInterface {
protected $secret;
protected $name;
protected $redirectURI;
protected $creatorPHID;
protected $isTrusted;
protected $viewPolicy;
protected $editPolicy;
protected $isDisabled;
public function getEditURI() {
$id = $this->getID();
return "/oauthserver/edit/{$id}/";
}
public function getViewURI() {
$id = $this->getID();
return "/oauthserver/client/view/{$id}/";
}
public static function initializeNewClient(PhabricatorUser $actor) {
return id(new PhabricatorOAuthServerClient())
->setCreatorPHID($actor->getPHID())
->setSecret(Filesystem::readRandomCharacters(32))
->setViewPolicy(PhabricatorPolicies::POLICY_USER)
->setEditPolicy($actor->getPHID())
->setIsDisabled(0)
->setIsTrusted(0);
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_COLUMN_SCHEMA => array(
'name' => 'text255',
'secret' => 'text32',
'redirectURI' => 'text255',
'isTrusted' => 'bool',
'isDisabled' => 'bool',
),
self::CONFIG_KEY_SCHEMA => array(
'creatorPHID' => array(
'columns' => array('creatorPHID'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorOAuthServerClientPHIDType::TYPECONST);
}
public function getURI() {
return urisprintf(
'/oauthserver/client/view/%d/',
$this->getID());
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return $this->getViewPolicy();
case PhabricatorPolicyCapability::CAN_EDIT:
return $this->getEditPolicy();
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new PhabricatorOAuthServerEditor();
}
public function getApplicationTransactionTemplate() {
return new PhabricatorOAuthServerTransaction();
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$this->openTransaction();
$this->delete();
$authorizations = id(new PhabricatorOAuthClientAuthorization())
->loadAllWhere('clientPHID = %s', $this->getPHID());
foreach ($authorizations as $authorization) {
$authorization->delete();
}
$tokens = id(new PhabricatorOAuthServerAccessToken())
->loadAllWhere('clientPHID = %s', $this->getPHID());
foreach ($tokens as $token) {
$token->delete();
}
$codes = id(new PhabricatorOAuthServerAuthorizationCode())
->loadAllWhere('clientPHID = %s', $this->getPHID());
foreach ($codes as $code) {
$code->delete();
}
$this->saveTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/storage/PhabricatorOAuthServerAccessToken.php | src/applications/oauthserver/storage/PhabricatorOAuthServerAccessToken.php | <?php
final class PhabricatorOAuthServerAccessToken
extends PhabricatorOAuthServerDAO {
protected $id;
protected $token;
protected $userPHID;
protected $clientPHID;
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'token' => 'text32',
),
self::CONFIG_KEY_SCHEMA => array(
'token' => array(
'columns' => array('token'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/storage/PhabricatorOAuthServerDAO.php | src/applications/oauthserver/storage/PhabricatorOAuthServerDAO.php | <?php
abstract class PhabricatorOAuthServerDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'oauth_server';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/query/PhabricatorOAuthServerClientSearchEngine.php | src/applications/oauthserver/query/PhabricatorOAuthServerClientSearchEngine.php | <?php
final class PhabricatorOAuthServerClientSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('OAuth Clients');
}
public function getApplicationClassName() {
return 'PhabricatorOAuthServerApplication';
}
public function canUseInPanelContext() {
return false;
}
public function newQuery() {
return id(new PhabricatorOAuthServerClientQuery());
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['creatorPHIDs']) {
$query->withCreatorPHIDs($map['creatorPHIDs']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorUsersSearchField())
->setAliases(array('creators'))
->setKey('creatorPHIDs')
->setConduitKey('creators')
->setLabel(pht('Creators'))
->setDescription(
pht('Search for applications created by particular users.')),
);
}
protected function getURI($path) {
return '/oauthserver/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array();
if ($this->requireViewer()->isLoggedIn()) {
$names['created'] = pht('Created');
}
$names['all'] = pht('All Applications');
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
case 'created':
return $query->setParameter(
'creatorPHIDs',
array($this->requireViewer()->getPHID()));
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $clients,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($clients, 'PhabricatorOAuthServerClient');
$viewer = $this->requireViewer();
$list = id(new PHUIObjectItemListView())
->setUser($viewer);
foreach ($clients as $client) {
$item = id(new PHUIObjectItemView())
->setObjectName(pht('Application %d', $client->getID()))
->setHeader($client->getName())
->setHref($client->getViewURI())
->setObject($client);
if ($client->getIsDisabled()) {
$item->setDisabled(true);
}
$list->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setObjectList($list);
$result->setNoDataString(pht('No clients found.'));
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/query/PhabricatorOAuthServerClientQuery.php | src/applications/oauthserver/query/PhabricatorOAuthServerClientQuery.php | <?php
final class PhabricatorOAuthServerClientQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $creatorPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withCreatorPHIDs(array $phids) {
$this->creatorPHIDs = $phids;
return $this;
}
protected function loadPage() {
$table = new PhabricatorOAuthServerClient();
$conn_r = $table->establishConnection('r');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T client %Q %Q %Q',
$table->getTableName(),
$this->buildWhereClause($conn_r),
$this->buildOrderClause($conn_r),
$this->buildLimitClause($conn_r));
return $table->loadAllFromArray($data);
}
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$where = array();
if ($this->ids) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->creatorPHIDs) {
$where[] = qsprintf(
$conn,
'creatorPHID IN (%Ls)',
$this->creatorPHIDs);
}
$where[] = $this->buildPagingClause($conn);
return $this->formatWhereClause($conn, $where);
}
public function getQueryApplicationClass() {
return 'PhabricatorOAuthServerApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/query/PhabricatorOAuthServerTransactionQuery.php | src/applications/oauthserver/query/PhabricatorOAuthServerTransactionQuery.php | <?php
final class PhabricatorOAuthServerTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new PhabricatorOAuthServerTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/query/PhabricatorOAuthServerSchemaSpec.php | src/applications/oauthserver/query/PhabricatorOAuthServerSchemaSpec.php | <?php
final class PhabricatorOAuthServerSchemaSpec
extends PhabricatorConfigSchemaSpec {
public function buildSchemata() {
$this->buildEdgeSchemata(new PhabricatorOAuthServerClient());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/query/PhabricatorOAuthClientAuthorizationQuery.php | src/applications/oauthserver/query/PhabricatorOAuthClientAuthorizationQuery.php | <?php
final class PhabricatorOAuthClientAuthorizationQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $phids;
private $userPHIDs;
private $clientPHIDs;
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withUserPHIDs(array $phids) {
$this->userPHIDs = $phids;
return $this;
}
public function withClientPHIDs(array $phids) {
$this->clientPHIDs = $phids;
return $this;
}
public function newResultObject() {
return new PhabricatorOAuthClientAuthorization();
}
protected function willFilterPage(array $authorizations) {
$client_phids = mpull($authorizations, 'getClientPHID');
$clients = id(new PhabricatorOAuthServerClientQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($client_phids)
->execute();
$clients = mpull($clients, null, 'getPHID');
foreach ($authorizations as $key => $authorization) {
$client = idx($clients, $authorization->getClientPHID());
if (!$client) {
$this->didRejectResult($authorization);
unset($authorizations[$key]);
continue;
}
$authorization->attachClient($client);
}
return $authorizations;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->userPHIDs !== null) {
$where[] = qsprintf(
$conn,
'userPHID IN (%Ls)',
$this->userPHIDs);
}
if ($this->clientPHIDs !== null) {
$where[] = qsprintf(
$conn,
'clientPHID IN (%Ls)',
$this->clientPHIDs);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorOAuthServerApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/editor/PhabricatorOAuthServerEditor.php | src/applications/oauthserver/editor/PhabricatorOAuthServerEditor.php | <?php
final class PhabricatorOAuthServerEditor
extends PhabricatorApplicationTransactionEditor {
public function getEditorApplicationClass() {
return 'PhabricatorOAuthServerApplication';
}
public function getEditorObjectsDescription() {
return pht('OAuth Applications');
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorOAuthServerTransaction::TYPE_NAME;
$types[] = PhabricatorOAuthServerTransaction::TYPE_REDIRECT_URI;
$types[] = PhabricatorOAuthServerTransaction::TYPE_DISABLED;
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
$types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;
return $types;
}
protected function getCustomTransactionOldValue(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case PhabricatorOAuthServerTransaction::TYPE_NAME:
return $object->getName();
case PhabricatorOAuthServerTransaction::TYPE_REDIRECT_URI:
return $object->getRedirectURI();
case PhabricatorOAuthServerTransaction::TYPE_DISABLED:
return $object->getIsDisabled();
}
}
protected function getCustomTransactionNewValue(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case PhabricatorOAuthServerTransaction::TYPE_NAME:
case PhabricatorOAuthServerTransaction::TYPE_REDIRECT_URI:
return $xaction->getNewValue();
case PhabricatorOAuthServerTransaction::TYPE_DISABLED:
return (int)$xaction->getNewValue();
}
}
protected function applyCustomInternalTransaction(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case PhabricatorOAuthServerTransaction::TYPE_NAME:
$object->setName($xaction->getNewValue());
return;
case PhabricatorOAuthServerTransaction::TYPE_REDIRECT_URI:
$object->setRedirectURI($xaction->getNewValue());
return;
case PhabricatorOAuthServerTransaction::TYPE_DISABLED:
$object->setIsDisabled($xaction->getNewValue());
return;
}
return parent::applyCustomInternalTransaction($object, $xaction);
}
protected function applyCustomExternalTransaction(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case PhabricatorOAuthServerTransaction::TYPE_NAME:
case PhabricatorOAuthServerTransaction::TYPE_REDIRECT_URI:
case PhabricatorOAuthServerTransaction::TYPE_DISABLED:
return;
}
return parent::applyCustomExternalTransaction($object, $xaction);
}
protected function validateTransaction(
PhabricatorLiskDAO $object,
$type,
array $xactions) {
$errors = parent::validateTransaction($object, $type, $xactions);
switch ($type) {
case PhabricatorOAuthServerTransaction::TYPE_NAME:
$missing = $this->validateIsEmptyTextField(
$object->getName(),
$xactions);
if ($missing) {
$error = new PhabricatorApplicationTransactionValidationError(
$type,
pht('Required'),
pht('OAuth applications must have a name.'),
nonempty(last($xactions), null));
$error->setIsMissingFieldError(true);
$errors[] = $error;
}
break;
case PhabricatorOAuthServerTransaction::TYPE_REDIRECT_URI:
$missing = $this->validateIsEmptyTextField(
$object->getRedirectURI(),
$xactions);
if ($missing) {
$error = new PhabricatorApplicationTransactionValidationError(
$type,
pht('Required'),
pht('OAuth applications must have a valid redirect URI.'),
nonempty(last($xactions), null));
$error->setIsMissingFieldError(true);
$errors[] = $error;
} else {
foreach ($xactions as $xaction) {
$redirect_uri = $xaction->getNewValue();
try {
$server = new PhabricatorOAuthServer();
$server->assertValidRedirectURI($redirect_uri);
} catch (Exception $ex) {
$errors[] = new PhabricatorApplicationTransactionValidationError(
$type,
pht('Invalid'),
$ex->getMessage(),
$xaction);
}
}
}
break;
}
return $errors;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/editor/PhabricatorOAuthServerEditEngine.php | src/applications/oauthserver/editor/PhabricatorOAuthServerEditEngine.php | <?php
final class PhabricatorOAuthServerEditEngine
extends PhabricatorEditEngine {
const ENGINECONST = 'oauthserver.application';
public function isEngineConfigurable() {
return false;
}
public function getEngineName() {
return pht('OAuth Applications');
}
public function getSummaryHeader() {
return pht('Edit OAuth Applications');
}
public function getSummaryText() {
return pht('This engine manages OAuth client applications.');
}
public function getEngineApplicationClass() {
return 'PhabricatorOAuthServerApplication';
}
protected function newEditableObject() {
return PhabricatorOAuthServerClient::initializeNewClient(
$this->getViewer());
}
protected function newObjectQuery() {
return id(new PhabricatorOAuthServerClientQuery());
}
protected function getObjectCreateTitleText($object) {
return pht('Create OAuth Server');
}
protected function getObjectCreateButtonText($object) {
return pht('Create OAuth Server');
}
protected function getObjectEditTitleText($object) {
return pht('Edit OAuth Server: %s', $object->getName());
}
protected function getObjectEditShortText($object) {
return pht('Edit OAuth Server');
}
protected function getObjectCreateShortText() {
return pht('Create OAuth Server');
}
protected function getObjectName() {
return pht('OAuth Server');
}
protected function getObjectViewURI($object) {
return $object->getViewURI();
}
protected function getCreateNewObjectPolicy() {
return $this->getApplication()->getPolicy(
PhabricatorOAuthServerCreateClientsCapability::CAPABILITY);
}
protected function buildCustomEditFields($object) {
return array(
id(new PhabricatorTextEditField())
->setKey('name')
->setLabel(pht('Name'))
->setIsRequired(true)
->setTransactionType(PhabricatorOAuthServerTransaction::TYPE_NAME)
->setDescription(pht('The name of the OAuth application.'))
->setConduitDescription(pht('Rename the application.'))
->setConduitTypeDescription(pht('New application name.'))
->setValue($object->getName()),
id(new PhabricatorTextEditField())
->setKey('redirectURI')
->setLabel(pht('Redirect URI'))
->setIsRequired(true)
->setTransactionType(
PhabricatorOAuthServerTransaction::TYPE_REDIRECT_URI)
->setDescription(
pht('The redirect URI for OAuth handshakes.'))
->setConduitDescription(
pht(
'Change where this application redirects users to during OAuth '.
'handshakes.'))
->setConduitTypeDescription(
pht(
'New OAuth application redirect URI.'))
->setValue($object->getRedirectURI()),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/panel/PhabricatorOAuthServerAuthorizationsSettingsPanel.php | src/applications/oauthserver/panel/PhabricatorOAuthServerAuthorizationsSettingsPanel.php | <?php
final class PhabricatorOAuthServerAuthorizationsSettingsPanel
extends PhabricatorSettingsPanel {
public function getPanelKey() {
return 'oauthorizations';
}
public function getPanelName() {
return pht('OAuth Authorizations');
}
public function getPanelMenuIcon() {
return 'fa-exchange';
}
public function getPanelGroupKey() {
return PhabricatorSettingsLogsPanelGroup::PANELGROUPKEY;
}
public function isEnabled() {
return PhabricatorApplication::isClassInstalled(
'PhabricatorOAuthServerApplication');
}
public function processRequest(AphrontRequest $request) {
$viewer = $request->getUser();
// TODO: It would be nice to simply disable this panel, but we can't do
// viewer-based checks for enabled panels right now.
$app_class = 'PhabricatorOAuthServerApplication';
$installed = PhabricatorApplication::isClassInstalledForViewer(
$app_class,
$viewer);
if (!$installed) {
$dialog = id(new AphrontDialogView())
->setUser($viewer)
->setTitle(pht('OAuth Not Available'))
->appendParagraph(
pht('You do not have access to OAuth authorizations.'))
->addCancelButton('/settings/');
return id(new AphrontDialogResponse())->setDialog($dialog);
}
$authorizations = id(new PhabricatorOAuthClientAuthorizationQuery())
->setViewer($viewer)
->withUserPHIDs(array($viewer->getPHID()))
->execute();
$authorizations = mpull($authorizations, null, 'getID');
$panel_uri = $this->getPanelURI();
$revoke = $request->getInt('revoke');
if ($revoke) {
if (empty($authorizations[$revoke])) {
return new Aphront404Response();
}
if ($request->isFormPost()) {
$authorizations[$revoke]->delete();
return id(new AphrontRedirectResponse())->setURI($panel_uri);
}
$dialog = id(new AphrontDialogView())
->setUser($viewer)
->setTitle(pht('Revoke Authorization?'))
->appendParagraph(
pht(
'This application will no longer be able to access this server '.
'on your behalf.'))
->addSubmitButton(pht('Revoke Authorization'))
->addCancelButton($panel_uri);
return id(new AphrontDialogResponse())->setDialog($dialog);
}
$highlight = $request->getInt('id');
$rows = array();
$rowc = array();
foreach ($authorizations as $authorization) {
if ($highlight == $authorization->getID()) {
$rowc[] = 'highlighted';
} else {
$rowc[] = null;
}
$button = javelin_tag(
'a',
array(
'href' => $this->getPanelURI('?revoke='.$authorization->getID()),
'class' => 'small button button-grey',
'sigil' => 'workflow',
),
pht('Revoke'));
$rows[] = array(
phutil_tag(
'a',
array(
'href' => $authorization->getClient()->getViewURI(),
),
$authorization->getClient()->getName()),
$authorization->getScopeString(),
phabricator_datetime($authorization->getDateCreated(), $viewer),
phabricator_datetime($authorization->getDateModified(), $viewer),
$button,
);
}
$table = new AphrontTableView($rows);
$table->setNoDataString(
pht("You haven't authorized any OAuth applications."));
$table->setRowClasses($rowc);
$table->setHeaders(
array(
pht('Application'),
pht('Scope'),
pht('Created'),
pht('Updated'),
null,
));
$table->setColumnClasses(
array(
'pri',
'wide',
'right',
'right',
'action',
));
$header = id(new PHUIHeaderView())
->setHeader(pht('OAuth Application Authorizations'));
$panel = id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::WHITE_CONFIG)
->appendChild($table);
return $panel;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/application/PhabricatorOAuthServerApplication.php | src/applications/oauthserver/application/PhabricatorOAuthServerApplication.php | <?php
final class PhabricatorOAuthServerApplication extends PhabricatorApplication {
public function getName() {
return pht('OAuth Server');
}
public function getBaseURI() {
return '/oauthserver/';
}
public function getShortDescription() {
return pht('OAuth Login Provider');
}
public function getIcon() {
return 'fa-hotel';
}
public function getTitleGlyph() {
return "\xE2\x99\x86";
}
public function getFlavorText() {
return pht(
'Log In with %s',
PlatformSymbols::getPlatformServerName());
}
public function getApplicationGroup() {
return self::GROUP_ADMIN;
}
public function isPrototype() {
return true;
}
public function getHelpDocumentationArticles(PhabricatorUser $viewer) {
return array(
array(
'name' => pht('Using the Phabricator OAuth Server'),
'href' => PhabricatorEnv::getDoclink(
'Using the Phabricator OAuth Server'),
),
);
}
public function getRoutes() {
return array(
'/oauthserver/' => array(
'(?:query/(?P<queryKey>[^/]+)/)?'
=> 'PhabricatorOAuthClientListController',
'auth/' => 'PhabricatorOAuthServerAuthController',
'token/' => 'PhabricatorOAuthServerTokenController',
$this->getEditRoutePattern('edit/') =>
'PhabricatorOAuthClientEditController',
'client/' => array(
'disable/(?P<id>\d+)/' => 'PhabricatorOAuthClientDisableController',
'view/(?P<id>\d+)/' => 'PhabricatorOAuthClientViewController',
'secret/(?P<id>\d+)/' => 'PhabricatorOAuthClientSecretController',
'test/(?P<id>\d+)/' => 'PhabricatorOAuthClientTestController',
),
),
);
}
protected function getCustomCapabilities() {
return array(
PhabricatorOAuthServerCreateClientsCapability::CAPABILITY => array(
'default' => PhabricatorPolicies::POLICY_ADMIN,
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/__tests__/PhabricatorOAuthServerTestCase.php | src/applications/oauthserver/__tests__/PhabricatorOAuthServerTestCase.php | <?php
final class PhabricatorOAuthServerTestCase
extends PhabricatorTestCase {
public function testValidateRedirectURI() {
static $map = array(
'http://www.google.com' => true,
'http://www.google.com/' => true,
'http://www.google.com/auth' => true,
'www.google.com' => false,
'http://www.google.com/auth#invalid' => false,
);
$server = new PhabricatorOAuthServer();
foreach ($map as $input => $expected) {
$uri = new PhutilURI($input);
$result = $server->validateRedirectURI($uri);
$this->assertEqual(
$expected,
$result,
pht("Validation of redirect URI '%s'", $input));
}
}
public function testValidateSecondaryRedirectURI() {
$server = new PhabricatorOAuthServer();
$primary_uri = new PhutilURI('http://www.google.com/');
static $test_domain_map = array(
'http://www.google.com' => false,
'http://www.google.com/' => true,
'http://www.google.com/auth' => false,
'http://www.google.com/?auth' => true,
'www.google.com' => false,
'http://www.google.com/auth#invalid' => false,
'http://www.example.com' => false,
);
foreach ($test_domain_map as $input => $expected) {
$uri = new PhutilURI($input);
$this->assertEqual(
$expected,
$server->validateSecondaryRedirectURI($uri, $primary_uri),
pht(
"Validation of redirect URI '%s' relative to '%s'",
$input,
$primary_uri));
}
$primary_uri = new PhutilURI('http://www.google.com/?auth');
static $test_query_map = array(
'http://www.google.com' => false,
'http://www.google.com/' => false,
'http://www.google.com/auth' => false,
'http://www.google.com/?auth' => true,
'http://www.google.com/?auth&stuff' => true,
'http://www.google.com/?stuff' => false,
);
foreach ($test_query_map as $input => $expected) {
$uri = new PhutilURI($input);
$this->assertEqual(
$expected,
$server->validateSecondaryRedirectURI($uri, $primary_uri),
pht(
"Validation of secondary redirect URI '%s' relative to '%s'",
$input,
$primary_uri));
}
$primary_uri = new PhutilURI('https://secure.example.com/');
$tests = array(
'https://secure.example.com/' => true,
'http://secure.example.com/' => false,
);
foreach ($tests as $input => $expected) {
$uri = new PhutilURI($input);
$this->assertEqual(
$expected,
$server->validateSecondaryRedirectURI($uri, $primary_uri),
pht('Validation (https): %s', $input));
}
$primary_uri = new PhutilURI('http://example.com/?z=2&y=3');
$tests = array(
'http://example.com/?z=2&y=3' => true,
'http://example.com/?y=3&z=2' => true,
'http://example.com/?y=3&z=2&x=1' => true,
'http://example.com/?y=2&z=3' => false,
'http://example.com/?y&x' => false,
'http://example.com/?z=2&x=3' => false,
);
foreach ($tests as $input => $expected) {
$uri = new PhutilURI($input);
$this->assertEqual(
$expected,
$server->validateSecondaryRedirectURI($uri, $primary_uri),
pht('Validation (params): %s', $input));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/phid/PhabricatorOAuthServerClientAuthorizationPHIDType.php | src/applications/oauthserver/phid/PhabricatorOAuthServerClientAuthorizationPHIDType.php | <?php
final class PhabricatorOAuthServerClientAuthorizationPHIDType
extends PhabricatorPHIDType {
const TYPECONST = 'OASA';
public function getTypeName() {
return pht('OAuth Authorization');
}
public function newObject() {
return new PhabricatorOAuthClientAuthorization();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorOAuthServerApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorOAuthClientAuthorizationQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$authorization = $objects[$phid];
$handle->setName(pht('Authorization %d', $authorization->getID()));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/phid/PhabricatorOAuthServerClientPHIDType.php | src/applications/oauthserver/phid/PhabricatorOAuthServerClientPHIDType.php | <?php
final class PhabricatorOAuthServerClientPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'OASC';
public function getTypeName() {
return pht('OAuth Application');
}
public function newObject() {
return new PhabricatorOAuthServerClient();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorOAuthServerApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PhabricatorOAuthServerClientQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$client = $objects[$phid];
$handle
->setName($client->getName())
->setURI($client->getURI());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/oauthserver/capability/PhabricatorOAuthServerCreateClientsCapability.php | src/applications/oauthserver/capability/PhabricatorOAuthServerCreateClientsCapability.php | <?php
final class PhabricatorOAuthServerCreateClientsCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'oauthserver.create';
public function getCapabilityName() {
return pht('Can Create OAuth Applications');
}
public function describeCapabilityRejection() {
return pht('You do not have permission to create OAuth applications.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/controller/PhabricatorPhurlController.php | src/applications/phurl/controller/PhabricatorPhurlController.php | <?php
abstract class PhabricatorPhurlController extends PhabricatorController {
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
id(new PhabricatorPhurlURLEditEngine())
->setViewer($this->getViewer())
->addActionToCrumbs($crumbs);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/controller/PhabricatorPhurlURLAccessController.php | src/applications/phurl/controller/PhabricatorPhurlURLAccessController.php | <?php
final class PhabricatorPhurlURLAccessController
extends PhabricatorPhurlController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$id = $request->getURIData('id');
$alias = $request->getURIData('alias');
if ($id) {
$url = id(new PhabricatorPhurlURLQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
} else if ($alias) {
$url = id(new PhabricatorPhurlURLQuery())
->setViewer($viewer)
->withAliases(array($alias))
->executeOne();
}
if (!$url) {
return new Aphront404Response();
}
if ($url->isValid()) {
return id(new AphrontRedirectResponse())
->setURI($url->getLongURL())
->setIsExternal(true);
} else {
return id(new AphrontRedirectResponse())->setURI('/'.$url->getMonogram());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/controller/PhabricatorPhurlURLEditController.php | src/applications/phurl/controller/PhabricatorPhurlURLEditController.php | <?php
final class PhabricatorPhurlURLEditController
extends PhabricatorPhurlController {
public function handleRequest(AphrontRequest $request) {
return id(new PhabricatorPhurlURLEditEngine())
->setController($this)
->buildResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/controller/PhabricatorPhurlShortURLController.php | src/applications/phurl/controller/PhabricatorPhurlShortURLController.php | <?php
final class PhabricatorPhurlShortURLController
extends PhabricatorPhurlController {
public function shouldRequireLogin() {
return false;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$append = $request->getURIData('append');
$main_domain_uri = PhabricatorEnv::getProductionURI('/u/'.$append);
return id(new AphrontRedirectResponse())
->setIsExternal(true)
->setURI($main_domain_uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/controller/PhabricatorPhurlShortURLDefaultController.php | src/applications/phurl/controller/PhabricatorPhurlShortURLDefaultController.php | <?php
final class PhabricatorPhurlShortURLDefaultController
extends PhabricatorPhurlController {
public function shouldRequireLogin() {
return false;
}
public function handleRequest(AphrontRequest $request) {
$dialog = $this->newDialog()
->setTitle(pht('Invalid URL'))
->appendParagraph(
pht('This domain can only be used to open URLs'.
' shortened using the Phurl application. The'.
' URL you are trying to access does not have'.
' a Phurl URL associated with it.'));
return id(new AphrontDialogResponse())
->setDialog($dialog)
->setHTTPResponseCode(404);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/controller/PhabricatorPhurlURLListController.php | src/applications/phurl/controller/PhabricatorPhurlURLListController.php | <?php
final class PhabricatorPhurlURLListController
extends PhabricatorPhurlController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$engine = new PhabricatorPhurlURLSearchEngine();
$controller = id(new PhabricatorApplicationSearchController())
->setQueryKey($request->getURIData('queryKey'))
->setSearchEngine($engine)
->setNavigation($this->buildSideNav());
return $this->delegateToController($controller);
}
public function buildSideNav() {
$user = $this->getRequest()->getUser();
$nav = new AphrontSideNavFilterView();
$nav->setBaseURI(new PhutilURI($this->getApplicationURI()));
id(new PhabricatorPhurlURLSearchEngine())
->setViewer($user)
->addNavigationItems($nav->getMenu());
$nav->selectFilter(null);
return $nav;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.