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/project/engine/PhabricatorProjectProfileMenuEngine.php | src/applications/project/engine/PhabricatorProjectProfileMenuEngine.php | <?php
final class PhabricatorProjectProfileMenuEngine
extends PhabricatorProfileMenuEngine {
protected function isMenuEngineConfigurable() {
return true;
}
protected function isMenuEnginePersonalizable() {
return false;
}
public function getItemURI($path) {
$project = $this->getProfileObject();
$id = $project->getID();
return "/project/{$id}/item/{$path}";
}
protected function getBuiltinProfileItems($object) {
$items = array();
$items[] = $this->newItem()
->setBuiltinKey(PhabricatorProject::ITEM_PICTURE)
->setMenuItemKey(PhabricatorProjectPictureProfileMenuItem::MENUITEMKEY)
->setIsHeadItem(true);
$items[] = $this->newItem()
->setBuiltinKey(PhabricatorProject::ITEM_PROFILE)
->setMenuItemKey(PhabricatorProjectDetailsProfileMenuItem::MENUITEMKEY);
$items[] = $this->newItem()
->setBuiltinKey(PhabricatorProject::ITEM_POINTS)
->setMenuItemKey(PhabricatorProjectPointsProfileMenuItem::MENUITEMKEY);
$items[] = $this->newItem()
->setBuiltinKey(PhabricatorProject::ITEM_WORKBOARD)
->setMenuItemKey(PhabricatorProjectWorkboardProfileMenuItem::MENUITEMKEY);
$items[] = $this->newItem()
->setBuiltinKey(PhabricatorProject::ITEM_REPORTS)
->setMenuItemKey(PhabricatorProjectReportsProfileMenuItem::MENUITEMKEY);
$items[] = $this->newItem()
->setBuiltinKey(PhabricatorProject::ITEM_MEMBERS)
->setMenuItemKey(PhabricatorProjectMembersProfileMenuItem::MENUITEMKEY);
$items[] = $this->newItem()
->setBuiltinKey(PhabricatorProject::ITEM_SUBPROJECTS)
->setMenuItemKey(
PhabricatorProjectSubprojectsProfileMenuItem::MENUITEMKEY);
$items[] = $this->newItem()
->setBuiltinKey(PhabricatorProject::ITEM_MANAGE)
->setMenuItemKey(PhabricatorProjectManageProfileMenuItem::MENUITEMKEY)
->setIsTailItem(true);
return $items;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/engine/PhabricatorBoardLayoutEngine.php | src/applications/project/engine/PhabricatorBoardLayoutEngine.php | <?php
final class PhabricatorBoardLayoutEngine extends Phobject {
private $viewer;
private $boardPHIDs;
private $objectPHIDs = array();
private $boards;
private $columnMap = array();
private $objectColumnMap = array();
private $boardLayout = array();
private $fetchAllBoards;
private $remQueue = array();
private $addQueue = array();
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setBoardPHIDs(array $board_phids) {
$this->boardPHIDs = array_fuse($board_phids);
return $this;
}
public function getBoardPHIDs() {
return $this->boardPHIDs;
}
public function setObjectPHIDs(array $object_phids) {
$this->objectPHIDs = array_fuse($object_phids);
return $this;
}
public function getObjectPHIDs() {
return $this->objectPHIDs;
}
/**
* Fetch all boards, even if the board is disabled.
*/
public function setFetchAllBoards($fetch_all) {
$this->fetchAllBoards = $fetch_all;
return $this;
}
public function getFetchAllBoards() {
return $this->fetchAllBoards;
}
public function executeLayout() {
$viewer = $this->getViewer();
$boards = $this->loadBoards();
if (!$boards) {
return $this;
}
$columns = $this->loadColumns($boards);
$positions = $this->loadPositions($boards);
foreach ($boards as $board_phid => $board) {
$board_columns = idx($columns, $board_phid);
// Don't layout boards with no columns. These boards need to be formally
// created first.
if (!$columns) {
continue;
}
$board_positions = idx($positions, $board_phid, array());
$this->layoutBoard($board, $board_columns, $board_positions);
}
return $this;
}
public function getColumns($board_phid) {
$columns = idx($this->boardLayout, $board_phid, array());
return array_select_keys($this->columnMap, array_keys($columns));
}
public function getColumnObjectPositions($board_phid, $column_phid) {
$columns = idx($this->boardLayout, $board_phid, array());
return idx($columns, $column_phid, array());
}
public function getColumnObjectPHIDs($board_phid, $column_phid) {
$positions = $this->getColumnObjectPositions($board_phid, $column_phid);
return mpull($positions, 'getObjectPHID');
}
public function getObjectColumns($board_phid, $object_phid) {
$board_map = idx($this->objectColumnMap, $board_phid, array());
$column_phids = idx($board_map, $object_phid);
if (!$column_phids) {
return array();
}
return array_select_keys($this->columnMap, $column_phids);
}
public function queueRemovePosition(
$board_phid,
$column_phid,
$object_phid) {
$board_layout = idx($this->boardLayout, $board_phid, array());
$positions = idx($board_layout, $column_phid, array());
$position = idx($positions, $object_phid);
if ($position) {
$this->remQueue[] = $position;
// If this position hasn't been saved yet, get it out of the add queue.
if (!$position->getID()) {
foreach ($this->addQueue as $key => $add_position) {
if ($add_position === $position) {
unset($this->addQueue[$key]);
}
}
}
}
unset($this->boardLayout[$board_phid][$column_phid][$object_phid]);
return $this;
}
public function queueAddPosition(
$board_phid,
$column_phid,
$object_phid,
array $after_phids,
array $before_phids) {
$board_layout = idx($this->boardLayout, $board_phid, array());
$positions = idx($board_layout, $column_phid, array());
// Check if the object is already in the column, and remove it if it is.
$object_position = idx($positions, $object_phid);
unset($positions[$object_phid]);
if (!$object_position) {
$object_position = id(new PhabricatorProjectColumnPosition())
->setBoardPHID($board_phid)
->setColumnPHID($column_phid)
->setObjectPHID($object_phid);
}
if (!$positions) {
$object_position->setSequence(0);
} else {
// The user's view of the board may fall out of date, so they might
// try to drop a card under a different card which is no longer where
// they thought it was.
// When this happens, we perform the move anyway, since this is almost
// certainly what users want when interacting with the UI. We'l try to
// fall back to another nearby card if the client provided us one. If
// we don't find any of the cards the client specified in the column,
// we'll just move the card to the default position.
$search_phids = array();
foreach ($after_phids as $after_phid) {
$search_phids[] = array($after_phid, false);
}
foreach ($before_phids as $before_phid) {
$search_phids[] = array($before_phid, true);
}
// This makes us fall back to the default position if we fail every
// candidate position. The default position counts as a "before" position
// because we want to put the new card at the top of the column.
$search_phids[] = array(null, true);
$found = false;
foreach ($search_phids as $search_position) {
list($relative_phid, $is_before) = $search_position;
foreach ($positions as $position) {
if (!$found) {
if ($relative_phid === null) {
$is_match = true;
} else {
$position_phid = $position->getObjectPHID();
$is_match = ($relative_phid === $position_phid);
}
if ($is_match) {
$found = true;
$sequence = $position->getSequence();
if (!$is_before) {
$sequence++;
}
$object_position->setSequence($sequence++);
if (!$is_before) {
// If we're inserting after this position, continue the loop so
// we don't update it.
continue;
}
}
}
if ($found) {
$position->setSequence($sequence++);
$this->addQueue[] = $position;
}
}
if ($found) {
break;
}
}
}
$this->addQueue[] = $object_position;
$positions[$object_phid] = $object_position;
$positions = msortv($positions, 'newColumnPositionOrderVector');
$this->boardLayout[$board_phid][$column_phid] = $positions;
return $this;
}
public function applyPositionUpdates() {
foreach ($this->remQueue as $position) {
if ($position->getID()) {
$position->delete();
}
}
$this->remQueue = array();
$adds = array();
$updates = array();
foreach ($this->addQueue as $position) {
$id = $position->getID();
if ($id) {
$updates[$id] = $position;
} else {
$adds[] = $position;
}
}
$this->addQueue = array();
$table = new PhabricatorProjectColumnPosition();
$conn_w = $table->establishConnection('w');
$pairs = array();
foreach ($updates as $id => $position) {
// This is ugly because MySQL gets upset with us if it is configured
// strictly and we attempt inserts which can't work. We'll never actually
// do these inserts since they'll always collide (triggering the ON
// DUPLICATE KEY logic), so we just provide dummy values in order to get
// there.
$pairs[] = qsprintf(
$conn_w,
'(%d, %d, "", "", "")',
$id,
$position->getSequence());
}
if ($pairs) {
queryfx(
$conn_w,
'INSERT INTO %T (id, sequence, boardPHID, columnPHID, objectPHID)
VALUES %LQ ON DUPLICATE KEY UPDATE sequence = VALUES(sequence)',
$table->getTableName(),
$pairs);
}
foreach ($adds as $position) {
$position->save();
}
return $this;
}
private function loadBoards() {
$viewer = $this->getViewer();
$board_phids = $this->getBoardPHIDs();
$boards = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withPHIDs($board_phids)
->execute();
$boards = mpull($boards, null, 'getPHID');
foreach ($boards as $key => $board) {
if (!($board instanceof PhabricatorWorkboardInterface)) {
unset($boards[$key]);
}
}
if (!$this->fetchAllBoards) {
foreach ($boards as $key => $board) {
if (!$board->getHasWorkboard()) {
unset($boards[$key]);
}
}
}
return $boards;
}
private function loadColumns(array $boards) {
$viewer = $this->getViewer();
$columns = id(new PhabricatorProjectColumnQuery())
->setViewer($viewer)
->withProjectPHIDs(array_keys($boards))
->needTriggers(true)
->execute();
$columns = msort($columns, 'getOrderingKey');
$columns = mpull($columns, null, 'getPHID');
$need_children = array();
foreach ($boards as $phid => $board) {
if ($board->getHasMilestones() || $board->getHasSubprojects()) {
$need_children[] = $phid;
}
}
if ($need_children) {
$children = id(new PhabricatorProjectQuery())
->setViewer($viewer)
->withParentProjectPHIDs($need_children)
->execute();
$children = mpull($children, null, 'getPHID');
$children = mgroup($children, 'getParentProjectPHID');
} else {
$children = array();
}
$columns = mgroup($columns, 'getProjectPHID');
foreach ($boards as $board_phid => $board) {
$board_columns = idx($columns, $board_phid, array());
// If the project has milestones, create any missing columns.
if ($board->getHasMilestones() || $board->getHasSubprojects()) {
$child_projects = idx($children, $board_phid, array());
if ($board_columns) {
$next_sequence = last($board_columns)->getSequence() + 1;
} else {
$next_sequence = 1;
}
$proxy_columns = mpull($board_columns, null, 'getProxyPHID');
foreach ($child_projects as $child_phid => $child) {
if (isset($proxy_columns[$child_phid])) {
continue;
}
$new_column = PhabricatorProjectColumn::initializeNewColumn($viewer)
->attachProject($board)
->attachProxy($child)
->setSequence($next_sequence++)
->setProjectPHID($board_phid)
->setProxyPHID($child_phid);
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$new_column->save();
unset($unguarded);
$board_columns[$new_column->getPHID()] = $new_column;
}
}
$board_columns = msort($board_columns, 'getOrderingKey');
$columns[$board_phid] = $board_columns;
}
foreach ($columns as $board_phid => $board_columns) {
foreach ($board_columns as $board_column) {
$column_phid = $board_column->getPHID();
$this->columnMap[$column_phid] = $board_column;
}
}
return $columns;
}
private function loadPositions(array $boards) {
$viewer = $this->getViewer();
$object_phids = $this->getObjectPHIDs();
if (!$object_phids) {
return array();
}
$positions = id(new PhabricatorProjectColumnPositionQuery())
->setViewer($viewer)
->withBoardPHIDs(array_keys($boards))
->withObjectPHIDs($object_phids)
->execute();
$positions = msortv($positions, 'newColumnPositionOrderVector');
$positions = mgroup($positions, 'getBoardPHID');
return $positions;
}
private function layoutBoard(
$board,
array $columns,
array $positions) {
$viewer = $this->getViewer();
$board_phid = $board->getPHID();
$position_groups = mgroup($positions, 'getObjectPHID');
$layout = array();
$default_phid = null;
foreach ($columns as $column) {
$column_phid = $column->getPHID();
$layout[$column_phid] = array();
if ($column->isDefaultColumn()) {
$default_phid = $column_phid;
}
}
// Find all the columns which are proxies for other objects.
$proxy_map = array();
foreach ($columns as $column) {
$proxy_phid = $column->getProxyPHID();
if ($proxy_phid) {
$proxy_map[$proxy_phid] = $column->getPHID();
}
}
$object_phids = $this->getObjectPHIDs();
// If we have proxies, we need to force cards into the correct proxy
// columns.
if ($proxy_map && $object_phids) {
$edge_query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs($object_phids)
->withEdgeTypes(
array(
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
));
$edge_query->execute();
$project_phids = $edge_query->getDestinationPHIDs();
$project_phids = array_fuse($project_phids);
} else {
$project_phids = array();
}
if ($project_phids) {
$projects = id(new PhabricatorProjectQuery())
->setViewer($viewer)
->withPHIDs($project_phids)
->execute();
$projects = mpull($projects, null, 'getPHID');
} else {
$projects = array();
}
// Build a map from every project that any task is tagged with to the
// ancestor project which has a column on this board, if one exists.
$ancestor_map = array();
foreach ($projects as $phid => $project) {
if (isset($proxy_map[$phid])) {
$ancestor_map[$phid] = $proxy_map[$phid];
} else {
$seen = array($phid);
foreach ($project->getAncestorProjects() as $ancestor) {
$ancestor_phid = $ancestor->getPHID();
$seen[] = $ancestor_phid;
if (isset($proxy_map[$ancestor_phid])) {
foreach ($seen as $project_phid) {
$ancestor_map[$project_phid] = $proxy_map[$ancestor_phid];
}
}
}
}
}
$view_sequence = 1;
foreach ($object_phids as $object_phid) {
$positions = idx($position_groups, $object_phid, array());
// First, check for objects that have corresponding proxy columns. We're
// going to overwrite normal column positions if a tag belongs to a proxy
// column, since you can't be in normal columns if you're in proxy
// columns.
$proxy_hits = array();
if ($proxy_map) {
$object_project_phids = $edge_query->getDestinationPHIDs(
array(
$object_phid,
));
foreach ($object_project_phids as $project_phid) {
if (isset($ancestor_map[$project_phid])) {
$proxy_hits[] = $ancestor_map[$project_phid];
}
}
}
if ($proxy_hits) {
// TODO: For now, only one column hit is permissible.
$proxy_hits = array_slice($proxy_hits, 0, 1);
$proxy_hits = array_fuse($proxy_hits);
// Check the object positions: we hope to find a position in each
// column the object should be part of. We're going to drop any
// invalid positions and create new positions where positions are
// missing.
foreach ($positions as $key => $position) {
$column_phid = $position->getColumnPHID();
if (isset($proxy_hits[$column_phid])) {
// Valid column, mark the position as found.
unset($proxy_hits[$column_phid]);
} else {
// Invalid column, ignore the position.
unset($positions[$key]);
}
}
// Create new positions for anything we haven't found.
foreach ($proxy_hits as $proxy_hit) {
$new_position = id(new PhabricatorProjectColumnPosition())
->setBoardPHID($board_phid)
->setColumnPHID($proxy_hit)
->setObjectPHID($object_phid)
->setSequence(0)
->setViewSequence($view_sequence++);
$this->addQueue[] = $new_position;
$positions[] = $new_position;
}
} else {
// Ignore any positions in columns which no longer exist. We don't
// actively destory them because the rest of the code ignores them and
// there's no real need to destroy the data.
foreach ($positions as $key => $position) {
$column_phid = $position->getColumnPHID();
if (empty($columns[$column_phid])) {
unset($positions[$key]);
}
}
// If the object has no position, put it on the default column if
// one exists.
if (!$positions && $default_phid) {
$new_position = id(new PhabricatorProjectColumnPosition())
->setBoardPHID($board_phid)
->setColumnPHID($default_phid)
->setObjectPHID($object_phid)
->setSequence(0)
->setViewSequence($view_sequence++);
$this->addQueue[] = $new_position;
$positions = array(
$new_position,
);
}
}
foreach ($positions as $position) {
$column_phid = $position->getColumnPHID();
$layout[$column_phid][$object_phid] = $position;
}
}
foreach ($layout as $column_phid => $map) {
$map = msortv($map, 'newColumnPositionOrderVector');
$layout[$column_phid] = $map;
foreach ($map as $object_phid => $position) {
$this->objectColumnMap[$board_phid][$object_phid][] = $column_phid;
}
}
$this->boardLayout[$board_phid] = $layout;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/engine/PhabricatorProjectEditEngine.php | src/applications/project/engine/PhabricatorProjectEditEngine.php | <?php
final class PhabricatorProjectEditEngine
extends PhabricatorEditEngine {
const ENGINECONST = 'projects.project';
private $parentProject;
private $milestoneProject;
public function setParentProject(PhabricatorProject $parent_project) {
$this->parentProject = $parent_project;
return $this;
}
public function getParentProject() {
return $this->parentProject;
}
public function setMilestoneProject(PhabricatorProject $milestone_project) {
$this->milestoneProject = $milestone_project;
return $this;
}
public function getMilestoneProject() {
return $this->milestoneProject;
}
public function isDefaultQuickCreateEngine() {
return true;
}
public function getQuickCreateOrderVector() {
return id(new PhutilSortVector())->addInt(200);
}
public function getEngineName() {
return pht('Projects');
}
public function getSummaryHeader() {
return pht('Configure Project Forms');
}
public function getSummaryText() {
return pht('Configure forms for creating projects.');
}
public function getEngineApplicationClass() {
return 'PhabricatorProjectApplication';
}
protected function newEditableObject() {
$parent = nonempty($this->parentProject, $this->milestoneProject);
return PhabricatorProject::initializeNewProject(
$this->getViewer(),
$parent);
}
protected function newObjectQuery() {
return id(new PhabricatorProjectQuery())
->needSlugs(true);
}
protected function getObjectCreateTitleText($object) {
return pht('Create New Project');
}
protected function getObjectEditTitleText($object) {
return pht('Edit Project: %s', $object->getName());
}
protected function getObjectEditShortText($object) {
return $object->getName();
}
protected function getObjectCreateShortText() {
return pht('Create Project');
}
protected function getObjectName() {
return pht('Project');
}
protected function getObjectViewURI($object) {
if ($this->getIsCreate()) {
return $object->getURI();
} else {
$id = $object->getID();
return "/project/manage/{$id}/";
}
}
protected function getObjectCreateCancelURI($object) {
$parent = $this->getParentProject();
$milestone = $this->getMilestoneProject();
if ($parent || $milestone) {
$id = nonempty($parent, $milestone)->getID();
return "/project/subprojects/{$id}/";
}
return parent::getObjectCreateCancelURI($object);
}
protected function getCreateNewObjectPolicy() {
return $this->getApplication()->getPolicy(
ProjectCreateProjectsCapability::CAPABILITY);
}
protected function willConfigureFields($object, array $fields) {
$is_milestone = ($this->getMilestoneProject() || $object->isMilestone());
$unavailable = array(
PhabricatorTransactions::TYPE_VIEW_POLICY,
PhabricatorTransactions::TYPE_EDIT_POLICY,
PhabricatorTransactions::TYPE_JOIN_POLICY,
PhabricatorTransactions::TYPE_SPACE,
PhabricatorProjectIconTransaction::TRANSACTIONTYPE,
PhabricatorProjectColorTransaction::TRANSACTIONTYPE,
);
$unavailable = array_fuse($unavailable);
if ($is_milestone) {
foreach ($fields as $key => $field) {
$xaction_type = $field->getTransactionType();
if (isset($unavailable[$xaction_type])) {
unset($fields[$key]);
}
}
}
return $fields;
}
protected function newBuiltinEngineConfigurations() {
$configuration = head(parent::newBuiltinEngineConfigurations());
// TODO: This whole method is clumsy, and the ordering for the custom
// field is especially clumsy. Maybe try to make this more natural to
// express.
$configuration
->setFieldOrder(
array(
'parent',
'milestone',
'milestone.previous',
'name',
'std:project:internal:description',
'icon',
'color',
'slugs',
));
return array(
$configuration,
);
}
protected function buildCustomEditFields($object) {
$slugs = mpull($object->getSlugs(), 'getSlug');
$slugs = array_fuse($slugs);
unset($slugs[$object->getPrimarySlug()]);
$slugs = array_values($slugs);
$milestone = $this->getMilestoneProject();
$parent = $this->getParentProject();
if ($parent) {
$parent_phid = $parent->getPHID();
} else {
$parent_phid = null;
}
$previous_milestone_phid = null;
if ($milestone) {
$milestone_phid = $milestone->getPHID();
// Load the current milestone so we can show the user a hint about what
// it was called, so they don't have to remember if the next one should
// be "Sprint 287" or "Sprint 278".
$number = ($milestone->loadNextMilestoneNumber() - 1);
if ($number > 0) {
$previous_milestone = id(new PhabricatorProjectQuery())
->setViewer($this->getViewer())
->withParentProjectPHIDs(array($milestone->getPHID()))
->withIsMilestone(true)
->withMilestoneNumberBetween($number, $number)
->executeOne();
if ($previous_milestone) {
$previous_milestone_phid = $previous_milestone->getPHID();
}
}
} else {
$milestone_phid = null;
}
$fields = array(
id(new PhabricatorHandlesEditField())
->setKey('parent')
->setLabel(pht('Parent'))
->setDescription(pht('Create a subproject of an existing project.'))
->setConduitDescription(
pht('Choose a parent project to create a subproject beneath.'))
->setConduitTypeDescription(pht('PHID of the parent project.'))
->setAliases(array('parentPHID'))
->setTransactionType(
PhabricatorProjectParentTransaction::TRANSACTIONTYPE)
->setHandleParameterType(new AphrontPHIDHTTPParameterType())
->setSingleValue($parent_phid)
->setIsReorderable(false)
->setIsDefaultable(false)
->setIsLockable(false)
->setIsLocked(true),
id(new PhabricatorHandlesEditField())
->setKey('milestone')
->setLabel(pht('Milestone Of'))
->setDescription(pht('Parent project to create a milestone for.'))
->setConduitDescription(
pht('Choose a parent project to create a new milestone for.'))
->setConduitTypeDescription(pht('PHID of the parent project.'))
->setAliases(array('milestonePHID'))
->setTransactionType(
PhabricatorProjectMilestoneTransaction::TRANSACTIONTYPE)
->setHandleParameterType(new AphrontPHIDHTTPParameterType())
->setSingleValue($milestone_phid)
->setIsReorderable(false)
->setIsDefaultable(false)
->setIsLockable(false)
->setIsLocked(true),
id(new PhabricatorHandlesEditField())
->setKey('milestone.previous')
->setLabel(pht('Previous Milestone'))
->setSingleValue($previous_milestone_phid)
->setIsReorderable(false)
->setIsDefaultable(false)
->setIsLockable(false)
->setIsLocked(true),
id(new PhabricatorTextEditField())
->setKey('name')
->setLabel(pht('Name'))
->setTransactionType(PhabricatorProjectNameTransaction::TRANSACTIONTYPE)
->setIsRequired(true)
->setDescription(pht('Project name.'))
->setConduitDescription(pht('Rename the project'))
->setConduitTypeDescription(pht('New project name.'))
->setValue($object->getName()),
id(new PhabricatorIconSetEditField())
->setKey('icon')
->setLabel(pht('Icon'))
->setTransactionType(
PhabricatorProjectIconTransaction::TRANSACTIONTYPE)
->setIconSet(new PhabricatorProjectIconSet())
->setDescription(pht('Project icon.'))
->setConduitDescription(pht('Change the project icon.'))
->setConduitTypeDescription(pht('New project icon.'))
->setValue($object->getIcon()),
id(new PhabricatorSelectEditField())
->setKey('color')
->setLabel(pht('Color'))
->setTransactionType(
PhabricatorProjectColorTransaction::TRANSACTIONTYPE)
->setOptions(PhabricatorProjectIconSet::getColorMap())
->setDescription(pht('Project tag color.'))
->setConduitDescription(pht('Change the project tag color.'))
->setConduitTypeDescription(pht('New project tag color.'))
->setValue($object->getColor()),
id(new PhabricatorStringListEditField())
->setKey('slugs')
->setLabel(pht('Additional Hashtags'))
->setTransactionType(
PhabricatorProjectSlugsTransaction::TRANSACTIONTYPE)
->setDescription(pht('Additional project slugs.'))
->setConduitDescription(pht('Change project slugs.'))
->setConduitTypeDescription(pht('New list of slugs.'))
->setValue($slugs),
);
$can_edit_members = (!$milestone) &&
(!$object->isMilestone()) &&
(!$object->getHasSubprojects());
if ($can_edit_members) {
// Show this on the web UI when creating a project, but not when editing
// one. It is always available via Conduit.
$show_field = (bool)$this->getIsCreate();
$members_field = id(new PhabricatorUsersEditField())
->setKey('members')
->setAliases(array('memberPHIDs'))
->setLabel(pht('Initial Members'))
->setIsFormField($show_field)
->setUseEdgeTransactions(true)
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue(
'edge:type',
PhabricatorProjectProjectHasMemberEdgeType::EDGECONST)
->setDescription(pht('Initial project members.'))
->setConduitDescription(pht('Set project members.'))
->setConduitTypeDescription(pht('New list of members.'))
->setValue(array());
$members_field->setViewer($this->getViewer());
$edit_add = $members_field->getConduitEditType('members.add')
->setConduitDescription(pht('Add members.'));
$edit_set = $members_field->getConduitEditType('members.set')
->setConduitDescription(
pht('Set members, overwriting the current value.'));
$edit_rem = $members_field->getConduitEditType('members.remove')
->setConduitDescription(pht('Remove members.'));
$fields[] = $members_field;
}
return $fields;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/engine/PhabricatorBoardRenderingEngine.php | src/applications/project/engine/PhabricatorBoardRenderingEngine.php | <?php
final class PhabricatorBoardRenderingEngine extends Phobject {
private $viewer;
private $objects;
private $excludedProjectPHIDs;
private $editMap;
private $loaded;
private $handles;
private $coverFiles;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setObjects(array $objects) {
$this->objects = mpull($objects, null, 'getPHID');
return $this;
}
public function getObjects() {
return $this->objects;
}
public function setExcludedProjectPHIDs(array $phids) {
$this->excludedProjectPHIDs = $phids;
return $this;
}
public function getExcludedProjectPHIDs() {
return $this->excludedProjectPHIDs;
}
public function setEditMap(array $edit_map) {
$this->editMap = $edit_map;
return $this;
}
public function getEditMap() {
return $this->editMap;
}
public function renderCard($phid) {
$this->willRender();
$viewer = $this->getViewer();
$object = idx($this->getObjects(), $phid);
$card = id(new ProjectBoardTaskCard())
->setViewer($viewer)
->setTask($object)
->setShowEditControls(true)
->setCanEdit($this->getCanEdit($phid));
$owner_phid = $object->getOwnerPHID();
if ($owner_phid) {
$owner_handle = $this->handles[$owner_phid];
$card->setOwner($owner_handle);
}
$project_phids = $object->getProjectPHIDs();
$project_handles = array_select_keys($this->handles, $project_phids);
if ($project_handles) {
$card
->setHideArchivedProjects(true)
->setProjectHandles($project_handles);
}
$cover_phid = $object->getCoverImageThumbnailPHID();
if ($cover_phid) {
$cover_file = idx($this->coverFiles, $cover_phid);
if ($cover_file) {
$card->setCoverImageFile($cover_file);
}
}
return $card;
}
private function willRender() {
if ($this->loaded) {
return;
}
$phids = array();
foreach ($this->objects as $object) {
$owner_phid = $object->getOwnerPHID();
if ($owner_phid) {
$phids[$owner_phid] = $owner_phid;
}
foreach ($object->getProjectPHIDs() as $phid) {
$phids[$phid] = $phid;
}
}
if ($this->excludedProjectPHIDs) {
foreach ($this->excludedProjectPHIDs as $excluded_phid) {
unset($phids[$excluded_phid]);
}
}
$viewer = $this->getViewer();
$handles = $viewer->loadHandles($phids);
$handles = iterator_to_array($handles);
$this->handles = $handles;
$cover_phids = array();
foreach ($this->objects as $object) {
$cover_phid = $object->getCoverImageThumbnailPHID();
if ($cover_phid) {
$cover_phids[$cover_phid] = $cover_phid;
}
}
if ($cover_phids) {
$cover_files = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs($cover_phids)
->execute();
$cover_files = mpull($cover_files, null, 'getPHID');
} else {
$cover_files = array();
}
$this->coverFiles = $cover_files;
$this->loaded = true;
}
private function getCanEdit($phid) {
if ($this->editMap === null) {
return true;
}
return idx($this->editMap, $phid);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/engine/PhabricatorBoardResponseEngine.php | src/applications/project/engine/PhabricatorBoardResponseEngine.php | <?php
final class PhabricatorBoardResponseEngine extends Phobject {
private $viewer;
private $objects;
private $boardPHID;
private $visiblePHIDs = array();
private $updatePHIDs = array();
private $ordering;
private $sounds;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setBoardPHID($board_phid) {
$this->boardPHID = $board_phid;
return $this;
}
public function getBoardPHID() {
return $this->boardPHID;
}
public function setObjects(array $objects) {
$this->objects = $objects;
return $this;
}
public function getObjects() {
return $this->objects;
}
public function setVisiblePHIDs(array $visible_phids) {
$this->visiblePHIDs = $visible_phids;
return $this;
}
public function getVisiblePHIDs() {
return $this->visiblePHIDs;
}
public function setUpdatePHIDs(array $update_phids) {
$this->updatePHIDs = $update_phids;
return $this;
}
public function getUpdatePHIDs() {
return $this->updatePHIDs;
}
public function setOrdering(PhabricatorProjectColumnOrder $ordering) {
$this->ordering = $ordering;
return $this;
}
public function getOrdering() {
return $this->ordering;
}
public function setSounds(array $sounds) {
$this->sounds = $sounds;
return $this;
}
public function getSounds() {
return $this->sounds;
}
public function buildResponse() {
$viewer = $this->getViewer();
$board_phid = $this->getBoardPHID();
$ordering = $this->getOrdering();
$update_phids = $this->getUpdatePHIDs();
$update_phids = array_fuse($update_phids);
$visible_phids = $this->getVisiblePHIDs();
$visible_phids = array_fuse($visible_phids);
$all_phids = $update_phids + $visible_phids;
// Load all the other tasks that are visible in the affected columns and
// perform layout for them.
if ($this->objects !== null) {
$all_objects = $this->getObjects();
$all_objects = mpull($all_objects, null, 'getPHID');
} else {
$all_objects = id(new ManiphestTaskQuery())
->setViewer($viewer)
->withPHIDs($all_phids)
->execute();
$all_objects = mpull($all_objects, null, 'getPHID');
}
// NOTE: The board layout engine is sensitive to PHID input order, and uses
// the input order as a component of the "natural" column ordering if no
// explicit ordering is specified. Rearrange the PHIDs in ID order.
$all_objects = msort($all_objects, 'getID');
$ordered_phids = mpull($all_objects, 'getPHID');
$layout_engine = id(new PhabricatorBoardLayoutEngine())
->setViewer($viewer)
->setBoardPHIDs(array($board_phid))
->setObjectPHIDs($ordered_phids)
->executeLayout();
$natural = array();
$update_columns = array();
foreach ($update_phids as $update_phid) {
$update_columns += $layout_engine->getObjectColumns(
$board_phid,
$update_phid);
}
foreach ($update_columns as $column_phid => $column) {
$column_object_phids = $layout_engine->getColumnObjectPHIDs(
$board_phid,
$column_phid);
$natural[$column_phid] = array_values($column_object_phids);
}
if ($ordering) {
$vectors = $ordering->getSortVectorsForObjects($all_objects);
$header_keys = $ordering->getHeaderKeysForObjects($all_objects);
$headers = $ordering->getHeadersForObjects($all_objects);
$headers = mpull($headers, 'toDictionary');
} else {
$vectors = array();
$header_keys = array();
$headers = array();
}
$templates = $this->newCardTemplates();
$cards = array();
foreach ($all_objects as $card_phid => $object) {
$card = array(
'vectors' => array(),
'headers' => array(),
'properties' => array(),
'nodeHTMLTemplate' => null,
);
if ($ordering) {
$order_key = $ordering->getColumnOrderKey();
$vector = idx($vectors, $card_phid);
if ($vector !== null) {
$card['vectors'][$order_key] = $vector;
}
$header = idx($header_keys, $card_phid);
if ($header !== null) {
$card['headers'][$order_key] = $header;
}
$card['properties'] = self::newTaskProperties($object);
}
if (isset($templates[$card_phid])) {
$card['nodeHTMLTemplate'] = hsprintf('%s', $templates[$card_phid]);
$card['update'] = true;
} else {
$card['update'] = false;
}
$card['vectors'] = (object)$card['vectors'];
$card['headers'] = (object)$card['headers'];
$card['properties'] = (object)$card['properties'];
$cards[$card_phid] = $card;
}
// Mark cards which are currently visible on the client but not visible
// on the board on the server for removal from the client view of the
// board state.
foreach ($visible_phids as $card_phid) {
if (!isset($cards[$card_phid])) {
$cards[$card_phid] = array(
'remove' => true,
);
}
}
$payload = array(
'columnMaps' => $natural,
'cards' => $cards,
'headers' => $headers,
'sounds' => $this->getSounds(),
);
return id(new AphrontAjaxResponse())
->setContent($payload);
}
public static function newTaskProperties($task) {
return array(
'points' => (double)$task->getPoints(),
'status' => $task->getStatus(),
'priority' => (int)$task->getPriority(),
'owner' => $task->getOwnerPHID(),
);
}
private function loadExcludedProjectPHIDs() {
$viewer = $this->getViewer();
$board_phid = $this->getBoardPHID();
$exclude_phids = array($board_phid);
$descendants = id(new PhabricatorProjectQuery())
->setViewer($viewer)
->withAncestorProjectPHIDs($exclude_phids)
->execute();
foreach ($descendants as $descendant) {
$exclude_phids[] = $descendant->getPHID();
}
return array_fuse($exclude_phids);
}
private function newCardTemplates() {
$viewer = $this->getViewer();
$update_phids = $this->getUpdatePHIDs();
if (!$update_phids) {
return array();
}
$update_phids = array_fuse($update_phids);
if ($this->objects === null) {
$objects = id(new ManiphestTaskQuery())
->setViewer($viewer)
->withPHIDs($update_phids)
->needProjectPHIDs(true)
->execute();
} else {
$objects = $this->getObjects();
$objects = mpull($objects, null, 'getPHID');
$objects = array_select_keys($objects, $update_phids);
}
if (!$objects) {
return array();
}
$excluded_phids = $this->loadExcludedProjectPHIDs();
$rendering_engine = id(new PhabricatorBoardRenderingEngine())
->setViewer($viewer)
->setObjects($objects)
->setExcludedProjectPHIDs($excluded_phids);
$templates = array();
foreach ($objects as $object) {
$object_phid = $object->getPHID();
$card = $rendering_engine->renderCard($object_phid);
$item = $card->getItem();
$template = hsprintf('%s', $item);
$templates[$object_phid] = $template;
}
return $templates;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectUserFunctionDatasource.php | src/applications/project/typeahead/PhabricatorProjectUserFunctionDatasource.php | <?php
final class PhabricatorProjectUserFunctionDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse User Projects');
}
public function getPlaceholderText() {
return pht('Type projects(<user>)...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorProjectLogicalUserDatasource(),
);
}
protected function evaluateFunction($function, array $argv_list) {
$result = parent::evaluateFunction($function, $argv_list);
foreach ($result as $k => $v) {
if ($v instanceof PhabricatorQueryConstraint) {
$result[$k] = $v->getValue();
}
}
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/project/typeahead/PhabricatorProjectLogicalOnlyDatasource.php | src/applications/project/typeahead/PhabricatorProjectLogicalOnlyDatasource.php | <?php
final class PhabricatorProjectLogicalOnlyDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Only');
}
public function getPlaceholderText() {
return pht('Type only()...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getDatasourceFunctions() {
return array(
'only' => array(
'name' => pht('Only Match Other Constraints'),
'summary' => pht(
'Find results with only the specified tags.'),
'description' => pht(
"This function is used with other tags, and causes the query to ".
"match only results with exactly those tags. For example, to find ".
"tasks tagged only iOS:".
"\n\n".
"> ios, only()".
"\n\n".
"This will omit results with any other project tag."),
),
);
}
public function loadResults() {
$results = array(
$this->renderOnlyFunctionToken(),
);
return $this->filterResultsAgainstTokens($results);
}
protected function evaluateFunction($function, array $argv_list) {
$results = array();
$results[] = new PhabricatorQueryConstraint(
PhabricatorQueryConstraint::OPERATOR_ONLY,
null);
return $results;
}
public function renderFunctionTokens(
$function,
array $argv_list) {
$tokens = array();
foreach ($argv_list as $argv) {
$tokens[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->renderOnlyFunctionToken());
}
return $tokens;
}
private function renderOnlyFunctionToken() {
return $this->newFunctionResult()
->setName(pht('Only'))
->setPHID('only()')
->setIcon('fa-asterisk')
->setUnique(true)
->addAttribute(
pht('Select only results with exactly the other specified tags.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectSubtypeDatasource.php | src/applications/project/typeahead/PhabricatorProjectSubtypeDatasource.php | <?php
final class PhabricatorProjectSubtypeDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Subtypes');
}
public function getPlaceholderText() {
return pht('Type a project subtype name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function loadResults() {
$results = $this->buildResults();
return $this->filterResultsAgainstTokens($results);
}
protected function renderSpecialTokens(array $values) {
return $this->renderTokensFromResults($this->buildResults(), $values);
}
private function buildResults() {
$results = array();
$subtype_map = id(new PhabricatorProject())->newEditEngineSubtypeMap();
foreach ($subtype_map->getSubtypes() as $key => $subtype) {
$result = id(new PhabricatorTypeaheadResult())
->setIcon($subtype->getIcon())
->setColor($subtype->getColor())
->setPHID($key)
->setName($subtype->getName());
$results[$key] = $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/project/typeahead/PhabricatorProjectLogicalAncestorDatasource.php | src/applications/project/typeahead/PhabricatorProjectLogicalAncestorDatasource.php | <?php
final class PhabricatorProjectLogicalAncestorDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Projects');
}
public function getPlaceholderText() {
return pht('Type a project name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorProjectDatasource(),
);
}
protected function didEvaluateTokens(array $results) {
$phids = array();
foreach ($results as $result) {
if (!is_string($result)) {
continue;
}
$phids[] = $result;
}
$map = array();
$skip = array();
if ($phids) {
$phids = array_fuse($phids);
$viewer = $this->getViewer();
$all_projects = id(new PhabricatorProjectQuery())
->setViewer($viewer)
->withAncestorProjectPHIDs($phids)
->execute();
foreach ($phids as $phid) {
$map[$phid][] = $phid;
}
foreach ($all_projects as $project) {
$project_phid = $project->getPHID();
$map[$project_phid][] = $project_phid;
foreach ($project->getAncestorProjects() as $ancestor) {
$ancestor_phid = $ancestor->getPHID();
if (isset($phids[$project_phid]) && isset($phids[$ancestor_phid])) {
// This is a descendant of some other project in the query, so
// we don't need to query for that project. This happens if a user
// runs a query for both "Engineering" and "Engineering > Warp
// Drive". We can only ever match the "Warp Drive" results, so
// we do not need to add the weaker "Engineering" constraint.
$skip[$ancestor_phid] = true;
}
$map[$ancestor_phid][] = $project_phid;
}
}
}
foreach ($results as $key => $result) {
if (!is_string($result)) {
continue;
}
if (empty($map[$result])) {
continue;
}
// This constraint is implied by another, stronger constraint.
if (isset($skip[$result])) {
unset($results[$key]);
continue;
}
// If we have duplicates, don't apply the second constraint.
$skip[$result] = true;
$results[$key] = new PhabricatorQueryConstraint(
PhabricatorQueryConstraint::OPERATOR_ANCESTOR,
$map[$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/project/typeahead/PhabricatorProjectNoProjectsDatasource.php | src/applications/project/typeahead/PhabricatorProjectNoProjectsDatasource.php | <?php
final class PhabricatorProjectNoProjectsDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Not Tagged With Any Projects');
}
public function getPlaceholderText() {
return pht('Type "not tagged with any projects"...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getDatasourceFunctions() {
return array(
'null' => array(
'name' => pht('Not Tagged With Any Projects'),
'summary' => pht(
'Find results which are not tagged with any projects.'),
'description' => pht(
"This function matches results which are not tagged with any ".
"projects. It is usually most often used to find objects which ".
"might have slipped through the cracks and not been organized ".
"properly.\n\n%s",
'> null()'),
),
);
}
public function loadResults() {
$results = array(
$this->buildNullResult(),
);
return $this->filterResultsAgainstTokens($results);
}
protected function evaluateFunction($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = new PhabricatorQueryConstraint(
PhabricatorQueryConstraint::OPERATOR_NULL,
'empty');
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->buildNullResult());
}
return $results;
}
private function buildNullResult() {
$name = pht('Not Tagged With Any Projects');
return $this->newFunctionResult()
->setUnique(true)
->setPHID('null()')
->setIcon('fa-ban')
->setName('null '.$name)
->setDisplayName($name)
->addAttribute(pht('Select results with no tags.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectLogicalDatasource.php | src/applications/project/typeahead/PhabricatorProjectLogicalDatasource.php | <?php
final class PhabricatorProjectLogicalDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Projects');
}
public function getPlaceholderText() {
return pht('Type a project name or function...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorProjectNoProjectsDatasource(),
new PhabricatorProjectLogicalAncestorDatasource(),
new PhabricatorProjectLogicalOrNotDatasource(),
new PhabricatorProjectLogicalViewerDatasource(),
new PhabricatorProjectLogicalOnlyDatasource(),
new PhabricatorProjectLogicalUserDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectLogicalOrNotDatasource.php | src/applications/project/typeahead/PhabricatorProjectLogicalOrNotDatasource.php | <?php
final class PhabricatorProjectLogicalOrNotDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Projects');
}
public function getPlaceholderText() {
return pht('Type any(<project>) or not(<project>)...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorProjectDatasource(),
);
}
public function getDatasourceFunctions() {
return array(
'any' => array(
'name' => pht('In Any: ...'),
'arguments' => pht('project'),
'summary' => pht('Find results in any of several projects.'),
'description' => pht(
'This function allows you to find results in one of several '.
'projects. Another way to think of this function is that it '.
'allows you to perform an "or" query.'.
"\n\n".
'By default, if you enter several projects, results are returned '.
'only if they belong to all of the projects you enter. That is, '.
'this query will only return results in //both// projects:'.
"\n\n".
'> ios, android'.
"\n\n".
'If you want to find results in any of several projects, you can '.
'use the `any()` function. For example, you can use this query to '.
'find results which are in //either// project:'.
"\n\n".
'> any(ios), any(android)'.
"\n\n".
'You can combine the `any()` function with normal project tokens '.
'to refine results. For example, use this query to find bugs in '.
'//either// iOS or Android:'.
"\n\n".
'> bug, any(ios), any(android)'),
),
'not' => array(
'name' => pht('Not In: ...'),
'arguments' => pht('project'),
'summary' => pht('Find results not in specific projects.'),
'description' => pht(
'This function allows you to find results which are not in '.
'one or more projects. For example, use this query to find '.
'results which are not associated with a specific project:'.
"\n\n".
'> not(vanilla)'.
"\n\n".
'You can exclude multiple projects. This will cause the query '.
'to return only results which are not in any of the excluded '.
'projects:'.
"\n\n".
'> not(vanilla), not(chocolate)'.
"\n\n".
'You can combine this function with other functions to refine '.
'results. For example, use this query to find iOS results which '.
'are not bugs:'.
"\n\n".
'> ios, not(bug)'),
),
);
}
protected function didLoadResults(array $results) {
$function = $this->getCurrentFunction();
$return_any = ($function !== 'not');
$return_not = ($function !== 'any');
$return = array();
foreach ($results as $result) {
$result
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setIcon('fa-asterisk')
->setColor(null)
->resetAttributes()
->addAttribute(pht('Function'));
if ($return_any) {
$return[] = id(clone $result)
->setPHID('any('.$result->getPHID().')')
->setDisplayName(pht('In Any: %s', $result->getDisplayName()))
->setName('any '.$result->getName())
->addAttribute(pht('Include results tagged with this project.'));
}
if ($return_not) {
$return[] = id(clone $result)
->setPHID('not('.$result->getPHID().')')
->setDisplayName(pht('Not In: %s', $result->getDisplayName()))
->setName('not '.$result->getName())
->addAttribute(pht('Exclude results tagged with this project.'));
}
}
return $return;
}
protected function evaluateFunction($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$operator = array(
'any' => PhabricatorQueryConstraint::OPERATOR_OR,
'not' => PhabricatorQueryConstraint::OPERATOR_NOT,
);
$results = array();
foreach ($phids as $phid) {
$results[] = new PhabricatorQueryConstraint(
$operator[$function],
$phid);
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$tokens = $this->renderTokens($phids);
foreach ($tokens as $token) {
$token->setColor(null);
if ($token->isInvalid()) {
if ($function == 'any') {
$token->setValue(pht('In Any: Invalid Project'));
} else {
$token->setValue(pht('Not In: Invalid Project'));
}
} else {
$token
->setIcon('fa-asterisk')
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION);
if ($function == 'any') {
$token
->setKey('any('.$token->getKey().')')
->setValue(pht('In Any: %s', $token->getValue()));
} else {
$token
->setKey('not('.$token->getKey().')')
->setValue(pht('Not In: %s', $token->getValue()));
}
}
}
return $tokens;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectOrUserFunctionDatasource.php | src/applications/project/typeahead/PhabricatorProjectOrUserFunctionDatasource.php | <?php
final class PhabricatorProjectOrUserFunctionDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Users and Projects');
}
public function getPlaceholderText() {
return pht('Type a user, project name, or function...');
}
public function getComponentDatasources() {
return array(
new PhabricatorViewerDatasource(),
new PhabricatorPeopleDatasource(),
new PhabricatorProjectDatasource(),
new PhabricatorProjectMembersDatasource(),
new PhabricatorProjectUserFunctionDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectOrUserDatasource.php | src/applications/project/typeahead/PhabricatorProjectOrUserDatasource.php | <?php
final class PhabricatorProjectOrUserDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Users and Projects');
}
public function getPlaceholderText() {
return pht('Type a user or project name...');
}
public function getComponentDatasources() {
return array(
new PhabricatorPeopleDatasource(),
new PhabricatorProjectDatasource(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectMembersDatasource.php | src/applications/project/typeahead/PhabricatorProjectMembersDatasource.php | <?php
final class PhabricatorProjectMembersDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse Members');
}
public function getPlaceholderText() {
return pht('Type members(<project>)...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorProjectDatasource(),
);
}
public function getDatasourceFunctions() {
return array(
'members' => array(
'name' => pht('Members: ...'),
'arguments' => pht('project'),
'summary' => pht('Find results for members of a project.'),
'description' => pht(
'This function allows you to find results for any of the members '.
'of a project:'.
"\n\n".
'> members(frontend)'),
),
);
}
protected function didLoadResults(array $results) {
foreach ($results as $result) {
$result
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setIcon('fa-users')
->setColor(null)
->setPHID('members('.$result->getPHID().')')
->setDisplayName(pht('Members: %s', $result->getDisplayName()))
->setName($result->getName().' members')
->resetAttributes()
->addAttribute(pht('Function'))
->addAttribute(pht('Select project members.'));
}
return $results;
}
protected function evaluateFunction($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$projects = id(new PhabricatorProjectQuery())
->setViewer($this->getViewer())
->needMembers(true)
->withPHIDs($phids)
->execute();
$results = array();
foreach ($projects as $project) {
foreach ($project->getMemberPHIDs() as $phid) {
$results[$phid] = $phid;
}
}
return array_values($results);
}
public function renderFunctionTokens($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$tokens = $this->renderTokens($phids);
foreach ($tokens as $token) {
// Remove any project color on this token.
$token->setColor(null);
if ($token->isInvalid()) {
$token
->setValue(pht('Members: Invalid Project'));
} else {
$token
->setIcon('fa-users')
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setKey('members('.$token->getKey().')')
->setValue(pht('Members: %s', $token->getValue()));
}
}
return $tokens;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectLogicalViewerDatasource.php | src/applications/project/typeahead/PhabricatorProjectLogicalViewerDatasource.php | <?php
final class PhabricatorProjectLogicalViewerDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Viewer Projects');
}
public function getPlaceholderText() {
return pht('Type viewerprojects()...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getDatasourceFunctions() {
return array(
'viewerprojects' => array(
'name' => pht("Current Viewer's Projects"),
'summary' => pht(
"Find results in any of the current viewer's projects."),
'description' => pht(
"This function matches results in any of the current viewing ".
"user's projects:".
"\n\n".
"> viewerprojects()".
"\n\n".
"This normally means //your// projects, but if you save a query ".
"using this function and send it to someone else, it will mean ".
"//their// projects when they run it (they become the current ".
"viewer). This can be useful for building dashboard panels."),
),
);
}
public function loadResults() {
if ($this->getViewer()->getPHID()) {
$results = array($this->renderViewerProjectsFunctionToken());
} else {
$results = array();
}
return $this->filterResultsAgainstTokens($results);
}
protected function canEvaluateFunction($function) {
if (!$this->getViewer()->getPHID()) {
return false;
}
return parent::canEvaluateFunction($function);
}
protected function evaluateFunction($function, array $argv_list) {
$viewer = $this->getViewer();
$projects = id(new PhabricatorProjectQuery())
->setViewer($viewer)
->withMemberPHIDs(array($viewer->getPHID()))
->execute();
$phids = mpull($projects, 'getPHID');
$results = array();
if ($phids) {
foreach ($phids as $phid) {
$results[] = new PhabricatorQueryConstraint(
PhabricatorQueryConstraint::OPERATOR_OR,
$phid);
}
} else {
$results[] = new PhabricatorQueryConstraint(
PhabricatorQueryConstraint::OPERATOR_EMPTY,
null);
}
return $results;
}
public function renderFunctionTokens(
$function,
array $argv_list) {
$tokens = array();
foreach ($argv_list as $argv) {
$tokens[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->renderViewerProjectsFunctionToken());
}
return $tokens;
}
private function renderViewerProjectsFunctionToken() {
return $this->newFunctionResult()
->setName(pht('Current Viewer\'s Projects'))
->setPHID('viewerprojects()')
->setIcon('fa-asterisk')
->setUnique(true)
->addAttribute(pht('Select projects current viewer is a member of.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectLogicalUserDatasource.php | src/applications/project/typeahead/PhabricatorProjectLogicalUserDatasource.php | <?php
final class PhabricatorProjectLogicalUserDatasource
extends PhabricatorTypeaheadCompositeDatasource {
public function getBrowseTitle() {
return pht('Browse User Projects');
}
public function getPlaceholderText() {
return pht('Type projects(<user>)...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function getComponentDatasources() {
return array(
new PhabricatorPeopleDatasource(),
);
}
public function getDatasourceFunctions() {
return array(
'projects' => array(
'name' => pht('Projects: ...'),
'arguments' => pht('username'),
'summary' => pht("Find results in any of a user's projects."),
'description' => pht(
"This function allows you to find results associated with any ".
"of the projects a specified user is a member of. For example, ".
"this will find results associated with all of the projects ".
"`%s` is a member of:\n\n%s\n\n",
'alincoln',
'> projects(alincoln)'),
),
);
}
protected function didLoadResults(array $results) {
foreach ($results as $result) {
$result
->setColor(null)
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setIcon('fa-asterisk')
->setPHID('projects('.$result->getPHID().')')
->setDisplayName(pht("User's Projects: %s", $result->getDisplayName()))
->setName('projects '.$result->getName());
}
return $results;
}
protected function evaluateFunction($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$phids = $this->resolvePHIDs($phids);
$projects = id(new PhabricatorProjectQuery())
->setViewer($this->getViewer())
->withMemberPHIDs($phids)
->execute();
$results = array();
foreach ($projects as $project) {
$results[] = new PhabricatorQueryConstraint(
PhabricatorQueryConstraint::OPERATOR_OR,
$project->getPHID());
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$phids = array();
foreach ($argv_list as $argv) {
$phids[] = head($argv);
}
$phids = $this->resolvePHIDs($phids);
$tokens = $this->renderTokens($phids);
foreach ($tokens as $token) {
$token->setColor(null);
if ($token->isInvalid()) {
$token
->setValue(pht("User's Projects: Invalid User"));
} else {
$token
->setIcon('fa-asterisk')
->setTokenType(PhabricatorTypeaheadTokenView::TYPE_FUNCTION)
->setKey('projects('.$token->getKey().')')
->setValue(pht("User's Projects: %s", $token->getValue()));
}
}
return $tokens;
}
private function resolvePHIDs(array $phids) {
// If we have a function like `projects(alincoln)`, try to resolve the
// username first. This won't happen normally, but can be passed in from
// the query string.
// The user might also give us an invalid username. In this case, we
// preserve it and return it in-place so we get an "invalid" token rendered
// in the UI. This shows the user where the issue is and best represents
// the user's input.
$usernames = array();
foreach ($phids as $key => $phid) {
if (phid_get_type($phid) != PhabricatorPeopleUserPHIDType::TYPECONST) {
$usernames[$key] = $phid;
}
}
if ($usernames) {
$users = id(new PhabricatorPeopleQuery())
->setViewer($this->getViewer())
->withUsernames($usernames)
->execute();
$users = mpull($users, null, 'getUsername');
foreach ($usernames as $key => $username) {
$user = idx($users, $username);
if ($user) {
$phids[$key] = $user->getPHID();
}
}
}
return $phids;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/typeahead/PhabricatorProjectDatasource.php | src/applications/project/typeahead/PhabricatorProjectDatasource.php | <?php
final class PhabricatorProjectDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Projects');
}
public function getPlaceholderText() {
return pht('Type a project name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorProjectApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
if ($raw_query !== null && strlen($raw_query)) {
// Allow users to type "#qa" or "qa" to find "Quality Assurance".
$raw_query = ltrim($raw_query, '#');
}
$tokens = self::tokenizeString($raw_query);
$query = id(new PhabricatorProjectQuery())
->needImages(true)
->needSlugs(true)
->setOrderVector(array('-status', 'id'));
if ($this->getPhase() == self::PHASE_PREFIX) {
$prefix = $this->getPrefixQuery();
$query->withNamePrefixes(array($prefix));
} else if ($tokens) {
$query->withNameTokens($tokens);
}
// If this is for policy selection, prevent users from using milestones.
$for_policy = $this->getParameter('policy');
if ($for_policy) {
$query->withIsMilestone(false);
}
$for_autocomplete = $this->getParameter('autocomplete');
$projs = $this->executeQuery($query);
$projs = mpull($projs, null, 'getPHID');
$must_have_cols = $this->getParameter('mustHaveColumns', false);
if ($must_have_cols) {
$columns = id(new PhabricatorProjectColumnQuery())
->setViewer($viewer)
->withProjectPHIDs(array_keys($projs))
->withIsProxyColumn(false)
->execute();
$has_cols = mgroup($columns, 'getProjectPHID');
} else {
$has_cols = array_fill_keys(array_keys($projs), true);
}
$is_browse = $this->getIsBrowse();
if ($is_browse && $projs) {
// TODO: This is a little ad-hoc, but we don't currently have
// infrastructure for bulk querying custom fields efficiently.
$table = new PhabricatorProjectCustomFieldStorage();
$descriptions = $table->loadAllWhere(
'objectPHID IN (%Ls) AND fieldIndex = %s',
array_keys($projs),
PhabricatorHash::digestForIndex('std:project:internal:description'));
$descriptions = mpull($descriptions, 'getFieldValue', 'getObjectPHID');
} else {
$descriptions = array();
}
$results = array();
foreach ($projs as $proj) {
$phid = $proj->getPHID();
if (!isset($has_cols[$phid])) {
continue;
}
$slug = $proj->getPrimarySlug();
if (!strlen($slug)) {
foreach ($proj->getSlugs() as $slug_object) {
$slug = $slug_object->getSlug();
if (strlen($slug)) {
break;
}
}
}
// If we're building results for the autocompleter and this project
// doesn't have any usable slugs, don't return it as a result.
if ($for_autocomplete && !strlen($slug)) {
continue;
}
$closed = null;
if ($proj->isArchived()) {
$closed = pht('Archived');
}
$all_strings = array();
// NOTE: We list the project's name first because results will be
// sorted into prefix vs content phases incorrectly if we don't: it
// will look like "Parent (Milestone)" matched "Parent" as a prefix,
// but it did not.
$all_strings[] = $proj->getName();
if ($proj->isMilestone()) {
$all_strings[] = $proj->getParentProject()->getName();
}
foreach ($proj->getSlugs() as $project_slug) {
$all_strings[] = $project_slug->getSlug();
}
$all_strings = implode("\n", $all_strings);
$proj_result = id(new PhabricatorTypeaheadResult())
->setName($all_strings)
->setDisplayName($proj->getDisplayName())
->setDisplayType($proj->getDisplayIconName())
->setURI($proj->getURI())
->setPHID($phid)
->setIcon($proj->getDisplayIconIcon())
->setColor($proj->getColor())
->setPriorityType('proj')
->setClosed($closed);
if (strlen($slug)) {
$proj_result->setAutocomplete('#'.$slug);
}
$proj_result->setImageURI($proj->getProfileImageURI());
if ($is_browse) {
$proj_result->addAttribute($proj->getDisplayIconName());
$description = idx($descriptions, $phid);
if ($description !== null && strlen($description)) {
$summary = PhabricatorMarkupEngine::summarizeSentence($description);
$proj_result->addAttribute($summary);
}
}
$results[] = $proj_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/project/capability/ProjectCreateProjectsCapability.php | src/applications/project/capability/ProjectCreateProjectsCapability.php | <?php
final class ProjectCreateProjectsCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'project.create';
public function getCapabilityName() {
return pht('Can Create Projects');
}
public function describeCapabilityRejection() {
return pht('You do not have permission to create new projects.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/capability/ProjectDefaultEditCapability.php | src/applications/project/capability/ProjectDefaultEditCapability.php | <?php
final class ProjectDefaultEditCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'project.default.edit';
public function getCapabilityName() {
return pht('Default Edit Policy');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/capability/ProjectDefaultJoinCapability.php | src/applications/project/capability/ProjectDefaultJoinCapability.php | <?php
final class ProjectDefaultJoinCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'project.default.join';
public function getCapabilityName() {
return pht('Default Join Policy');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/capability/ProjectDefaultViewCapability.php | src/applications/project/capability/ProjectDefaultViewCapability.php | <?php
final class ProjectDefaultViewCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'project.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/project/capability/ProjectCanLockProjectsCapability.php | src/applications/project/capability/ProjectCanLockProjectsCapability.php | <?php
final class ProjectCanLockProjectsCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'project.can.lock';
public function getCapabilityName() {
return pht('Can Lock Project Membership');
}
public function describeCapabilityRejection() {
return pht('You do not have permission to lock project membership.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/remarkup/ProjectRemarkupRule.php | src/applications/project/remarkup/ProjectRemarkupRule.php | <?php
final class ProjectRemarkupRule extends PhabricatorObjectRemarkupRule {
protected function getObjectNamePrefix() {
return '#';
}
protected function renderObjectRef(
$object,
PhabricatorObjectHandle $handle,
$anchor,
$id) {
if ($this->getEngine()->isTextMode()) {
return '#'.$id;
}
$tag = $handle->renderTag();
$tag->setPHID($handle->getPHID());
return $tag;
}
protected function getObjectIDPattern() {
// NOTE: The latter half of this rule matches monograms with internal
// periods, like `#domain.com`, but does not match monograms with terminal
// periods, because they're probably just punctuation.
// Broadly, this will not match every possible project monogram, and we
// accept some false negatives -- like `#dot.` -- in order to avoid a bunch
// of false positives on general use of the `#` character.
// In other contexts, the PhabricatorProjectProjectPHIDType pattern is
// controlling and these names should parse correctly.
// These characters may never appear anywhere in a hashtag.
$never = '\s?!,:;{}#\\(\\)"\'\\*/~';
// These characters may not appear at the edge of the string.
$never_edge = '.';
return
'[^'.$never_edge.$never.']+'.
'(?:'.
'[^'.$never.']*'.
'[^'.$never_edge.$never.']+'.
')*';
}
protected function loadObjects(array $ids) {
$viewer = $this->getEngine()->getConfig('viewer');
// Put the "#" back on the front of these IDs.
$names = array();
foreach ($ids as $id) {
$names[] = '#'.$id;
}
// Issue a query by object name.
$query = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withNames($names);
$query->execute();
$projects = $query->getNamedResults();
// Slice the "#" off again.
$result = array();
foreach ($projects as $name => $project) {
$result[substr($name, 1)] = $project;
}
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/project/remarkup/__tests__/ProjectRemarkupRuleTestCase.php | src/applications/project/remarkup/__tests__/ProjectRemarkupRuleTestCase.php | <?php
final class ProjectRemarkupRuleTestCase extends PhabricatorTestCase {
public function testProjectObjectRemarkup() {
$cases = array(
'I like #ducks.' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 8,
'id' => 'ducks',
),
),
),
'We should make a post on #blog.example.com tomorrow.' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 26,
'id' => 'blog.example.com',
),
),
),
'We should make a post on #blog.example.com.' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 26,
'id' => 'blog.example.com',
),
),
),
'#123' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 1,
'id' => '123',
),
),
),
'#2x4' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 1,
'id' => '2x4',
),
),
),
'#security#123' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 1,
'id' => 'security',
'tail' => '123',
),
),
),
// Don't match a terminal parenthesis. This fixes these constructs in
// natural language.
'There is some documentation (see #guides).' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 34,
'id' => 'guides',
),
),
),
// Don't match internal parentheses either. This makes the terminal
// parenthesis behavior less arbitrary (otherwise, we match open
// parentheses but not closing parentheses, which is surprising).
'#a(b)c' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 1,
'id' => 'a',
),
),
),
'#s3' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 1,
'id' => 's3',
),
),
),
'Is this #urgent?' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 9,
'id' => 'urgent',
),
),
),
'This is "#urgent".' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 10,
'id' => 'urgent',
),
),
),
"This is '#urgent'." => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 10,
'id' => 'urgent',
),
),
),
'**#orbital**' => array(
'embed' => array(),
'ref' => array(
array(
'offset' => 3,
'id' => 'orbital',
),
),
),
);
foreach ($cases as $input => $expect) {
$rule = new ProjectRemarkupRule();
$matches = $rule->extractReferences($input);
$this->assertEqual($expect, $matches, $input);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/constants/PhabricatorProjectStatus.php | src/applications/project/constants/PhabricatorProjectStatus.php | <?php
final class PhabricatorProjectStatus extends Phobject {
const STATUS_ACTIVE = 0;
const STATUS_ARCHIVED = 100;
public static function getNameForStatus($status) {
$map = array(
self::STATUS_ACTIVE => pht('Active'),
self::STATUS_ARCHIVED => pht('Archived'),
);
return idx($map, coalesce($status, '?'), pht('Unknown'));
}
public static function getStatusMap() {
return array(
self::STATUS_ACTIVE => pht('Active'),
self::STATUS_ARCHIVED => pht('Archived'),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/project/constants/PhabricatorProjectWorkboardBackgroundColor.php | src/applications/project/constants/PhabricatorProjectWorkboardBackgroundColor.php | <?php
final class PhabricatorProjectWorkboardBackgroundColor extends Phobject {
public static function getOptions() {
$options = array(
array(
'key' => '',
'name' => pht('Use Parent Background (Default)'),
'special' => 'parent',
'icon' => 'fa-chevron-circle-up',
'group' => 'basic',
),
array(
'key' => 'none',
'name' => pht('No Background'),
'special' => 'none',
'icon' => 'fa-ban',
'group' => 'basic',
),
array(
'key' => 'red',
'name' => pht('Red'),
),
array(
'key' => 'orange',
'name' => pht('Orange'),
),
array(
'key' => 'yellow',
'name' => pht('Yellow'),
),
array(
'key' => 'green',
'name' => pht('Green'),
),
array(
'key' => 'blue',
'name' => pht('Blue'),
),
array(
'key' => 'indigo',
'name' => pht('Indigo'),
),
array(
'key' => 'violet',
'name' => pht('Violet'),
),
array(
'key' => 'sky',
'name' => pht('Sky'),
),
array(
'key' => 'pink',
'name' => pht('Pink'),
),
array(
'key' => 'fire',
'name' => pht('Fire'),
),
array(
'key' => 'grey',
'name' => pht('Grey'),
),
array(
'key' => 'gradient-red',
'name' => pht('Ripe Peach'),
),
array(
'key' => 'gradient-orange',
'name' => pht('Ripe Orange'),
),
array(
'key' => 'gradient-yellow',
'name' => pht('Ripe Mango'),
),
array(
'key' => 'gradient-green',
'name' => pht('Shallows'),
),
array(
'key' => 'gradient-blue',
'name' => pht('Reef'),
),
array(
'key' => 'gradient-bluegrey',
'name' => pht('Depths'),
),
array(
'key' => 'gradient-indigo',
'name' => pht('This One Is Purple'),
),
array(
'key' => 'gradient-violet',
'name' => pht('Unripe Plum'),
),
array(
'key' => 'gradient-sky',
'name' => pht('Blue Sky'),
),
array(
'key' => 'gradient-pink',
'name' => pht('Intensity'),
),
array(
'key' => 'gradient-grey',
'name' => pht('Into The Expanse'),
),
);
foreach ($options as $key => $option) {
if (empty($option['group'])) {
if (preg_match('/^gradient/', $option['key'])) {
$option['group'] = 'gradient';
} else {
$option['group'] = 'solid';
}
}
$options[$key] = $option;
}
return ipull($options, null, 'key');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/PhabricatorImageTransformer.php | src/applications/files/PhabricatorImageTransformer.php | <?php
/**
* @task enormous Detecting Enormous Images
* @task save Saving Image Data
*/
final class PhabricatorImageTransformer extends Phobject {
/* -( Saving Image Data )-------------------------------------------------- */
/**
* Save an image resource to a string representation suitable for storage or
* transmission as an image file.
*
* Optionally, you can specify a preferred MIME type like `"image/png"`.
* Generally, you should specify the MIME type of the original file if you're
* applying file transformations. The MIME type may not be honored if
* Phabricator can not encode images in the given format (based on available
* extensions), but can save images in another format.
*
* @param resource GD image resource.
* @param string? Optionally, preferred mime type.
* @return string Bytes of an image file.
* @task save
*/
public static function saveImageDataInAnyFormat($data, $preferred_mime = '') {
$preferred = null;
switch ($preferred_mime) {
case 'image/gif':
$preferred = self::saveImageDataAsGIF($data);
break;
case 'image/png':
$preferred = self::saveImageDataAsPNG($data);
break;
}
if ($preferred !== null) {
return $preferred;
}
$data = self::saveImageDataAsJPG($data);
if ($data !== null) {
return $data;
}
$data = self::saveImageDataAsPNG($data);
if ($data !== null) {
return $data;
}
$data = self::saveImageDataAsGIF($data);
if ($data !== null) {
return $data;
}
throw new Exception(pht('Failed to save image data into any format.'));
}
/**
* Save an image in PNG format, returning the file data as a string.
*
* @param resource GD image resource.
* @return string|null PNG file as a string, or null on failure.
* @task save
*/
private static function saveImageDataAsPNG($image) {
if (!function_exists('imagepng')) {
return null;
}
// NOTE: Empirically, the highest compression level (9) seems to take
// up to twice as long as the default compression level (6) but produce
// only slightly smaller files (10% on avatars, 3% on screenshots).
ob_start();
$result = imagepng($image, null, 6);
$output = ob_get_clean();
if (!$result) {
return null;
}
return $output;
}
/**
* Save an image in GIF format, returning the file data as a string.
*
* @param resource GD image resource.
* @return string|null GIF file as a string, or null on failure.
* @task save
*/
private static function saveImageDataAsGIF($image) {
if (!function_exists('imagegif')) {
return null;
}
ob_start();
$result = imagegif($image);
$output = ob_get_clean();
if (!$result) {
return null;
}
return $output;
}
/**
* Save an image in JPG format, returning the file data as a string.
*
* @param resource GD image resource.
* @return string|null JPG file as a string, or null on failure.
* @task save
*/
private static function saveImageDataAsJPG($image) {
if (!function_exists('imagejpeg')) {
return null;
}
ob_start();
$result = imagejpeg($image);
$output = ob_get_clean();
if (!$result) {
return null;
}
return $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/controller/PhabricatorFileImageProxyController.php | src/applications/files/controller/PhabricatorFileImageProxyController.php | <?php
final class PhabricatorFileImageProxyController
extends PhabricatorFileController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$img_uri = $request->getStr('uri');
// Validate the URI before doing anything
PhabricatorEnv::requireValidRemoteURIForLink($img_uri);
$uri = new PhutilURI($img_uri);
$proto = $uri->getProtocol();
$allowed_protocols = array(
'http',
'https',
);
if (!in_array($proto, $allowed_protocols)) {
throw new Exception(
pht(
'The provided image URI must use one of these protocols: %s.',
implode(', ', $allowed_protocols)));
}
// Check if we already have the specified image URI downloaded
$cached_request = id(new PhabricatorFileExternalRequest())->loadOneWhere(
'uriIndex = %s',
PhabricatorHash::digestForIndex($img_uri));
if ($cached_request) {
return $this->getExternalResponse($cached_request);
}
$ttl = PhabricatorTime::getNow() + phutil_units('7 days in seconds');
$external_request = id(new PhabricatorFileExternalRequest())
->setURI($img_uri)
->setTTL($ttl);
// Cache missed, so we'll need to validate and download the image.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$save_request = false;
try {
// Rate limit outbound fetches to make this mechanism less useful for
// scanning networks and ports.
PhabricatorSystemActionEngine::willTakeAction(
array($viewer->getPHID()),
new PhabricatorFilesOutboundRequestAction(),
1);
$file = PhabricatorFile::newFromFileDownload(
$uri,
array(
'viewPolicy' => PhabricatorPolicies::POLICY_NOONE,
'canCDN' => true,
));
if (!$file->isViewableImage()) {
$mime_type = $file->getMimeType();
$engine = new PhabricatorDestructionEngine();
$engine->destroyObject($file);
$file = null;
throw new Exception(
pht(
'The URI "%s" does not correspond to a valid image file (got '.
'a file with MIME type "%s"). You must specify the URI of a '.
'valid image file.',
$uri,
$mime_type));
}
$file->save();
$external_request
->setIsSuccessful(1)
->setFilePHID($file->getPHID());
$save_request = true;
} catch (HTTPFutureHTTPResponseStatus $status) {
$external_request
->setIsSuccessful(0)
->setResponseMessage($status->getMessage());
$save_request = true;
} catch (Exception $ex) {
// Not actually saving the request in this case
$external_request->setResponseMessage($ex->getMessage());
}
if ($save_request) {
try {
$external_request->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// We may have raced against another identical request. If we did,
// just throw our result away and use the winner's result.
$external_request = $external_request->loadOneWhere(
'uriIndex = %s',
PhabricatorHash::digestForIndex($img_uri));
if (!$external_request) {
throw new Exception(
pht(
'Hit duplicate key collision when saving proxied image, but '.
'failed to load duplicate row (for URI "%s").',
$img_uri));
}
}
}
unset($unguarded);
return $this->getExternalResponse($external_request);
}
private function getExternalResponse(
PhabricatorFileExternalRequest $request) {
if (!$request->getIsSuccessful()) {
throw new Exception(
pht(
'Request to "%s" failed: %s',
$request->getURI(),
$request->getResponseMessage()));
}
$file = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs(array($request->getFilePHID()))
->executeOne();
if (!$file) {
throw new Exception(
pht(
'The underlying file does not exist, but the cached request was '.
'successful. This likely means the file record was manually '.
'deleted by an administrator.'));
}
return id(new AphrontAjaxResponse())
->setContent(
array(
'imageURI' => $file->getViewURI(),
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileUICurtainAttachController.php | src/applications/files/controller/PhabricatorFileUICurtainAttachController.php | <?php
final class PhabricatorFileUICurtainAttachController
extends PhabricatorFileController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$object_phid = $request->getURIData('objectPHID');
$file_phid = $request->getURIData('filePHID');
$object = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withPHIDs(array($object_phid))
->executeOne();
if (!$object) {
return new Aphront404Response();
}
$attachment = id(new PhabricatorFileAttachmentQuery())
->setViewer($viewer)
->withObjectPHIDs(array($object->getPHID()))
->withFilePHIDs(array($file_phid))
->needFiles(true)
->withVisibleFiles(true)
->executeOne();
if (!$attachment) {
return new Aphront404Response();
}
$handles = $viewer->loadHandles(
array(
$object_phid,
$file_phid,
));
$object_handle = $handles[$object_phid];
$file_handle = $handles[$file_phid];
$cancel_uri = $object_handle->getURI();
$dialog = $this->newDialog()
->setViewer($viewer)
->setTitle(pht('Attach File'))
->addCancelButton($cancel_uri, pht('Close'));
$file_link = phutil_tag('strong', array(), $file_handle->renderLink());
$object_link = phutil_tag('strong', array(), $object_handle->renderLink());
if ($attachment->isPolicyAttachment()) {
$body = pht(
'The file %s is already attached to the object %s.',
$file_link,
$object_link);
return $dialog->appendParagraph($body);
}
if (!$request->isDialogFormPost()) {
$dialog->appendRemarkup(
pht(
'(WARNING) This file is referenced by this object, but '.
'not formally attached to it. Users who can see the object may '.
'not be able to see the file.'));
$dialog->appendParagraph(
pht(
'Do you want to attach the file %s to the object %s?',
$file_link,
$object_link));
$dialog->addSubmitButton(pht('Attach File'));
return $dialog;
}
if (!$request->getBool('confirm')) {
$dialog->setTitle(pht('Confirm File Attachment'));
$dialog->addHiddenInput('confirm', 1);
$dialog->appendRemarkup(
pht(
'(IMPORTANT) If you attach this file to this object, any user who '.
'has permission to view the object will be able to view and '.
'download the file!'));
$dialog->appendParagraph(
pht(
'Really attach the file %s to the object %s, allowing any user '.
'who can view the object to view and download the file?',
$file_link,
$object_link));
$dialog->addSubmitButton(pht('Grant Permission'));
return $dialog;
}
if (!($object instanceof PhabricatorApplicationTransactionInterface)) {
$dialog->appendParagraph(
pht(
'This object (of class "%s") does not implement the required '.
'interface ("%s"), so files can not be manually attached to it.',
get_class($object),
'PhabricatorApplicationTransactionInterface'));
return $dialog;
}
$editor = $object->getApplicationTransactionEditor()
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true);
$template = $object->getApplicationTransactionTemplate();
$xactions = array();
$xactions[] = id(clone $template)
->setTransactionType(PhabricatorTransactions::TYPE_FILE)
->setNewValue(
array(
$file_phid => PhabricatorFileAttachment::MODE_ATTACH,
));
$editor->applyTransactions($object, $xactions);
return $this->newRedirect()
->setURI($cancel_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/controller/PhabricatorFileListController.php | src/applications/files/controller/PhabricatorFileListController.php | <?php
final class PhabricatorFileListController extends PhabricatorFileController {
public function shouldAllowPublic() {
return true;
}
public function isGlobalDragAndDropUploadEnabled() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new PhabricatorFileSearchEngine())
->setController($this)
->buildResponse();
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$crumbs->addAction(
id(new PHUIListItemView())
->setName(pht('Upload File'))
->setIcon('fa-upload')
->setHref($this->getApplicationURI('/upload/')));
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/files/controller/PhabricatorFileController.php | src/applications/files/controller/PhabricatorFileController.php | <?php
abstract class PhabricatorFileController extends PhabricatorController {
public function buildApplicationMenu() {
return $this->newApplicationMenu()
->setSearchEngine(new PhabricatorFileSearchEngine());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileLightboxController.php | src/applications/files/controller/PhabricatorFileLightboxController.php | <?php
final class PhabricatorFileLightboxController
extends PhabricatorFileController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$phid = $request->getURIData('phid');
$comment = $request->getStr('comment');
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($phid))
->executeOne();
if (!$file) {
return new Aphront404Response();
}
if ($comment !== null && strlen($comment)) {
$xactions = array();
$xactions[] = id(new PhabricatorFileTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)
->attachComment(
id(new PhabricatorFileTransactionComment())
->setContent($comment));
$editor = id(new PhabricatorFileEditor())
->setActor($viewer)
->setContinueOnNoEffect(true)
->setContentSourceFromRequest($request);
$editor->applyTransactions($file, $xactions);
}
$transactions = id(new PhabricatorFileTransactionQuery())
->withTransactionTypes(array(PhabricatorTransactions::TYPE_COMMENT));
$timeline = $this->buildTransactionTimeline($file, $transactions);
$comment_form = $this->renderCommentForm($file);
$info = phutil_tag(
'div',
array(
'class' => 'phui-comment-panel-header',
),
$file->getName());
require_celerity_resource('phui-comment-panel-css');
$content = phutil_tag(
'div',
array(
'class' => 'phui-comment-panel',
),
array(
$info,
$timeline,
$comment_form,
));
return id(new AphrontAjaxResponse())
->setContent($content);
}
private function renderCommentForm(PhabricatorFile $file) {
$viewer = $this->getViewer();
if (!$viewer->isLoggedIn()) {
$login_href = id(new PhutilURI('/auth/start/'))
->replaceQueryParam('next', '/'.$file->getMonogram());
return id(new PHUIFormLayoutView())
->addClass('phui-comment-panel-empty')
->appendChild(
id(new PHUIButtonView())
->setTag('a')
->setText(pht('Log In to Comment'))
->setHref((string)$login_href));
}
$draft = PhabricatorDraft::newFromUserAndKey(
$viewer,
$file->getPHID());
$post_uri = $this->getApplicationURI('thread/'.$file->getPHID().'/');
$form = id(new AphrontFormView())
->setUser($viewer)
->setAction($post_uri)
->addSigil('lightbox-comment-form')
->addClass('lightbox-comment-form')
->setWorkflow(true)
->appendChild(
id(new PhabricatorRemarkupControl())
->setUser($viewer)
->setName('comment')
->setValue($draft->getDraft()))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Comment')));
$view = phutil_tag_div('phui-comment-panel', $form);
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/files/controller/PhabricatorFileDeleteController.php | src/applications/files/controller/PhabricatorFileDeleteController.php | <?php
final class PhabricatorFileDeleteController extends PhabricatorFileController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withIDs(array($id))
->withIsDeleted(false)
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$file) {
return new Aphront404Response();
}
if (($viewer->getPHID() != $file->getAuthorPHID()) &&
(!$viewer->getIsAdmin())) {
return new Aphront403Response();
}
if ($request->isFormPost()) {
$xactions = array();
$xactions[] = id(new PhabricatorFileTransaction())
->setTransactionType(PhabricatorFileDeleteTransaction::TRANSACTIONTYPE)
->setNewValue(true);
id(new PhabricatorFileEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true)
->applyTransactions($file, $xactions);
return id(new AphrontRedirectResponse())->setURI('/file/');
}
return $this->newDialog()
->setTitle(pht('Really delete file?'))
->appendChild(hsprintf(
'<p>%s</p>',
pht(
'Permanently delete "%s"? This action can not be undone.',
$file->getName())))
->addSubmitButton(pht('Delete'))
->addCancelButton($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/controller/PhabricatorFileDataController.php | src/applications/files/controller/PhabricatorFileDataController.php | <?php
final class PhabricatorFileDataController extends PhabricatorFileController {
private $phid;
private $key;
private $file;
public function shouldRequireLogin() {
return false;
}
public function shouldAllowPartialSessions() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$this->phid = $request->getURIData('phid');
$this->key = $request->getURIData('key');
$alt = PhabricatorEnv::getEnvConfig('security.alternate-file-domain');
$base_uri = PhabricatorEnv::getEnvConfig('phabricator.base-uri');
$alt_uri = new PhutilURI($alt);
$alt_domain = $alt_uri->getDomain();
$req_domain = $request->getHost();
$main_domain = id(new PhutilURI($base_uri))->getDomain();
$request_kind = $request->getURIData('kind');
$is_download = ($request_kind === 'download');
if (($alt === null || !strlen($alt)) || $main_domain == $alt_domain) {
// No alternate domain.
$should_redirect = false;
$is_alternate_domain = false;
} else if ($req_domain != $alt_domain) {
// Alternate domain, but this request is on the main domain.
$should_redirect = true;
$is_alternate_domain = false;
} else {
// Alternate domain, and on the alternate domain.
$should_redirect = false;
$is_alternate_domain = true;
}
$response = $this->loadFile();
if ($response) {
return $response;
}
$file = $this->getFile();
if ($should_redirect) {
return id(new AphrontRedirectResponse())
->setIsExternal(true)
->setURI($file->getCDNURI($request_kind));
}
$response = new AphrontFileResponse();
$response->setCacheDurationInSeconds(60 * 60 * 24 * 30);
$response->setCanCDN($file->getCanCDN());
$begin = null;
$end = null;
// NOTE: It's important to accept "Range" requests when playing audio.
// If we don't, Safari has difficulty figuring out how long sounds are
// and glitches when trying to loop them. In particular, Safari sends
// an initial request for bytes 0-1 of the audio file, and things go south
// if we can't respond with a 206 Partial Content.
$range = $request->getHTTPHeader('range');
if ($range !== null && strlen($range)) {
list($begin, $end) = $response->parseHTTPRange($range);
}
if (!$file->isViewableInBrowser()) {
$is_download = true;
}
$request_type = $request->getHTTPHeader('X-Phabricator-Request-Type');
$is_lfs = ($request_type == 'git-lfs');
if (!$is_download) {
$response->setMimeType($file->getViewableMimeType());
} else {
$is_post = $request->isHTTPPost();
$is_public = !$viewer->isLoggedIn();
// NOTE: Require POST to download files from the primary domain. If the
// request is not a POST request but arrives on the primary domain, we
// render a confirmation dialog. For discussion, see T13094.
// There are two exceptions to this rule:
// Git LFS requests can download with GET. This is safe (Git LFS won't
// execute files it downloads) and necessary to support Git LFS.
// Requests with no credentials may also download with GET. This
// primarily supports downloading files with `arc download` or other
// API clients. This is only "mostly" safe: if you aren't logged in, you
// are likely immune to XSS and CSRF. However, an attacker may still be
// able to set cookies on this domain (for example, to fixate your
// session). For now, we accept these risks because users running
// Phabricator in this mode are knowingly accepting a security risk
// against setup advice, and there's significant value in having
// API development against test and production installs work the same
// way.
$is_safe = ($is_alternate_domain || $is_post || $is_lfs || $is_public);
if (!$is_safe) {
return $this->newDialog()
->setSubmitURI($file->getDownloadURI())
->setTitle(pht('Download File'))
->appendParagraph(
pht(
'Download file %s (%s)?',
phutil_tag('strong', array(), $file->getName()),
phutil_format_bytes($file->getByteSize())))
->addCancelButton($file->getURI())
->addSubmitButton(pht('Download File'));
}
$response->setMimeType($file->getMimeType());
$response->setDownload($file->getName());
}
$iterator = $file->getFileDataIterator($begin, $end);
$response->setContentLength($file->getByteSize());
$response->setContentIterator($iterator);
// In Chrome, we must permit this domain in "object-src" CSP when serving a
// PDF or the browser will refuse to render it.
if (!$is_download && $file->isPDF()) {
$request_uri = id(clone $request->getAbsoluteRequestURI())
->setPath(null)
->setFragment(null)
->removeAllQueryParams();
$response->addContentSecurityPolicyURI(
'object-src',
(string)$request_uri);
}
if ($this->shouldCompressFileDataResponse($file)) {
$response->setCompressResponse(true);
}
return $response;
}
private function loadFile() {
// Access to files is provided by knowledge of a per-file secret key in
// the URI. Knowledge of this secret is sufficient to retrieve the file.
// For some requests, we also have a valid viewer. However, for many
// requests (like alternate domain requests or Git LFS requests) we will
// not. Even if we do have a valid viewer, use the omnipotent viewer to
// make this logic simpler and more consistent.
// Beyond making the policy check itself more consistent, this also makes
// sure we're consistent about returning HTTP 404 on bad requests instead
// of serving HTTP 200 with a login page, which can mislead some clients.
$viewer = PhabricatorUser::getOmnipotentUser();
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($this->phid))
->withIsDeleted(false)
->executeOne();
if (!$file) {
return new Aphront404Response();
}
// We may be on the CDN domain, so we need to use a fully-qualified URI
// here to make sure we end up back on the main domain.
$info_uri = PhabricatorEnv::getURI($file->getInfoURI());
if (!$file->validateSecretKey($this->key)) {
$dialog = $this->newDialog()
->setTitle(pht('Invalid Authorization'))
->appendParagraph(
pht(
'The link you followed to access this file is no longer '.
'valid. The visibility of the file may have changed after '.
'the link was generated.'))
->appendParagraph(
pht(
'You can continue to the file detail page to get more '.
'information and attempt to access the file.'))
->addCancelButton($info_uri, pht('Continue'));
return id(new AphrontDialogResponse())
->setDialog($dialog)
->setHTTPResponseCode(404);
}
if ($file->getIsPartial()) {
$dialog = $this->newDialog()
->setTitle(pht('Partial Upload'))
->appendParagraph(
pht(
'This file has only been partially uploaded. It must be '.
'uploaded completely before you can download it.'))
->appendParagraph(
pht(
'You can continue to the file detail page to monitor the '.
'upload progress of the file.'))
->addCancelButton($info_uri, pht('Continue'));
return id(new AphrontDialogResponse())
->setDialog($dialog)
->setHTTPResponseCode(404);
}
$this->file = $file;
return null;
}
private function getFile() {
if (!$this->file) {
throw new PhutilInvalidStateException('loadFile');
}
return $this->file;
}
private function shouldCompressFileDataResponse(PhabricatorFile $file) {
// If the client sends "Accept-Encoding: gzip", we have the option of
// compressing the response.
// We generally expect this to be a good idea if the file compresses well,
// but maybe not such a great idea if the file is already compressed (like
// an image or video) or compresses poorly: the CPU cost of compressing and
// decompressing the stream may exceed the bandwidth savings during
// transfer.
// Ideally, we'd probably make this decision by compressing files when
// they are uploaded, storing the compressed size, and then doing a test
// here using the compression savings and estimated transfer speed.
// For now, just guess that we shouldn't compress images or videos or
// files that look like they are already compressed, and should compress
// everything else.
if ($file->isViewableImage()) {
return false;
}
if ($file->isAudio()) {
return false;
}
if ($file->isVideo()) {
return false;
}
$compressed_types = array(
'application/x-gzip',
'application/x-compress',
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
);
$compressed_types = array_fuse($compressed_types);
$mime_type = $file->getMimeType();
if (isset($compressed_types[$mime_type])) {
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/controller/PhabricatorFileUploadController.php | src/applications/files/controller/PhabricatorFileUploadController.php | <?php
final class PhabricatorFileUploadController extends PhabricatorFileController {
public function isGlobalDragAndDropUploadEnabled() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getUser();
$file = PhabricatorFile::initializeNewFile();
$e_file = true;
$errors = array();
if ($request->isFormPost()) {
$view_policy = $request->getStr('viewPolicy');
if (!$request->getFileExists('file')) {
$e_file = pht('Required');
$errors[] = pht('You must select a file to upload.');
} else {
$file = PhabricatorFile::newFromPHPUpload(
idx($_FILES, 'file'),
array(
'name' => $request->getStr('name'),
'authorPHID' => $viewer->getPHID(),
'viewPolicy' => $view_policy,
'isExplicitUpload' => true,
));
}
if (!$errors) {
return id(new AphrontRedirectResponse())->setURI($file->getInfoURI());
}
$file->setViewPolicy($view_policy);
}
$support_id = celerity_generate_unique_node_id();
$instructions = id(new AphrontFormMarkupControl())
->setControlID($support_id)
->setControlStyle('display: none')
->setValue(hsprintf(
'<br /><br /><strong>%s</strong> %s<br /><br />',
pht('Drag and Drop:'),
pht(
'You can also upload files by dragging and dropping them from your '.
'desktop onto this page or the home page.')));
$policies = id(new PhabricatorPolicyQuery())
->setViewer($viewer)
->setObject($file)
->execute();
$form = id(new AphrontFormView())
->setUser($viewer)
->setEncType('multipart/form-data')
->appendChild(
id(new AphrontFormFileControl())
->setLabel(pht('File'))
->setName('file')
->setError($e_file))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Name'))
->setName('name')
->setValue($request->getStr('name')))
->appendChild(
id(new AphrontFormPolicyControl())
->setUser($viewer)
->setCapability(PhabricatorPolicyCapability::CAN_VIEW)
->setPolicyObject($file)
->setPolicies($policies)
->setName('viewPolicy'))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Upload'))
->addCancelButton('/file/'))
->appendChild($instructions);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb(pht('Upload'), $request->getRequestURI());
$crumbs->setBorder(true);
$title = pht('Upload File');
$global_upload = id(new PhabricatorGlobalUploadTargetView())
->setUser($viewer)
->setShowIfSupportedID($support_id);
$form_box = id(new PHUIObjectBoxView())
->setHeaderText($title)
->setFormErrors($errors)
->setBackground(PHUIObjectBoxView::WHITE_CONFIG)
->setForm($form);
$view = id(new PHUITwoColumnView())
->setFooter(array(
$form_box,
$global_upload,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild($view);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileTransformListController.php | src/applications/files/controller/PhabricatorFileTransformListController.php | <?php
final class PhabricatorFileTransformListController
extends PhabricatorFileController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->executeOne();
if (!$file) {
return new Aphront404Response();
}
$monogram = $file->getMonogram();
$xdst = id(new PhabricatorTransformedFile())->loadAllWhere(
'transformedPHID = %s',
$file->getPHID());
$dst_rows = array();
foreach ($xdst as $source) {
$dst_rows[] = array(
$source->getTransform(),
$viewer->renderHandle($source->getOriginalPHID()),
);
}
$dst_table = id(new AphrontTableView($dst_rows))
->setHeaders(
array(
pht('Key'),
pht('Source'),
))
->setColumnClasses(
array(
'',
'wide',
))
->setNoDataString(
pht(
'This file was not created by transforming another file.'));
$xsrc = id(new PhabricatorTransformedFile())->loadAllWhere(
'originalPHID = %s',
$file->getPHID());
$xsrc = mpull($xsrc, 'getTransformedPHID', 'getTransform');
$src_rows = array();
$xforms = PhabricatorFileTransform::getAllTransforms();
foreach ($xforms as $xform) {
$dst_phid = idx($xsrc, $xform->getTransformKey());
if ($xform->canApplyTransform($file)) {
$can_apply = pht('Yes');
$view_href = $file->getURIForTransform($xform);
$view_href = new PhutilURI($view_href);
$view_href->replaceQueryParam('regenerate', 'true');
$view_text = pht('Regenerate');
$view_link = phutil_tag(
'a',
array(
'class' => 'small button button-grey',
'href' => $view_href,
),
$view_text);
} else {
$can_apply = phutil_tag('em', array(), pht('No'));
$view_link = phutil_tag('em', array(), pht('None'));
}
if ($dst_phid) {
$dst_link = $viewer->renderHandle($dst_phid);
} else {
$dst_link = phutil_tag('em', array(), pht('None'));
}
$src_rows[] = array(
$xform->getTransformName(),
$xform->getTransformKey(),
$can_apply,
$dst_link,
$view_link,
);
}
$src_table = id(new AphrontTableView($src_rows))
->setHeaders(
array(
pht('Name'),
pht('Key'),
pht('Supported'),
pht('Transform'),
pht('View'),
))
->setColumnClasses(
array(
'wide',
'',
'',
'',
'action',
));
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($monogram, '/'.$monogram);
$crumbs->addTextCrumb(pht('Transforms'));
$crumbs->setBorder(true);
$dst_box = id(new PHUIObjectBoxView())
->setHeaderText(pht('File Sources'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($dst_table);
$src_box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Available Transforms'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($src_table);
$title = pht('%s Transforms', $file->getName());
$header = id(new PHUIHeaderView())
->setHeader($title)
->setHeaderIcon('fa-arrows-alt');
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$dst_box,
$src_box,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild($view);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileComposeController.php | src/applications/files/controller/PhabricatorFileComposeController.php | <?php
final class PhabricatorFileComposeController
extends PhabricatorFileController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$color_map = PhabricatorFilesComposeIconBuiltinFile::getAllColors();
$icon_map = $this->getIconMap();
if ($request->isFormPost()) {
$project_phid = $request->getStr('projectPHID');
if ($project_phid) {
$project = id(new PhabricatorProjectQuery())
->setViewer($viewer)
->withPHIDs(array($project_phid))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$project) {
return new Aphront404Response();
}
}
$icon = $request->getStr('icon');
$color = $request->getStr('color');
$composer = id(new PhabricatorFilesComposeIconBuiltinFile())
->setIcon($icon)
->setColor($color);
$data = $composer->loadBuiltinFileData();
$file = PhabricatorFile::newFromFileData(
$data,
array(
'name' => $composer->getBuiltinDisplayName(),
'profile' => true,
'canCDN' => true,
));
if ($project_phid) {
$edit_uri = '/project/manage/'.$project->getID().'/';
$xactions = array();
$xactions[] = id(new PhabricatorProjectTransaction())
->setTransactionType(
PhabricatorProjectImageTransaction::TRANSACTIONTYPE)
->setNewValue($file->getPHID());
$editor = id(new PhabricatorProjectTransactionEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnMissingFields(true)
->setContinueOnNoEffect(true);
$editor->applyTransactions($project, $xactions);
return id(new AphrontRedirectResponse())->setURI($edit_uri);
} else {
$content = array(
'phid' => $file->getPHID(),
);
return id(new AphrontAjaxResponse())->setContent($content);
}
}
$value_color = head_key($color_map);
$value_icon = head_key($icon_map);
require_celerity_resource('people-profile-css');
$buttons = array();
foreach ($color_map as $color => $info) {
$quip = idx($info, 'quip');
$buttons[] = javelin_tag(
'button',
array(
'class' => 'button-grey profile-image-button',
'sigil' => 'has-tooltip compose-select-color',
'style' => 'margin: 0 8px 8px 0',
'meta' => array(
'color' => $color,
'tip' => $quip,
),
),
id(new PHUIIconView())
->addClass('compose-background-'.$color));
}
$icons = array();
foreach ($icon_map as $icon => $spec) {
$quip = idx($spec, 'quip');
$icons[] = javelin_tag(
'button',
array(
'class' => 'button-grey profile-image-button',
'sigil' => 'has-tooltip compose-select-icon',
'style' => 'margin: 0 8px 8px 0',
'meta' => array(
'icon' => $icon,
'tip' => $quip,
),
),
id(new PHUIIconView())
->setIcon($icon)
->addClass('compose-icon-bg'));
}
$dialog_id = celerity_generate_unique_node_id();
$color_input_id = celerity_generate_unique_node_id();
$icon_input_id = celerity_generate_unique_node_id();
$preview_id = celerity_generate_unique_node_id();
$preview = id(new PHUIIconView())
->setID($preview_id)
->addClass('compose-background-'.$value_color)
->setIcon($value_icon)
->addClass('compose-icon-bg');
$color_input = javelin_tag(
'input',
array(
'type' => 'hidden',
'name' => 'color',
'value' => $value_color,
'id' => $color_input_id,
));
$icon_input = javelin_tag(
'input',
array(
'type' => 'hidden',
'name' => 'icon',
'value' => $value_icon,
'id' => $icon_input_id,
));
Javelin::initBehavior('phabricator-tooltips');
Javelin::initBehavior(
'icon-composer',
array(
'dialogID' => $dialog_id,
'colorInputID' => $color_input_id,
'iconInputID' => $icon_input_id,
'previewID' => $preview_id,
'defaultColor' => $value_color,
'defaultIcon' => $value_icon,
));
return $this->newDialog()
->setFormID($dialog_id)
->setClass('compose-dialog')
->setTitle(pht('Compose Image'))
->appendChild(
phutil_tag(
'div',
array(
'class' => 'compose-header',
),
pht('Choose Background Color')))
->appendChild($buttons)
->appendChild(
phutil_tag(
'div',
array(
'class' => 'compose-header',
),
pht('Choose Icon')))
->appendChild($icons)
->appendChild(
phutil_tag(
'div',
array(
'class' => 'compose-header',
),
pht('Preview')))
->appendChild($preview)
->appendChild($color_input)
->appendChild($icon_input)
->addCancelButton('/')
->addSubmitButton(pht('Save Image'));
}
private function getIconMap() {
$icon_map = PhabricatorFilesComposeIconBuiltinFile::getAllIcons();
$first = array(
'fa-briefcase',
'fa-tags',
'fa-folder',
'fa-group',
'fa-bug',
'fa-trash-o',
'fa-calendar',
'fa-flag-checkered',
'fa-envelope',
'fa-truck',
'fa-lock',
'fa-umbrella',
'fa-cloud',
'fa-building',
'fa-credit-card',
'fa-flask',
);
$icon_map = array_select_keys($icon_map, $first) + $icon_map;
return $icon_map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileEditController.php | src/applications/files/controller/PhabricatorFileEditController.php | <?php
final class PhabricatorFileEditController
extends PhabricatorFileController {
public function handleRequest(AphrontRequest $request) {
return id(new PhabricatorFileEditEngine())
->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/files/controller/PhabricatorFileIconSetSelectController.php | src/applications/files/controller/PhabricatorFileIconSetSelectController.php | <?php
final class PhabricatorFileIconSetSelectController
extends PhabricatorFileController {
public function handleRequest(AphrontRequest $request) {
$key = $request->getURIData('key');
$set = PhabricatorIconSet::getIconSetByKey($key);
if (!$set) {
return new Aphront404Response();
}
$v_icon = $request->getStr('icon');
if ($request->isFormPost()) {
$icon = $set->getIcon($v_icon);
if ($icon) {
$payload = array(
'value' => $icon->getKey(),
'display' => $set->renderIconForControl($icon),
);
return id(new AphrontAjaxResponse())
->setContent($payload);
}
}
require_celerity_resource('phui-icon-set-selector-css');
Javelin::initBehavior('phabricator-tooltips');
$ii = 0;
$buttons = array();
$breakpoint = ceil(sqrt(count($set->getIcons())));
foreach ($set->getIcons() as $icon) {
$label = $icon->getLabel();
$view = id(new PHUIIconView())
->setIcon($icon->getIcon());
$classes = array();
$classes[] = 'icon-button';
$is_selected = ($icon->getKey() == $v_icon);
if ($is_selected) {
$classes[] = 'selected';
}
$is_disabled = $icon->getIsDisabled();
if ($is_disabled && !$is_selected) {
continue;
}
$aural = javelin_tag(
'span',
array(
'aural' => true,
),
pht('Choose "%s" Icon', $label));
$buttons[] = javelin_tag(
'button',
array(
'class' => implode(' ', $classes),
'name' => 'icon',
'value' => $icon->getKey(),
'type' => 'submit',
'sigil' => 'has-tooltip',
'meta' => array(
'tip' => $label,
),
),
array(
$aural,
$view,
));
if ((++$ii % $breakpoint) == 0) {
$buttons[] = phutil_tag('br');
}
}
$buttons = phutil_tag(
'div',
array(
'class' => 'icon-grid',
),
$buttons);
$dialog_title = $set->getSelectIconTitleText();
return $this->newDialog()
->setTitle($dialog_title)
->appendChild($buttons)
->addCancelButton('/');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileUploadDialogController.php | src/applications/files/controller/PhabricatorFileUploadDialogController.php | <?php
final class PhabricatorFileUploadDialogController
extends PhabricatorFileController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$e_file = true;
$errors = array();
if ($request->isDialogFormPost()) {
$file_phids = $request->getStrList('filePHIDs');
if ($file_phids) {
$files = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs($file_phids)
->setRaisePolicyExceptions(true)
->execute();
} else {
$files = array();
}
if ($files) {
$results = array();
foreach ($files as $file) {
$results[] = $file->getDragAndDropDictionary();
}
$content = array(
'files' => $results,
);
return id(new AphrontAjaxResponse())->setContent($content);
} else {
$e_file = pht('Required');
$errors[] = pht('You must choose a file to upload.');
}
}
if ($request->getURIData('single')) {
$allow_multiple = false;
} else {
$allow_multiple = true;
}
$form = id(new AphrontFormView())
->appendChild(
id(new PHUIFormFileControl())
->setName('filePHIDs')
->setLabel(pht('Upload File'))
->setAllowMultiple($allow_multiple)
->setError($e_file));
return $this->newDialog()
->setTitle(pht('File'))
->setErrors($errors)
->appendForm($form)
->addSubmitButton(pht('Upload'))
->addCancelButton('/');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileViewController.php | src/applications/files/controller/PhabricatorFileViewController.php | <?php
final class PhabricatorFileViewController extends PhabricatorFileController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$phid = $request->getURIData('phid');
if ($phid) {
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($phid))
->withIsDeleted(false)
->executeOne();
if (!$file) {
return new Aphront404Response();
}
return id(new AphrontRedirectResponse())->setURI($file->getInfoURI());
}
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withIDs(array($id))
->withIsDeleted(false)
->executeOne();
if (!$file) {
return new Aphront404Response();
}
$phid = $file->getPHID();
$header = id(new PHUIHeaderView())
->setUser($viewer)
->setPolicyObject($file)
->setHeader($file->getName())
->setHeaderIcon('fa-file-o');
$ttl = $file->getTTL();
if ($ttl !== null) {
$ttl_tag = id(new PHUITagView())
->setType(PHUITagView::TYPE_SHADE)
->setColor(PHUITagView::COLOR_YELLOW)
->setName(pht('Temporary'));
$header->addTag($ttl_tag);
}
$partial = $file->getIsPartial();
if ($partial) {
$partial_tag = id(new PHUITagView())
->setType(PHUITagView::TYPE_SHADE)
->setColor(PHUITagView::COLOR_ORANGE)
->setName(pht('Partial Upload'));
$header->addTag($partial_tag);
}
$curtain = $this->buildCurtainView($file);
$timeline = $this->buildTransactionView($file);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb(
$file->getMonogram(),
$file->getInfoURI());
$crumbs->setBorder(true);
$object_box = id(new PHUIObjectBoxView())
->setHeaderText(pht('File Metadata'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY);
$this->buildPropertyViews($object_box, $file);
$title = $file->getName();
$file_content = $this->newFileContent($file);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(
array(
$file_content,
$object_box,
$timeline,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->setPageObjectPHIDs(array($file->getPHID()))
->appendChild($view);
}
private function buildTransactionView(PhabricatorFile $file) {
$viewer = $this->getViewer();
$timeline = $this->buildTransactionTimeline(
$file,
new PhabricatorFileTransactionQuery());
$comment_view = id(new PhabricatorFileEditEngine())
->setViewer($viewer)
->buildEditEngineCommentView($file);
$monogram = $file->getMonogram();
$timeline->setQuoteRef($monogram);
$comment_view->setTransactionTimeline($timeline);
return array(
$timeline,
$comment_view,
);
}
private function buildCurtainView(PhabricatorFile $file) {
$viewer = $this->getViewer();
$id = $file->getID();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$file,
PhabricatorPolicyCapability::CAN_EDIT);
$curtain = $this->newCurtainView($file);
$can_download = !$file->getIsPartial();
if ($file->isViewableInBrowser()) {
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('View File'))
->setIcon('fa-file-o')
->setHref($file->getViewURI())
->setDisabled(!$can_download)
->setWorkflow(!$can_download));
} else {
$curtain->addAction(
id(new PhabricatorActionView())
->setUser($viewer)
->setDownload($can_download)
->setName(pht('Download File'))
->setIcon('fa-download')
->setHref($file->getDownloadURI())
->setDisabled(!$can_download)
->setWorkflow(!$can_download));
}
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Edit File'))
->setIcon('fa-pencil')
->setHref($this->getApplicationURI("/edit/{$id}/"))
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit));
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('Delete File'))
->setIcon('fa-times')
->setHref($this->getApplicationURI("/delete/{$id}/"))
->setWorkflow(true)
->setDisabled(!$can_edit));
$curtain->addAction(
id(new PhabricatorActionView())
->setName(pht('View Transforms'))
->setIcon('fa-crop')
->setHref($this->getApplicationURI("/transforms/{$id}/")));
$phids = array();
$viewer_phid = $viewer->getPHID();
$author_phid = $file->getAuthorPHID();
if ($author_phid) {
$phids[] = $author_phid;
}
$handles = $viewer->loadHandles($phids);
if ($author_phid) {
$author_refs = id(new PHUICurtainObjectRefListView())
->setViewer($viewer);
$author_ref = $author_refs->newObjectRefView()
->setHandle($handles[$author_phid])
->setEpoch($file->getDateCreated())
->setHighlighted($author_phid === $viewer_phid);
$curtain->newPanel()
->setHeaderText(pht('Authored By'))
->appendChild($author_refs);
}
$curtain->newPanel()
->setHeaderText(pht('Size'))
->appendChild(phutil_format_bytes($file->getByteSize()));
$width = $file->getImageWidth();
$height = $file->getImageHeight();
if ($width || $height) {
$curtain->newPanel()
->setHeaderText(pht('Dimensions'))
->appendChild(
pht(
"%spx \xC3\x97 %spx",
new PhutilNumber($width),
new PhutilNumber($height)));
}
return $curtain;
}
private function buildPropertyViews(
PHUIObjectBoxView $box,
PhabricatorFile $file) {
$request = $this->getRequest();
$viewer = $request->getUser();
$tab_group = id(new PHUITabGroupView());
$box->addTabGroup($tab_group);
$finfo = new PHUIPropertyListView();
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Details'))
->setKey('details')
->appendChild($finfo));
$finfo->addProperty(
pht('Mime Type'),
$file->getMimeType());
$ttl = $file->getTtl();
if ($ttl) {
$delta = $ttl - PhabricatorTime::getNow();
$finfo->addProperty(
pht('Expires'),
pht(
'%s (%s)',
phabricator_datetime($ttl, $viewer),
phutil_format_relative_time_detailed($delta)));
}
$is_image = $file->isViewableImage();
if ($is_image) {
$image_string = pht('Yes');
$cache_string = $file->getCanCDN() ? pht('Yes') : pht('No');
} else {
$image_string = pht('No');
$cache_string = pht('Not Applicable');
}
$types = array();
if ($file->isViewableImage()) {
$types[] = pht('Image');
}
if ($file->isVideo()) {
$types[] = pht('Video');
}
if ($file->isAudio()) {
$types[] = pht('Audio');
}
if ($file->getCanCDN()) {
$types[] = pht('Can CDN');
}
$builtin = $file->getBuiltinName();
if ($builtin !== null) {
$types[] = pht('Builtin ("%s")', $builtin);
}
if ($file->getIsProfileImage()) {
$types[] = pht('Profile');
}
if ($types) {
$types = implode(', ', $types);
$finfo->addProperty(pht('Attributes'), $types);
}
$finfo->addProperty(
pht('Storage Engine'),
$file->getStorageEngine());
$engine = $this->loadStorageEngine($file);
if ($engine && $engine->isChunkEngine()) {
$format_name = pht('Chunks');
} else {
$format_key = $file->getStorageFormat();
$format = PhabricatorFileStorageFormat::getFormat($format_key);
if ($format) {
$format_name = $format->getStorageFormatName();
} else {
$format_name = pht('Unknown ("%s")', $format_key);
}
}
$finfo->addProperty(pht('Storage Format'), $format_name);
$finfo->addProperty(
pht('Storage Handle'),
$file->getStorageHandle());
$custom_alt = $file->getCustomAltText();
if ($custom_alt !== null && strlen($custom_alt)) {
$finfo->addProperty(pht('Custom Alt Text'), $custom_alt);
}
$default_alt = $file->getDefaultAltText();
if ($default_alt !== null && strlen($default_alt)) {
$finfo->addProperty(pht('Default Alt Text'), $default_alt);
}
$attachments_table = $this->newAttachmentsView($file);
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Attached'))
->setKey('attached')
->appendChild($attachments_table));
$engine = $this->loadStorageEngine($file);
if ($engine) {
if ($engine->isChunkEngine()) {
$chunkinfo = new PHUIPropertyListView();
$tab_group->addTab(
id(new PHUITabView())
->setName(pht('Chunks'))
->setKey('chunks')
->appendChild($chunkinfo));
$chunks = id(new PhabricatorFileChunkQuery())
->setViewer($viewer)
->withChunkHandles(array($file->getStorageHandle()))
->execute();
$chunks = msort($chunks, 'getByteStart');
$rows = array();
$completed = array();
foreach ($chunks as $chunk) {
$is_complete = $chunk->getDataFilePHID();
$rows[] = array(
$chunk->getByteStart(),
$chunk->getByteEnd(),
($is_complete ? pht('Yes') : pht('No')),
);
if ($is_complete) {
$completed[] = $chunk;
}
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Offset'),
pht('End'),
pht('Complete'),
))
->setColumnClasses(
array(
'',
'',
'wide',
));
$chunkinfo->addProperty(
pht('Total Chunks'),
count($chunks));
$chunkinfo->addProperty(
pht('Completed Chunks'),
count($completed));
$chunkinfo->addRawContent($table);
}
}
}
private function loadStorageEngine(PhabricatorFile $file) {
$engine = null;
try {
$engine = $file->instantiateStorageEngine();
} catch (Exception $ex) {
// Don't bother raising this anywhere for now.
}
return $engine;
}
private function newFileContent(PhabricatorFile $file) {
$request = $this->getRequest();
$ref = id(new PhabricatorDocumentRef())
->setFile($file);
$engine = id(new PhabricatorFileDocumentRenderingEngine())
->setRequest($request);
return $engine->newDocumentView($ref);
}
private function newAttachmentsView(PhabricatorFile $file) {
$viewer = $this->getViewer();
$attachments = id(new PhabricatorFileAttachmentQuery())
->setViewer($viewer)
->withFilePHIDs(array($file->getPHID()))
->execute();
$handles = $viewer->loadHandles(mpull($attachments, 'getObjectPHID'));
$rows = array();
$mode_map = PhabricatorFileAttachment::getModeNameMap();
$mode_attach = PhabricatorFileAttachment::MODE_ATTACH;
foreach ($attachments as $attachment) {
$object_phid = $attachment->getObjectPHID();
$handle = $handles[$object_phid];
$attachment_mode = $attachment->getAttachmentMode();
$mode_name = idx($mode_map, $attachment_mode);
if ($mode_name === null) {
$mode_name = pht('Unknown ("%s")', $attachment_mode);
}
$detach_uri = urisprintf(
'/file/ui/detach/%s/%s/',
$object_phid,
$file->getPHID());
$is_disabled = !$attachment->canDetach();
$detach_button = id(new PHUIButtonView())
->setHref($detach_uri)
->setTag('a')
->setWorkflow(true)
->setDisabled($is_disabled)
->setColor(PHUIButtonView::GREY)
->setSize(PHUIButtonView::SMALL)
->setText(pht('Detach File'));
javelin_tag(
'a',
array(
'href' => $detach_uri,
'sigil' => 'workflow',
'disabled' => true,
'class' => 'small button button-grey disabled',
),
pht('Detach File'));
$rows[] = array(
$handle->renderLink(),
$mode_name,
$detach_button,
);
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Attached To'),
pht('Mode'),
null,
))
->setColumnClasses(
array(
'pri wide',
null,
null,
));
return $table;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileDropUploadController.php | src/applications/files/controller/PhabricatorFileDropUploadController.php | <?php
final class PhabricatorFileDropUploadController
extends PhabricatorFileController {
public function shouldAllowRestrictedParameter($parameter_name) {
// Prevent false positives from file content when it is submitted via
// drag-and-drop upload.
return true;
}
/**
* @phutil-external-symbol class PhabricatorStartup
*/
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
// NOTE: Throws if valid CSRF token is not present in the request.
$request->validateCSRF();
$name = $request->getStr('name');
$file_phid = $request->getStr('phid');
// If there's no explicit view policy, make it very restrictive by default.
// This is the correct policy for files dropped onto objects during
// creation, comment and edit flows.
$view_policy = $request->getStr('viewPolicy');
if (!$view_policy) {
$view_policy = $viewer->getPHID();
}
$is_chunks = $request->getBool('querychunks');
if ($is_chunks) {
$params = array(
'filePHID' => $file_phid,
);
$result = id(new ConduitCall('file.querychunks', $params))
->setUser($viewer)
->execute();
return id(new AphrontAjaxResponse())->setContent($result);
}
$is_allocate = $request->getBool('allocate');
if ($is_allocate) {
$params = array(
'name' => $name,
'contentLength' => $request->getInt('length'),
'viewPolicy' => $view_policy,
);
$result = id(new ConduitCall('file.allocate', $params))
->setUser($viewer)
->execute();
$file_phid = $result['filePHID'];
if ($file_phid) {
$file = $this->loadFile($file_phid);
$result += $file->getDragAndDropDictionary();
}
return id(new AphrontAjaxResponse())->setContent($result);
}
// Read the raw request data. We're either doing a chunk upload or a
// vanilla upload, so we need it.
$data = PhabricatorStartup::getRawInput();
$is_chunk_upload = $request->getBool('uploadchunk');
if ($is_chunk_upload) {
$params = array(
'filePHID' => $file_phid,
'byteStart' => $request->getInt('byteStart'),
'data' => $data,
);
$result = id(new ConduitCall('file.uploadchunk', $params))
->setUser($viewer)
->execute();
$file = $this->loadFile($file_phid);
if ($file->getIsPartial()) {
$result = array();
} else {
$result = array(
'complete' => true,
) + $file->getDragAndDropDictionary();
}
return id(new AphrontAjaxResponse())->setContent($result);
}
$file = PhabricatorFile::newFromXHRUpload(
$data,
array(
'name' => $request->getStr('name'),
'authorPHID' => $viewer->getPHID(),
'viewPolicy' => $view_policy,
'isExplicitUpload' => true,
));
$result = $file->getDragAndDropDictionary();
return id(new AphrontAjaxResponse())->setContent($result);
}
private function loadFile($file_phid) {
$viewer = $this->getViewer();
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($file_phid))
->executeOne();
if (!$file) {
throw new Exception(pht('Failed to load file.'));
}
return $file;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileDocumentController.php | src/applications/files/controller/PhabricatorFileDocumentController.php | <?php
final class PhabricatorFileDocumentController
extends PhabricatorFileController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$engine = id(new PhabricatorFileDocumentRenderingEngine())
->setRequest($request)
->setController($this);
$viewer = $request->getViewer();
$file_phid = $request->getURIData('phid');
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($file_phid))
->executeOne();
if (!$file) {
return $engine->newErrorResponse(
pht(
'This file ("%s") does not exist or could not be loaded.',
$file_phid));
}
$ref = id(new PhabricatorDocumentRef())
->setFile($file);
return $engine->newRenderResponse($ref);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileDetachController.php | src/applications/files/controller/PhabricatorFileDetachController.php | <?php
final class PhabricatorFileDetachController
extends PhabricatorFileController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$object_phid = $request->getURIData('objectPHID');
$file_phid = $request->getURIData('filePHID');
$object = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withPHIDs(array($object_phid))
->executeOne();
if (!$object) {
return new Aphront404Response();
}
$handles = $viewer->loadHandles(
array(
$object_phid,
$file_phid,
));
$object_handle = $handles[$object_phid];
$file_handle = $handles[$file_phid];
$cancel_uri = $file_handle->getURI();
$dialog = $this->newDialog()
->setViewer($viewer)
->setTitle(pht('Detach File'))
->addCancelButton($cancel_uri, pht('Close'));
$file_link = phutil_tag('strong', array(), $file_handle->renderLink());
$object_link = phutil_tag('strong', array(), $object_handle->renderLink());
$attachment = id(new PhabricatorFileAttachmentQuery())
->setViewer($viewer)
->withObjectPHIDs(array($object->getPHID()))
->withFilePHIDs(array($file_phid))
->needFiles(true)
->withVisibleFiles(true)
->executeOne();
if (!$attachment) {
$body = pht(
'The file %s is not attached to the object %s.',
$file_link,
$object_link);
return $dialog->appendParagraph($body);
}
$mode_reference = PhabricatorFileAttachment::MODE_REFERENCE;
if ($attachment->getAttachmentMode() === $mode_reference) {
$body = pht(
'The file %s is referenced by the object %s, but not attached to '.
'it, so it can not be detached.',
$file_link,
$object_link);
return $dialog->appendParagraph($body);
}
if (!$attachment->canDetach()) {
$body = pht(
'The file %s can not be detached from the object %s.',
$file_link,
$object_link);
return $dialog->appendParagraph($body);
}
if (!$request->isDialogFormPost()) {
$dialog->appendParagraph(
pht(
'Detach the file %s from the object %s?',
$file_link,
$object_link));
$dialog->addSubmitButton(pht('Detach File'));
return $dialog;
}
if (!($object instanceof PhabricatorApplicationTransactionInterface)) {
$dialog->appendParagraph(
pht(
'This object (of class "%s") does not implement the required '.
'interface ("%s"), so files can not be manually detached from it.',
get_class($object),
'PhabricatorApplicationTransactionInterface'));
return $dialog;
}
$editor = $object->getApplicationTransactionEditor()
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true);
$template = $object->getApplicationTransactionTemplate();
$xactions = array();
$xactions[] = id(clone $template)
->setTransactionType(PhabricatorTransactions::TYPE_FILE)
->setNewValue(
array(
$file_phid => PhabricatorFileAttachment::MODE_DETACH,
));
$editor->applyTransactions($object, $xactions);
return $this->newRedirect()
->setURI($cancel_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/controller/PhabricatorFileUICurtainListController.php | src/applications/files/controller/PhabricatorFileUICurtainListController.php | <?php
final class PhabricatorFileUICurtainListController
extends PhabricatorFileController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$object_phid = $request->getURIData('phid');
$object = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withPHIDs(array($object_phid))
->executeOne();
if (!$object) {
return new Aphront404Response();
}
$attachments = id(new PhabricatorFileAttachmentQuery())
->setViewer($viewer)
->withObjectPHIDs(array($object->getPHID()))
->needFiles(true)
->execute();
$handles = $viewer->loadHandles(array($object_phid));
$object_handle = $handles[$object_phid];
$file_phids = mpull($attachments, 'getFilePHID');
$file_handles = $viewer->loadHandles($file_phids);
$list = id(new PHUIObjectItemListView())
->setUser($viewer);
foreach ($attachments as $attachment) {
$file_phid = $attachment->getFilePHID();
$handle = $file_handles[$file_phid];
$item = id(new PHUIObjectItemView())
->setHeader($handle->getFullName())
->setHref($handle->getURI())
->setDisabled($handle->isDisabled());
if ($handle->getImageURI()) {
$item->setImageURI($handle->getImageURI());
}
$list->addItem($item);
}
return $this->newDialog()
->setViewer($viewer)
->setWidth(AphrontDialogView::WIDTH_FORM)
->setTitle(pht('Referenced Files'))
->setObjectList($list)
->addCancelButton($object_handle->getURI(), pht('Close'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/controller/PhabricatorFileTransformController.php | src/applications/files/controller/PhabricatorFileTransformController.php | <?php
final class PhabricatorFileTransformController
extends PhabricatorFileController {
public function shouldRequireLogin() {
return false;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
// NOTE: This is a public/CDN endpoint, and permission to see files is
// controlled by knowing the secret key, not by authentication.
$is_regenerate = $request->getBool('regenerate');
$source_phid = $request->getURIData('phid');
$file = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs(array($source_phid))
->executeOne();
if (!$file) {
return new Aphront404Response();
}
$secret_key = $request->getURIData('key');
if (!$file->validateSecretKey($secret_key)) {
return new Aphront403Response();
}
$transform = $request->getURIData('transform');
$xform = $this->loadTransform($source_phid, $transform);
if ($xform) {
if ($is_regenerate) {
$this->destroyTransform($xform);
} else {
return $this->buildTransformedFileResponse($xform);
}
}
$xforms = PhabricatorFileTransform::getAllTransforms();
if (!isset($xforms[$transform])) {
return new Aphront404Response();
}
$xform = $xforms[$transform];
// We're essentially just building a cache here and don't need CSRF
// protection.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$xformed_file = null;
if ($xform->canApplyTransform($file)) {
try {
$xformed_file = $xforms[$transform]->applyTransform($file);
} catch (Exception $ex) {
// In normal transform mode, we ignore failures and generate a
// default transform below. If we're explicitly regenerating the
// thumbnail, rethrow the exception.
if ($is_regenerate) {
throw $ex;
}
}
}
if (!$xformed_file) {
$xformed_file = $xform->getDefaultTransform($file);
}
if (!$xformed_file) {
return new Aphront400Response();
}
$xform = id(new PhabricatorTransformedFile())
->setOriginalPHID($source_phid)
->setTransform($transform)
->setTransformedPHID($xformed_file->getPHID());
try {
$xform->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// If we collide when saving, we've raced another endpoint which was
// transforming the same file. Just throw our work away and use that
// transform instead.
$this->destroyTransform($xform);
$xform = $this->loadTransform($source_phid, $transform);
if (!$xform) {
return new Aphront404Response();
}
}
return $this->buildTransformedFileResponse($xform);
}
private function buildTransformedFileResponse(
PhabricatorTransformedFile $xform) {
$file = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs(array($xform->getTransformedPHID()))
->executeOne();
if (!$file) {
return new Aphront404Response();
}
// TODO: We could just delegate to the file view controller instead,
// which would save the client a roundtrip, but is slightly more complex.
return $file->getRedirectResponse();
}
private function destroyTransform(PhabricatorTransformedFile $xform) {
$engine = new PhabricatorDestructionEngine();
$file = id(new PhabricatorFileQuery())
->setViewer($engine->getViewer())
->withPHIDs(array($xform->getTransformedPHID()))
->executeOne();
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
if (!$file) {
if ($xform->getID()) {
$xform->delete();
}
} else {
$engine->destroyObject($file);
}
unset($unguarded);
}
private function loadTransform($source_phid, $transform) {
return id(new PhabricatorTransformedFile())->loadOneWhere(
'originalPHID = %s AND transform = %s',
$source_phid,
$transform);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/engineextension/PhabricatorFilesCurtainExtension.php | src/applications/files/engineextension/PhabricatorFilesCurtainExtension.php | <?php
final class PhabricatorFilesCurtainExtension
extends PHUICurtainExtension {
const EXTENSIONKEY = 'files.files';
public function shouldEnableForObject($object) {
return true;
}
public function getExtensionApplication() {
return new PhabricatorFilesApplication();
}
public function buildCurtainPanel($object) {
$viewer = $this->getViewer();
$attachment_table = new PhabricatorFileAttachment();
$attachment_conn = $attachment_table->establishConnection('r');
$exact_limit = 100;
$visible_limit = 8;
$attachments = id(new PhabricatorFileAttachmentQuery())
->setViewer($viewer)
->withObjectPHIDs(array($object->getPHID()))
->setLimit($exact_limit + 1)
->needFiles(true)
->execute();
$visible_attachments = array_slice($attachments, 0, $visible_limit, true);
$visible_phids = mpull($visible_attachments, 'getFilePHID');
$handles = $viewer->loadHandles($visible_phids);
$ref_list = id(new PHUICurtainObjectRefListView())
->setViewer($viewer)
->setEmptyMessage(pht('None'));
$view_capability = PhabricatorPolicyCapability::CAN_VIEW;
$object_policies = PhabricatorPolicyQuery::loadPolicies(
$viewer,
$object);
$object_policy = idx($object_policies, $view_capability);
foreach ($visible_attachments as $attachment) {
$file_phid = $attachment->getFilePHID();
$handle = $handles[$file_phid];
$ref = $ref_list->newObjectRefView()
->setHandle($handle);
$file = $attachment->getFile();
if (!$file) {
// ...
} else {
if (!$attachment->isPolicyAttachment()) {
$file_policies = PhabricatorPolicyQuery::loadPolicies(
$viewer,
$file);
$file_policy = idx($file_policies, $view_capability);
if ($object_policy->isStrongerThanOrEqualTo($file_policy)) {
// The file is not attached to the object, but the file policy
// allows anyone who can see the object to see the file too, so
// there is no material problem with the file not being attached.
} else {
$attach_uri = urisprintf(
'/file/ui/curtain/attach/%s/%s/',
$object->getPHID(),
$file->getPHID());
$attached_link = javelin_tag(
'a',
array(
'href' => $attach_uri,
'sigil' => 'workflow',
),
pht('File Not Attached'));
$ref->setExiled(
true,
$attached_link);
}
}
}
$epoch = $attachment->getDateCreated();
$ref->setEpoch($epoch);
}
$show_all = (count($visible_attachments) < count($attachments));
if ($show_all) {
$view_all_uri = urisprintf(
'/file/ui/curtain/list/%s/',
$object->getPHID());
$loaded_count = count($attachments);
if ($loaded_count > $exact_limit) {
$link_text = pht('View All Files');
} else {
$link_text = pht('View All %d Files', new PhutilNumber($loaded_count));
}
$ref_list->newTailLink()
->setURI($view_all_uri)
->setText($link_text)
->setWorkflow(true);
}
return $this->newPanel()
->setHeaderText(pht('Referenced Files'))
->setOrder(15000)
->appendChild($ref_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/storage/PhabricatorFileTransaction.php | src/applications/files/storage/PhabricatorFileTransaction.php | <?php
final class PhabricatorFileTransaction
extends PhabricatorModularTransaction {
public function getApplicationName() {
return 'file';
}
public function getApplicationTransactionType() {
return PhabricatorFileFilePHIDType::TYPECONST;
}
public function getApplicationTransactionCommentObject() {
return new PhabricatorFileTransactionComment();
}
public function getBaseTransactionClass() {
return 'PhabricatorFileTransactionType';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/PhabricatorFileExternalRequest.php | src/applications/files/storage/PhabricatorFileExternalRequest.php | <?php
final class PhabricatorFileExternalRequest extends PhabricatorFileDAO
implements
PhabricatorDestructibleInterface {
protected $uri;
protected $uriIndex;
protected $ttl;
protected $filePHID;
protected $isSuccessful;
protected $responseMessage;
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'uri' => 'text',
'uriIndex' => 'bytes12',
'ttl' => 'epoch',
'filePHID' => 'phid?',
'isSuccessful' => 'bool',
'responseMessage' => 'text?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_uriindex' => array(
'columns' => array('uriIndex'),
'unique' => true,
),
'key_ttl' => array(
'columns' => array('ttl'),
),
'key_file' => array(
'columns' => array('filePHID'),
),
),
) + parent::getConfiguration();
}
public function save() {
$hash = PhabricatorHash::digestForIndex($this->getURI());
$this->setURIIndex($hash);
return parent::save();
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$file_phid = $this->getFilePHID();
if ($file_phid) {
$file = id(new PhabricatorFileQuery())
->setViewer($engine->getViewer())
->withPHIDs(array($file_phid))
->executeOne();
if ($file) {
$engine->destroyObject($file);
}
}
$this->delete();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/PhabricatorFileStorageBlob.php | src/applications/files/storage/PhabricatorFileStorageBlob.php | <?php
/**
* Simple blob store DAO for @{class:PhabricatorMySQLFileStorageEngine}.
*/
final class PhabricatorFileStorageBlob extends PhabricatorFileDAO {
protected $data;
protected function getConfiguration() {
return array(
self::CONFIG_BINARY => array(
'data' => 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/files/storage/PhabricatorFileChunk.php | src/applications/files/storage/PhabricatorFileChunk.php | <?php
final class PhabricatorFileChunk extends PhabricatorFileDAO
implements
PhabricatorPolicyInterface,
PhabricatorDestructibleInterface {
protected $chunkHandle;
protected $byteStart;
protected $byteEnd;
protected $dataFilePHID;
private $dataFile = self::ATTACHABLE;
protected function getConfiguration() {
return array(
self::CONFIG_TIMESTAMPS => false,
self::CONFIG_COLUMN_SCHEMA => array(
'chunkHandle' => 'bytes12',
'byteStart' => 'uint64',
'byteEnd' => 'uint64',
'dataFilePHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_file' => array(
'columns' => array('chunkHandle', 'byteStart', 'byteEnd'),
),
'key_data' => array(
'columns' => array('dataFilePHID'),
),
),
) + parent::getConfiguration();
}
public static function newChunkHandle() {
$seed = Filesystem::readRandomBytes(64);
return PhabricatorHash::digestForIndex($seed);
}
public static function initializeNewChunk($handle, $start, $end) {
return id(new PhabricatorFileChunk())
->setChunkHandle($handle)
->setByteStart($start)
->setByteEnd($end);
}
public function attachDataFile(PhabricatorFile $file = null) {
$this->dataFile = $file;
return $this;
}
public function getDataFile() {
return $this->assertAttached($this->dataFile);
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
// These objects are low-level and only accessed through the storage
// engine, so policies are mostly just in place to let us use the common
// query infrastructure.
return PhabricatorPolicies::getMostOpenPolicy();
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$data_phid = $this->getDataFilePHID();
if ($data_phid) {
$data_file = id(new PhabricatorFileQuery())
->setViewer($engine->getViewer())
->withPHIDs(array($data_phid))
->executeOne();
if ($data_file) {
$engine->destroyObject($data_file);
}
}
$this->delete();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/PhabricatorFileDAO.php | src/applications/files/storage/PhabricatorFileDAO.php | <?php
abstract class PhabricatorFileDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'file';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/PhabricatorTransformedFile.php | src/applications/files/storage/PhabricatorTransformedFile.php | <?php
final class PhabricatorTransformedFile extends PhabricatorFileDAO {
protected $originalPHID;
protected $transform;
protected $transformedPHID;
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'transform' => 'text128',
),
self::CONFIG_KEY_SCHEMA => array(
'originalPHID' => array(
'columns' => array('originalPHID', 'transform'),
'unique' => true,
),
'transformedPHID' => array(
'columns' => array('transformedPHID'),
),
),
) + 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/files/storage/PhabricatorFile.php | src/applications/files/storage/PhabricatorFile.php | <?php
/**
* Parameters
* ==========
*
* When creating a new file using a method like @{method:newFromFileData}, these
* parameters are supported:
*
* | name | Human readable filename.
* | authorPHID | User PHID of uploader.
* | ttl.absolute | Temporary file lifetime as an epoch timestamp.
* | ttl.relative | Temporary file lifetime, relative to now, in seconds.
* | viewPolicy | File visibility policy.
* | isExplicitUpload | Used to show users files they explicitly uploaded.
* | canCDN | Allows the file to be cached and delivered over a CDN.
* | profile | Marks the file as a profile image.
* | format | Internal encoding format.
* | mime-type | Optional, explicit file MIME type.
* | builtin | Optional filename, identifies this as a builtin.
*
*/
final class PhabricatorFile extends PhabricatorFileDAO
implements
PhabricatorApplicationTransactionInterface,
PhabricatorTokenReceiverInterface,
PhabricatorSubscribableInterface,
PhabricatorFlaggableInterface,
PhabricatorPolicyInterface,
PhabricatorDestructibleInterface,
PhabricatorConduitResultInterface,
PhabricatorIndexableInterface,
PhabricatorNgramsInterface {
const METADATA_IMAGE_WIDTH = 'width';
const METADATA_IMAGE_HEIGHT = 'height';
const METADATA_CAN_CDN = 'canCDN';
const METADATA_BUILTIN = 'builtin';
const METADATA_PARTIAL = 'partial';
const METADATA_PROFILE = 'profile';
const METADATA_STORAGE = 'storage';
const METADATA_INTEGRITY = 'integrity';
const METADATA_CHUNK = 'chunk';
const METADATA_ALT_TEXT = 'alt';
const STATUS_ACTIVE = 'active';
const STATUS_DELETED = 'deleted';
protected $name;
protected $mimeType;
protected $byteSize;
protected $authorPHID;
protected $secretKey;
protected $contentHash;
protected $metadata = array();
protected $mailKey;
protected $builtinKey;
protected $storageEngine;
protected $storageFormat;
protected $storageHandle;
protected $ttl;
protected $isExplicitUpload = 1;
protected $viewPolicy = PhabricatorPolicies::POLICY_USER;
protected $isPartial = 0;
protected $isDeleted = 0;
private $objects = self::ATTACHABLE;
private $objectPHIDs = self::ATTACHABLE;
private $originalFile = self::ATTACHABLE;
private $transforms = self::ATTACHABLE;
public static function initializeNewFile() {
$app = id(new PhabricatorApplicationQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withClasses(array('PhabricatorFilesApplication'))
->executeOne();
$view_policy = $app->getPolicy(
FilesDefaultViewCapability::CAPABILITY);
return id(new PhabricatorFile())
->setViewPolicy($view_policy)
->setIsPartial(0)
->attachOriginalFile(null)
->attachObjects(array())
->attachObjectPHIDs(array());
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'metadata' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'name' => 'sort255?',
'mimeType' => 'text255?',
'byteSize' => 'uint64',
'storageEngine' => 'text32',
'storageFormat' => 'text32',
'storageHandle' => 'text255',
'authorPHID' => 'phid?',
'secretKey' => 'bytes20?',
'contentHash' => 'bytes64?',
'ttl' => 'epoch?',
'isExplicitUpload' => 'bool?',
'mailKey' => 'bytes20',
'isPartial' => 'bool',
'builtinKey' => 'text64?',
'isDeleted' => 'bool',
),
self::CONFIG_KEY_SCHEMA => array(
'key_phid' => null,
'phid' => array(
'columns' => array('phid'),
'unique' => true,
),
'authorPHID' => array(
'columns' => array('authorPHID'),
),
'contentHash' => array(
'columns' => array('contentHash'),
),
'key_ttl' => array(
'columns' => array('ttl'),
),
'key_dateCreated' => array(
'columns' => array('dateCreated'),
),
'key_partial' => array(
'columns' => array('authorPHID', 'isPartial'),
),
'key_builtin' => array(
'columns' => array('builtinKey'),
'unique' => true,
),
'key_engine' => array(
'columns' => array('storageEngine', 'storageHandle(64)'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorFileFilePHIDType::TYPECONST);
}
public function save() {
if (!$this->getSecretKey()) {
$this->setSecretKey($this->generateSecretKey());
}
if (!$this->getMailKey()) {
$this->setMailKey(Filesystem::readRandomCharacters(20));
}
return parent::save();
}
public function saveAndIndex() {
$this->save();
if ($this->isIndexableFile()) {
PhabricatorSearchWorker::queueDocumentForIndexing($this->getPHID());
}
return $this;
}
private function isIndexableFile() {
if ($this->getIsChunk()) {
return false;
}
return true;
}
public function getMonogram() {
return 'F'.$this->getID();
}
public function scrambleSecret() {
return $this->setSecretKey($this->generateSecretKey());
}
public static function readUploadedFileData($spec) {
if (!$spec) {
throw new Exception(pht('No file was uploaded!'));
}
$err = idx($spec, 'error');
if ($err) {
throw new PhabricatorFileUploadException($err);
}
$tmp_name = idx($spec, 'tmp_name');
// NOTE: If we parsed the request body ourselves, the files we wrote will
// not be registered in the `is_uploaded_file()` list. It's fine to skip
// this check: it just protects against sloppy code from the long ago era
// of "register_globals".
if (ini_get('enable_post_data_reading')) {
$is_valid = @is_uploaded_file($tmp_name);
if (!$is_valid) {
throw new Exception(pht('File is not an uploaded file.'));
}
}
$file_data = Filesystem::readFile($tmp_name);
$file_size = idx($spec, 'size');
if (strlen($file_data) != $file_size) {
throw new Exception(pht('File size disagrees with uploaded size.'));
}
return $file_data;
}
public static function newFromPHPUpload($spec, array $params = array()) {
$file_data = self::readUploadedFileData($spec);
$file_name = nonempty(
idx($params, 'name'),
idx($spec, 'name'));
$params = array(
'name' => $file_name,
) + $params;
return self::newFromFileData($file_data, $params);
}
public static function newFromXHRUpload($data, array $params = array()) {
return self::newFromFileData($data, $params);
}
public static function newFileFromContentHash($hash, array $params) {
if ($hash === null) {
return null;
}
// Check to see if a file with same hash already exists.
$file = id(new PhabricatorFile())->loadOneWhere(
'contentHash = %s LIMIT 1',
$hash);
if (!$file) {
return null;
}
$copy_of_storage_engine = $file->getStorageEngine();
$copy_of_storage_handle = $file->getStorageHandle();
$copy_of_storage_format = $file->getStorageFormat();
$copy_of_storage_properties = $file->getStorageProperties();
$copy_of_byte_size = $file->getByteSize();
$copy_of_mime_type = $file->getMimeType();
$new_file = self::initializeNewFile();
$new_file->setByteSize($copy_of_byte_size);
$new_file->setContentHash($hash);
$new_file->setStorageEngine($copy_of_storage_engine);
$new_file->setStorageHandle($copy_of_storage_handle);
$new_file->setStorageFormat($copy_of_storage_format);
$new_file->setStorageProperties($copy_of_storage_properties);
$new_file->setMimeType($copy_of_mime_type);
$new_file->copyDimensions($file);
$new_file->readPropertiesFromParameters($params);
$new_file->saveAndIndex();
return $new_file;
}
public static function newChunkedFile(
PhabricatorFileStorageEngine $engine,
$length,
array $params) {
$file = self::initializeNewFile();
$file->setByteSize($length);
// NOTE: Once we receive the first chunk, we'll detect its MIME type and
// update the parent file if a MIME type hasn't been provided. This matters
// for large media files like video.
$mime_type = idx($params, 'mime-type');
if ($mime_type === null || !strlen($mime_type)) {
$file->setMimeType('application/octet-stream');
}
$chunked_hash = idx($params, 'chunkedHash');
// Get rid of this parameter now; we aren't passing it any further down
// the stack.
unset($params['chunkedHash']);
if ($chunked_hash) {
$file->setContentHash($chunked_hash);
} else {
// See PhabricatorChunkedFileStorageEngine::getChunkedHash() for some
// discussion of this.
$seed = Filesystem::readRandomBytes(64);
$hash = PhabricatorChunkedFileStorageEngine::getChunkedHashForInput(
$seed);
$file->setContentHash($hash);
}
$file->setStorageEngine($engine->getEngineIdentifier());
$file->setStorageHandle(PhabricatorFileChunk::newChunkHandle());
// Chunked files are always stored raw because they do not actually store
// data. The chunks do, and can be individually formatted.
$file->setStorageFormat(PhabricatorFileRawStorageFormat::FORMATKEY);
$file->setIsPartial(1);
$file->readPropertiesFromParameters($params);
return $file;
}
private static function buildFromFileData($data, array $params = array()) {
if (isset($params['storageEngines'])) {
$engines = $params['storageEngines'];
} else {
$size = strlen($data);
$engines = PhabricatorFileStorageEngine::loadStorageEngines($size);
if (!$engines) {
throw new Exception(
pht(
'No configured storage engine can store this file. See '.
'"Configuring File Storage" in the documentation for '.
'information on configuring storage engines.'));
}
}
assert_instances_of($engines, 'PhabricatorFileStorageEngine');
if (!$engines) {
throw new Exception(pht('No valid storage engines are available!'));
}
$file = self::initializeNewFile();
$aes_type = PhabricatorFileAES256StorageFormat::FORMATKEY;
$has_aes = PhabricatorKeyring::getDefaultKeyName($aes_type);
if ($has_aes !== null) {
$default_key = PhabricatorFileAES256StorageFormat::FORMATKEY;
} else {
$default_key = PhabricatorFileRawStorageFormat::FORMATKEY;
}
$key = idx($params, 'format', $default_key);
// Callers can pass in an object explicitly instead of a key. This is
// primarily useful for unit tests.
if ($key instanceof PhabricatorFileStorageFormat) {
$format = clone $key;
} else {
$format = clone PhabricatorFileStorageFormat::requireFormat($key);
}
$format->setFile($file);
$properties = $format->newStorageProperties();
$file->setStorageFormat($format->getStorageFormatKey());
$file->setStorageProperties($properties);
$data_handle = null;
$engine_identifier = null;
$integrity_hash = null;
$exceptions = array();
foreach ($engines as $engine) {
$engine_class = get_class($engine);
try {
$result = $file->writeToEngine(
$engine,
$data,
$params);
list($engine_identifier, $data_handle, $integrity_hash) = $result;
// We stored the file somewhere so stop trying to write it to other
// places.
break;
} catch (PhabricatorFileStorageConfigurationException $ex) {
// If an engine is outright misconfigured (or misimplemented), raise
// that immediately since it probably needs attention.
throw $ex;
} catch (Exception $ex) {
phlog($ex);
// If an engine doesn't work, keep trying all the other valid engines
// in case something else works.
$exceptions[$engine_class] = $ex;
}
}
if (!$data_handle) {
throw new PhutilAggregateException(
pht('All storage engines failed to write file:'),
$exceptions);
}
$file->setByteSize(strlen($data));
$hash = self::hashFileContent($data);
$file->setContentHash($hash);
$file->setStorageEngine($engine_identifier);
$file->setStorageHandle($data_handle);
$file->setIntegrityHash($integrity_hash);
$file->readPropertiesFromParameters($params);
if (!$file->getMimeType()) {
$tmp = new TempFile();
Filesystem::writeFile($tmp, $data);
$file->setMimeType(Filesystem::getMimeType($tmp));
unset($tmp);
}
try {
$file->updateDimensions(false);
} catch (Exception $ex) {
// Do nothing.
}
$file->saveAndIndex();
return $file;
}
public static function newFromFileData($data, array $params = array()) {
$hash = self::hashFileContent($data);
if ($hash !== null) {
$file = self::newFileFromContentHash($hash, $params);
if ($file) {
return $file;
}
}
return self::buildFromFileData($data, $params);
}
public function migrateToEngine(
PhabricatorFileStorageEngine $engine,
$make_copy) {
if (!$this->getID() || !$this->getStorageHandle()) {
throw new Exception(
pht("You can not migrate a file which hasn't yet been saved."));
}
$data = $this->loadFileData();
$params = array(
'name' => $this->getName(),
);
list($new_identifier, $new_handle, $integrity_hash) = $this->writeToEngine(
$engine,
$data,
$params);
$old_engine = $this->instantiateStorageEngine();
$old_identifier = $this->getStorageEngine();
$old_handle = $this->getStorageHandle();
$this->setStorageEngine($new_identifier);
$this->setStorageHandle($new_handle);
$this->setIntegrityHash($integrity_hash);
$this->save();
if (!$make_copy) {
$this->deleteFileDataIfUnused(
$old_engine,
$old_identifier,
$old_handle);
}
return $this;
}
public function migrateToStorageFormat(PhabricatorFileStorageFormat $format) {
if (!$this->getID() || !$this->getStorageHandle()) {
throw new Exception(
pht("You can not migrate a file which hasn't yet been saved."));
}
$data = $this->loadFileData();
$params = array(
'name' => $this->getName(),
);
$engine = $this->instantiateStorageEngine();
$old_handle = $this->getStorageHandle();
$properties = $format->newStorageProperties();
$this->setStorageFormat($format->getStorageFormatKey());
$this->setStorageProperties($properties);
list($identifier, $new_handle, $integrity_hash) = $this->writeToEngine(
$engine,
$data,
$params);
$this->setStorageHandle($new_handle);
$this->setIntegrityHash($integrity_hash);
$this->save();
$this->deleteFileDataIfUnused(
$engine,
$identifier,
$old_handle);
return $this;
}
public function cycleMasterStorageKey(PhabricatorFileStorageFormat $format) {
if (!$this->getID() || !$this->getStorageHandle()) {
throw new Exception(
pht("You can not cycle keys for a file which hasn't yet been saved."));
}
$properties = $format->cycleStorageProperties();
$this->setStorageProperties($properties);
$this->save();
return $this;
}
private function writeToEngine(
PhabricatorFileStorageEngine $engine,
$data,
array $params) {
$engine_class = get_class($engine);
$format = $this->newStorageFormat();
$data_iterator = array($data);
$formatted_iterator = $format->newWriteIterator($data_iterator);
$formatted_data = $this->loadDataFromIterator($formatted_iterator);
$integrity_hash = $engine->newIntegrityHash($formatted_data, $format);
$data_handle = $engine->writeFile($formatted_data, $params);
if (!$data_handle || strlen($data_handle) > 255) {
// This indicates an improperly implemented storage engine.
throw new PhabricatorFileStorageConfigurationException(
pht(
"Storage engine '%s' executed %s but did not return a valid ".
"handle ('%s') to the data: it must be nonempty and no longer ".
"than 255 characters.",
$engine_class,
'writeFile()',
$data_handle));
}
$engine_identifier = $engine->getEngineIdentifier();
if (!$engine_identifier || strlen($engine_identifier) > 32) {
throw new PhabricatorFileStorageConfigurationException(
pht(
"Storage engine '%s' returned an improper engine identifier '{%s}': ".
"it must be nonempty and no longer than 32 characters.",
$engine_class,
$engine_identifier));
}
return array($engine_identifier, $data_handle, $integrity_hash);
}
/**
* Download a remote resource over HTTP and save the response body as a file.
*
* This method respects `security.outbound-blacklist`, and protects against
* HTTP redirection (by manually following "Location" headers and verifying
* each destination). It does not protect against DNS rebinding. See
* discussion in T6755.
*/
public static function newFromFileDownload($uri, array $params = array()) {
$timeout = 5;
$redirects = array();
$current = $uri;
while (true) {
try {
if (count($redirects) > 10) {
throw new Exception(
pht('Too many redirects trying to fetch remote URI.'));
}
$resolved = PhabricatorEnv::requireValidRemoteURIForFetch(
$current,
array(
'http',
'https',
));
list($resolved_uri, $resolved_domain) = $resolved;
$current = new PhutilURI($current);
if ($current->getProtocol() == 'http') {
// For HTTP, we can use a pre-resolved URI to defuse DNS rebinding.
$fetch_uri = $resolved_uri;
$fetch_host = $resolved_domain;
} else {
// For HTTPS, we can't: cURL won't verify the SSL certificate if
// the domain has been replaced with an IP. But internal services
// presumably will not have valid certificates for rebindable
// domain names on attacker-controlled domains, so the DNS rebinding
// attack should generally not be possible anyway.
$fetch_uri = $current;
$fetch_host = null;
}
$future = id(new HTTPSFuture($fetch_uri))
->setFollowLocation(false)
->setTimeout($timeout);
if ($fetch_host !== null) {
$future->addHeader('Host', $fetch_host);
}
list($status, $body, $headers) = $future->resolve();
if ($status->isRedirect()) {
// This is an HTTP 3XX status, so look for a "Location" header.
$location = null;
foreach ($headers as $header) {
list($name, $value) = $header;
if (phutil_utf8_strtolower($name) == 'location') {
$location = $value;
break;
}
}
// HTTP 3XX status with no "Location" header, just treat this like
// a normal HTTP error.
if ($location === null) {
throw $status;
}
if (isset($redirects[$location])) {
throw new Exception(
pht('Encountered loop while following redirects.'));
}
$redirects[$location] = $location;
$current = $location;
// We'll fall off the bottom and go try this URI now.
} else if ($status->isError()) {
// This is something other than an HTTP 2XX or HTTP 3XX status, so
// just bail out.
throw $status;
} else {
// This is HTTP 2XX, so use the response body to save the file data.
// Provide a default name based on the URI, truncating it if the URI
// is exceptionally long.
$default_name = basename($uri);
$default_name = id(new PhutilUTF8StringTruncator())
->setMaximumBytes(64)
->truncateString($default_name);
$params = $params + array(
'name' => $default_name,
);
return self::newFromFileData($body, $params);
}
} catch (Exception $ex) {
if ($redirects) {
throw new PhutilProxyException(
pht(
'Failed to fetch remote URI "%s" after following %s redirect(s) '.
'(%s): %s',
$uri,
phutil_count($redirects),
implode(' > ', array_keys($redirects)),
$ex->getMessage()),
$ex);
} else {
throw $ex;
}
}
}
}
public static function normalizeFileName($file_name) {
$pattern = "@[\\x00-\\x19#%&+!~'\$\"\/=\\\\?<> ]+@";
$file_name = preg_replace($pattern, '_', $file_name);
$file_name = preg_replace('@_+@', '_', $file_name);
$file_name = trim($file_name, '_');
$disallowed_filenames = array(
'.' => 'dot',
'..' => 'dotdot',
'' => 'file',
);
$file_name = idx($disallowed_filenames, $file_name, $file_name);
return $file_name;
}
public function delete() {
// We want to delete all the rows which mark this file as the transformation
// of some other file (since we're getting rid of it). We also delete all
// the transformations of this file, so that a user who deletes an image
// doesn't need to separately hunt down and delete a bunch of thumbnails and
// resizes of it.
$outbound_xforms = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withTransforms(
array(
array(
'originalPHID' => $this->getPHID(),
'transform' => true,
),
))
->execute();
foreach ($outbound_xforms as $outbound_xform) {
$outbound_xform->delete();
}
$inbound_xforms = id(new PhabricatorTransformedFile())->loadAllWhere(
'transformedPHID = %s',
$this->getPHID());
$this->openTransaction();
foreach ($inbound_xforms as $inbound_xform) {
$inbound_xform->delete();
}
$ret = parent::delete();
$this->saveTransaction();
$this->deleteFileDataIfUnused(
$this->instantiateStorageEngine(),
$this->getStorageEngine(),
$this->getStorageHandle());
return $ret;
}
/**
* Destroy stored file data if there are no remaining files which reference
* it.
*/
public function deleteFileDataIfUnused(
PhabricatorFileStorageEngine $engine,
$engine_identifier,
$handle) {
// Check to see if any files are using storage.
$usage = id(new PhabricatorFile())->loadAllWhere(
'storageEngine = %s AND storageHandle = %s LIMIT 1',
$engine_identifier,
$handle);
// If there are no files using the storage, destroy the actual storage.
if (!$usage) {
try {
$engine->deleteFile($handle);
} catch (Exception $ex) {
// In the worst case, we're leaving some data stranded in a storage
// engine, which is not a big deal.
phlog($ex);
}
}
}
public static function hashFileContent($data) {
// NOTE: Hashing can fail if the algorithm isn't available in the current
// build of PHP. It's fine if we're unable to generate a content hash:
// it just means we'll store extra data when users upload duplicate files
// instead of being able to deduplicate it.
$hash = hash('sha256', $data, $raw_output = false);
if ($hash === false) {
return null;
}
return $hash;
}
public function loadFileData() {
$iterator = $this->getFileDataIterator();
return $this->loadDataFromIterator($iterator);
}
/**
* Return an iterable which emits file content bytes.
*
* @param int Offset for the start of data.
* @param int Offset for the end of data.
* @return Iterable Iterable object which emits requested data.
*/
public function getFileDataIterator($begin = null, $end = null) {
$engine = $this->instantiateStorageEngine();
$format = $this->newStorageFormat();
$iterator = $engine->getRawFileDataIterator(
$this,
$begin,
$end,
$format);
return $iterator;
}
public function getURI() {
return $this->getInfoURI();
}
public function getViewURI() {
if (!$this->getPHID()) {
throw new Exception(
pht('You must save a file before you can generate a view URI.'));
}
return $this->getCDNURI('data');
}
public function getCDNURI($request_kind) {
if (($request_kind !== 'data') &&
($request_kind !== 'download')) {
throw new Exception(
pht(
'Unknown file content request kind "%s".',
$request_kind));
}
$name = self::normalizeFileName($this->getName());
$name = phutil_escape_uri($name);
$parts = array();
$parts[] = 'file';
$parts[] = $request_kind;
// If this is an instanced install, add the instance identifier to the URI.
// Instanced configurations behind a CDN may not be able to control the
// request domain used by the CDN (as with AWS CloudFront). Embedding the
// instance identity in the path allows us to distinguish between requests
// originating from different instances but served through the same CDN.
$instance = PhabricatorEnv::getEnvConfig('cluster.instance');
if ($instance !== null && strlen($instance)) {
$parts[] = '@'.$instance;
}
$parts[] = $this->getSecretKey();
$parts[] = $this->getPHID();
$parts[] = $name;
$path = '/'.implode('/', $parts);
// If this file is only partially uploaded, we're just going to return a
// local URI to make sure that Ajax works, since the page is inevitably
// going to give us an error back.
if ($this->getIsPartial()) {
return PhabricatorEnv::getURI($path);
} else {
return PhabricatorEnv::getCDNURI($path);
}
}
public function getInfoURI() {
return '/'.$this->getMonogram();
}
public function getBestURI() {
if ($this->isViewableInBrowser()) {
return $this->getViewURI();
} else {
return $this->getInfoURI();
}
}
public function getDownloadURI() {
return $this->getCDNURI('download');
}
public function getURIForTransform(PhabricatorFileTransform $transform) {
return $this->getTransformedURI($transform->getTransformKey());
}
private function getTransformedURI($transform) {
$parts = array();
$parts[] = 'file';
$parts[] = 'xform';
$instance = PhabricatorEnv::getEnvConfig('cluster.instance');
if ($instance !== null && strlen($instance)) {
$parts[] = '@'.$instance;
}
$parts[] = $transform;
$parts[] = $this->getPHID();
$parts[] = $this->getSecretKey();
$path = implode('/', $parts);
$path = $path.'/';
return PhabricatorEnv::getCDNURI($path);
}
public function isViewableInBrowser() {
return ($this->getViewableMimeType() !== null);
}
public function isViewableImage() {
if (!$this->isViewableInBrowser()) {
return false;
}
$mime_map = PhabricatorEnv::getEnvConfig('files.image-mime-types');
$mime_type = $this->getMimeType();
return idx($mime_map, $mime_type);
}
public function isAudio() {
if (!$this->isViewableInBrowser()) {
return false;
}
$mime_map = PhabricatorEnv::getEnvConfig('files.audio-mime-types');
$mime_type = $this->getMimeType();
return idx($mime_map, $mime_type);
}
public function isVideo() {
if (!$this->isViewableInBrowser()) {
return false;
}
$mime_map = PhabricatorEnv::getEnvConfig('files.video-mime-types');
$mime_type = $this->getMimeType();
return idx($mime_map, $mime_type);
}
public function isPDF() {
if (!$this->isViewableInBrowser()) {
return false;
}
$mime_map = array(
'application/pdf' => 'application/pdf',
);
$mime_type = $this->getMimeType();
return idx($mime_map, $mime_type);
}
public function isTransformableImage() {
// NOTE: The way the 'gd' extension works in PHP is that you can install it
// with support for only some file types, so it might be able to handle
// PNG but not JPEG. Try to generate thumbnails for whatever we can. Setup
// warns you if you don't have complete support.
$matches = null;
$ok = preg_match(
'@^image/(gif|png|jpe?g)@',
$this->getViewableMimeType(),
$matches);
if (!$ok) {
return false;
}
switch ($matches[1]) {
case 'jpg';
case 'jpeg':
return function_exists('imagejpeg');
break;
case 'png':
return function_exists('imagepng');
break;
case 'gif':
return function_exists('imagegif');
break;
default:
throw new Exception(pht('Unknown type matched as image MIME type.'));
}
}
public static function getTransformableImageFormats() {
$supported = array();
if (function_exists('imagejpeg')) {
$supported[] = 'jpg';
}
if (function_exists('imagepng')) {
$supported[] = 'png';
}
if (function_exists('imagegif')) {
$supported[] = 'gif';
}
return $supported;
}
public function getDragAndDropDictionary() {
return array(
'id' => $this->getID(),
'phid' => $this->getPHID(),
'uri' => $this->getBestURI(),
);
}
public function instantiateStorageEngine() {
return self::buildEngine($this->getStorageEngine());
}
public static function buildEngine($engine_identifier) {
$engines = self::buildAllEngines();
foreach ($engines as $engine) {
if ($engine->getEngineIdentifier() == $engine_identifier) {
return $engine;
}
}
throw new Exception(
pht(
"Storage engine '%s' could not be located!",
$engine_identifier));
}
public static function buildAllEngines() {
return id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorFileStorageEngine')
->execute();
}
public function getViewableMimeType() {
$mime_map = PhabricatorEnv::getEnvConfig('files.viewable-mime-types');
$mime_type = $this->getMimeType();
$mime_parts = explode(';', $mime_type);
$mime_type = trim(reset($mime_parts));
return idx($mime_map, $mime_type);
}
public function getDisplayIconForMimeType() {
$mime_map = PhabricatorEnv::getEnvConfig('files.icon-mime-types');
$mime_type = $this->getMimeType();
return idx($mime_map, $mime_type, 'fa-file-o');
}
public function validateSecretKey($key) {
return ($key == $this->getSecretKey());
}
public function generateSecretKey() {
return Filesystem::readRandomCharacters(20);
}
public function setStorageProperties(array $properties) {
$this->metadata[self::METADATA_STORAGE] = $properties;
return $this;
}
public function getStorageProperties() {
return idx($this->metadata, self::METADATA_STORAGE, array());
}
public function getStorageProperty($key, $default = null) {
$properties = $this->getStorageProperties();
return idx($properties, $key, $default);
}
public function loadDataFromIterator($iterator) {
$result = '';
foreach ($iterator as $chunk) {
$result .= $chunk;
}
return $result;
}
public function updateDimensions($save = true) {
if (!$this->isViewableImage()) {
throw new Exception(pht('This file is not a viewable image.'));
}
if (!function_exists('imagecreatefromstring')) {
throw new Exception(pht('Cannot retrieve image information.'));
}
if ($this->getIsChunk()) {
throw new Exception(
pht('Refusing to assess image dimensions of file chunk.'));
}
$engine = $this->instantiateStorageEngine();
if ($engine->isChunkEngine()) {
throw new Exception(
pht('Refusing to assess image dimensions of chunked file.'));
}
$data = $this->loadFileData();
$img = @imagecreatefromstring($data);
if ($img === false) {
throw new Exception(pht('Error when decoding image.'));
}
$this->metadata[self::METADATA_IMAGE_WIDTH] = imagesx($img);
$this->metadata[self::METADATA_IMAGE_HEIGHT] = imagesy($img);
if ($save) {
$this->save();
}
return $this;
}
public function copyDimensions(PhabricatorFile $file) {
$metadata = $file->getMetadata();
$width = idx($metadata, self::METADATA_IMAGE_WIDTH);
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/PhabricatorFileTransactionComment.php | src/applications/files/storage/PhabricatorFileTransactionComment.php | <?php
final class PhabricatorFileTransactionComment
extends PhabricatorApplicationTransactionComment {
public function getApplicationTransactionObject() {
return new PhabricatorFileTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/PhabricatorFileSchemaSpec.php | src/applications/files/storage/PhabricatorFileSchemaSpec.php | <?php
final class PhabricatorFileSchemaSpec
extends PhabricatorConfigSchemaSpec {
public function buildSchemata() {
$this->buildEdgeSchemata(new PhabricatorFile());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/PhabricatorFileNameNgrams.php | src/applications/files/storage/PhabricatorFileNameNgrams.php | <?php
final class PhabricatorFileNameNgrams
extends PhabricatorSearchNgrams {
public function getNgramKey() {
return 'filename';
}
public function getColumnName() {
return 'name';
}
public function getApplicationName() {
return 'file';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/PhabricatorFileAttachment.php | src/applications/files/storage/PhabricatorFileAttachment.php | <?php
final class PhabricatorFileAttachment
extends PhabricatorFileDAO
implements
PhabricatorPolicyInterface,
PhabricatorExtendedPolicyInterface {
protected $objectPHID;
protected $filePHID;
protected $attacherPHID;
protected $attachmentMode;
private $object = self::ATTACHABLE;
private $file = self::ATTACHABLE;
const MODE_ATTACH = 'attach';
const MODE_REFERENCE = 'reference';
const MODE_DETACH = 'detach';
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'objectPHID' => 'phid',
'filePHID' => 'phid',
'attacherPHID' => 'phid?',
'attachmentMode' => 'text32',
),
self::CONFIG_KEY_SCHEMA => array(
'key_object' => array(
'columns' => array('objectPHID', 'filePHID'),
'unique' => true,
),
'key_file' => array(
'columns' => array('filePHID'),
),
),
) + parent::getConfiguration();
}
public static function getModeList() {
return array(
self::MODE_ATTACH,
self::MODE_REFERENCE,
self::MODE_DETACH,
);
}
public static function getModeNameMap() {
return array(
self::MODE_ATTACH => pht('Attached'),
self::MODE_REFERENCE => pht('Referenced'),
);
}
public function isPolicyAttachment() {
switch ($this->getAttachmentMode()) {
case self::MODE_ATTACH:
return true;
default:
return false;
}
}
public function attachObject($object) {
$this->object = $object;
return $this;
}
public function getObject() {
return $this->assertAttached($this->object);
}
public function attachFile(PhabricatorFile $file = null) {
$this->file = $file;
return $this;
}
public function getFile() {
return $this->assertAttached($this->file);
}
public function canDetach() {
switch ($this->getAttachmentMode()) {
case self::MODE_ATTACH:
return true;
}
return false;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return PhabricatorPolicies::getMostOpenPolicy();
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
/* -( PhabricatorExtendedPolicyInterface )--------------------------------- */
public function getExtendedPolicy($capability, PhabricatorUser $viewer) {
return array(
array($this->getObject(), $capability),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/storage/__tests__/PhabricatorFileTestCase.php | src/applications/files/storage/__tests__/PhabricatorFileTestCase.php | <?php
final class PhabricatorFileTestCase extends PhabricatorTestCase {
protected function getPhabricatorTestCaseConfiguration() {
return array(
self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
);
}
public function testFileDirectScramble() {
// Changes to a file's view policy should scramble the file secret.
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$author = $this->generateNewTestUser();
$params = array(
'name' => 'test.dat',
'viewPolicy' => PhabricatorPolicies::POLICY_USER,
'authorPHID' => $author->getPHID(),
'storageEngines' => array(
$engine,
),
);
$file = PhabricatorFile::newFromFileData($data, $params);
$secret1 = $file->getSecretKey();
// First, change the name: this should not scramble the secret.
$xactions = array();
$xactions[] = id(new PhabricatorFileTransaction())
->setTransactionType(PhabricatorFileNameTransaction::TRANSACTIONTYPE)
->setNewValue('test.dat2');
$engine = id(new PhabricatorFileEditor())
->setActor($author)
->setContentSource($this->newContentSource())
->applyTransactions($file, $xactions);
$file = $file->reload();
$secret2 = $file->getSecretKey();
$this->assertEqual(
$secret1,
$secret2,
pht('No secret scramble on non-policy edit.'));
// Now, change the view policy. This should scramble the secret.
$xactions = array();
$xactions[] = id(new PhabricatorFileTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY)
->setNewValue($author->getPHID());
$engine = id(new PhabricatorFileEditor())
->setActor($author)
->setContentSource($this->newContentSource())
->applyTransactions($file, $xactions);
$file = $file->reload();
$secret3 = $file->getSecretKey();
$this->assertTrue(
($secret1 !== $secret3),
pht('Changing file view policy should scramble secret.'));
}
public function testFileIndirectScramble() {
// When a file is attached to an object like a task and the task view
// policy changes, the file secret should be scrambled. This invalidates
// old URIs if tasks get locked down.
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$author = $this->generateNewTestUser();
$params = array(
'name' => 'test.dat',
'viewPolicy' => $author->getPHID(),
'authorPHID' => $author->getPHID(),
'storageEngines' => array(
$engine,
),
);
$file = PhabricatorFile::newFromFileData($data, $params);
$secret1 = $file->getSecretKey();
$task = ManiphestTask::initializeNewTask($author);
$xactions = array();
$xactions[] = id(new ManiphestTransaction())
->setTransactionType(ManiphestTaskTitleTransaction::TRANSACTIONTYPE)
->setNewValue(pht('File Scramble Test Task'));
$xactions[] = id(new ManiphestTransaction())
->setTransactionType(
ManiphestTaskDescriptionTransaction::TRANSACTIONTYPE)
->setNewValue('{'.$file->getMonogram().'}')
->setMetadataValue(
'remarkup.control',
array(
'attachedFilePHIDs' => array(
$file->getPHID(),
),
));
id(new ManiphestTransactionEditor())
->setActor($author)
->setContentSource($this->newContentSource())
->applyTransactions($task, $xactions);
$file = $file->reload();
$secret2 = $file->getSecretKey();
$this->assertEqual(
$secret1,
$secret2,
pht(
'File policy should not scramble when attached to '.
'newly created object.'));
$xactions = array();
$xactions[] = id(new ManiphestTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY)
->setNewValue($author->getPHID());
id(new ManiphestTransactionEditor())
->setActor($author)
->setContentSource($this->newContentSource())
->applyTransactions($task, $xactions);
$file = $file->reload();
$secret3 = $file->getSecretKey();
$this->assertTrue(
($secret1 !== $secret3),
pht('Changing attached object view policy should scramble secret.'));
}
public function testFileVisibility() {
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$author = $this->generateNewTestUser();
$viewer = $this->generateNewTestUser();
$users = array($author, $viewer);
$params = array(
'name' => 'test.dat',
'viewPolicy' => PhabricatorPolicies::POLICY_NOONE,
'authorPHID' => $author->getPHID(),
'storageEngines' => array(
$engine,
),
);
$file = PhabricatorFile::newFromFileData($data, $params);
$filter = new PhabricatorPolicyFilter();
// Test bare file policies.
$this->assertEqual(
array(
true,
false,
),
$this->canViewFile($users, $file),
pht('File Visibility'));
// Create an object and test object policies.
$object = ManiphestTask::initializeNewTask($author)
->setTitle(pht('File Visibility Test Task'))
->setViewPolicy(PhabricatorPolicies::getMostOpenPolicy())
->save();
$this->assertTrue(
$filter->hasCapability(
$author,
$object,
PhabricatorPolicyCapability::CAN_VIEW),
pht('Object Visible to Author'));
$this->assertTrue(
$filter->hasCapability(
$viewer,
$object,
PhabricatorPolicyCapability::CAN_VIEW),
pht('Object Visible to Others'));
// Reference the file in a comment. This should not affect the file
// policy.
$file_ref = '{F'.$file->getID().'}';
$xactions = array();
$xactions[] = id(new ManiphestTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)
->attachComment(
id(new ManiphestTransactionComment())
->setContent($file_ref));
id(new ManiphestTransactionEditor())
->setActor($author)
->setContentSource($this->newContentSource())
->applyTransactions($object, $xactions);
// Test the referenced file's visibility.
$this->assertEqual(
array(
true,
false,
),
$this->canViewFile($users, $file),
pht('Referenced File Visibility'));
// Attach the file to the object and test that the association opens a
// policy exception for the non-author viewer.
$xactions = array();
$xactions[] = id(new ManiphestTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)
->setMetadataValue(
'remarkup.control',
array(
'attachedFilePHIDs' => array(
$file->getPHID(),
),
))
->attachComment(
id(new ManiphestTransactionComment())
->setContent($file_ref));
id(new ManiphestTransactionEditor())
->setActor($author)
->setContentSource($this->newContentSource())
->applyTransactions($object, $xactions);
// Test the attached file's visibility.
$this->assertEqual(
array(
true,
true,
),
$this->canViewFile($users, $file),
pht('Attached File Visibility'));
// Create a "thumbnail" of the original file.
$params = array(
'name' => 'test.thumb.dat',
'viewPolicy' => PhabricatorPolicies::POLICY_NOONE,
'storageEngines' => array(
$engine,
),
);
$xform = PhabricatorFile::newFromFileData($data, $params);
id(new PhabricatorTransformedFile())
->setOriginalPHID($file->getPHID())
->setTransform('test-thumb')
->setTransformedPHID($xform->getPHID())
->save();
// Test the thumbnail's visibility.
$this->assertEqual(
array(
true,
true,
),
$this->canViewFile($users, $xform),
pht('Attached Thumbnail Visibility'));
}
private function canViewFile(array $users, PhabricatorFile $file) {
$results = array();
foreach ($users as $user) {
$results[] = (bool)id(new PhabricatorFileQuery())
->setViewer($user)
->withPHIDs(array($file->getPHID()))
->execute();
}
return $results;
}
public function testFileStorageReadWrite() {
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$params = array(
'name' => 'test.dat',
'storageEngines' => array(
$engine,
),
);
$file = PhabricatorFile::newFromFileData($data, $params);
// Test that the storage engine worked, and was the target of the write. We
// don't actually care what the data is (future changes may compress or
// encrypt it), just that it exists in the test storage engine.
$engine->readFile($file->getStorageHandle());
// Now test that we get the same data back out.
$this->assertEqual($data, $file->loadFileData());
}
public function testFileStorageUploadDifferentFiles() {
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$other_data = Filesystem::readRandomCharacters(64);
$params = array(
'name' => 'test.dat',
'storageEngines' => array(
$engine,
),
);
$first_file = PhabricatorFile::newFromFileData($data, $params);
$second_file = PhabricatorFile::newFromFileData($other_data, $params);
// Test that the second file uses different storage handle from
// the first file.
$first_handle = $first_file->getStorageHandle();
$second_handle = $second_file->getStorageHandle();
$this->assertTrue($first_handle != $second_handle);
}
public function testFileStorageUploadSameFile() {
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$hash = PhabricatorFile::hashFileContent($data);
if ($hash === null) {
$this->assertSkipped(pht('File content hashing is not available.'));
}
$params = array(
'name' => 'test.dat',
'storageEngines' => array(
$engine,
),
);
$first_file = PhabricatorFile::newFromFileData($data, $params);
$second_file = PhabricatorFile::newFromFileData($data, $params);
// Test that the second file uses the same storage handle as
// the first file.
$handle = $first_file->getStorageHandle();
$second_handle = $second_file->getStorageHandle();
$this->assertEqual($handle, $second_handle);
}
public function testFileStorageDelete() {
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$params = array(
'name' => 'test.dat',
'storageEngines' => array(
$engine,
),
);
$file = PhabricatorFile::newFromFileData($data, $params);
$handle = $file->getStorageHandle();
$file->delete();
$caught = null;
try {
$engine->readFile($handle);
} catch (Exception $ex) {
$caught = $ex;
}
$this->assertTrue($caught instanceof Exception);
}
public function testFileStorageDeleteSharedHandle() {
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$params = array(
'name' => 'test.dat',
'storageEngines' => array(
$engine,
),
);
$first_file = PhabricatorFile::newFromFileData($data, $params);
$second_file = PhabricatorFile::newFromFileData($data, $params);
$first_file->delete();
$this->assertEqual($data, $second_file->loadFileData());
}
public function testReadWriteTtlFiles() {
$engine = new PhabricatorTestStorageEngine();
$data = Filesystem::readRandomCharacters(64);
$ttl = (PhabricatorTime::getNow() + phutil_units('24 hours in seconds'));
$params = array(
'name' => 'test.dat',
'ttl.absolute' => $ttl,
'storageEngines' => array(
$engine,
),
);
$file = PhabricatorFile::newFromFileData($data, $params);
$this->assertEqual($ttl, $file->getTTL());
}
public function testFileTransformDelete() {
// We want to test that a file deletes all its inbound transformation
// records and outbound transformed derivatives when it is deleted.
// First, we create a chain of transforms, A -> B -> C.
$engine = new PhabricatorTestStorageEngine();
$params = array(
'name' => 'test.txt',
'storageEngines' => array(
$engine,
),
);
$a = PhabricatorFile::newFromFileData('a', $params);
$b = PhabricatorFile::newFromFileData('b', $params);
$c = PhabricatorFile::newFromFileData('c', $params);
id(new PhabricatorTransformedFile())
->setOriginalPHID($a->getPHID())
->setTransform('test:a->b')
->setTransformedPHID($b->getPHID())
->save();
id(new PhabricatorTransformedFile())
->setOriginalPHID($b->getPHID())
->setTransform('test:b->c')
->setTransformedPHID($c->getPHID())
->save();
// Now, verify that A -> B and B -> C exist.
$xform_a = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withTransforms(
array(
array(
'originalPHID' => $a->getPHID(),
'transform' => true,
),
))
->execute();
$this->assertEqual(1, count($xform_a));
$this->assertEqual($b->getPHID(), head($xform_a)->getPHID());
$xform_b = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withTransforms(
array(
array(
'originalPHID' => $b->getPHID(),
'transform' => true,
),
))
->execute();
$this->assertEqual(1, count($xform_b));
$this->assertEqual($c->getPHID(), head($xform_b)->getPHID());
// Delete "B".
$b->delete();
// Now, verify that the A -> B and B -> C links are gone.
$xform_a = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withTransforms(
array(
array(
'originalPHID' => $a->getPHID(),
'transform' => true,
),
))
->execute();
$this->assertEqual(0, count($xform_a));
$xform_b = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withTransforms(
array(
array(
'originalPHID' => $b->getPHID(),
'transform' => true,
),
))
->execute();
$this->assertEqual(0, count($xform_b));
// Also verify that C has been deleted.
$alternate_c = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs(array($c->getPHID()))
->execute();
$this->assertEqual(array(), $alternate_c);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/management/PhabricatorFilesManagementCycleWorkflow.php | src/applications/files/management/PhabricatorFilesManagementCycleWorkflow.php | <?php
final class PhabricatorFilesManagementCycleWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$arguments = $this->newIteratorArguments();
$arguments[] = array(
'name' => 'key',
'param' => 'keyname',
'help' => pht('Select a specific storage key to cycle to.'),
);
$this
->setName('cycle')
->setSynopsis(
pht('Cycle master key for encrypted files.'))
->setArguments($arguments);
}
public function execute(PhutilArgumentParser $args) {
$iterator = $this->buildIterator($args);
$format_map = PhabricatorFileStorageFormat::getAllFormats();
$engines = PhabricatorFileStorageEngine::loadAllEngines();
$key_name = $args->getArg('key');
$failed = array();
foreach ($iterator as $file) {
$monogram = $file->getMonogram();
$engine_key = $file->getStorageEngine();
$engine = idx($engines, $engine_key);
if (!$engine) {
echo tsprintf(
"%s\n",
pht(
'%s: Uses unknown storage engine "%s".',
$monogram,
$engine_key));
$failed[] = $file;
continue;
}
if ($engine->isChunkEngine()) {
echo tsprintf(
"%s\n",
pht(
'%s: Stored as chunks, declining to cycle directly.',
$monogram));
continue;
}
$format_key = $file->getStorageFormat();
if (empty($format_map[$format_key])) {
echo tsprintf(
"%s\n",
pht(
'%s: Uses unknown storage format "%s".',
$monogram,
$format_key));
$failed[] = $file;
continue;
}
$format = clone $format_map[$format_key];
$format->setFile($file);
if (!$format->canCycleMasterKey()) {
echo tsprintf(
"%s\n",
pht(
'%s: Storage format ("%s") does not support key cycling.',
$monogram,
$format->getStorageFormatName()));
continue;
}
echo tsprintf(
"%s\n",
pht(
'%s: Cycling master key.',
$monogram));
try {
if ($key_name) {
$format->selectMasterKey($key_name);
}
$file->cycleMasterStorageKey($format);
echo tsprintf(
"%s\n",
pht('Done.'));
} catch (Exception $ex) {
echo tsprintf(
"%B\n",
pht('Failed! %s', (string)$ex));
$failed[] = $file;
}
}
if ($failed) {
$monograms = mpull($failed, 'getMonogram');
echo tsprintf(
"%s\n",
pht('Failures: %s.', implode(', ', $monograms)));
return 1;
}
return 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/management/PhabricatorFilesManagementIntegrityWorkflow.php | src/applications/files/management/PhabricatorFilesManagementIntegrityWorkflow.php | <?php
final class PhabricatorFilesManagementIntegrityWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$arguments = $this->newIteratorArguments();
$arguments[] = array(
'name' => 'strip',
'help' => pht(
'DANGEROUS. Strip integrity hashes from files. This makes '.
'files vulnerable to corruption or tampering.'),
);
$arguments[] = array(
'name' => 'corrupt',
'help' => pht(
'Corrupt integrity hashes for given files. This is intended '.
'for debugging.'),
);
$arguments[] = array(
'name' => 'compute',
'help' => pht(
'Compute and update integrity hashes for files which do not '.
'yet have them.'),
);
$arguments[] = array(
'name' => 'overwrite',
'help' => pht(
'DANGEROUS. Recompute and update integrity hashes, overwriting '.
'invalid hashes. This may mark corrupt or dangerous files as '.
'valid.'),
);
$arguments[] = array(
'name' => 'force',
'short' => 'f',
'help' => pht(
'Execute dangerous operations without prompting for '.
'confirmation.'),
);
$this
->setName('integrity')
->setSynopsis(pht('Verify or recalculate file integrity hashes.'))
->setArguments($arguments);
}
public function execute(PhutilArgumentParser $args) {
$modes = array();
$is_strip = $args->getArg('strip');
if ($is_strip) {
$modes[] = 'strip';
}
$is_corrupt = $args->getArg('corrupt');
if ($is_corrupt) {
$modes[] = 'corrupt';
}
$is_compute = $args->getArg('compute');
if ($is_compute) {
$modes[] = 'compute';
}
$is_overwrite = $args->getArg('overwrite');
if ($is_overwrite) {
$modes[] = 'overwrite';
}
$is_verify = !$modes;
if ($is_verify) {
$modes[] = 'verify';
}
if (count($modes) > 1) {
throw new PhutilArgumentUsageException(
pht(
'You have selected multiple operation modes (%s). Choose a '.
'single mode to operate in.',
implode(', ', $modes)));
}
$is_force = $args->getArg('force');
if (!$is_force) {
$prompt = null;
if ($is_strip) {
$prompt = pht(
'Stripping integrity hashes is dangerous and makes files '.
'vulnerable to corruption or tampering.');
}
if ($is_corrupt) {
$prompt = pht(
'Corrupting integrity hashes will prevent files from being '.
'accessed. This mode is intended only for development and '.
'debugging.');
}
if ($is_overwrite) {
$prompt = pht(
'Overwriting integrity hashes is dangerous and may mark files '.
'which have been corrupted or tampered with as safe.');
}
if ($prompt) {
$this->logWarn(pht('DANGEROUS'), $prompt);
if (!phutil_console_confirm(pht('Continue anyway?'))) {
throw new PhutilArgumentUsageException(pht('Aborted workflow.'));
}
}
}
$iterator = $this->buildIterator($args);
$failure_count = 0;
$total_count = 0;
foreach ($iterator as $file) {
$total_count++;
$display_name = $file->getMonogram();
$old_hash = $file->getIntegrityHash();
if ($is_strip) {
if ($old_hash === null) {
$this->logInfo(
pht('SKIPPED'),
pht(
'File "%s" does not have an integrity hash to strip.',
$display_name));
} else {
$file
->setIntegrityHash(null)
->save();
$this->logWarn(
pht('STRIPPED'),
pht(
'Stripped integrity hash for "%s".',
$display_name));
}
continue;
}
$need_hash = ($is_verify && $old_hash) ||
($is_compute && ($old_hash === null)) ||
($is_corrupt) ||
($is_overwrite);
if ($need_hash) {
try {
$new_hash = $file->newIntegrityHash();
} catch (Exception $ex) {
$failure_count++;
$this->logFail(
pht('ERROR'),
pht(
'Unable to compute integrity hash for file "%s": %s',
$display_name,
$ex->getMessage()));
continue;
}
} else {
$new_hash = null;
}
// NOTE: When running in "corrupt" mode, we only corrupt the hash if
// we're able to compute a valid hash. Some files, like chunked files,
// do not support integrity hashing so corrupting them would create an
// unusual state.
if ($is_corrupt) {
if ($new_hash === null) {
$this->logInfo(
pht('IGNORED'),
pht(
'Storage for file "%s" does not support integrity hashing.',
$display_name));
} else {
$file
->setIntegrityHash('<corrupted>')
->save();
$this->logWarn(
pht('CORRUPTED'),
pht(
'Corrupted integrity hash for file "%s".',
$display_name));
}
continue;
}
if ($is_verify) {
if ($old_hash === null) {
$this->logInfo(
pht('NONE'),
pht(
'File "%s" has no stored integrity hash.',
$display_name));
} else if ($new_hash === null) {
$failure_count++;
$this->logWarn(
pht('UNEXPECTED'),
pht(
'Storage for file "%s" does not support integrity hashing, '.
'but the file has an integrity hash.',
$display_name));
} else if (phutil_hashes_are_identical($old_hash, $new_hash)) {
$this->logOkay(
pht('VALID'),
pht(
'File "%s" has a valid integrity hash.',
$display_name));
} else {
$failure_count++;
$this->logFail(
pht('MISMATCH'),
pht(
'File "%s" has an invalid integrity hash!',
$display_name));
}
continue;
}
if ($is_compute) {
if ($old_hash !== null) {
$this->logInfo(
pht('SKIP'),
pht(
'File "%s" already has an integrity hash.',
$display_name));
} else if ($new_hash === null) {
$this->logInfo(
pht('IGNORED'),
pht(
'Storage for file "%s" does not support integrity hashing.',
$display_name));
} else {
$file
->setIntegrityHash($new_hash)
->save();
$this->logOkay(
pht('COMPUTE'),
pht(
'Computed and stored integrity hash for file "%s".',
$display_name));
}
continue;
}
if ($is_overwrite) {
$same_hash = ($old_hash !== null) &&
($new_hash !== null) &&
phutil_hashes_are_identical($old_hash, $new_hash);
if ($new_hash === null) {
$this->logInfo(
pht('IGNORED'),
pht(
'Storage for file "%s" does not support integrity hashing.',
$display_name));
} else if ($same_hash) {
$this->logInfo(
pht('UNCHANGED'),
pht(
'File "%s" already has the correct integrity hash.',
$display_name));
} else {
$file
->setIntegrityHash($new_hash)
->save();
$this->logOkay(
pht('OVERWRITE'),
pht(
'Overwrote integrity hash for file "%s".',
$display_name));
}
continue;
}
}
if ($failure_count) {
$this->logFail(
pht('FAIL'),
pht(
'Processed %s file(s), encountered %s error(s).',
new PhutilNumber($total_count),
new PhutilNumber($failure_count)));
} else {
$this->logOkay(
pht('DONE'),
pht(
'Processed %s file(s) with no errors.',
new PhutilNumber($total_count)));
}
return 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/management/PhabricatorFilesManagementCompactWorkflow.php | src/applications/files/management/PhabricatorFilesManagementCompactWorkflow.php | <?php
final class PhabricatorFilesManagementCompactWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$arguments = $this->newIteratorArguments();
$arguments[] = array(
'name' => 'dry-run',
'help' => pht('Show what would be compacted.'),
);
$this
->setName('compact')
->setSynopsis(
pht(
'Merge identical files to share the same storage. In some cases, '.
'this can repair files with missing data.'))
->setArguments($arguments);
}
public function execute(PhutilArgumentParser $args) {
$console = PhutilConsole::getConsole();
$iterator = $this->buildIterator($args);
$is_dry_run = $args->getArg('dry-run');
foreach ($iterator as $file) {
$monogram = $file->getMonogram();
$hash = $file->getContentHash();
if (!$hash) {
$console->writeOut(
"%s\n",
pht('%s: No content hash.', $monogram));
continue;
}
// Find other files with the same content hash. We're going to point
// them at the data for this file.
$similar_files = id(new PhabricatorFile())->loadAllWhere(
'contentHash = %s AND id != %d AND
(storageEngine != %s OR storageHandle != %s)',
$hash,
$file->getID(),
$file->getStorageEngine(),
$file->getStorageHandle());
if (!$similar_files) {
$console->writeOut(
"%s\n",
pht('%s: No other files with the same content hash.', $monogram));
continue;
}
// Only compact files into this one if we can load the data. This
// prevents us from breaking working files if we're missing some data.
try {
$data = $file->loadFileData();
} catch (Exception $ex) {
$data = null;
}
if ($data === null) {
$console->writeOut(
"%s\n",
pht(
'%s: Unable to load file data; declining to compact.',
$monogram));
continue;
}
foreach ($similar_files as $similar_file) {
if ($is_dry_run) {
$console->writeOut(
"%s\n",
pht(
'%s: Would compact storage with %s.',
$monogram,
$similar_file->getMonogram()));
continue;
}
$console->writeOut(
"%s\n",
pht(
'%s: Compacting storage with %s.',
$monogram,
$similar_file->getMonogram()));
$old_instance = null;
try {
$old_instance = $similar_file->instantiateStorageEngine();
$old_engine = $similar_file->getStorageEngine();
$old_handle = $similar_file->getStorageHandle();
} catch (Exception $ex) {
// If the old stuff is busted, we just won't try to delete the
// old data.
phlog($ex);
}
$similar_file
->setStorageEngine($file->getStorageEngine())
->setStorageHandle($file->getStorageHandle())
->save();
if ($old_instance) {
$similar_file->deleteFileDataIfUnused(
$old_instance,
$old_engine,
$old_handle);
}
}
}
return 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/management/PhabricatorFilesManagementMigrateWorkflow.php | src/applications/files/management/PhabricatorFilesManagementMigrateWorkflow.php | <?php
final class PhabricatorFilesManagementMigrateWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$arguments = $this->newIteratorArguments();
$arguments[] = array(
'name' => 'engine',
'param' => 'storage-engine',
'help' => pht('Migrate to the named storage engine.'),
);
$arguments[] = array(
'name' => 'dry-run',
'help' => pht('Show what would be migrated.'),
);
$arguments[] = array(
'name' => 'min-size',
'param' => 'bytes',
'help' => pht(
'Do not migrate data for files which are smaller than a given '.
'filesize.'),
);
$arguments[] = array(
'name' => 'max-size',
'param' => 'bytes',
'help' => pht(
'Do not migrate data for files which are larger than a given '.
'filesize.'),
);
$arguments[] = array(
'name' => 'copy',
'help' => pht(
'Copy file data instead of moving it: after migrating, do not '.
'remove the old data even if it is no longer referenced.'),
);
$arguments[] = array(
'name' => 'local-disk-source',
'param' => 'path',
'help' => pht(
'When migrating from a local disk source, use the specified '.
'path as the root directory.'),
);
$this
->setName('migrate')
->setSynopsis(pht('Migrate files between storage engines.'))
->setArguments($arguments);
}
public function execute(PhutilArgumentParser $args) {
// See T13306. This flag allows you to import files from a backup of
// local disk storage into some other engine. When the caller provides
// the flag, we override the local disk engine configuration and treat
// it as though it is configured to use the specified location.
$local_disk_source = $args->getArg('local-disk-source');
if (strlen($local_disk_source)) {
$path = Filesystem::resolvePath($local_disk_source);
try {
Filesystem::assertIsDirectory($path);
} catch (FilesystemException $ex) {
throw new PhutilArgumentUsageException(
pht(
'The "--local-disk-source" argument must point to a valid, '.
'readable directory on local disk.'));
}
$env = PhabricatorEnv::beginScopedEnv();
$env->overrideEnvConfig('storage.local-disk.path', $path);
}
$target_key = $args->getArg('engine');
if (!$target_key) {
throw new PhutilArgumentUsageException(
pht(
'Specify an engine to migrate to with `%s`. '.
'Use `%s` to get a list of engines.',
'--engine',
'files engines'));
}
$target_engine = PhabricatorFile::buildEngine($target_key);
$iterator = $this->buildIterator($args);
$is_dry_run = $args->getArg('dry-run');
$min_size = (int)$args->getArg('min-size');
$max_size = (int)$args->getArg('max-size');
$is_copy = $args->getArg('copy');
$failed = array();
$engines = PhabricatorFileStorageEngine::loadAllEngines();
$total_bytes = 0;
$total_files = 0;
foreach ($iterator as $file) {
$monogram = $file->getMonogram();
// See T7148. When we export data for an instance, we copy all the data
// for Files from S3 into the database dump so that the database dump is
// a complete, standalone archive of all the data. In the general case,
// installs may have a similar process using "--copy" to create a more
// complete backup.
// When doing this, we may run into temporary files which have been
// deleted between the time we took the original dump and the current
// timestamp. These files can't be copied since the data no longer
// exists: the daemons on the live install already deleted it.
// Simply avoid this whole mess by declining to migrate expired temporary
// files. They're as good as dead anyway.
$ttl = $file->getTTL();
if ($ttl) {
if ($ttl < PhabricatorTime::getNow()) {
echo tsprintf(
"%s\n",
pht(
'%s: Skipping expired temporary file.',
$monogram));
continue;
}
}
$engine_key = $file->getStorageEngine();
$engine = idx($engines, $engine_key);
if (!$engine) {
echo tsprintf(
"%s\n",
pht(
'%s: Uses unknown storage engine "%s".',
$monogram,
$engine_key));
$failed[] = $file;
continue;
}
if ($engine->isChunkEngine()) {
echo tsprintf(
"%s\n",
pht(
'%s: Stored as chunks, no data to migrate directly.',
$monogram));
continue;
}
if ($engine_key === $target_key) {
echo tsprintf(
"%s\n",
pht(
'%s: Already stored in engine "%s".',
$monogram,
$target_key));
continue;
}
$byte_size = $file->getByteSize();
if ($min_size && ($byte_size < $min_size)) {
echo tsprintf(
"%s\n",
pht(
'%s: File size (%s) is smaller than minimum size (%s).',
$monogram,
phutil_format_bytes($byte_size),
phutil_format_bytes($min_size)));
continue;
}
if ($max_size && ($byte_size > $max_size)) {
echo tsprintf(
"%s\n",
pht(
'%s: File size (%s) is larger than maximum size (%s).',
$monogram,
phutil_format_bytes($byte_size),
phutil_format_bytes($max_size)));
continue;
}
if ($is_dry_run) {
echo tsprintf(
"%s\n",
pht(
'%s: (%s) Would migrate from "%s" to "%s" (dry run)...',
$monogram,
phutil_format_bytes($byte_size),
$engine_key,
$target_key));
} else {
echo tsprintf(
"%s\n",
pht(
'%s: (%s) Migrating from "%s" to "%s"...',
$monogram,
phutil_format_bytes($byte_size),
$engine_key,
$target_key));
}
try {
if ($is_dry_run) {
// Do nothing, this is a dry run.
} else {
$file->migrateToEngine($target_engine, $is_copy);
}
$total_files += 1;
$total_bytes += $byte_size;
echo tsprintf(
"%s\n",
pht('Done.'));
} catch (Exception $ex) {
echo tsprintf(
"%s\n",
pht('Failed! %s', (string)$ex));
$failed[] = $file;
throw $ex;
}
}
echo tsprintf(
"%s\n",
pht(
'Total Migrated Files: %s',
new PhutilNumber($total_files)));
echo tsprintf(
"%s\n",
pht(
'Total Migrated Bytes: %s',
phutil_format_bytes($total_bytes)));
if ($is_dry_run) {
echo tsprintf(
"%s\n",
pht(
'This was a dry run, so no real migrations were performed.'));
}
if ($failed) {
$monograms = mpull($failed, 'getMonogram');
echo tsprintf(
"%s\n",
pht('Failures: %s.', implode(', ', $monograms)));
return 1;
}
return 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/management/PhabricatorFilesManagementGenerateKeyWorkflow.php | src/applications/files/management/PhabricatorFilesManagementGenerateKeyWorkflow.php | <?php
final class PhabricatorFilesManagementGenerateKeyWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$this
->setName('generate-key')
->setSynopsis(
pht('Generate an encryption key.'))
->setArguments(
array(
array(
'name' => 'type',
'param' => 'keytype',
'help' => pht('Select the type of key to generate.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$type = $args->getArg('type');
if (!strlen($type)) {
throw new PhutilArgumentUsageException(
pht(
'Specify the type of key to generate with --type.'));
}
$format = PhabricatorFileStorageFormat::getFormat($type);
if (!$format) {
throw new PhutilArgumentUsageException(
pht(
'No key type "%s" exists.',
$type));
}
if (!$format->canGenerateNewKeyMaterial()) {
throw new PhutilArgumentUsageException(
pht(
'Storage format "%s" can not generate keys.',
$format->getStorageFormatName()));
}
$material = $format->generateNewKeyMaterial();
$structure = array(
'name' => 'generated-key-'.Filesystem::readRandomCharacters(12),
'type' => $type,
'material.base64' => $material,
);
$json = id(new PhutilJSON())->encodeFormatted($structure);
echo tsprintf(
"%s: %s\n\n%B\n",
pht('Key Material'),
$format->getStorageFormatName(),
$json);
return 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/management/PhabricatorFilesManagementRebuildWorkflow.php | src/applications/files/management/PhabricatorFilesManagementRebuildWorkflow.php | <?php
final class PhabricatorFilesManagementRebuildWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$arguments = $this->newIteratorArguments();
$arguments[] = array(
'name' => 'dry-run',
'help' => pht('Show what would be updated.'),
);
$arguments[] = array(
'name' => 'rebuild-mime',
'help' => pht('Rebuild MIME information.'),
);
$arguments[] = array(
'name' => 'rebuild-dimensions',
'help' => pht('Rebuild image dimension information.'),
);
$this
->setName('rebuild')
->setSynopsis(pht('Rebuild metadata of old files.'))
->setArguments($arguments);
}
public function execute(PhutilArgumentParser $args) {
$console = PhutilConsole::getConsole();
$iterator = $this->buildIterator($args);
$update = array(
'mime' => $args->getArg('rebuild-mime'),
'dimensions' => $args->getArg('rebuild-dimensions'),
);
// If the user didn't select anything, rebuild everything.
if (!array_filter($update)) {
foreach ($update as $key => $ignored) {
$update[$key] = true;
}
}
$is_dry_run = $args->getArg('dry-run');
$failed = array();
foreach ($iterator as $file) {
$fid = 'F'.$file->getID();
if ($update['mime']) {
$tmp = new TempFile();
Filesystem::writeFile($tmp, $file->loadFileData());
$new_type = Filesystem::getMimeType($tmp);
if ($new_type == $file->getMimeType()) {
$console->writeOut(
"%s\n",
pht(
'%s: Mime type not changed (%s).',
$fid,
$new_type));
} else {
if ($is_dry_run) {
$console->writeOut(
"%s\n",
pht(
"%s: Would update Mime type: '%s' -> '%s'.",
$fid,
$file->getMimeType(),
$new_type));
} else {
$console->writeOut(
"%s\n",
pht(
"%s: Updating Mime type: '%s' -> '%s'.",
$fid,
$file->getMimeType(),
$new_type));
$file->setMimeType($new_type);
$file->save();
}
}
}
if ($update['dimensions']) {
if (!$file->isViewableImage()) {
$console->writeOut(
"%s\n",
pht('%s: Not an image file.', $fid));
continue;
}
$metadata = $file->getMetadata();
$image_width = idx($metadata, PhabricatorFile::METADATA_IMAGE_WIDTH);
$image_height = idx($metadata, PhabricatorFile::METADATA_IMAGE_HEIGHT);
if ($image_width && $image_height) {
$console->writeOut(
"%s\n",
pht('%s: Image dimensions already exist.', $fid));
continue;
}
if ($is_dry_run) {
$console->writeOut(
"%s\n",
pht('%s: Would update file dimensions (dry run)', $fid));
continue;
}
$console->writeOut(
pht('%s: Updating metadata... ', $fid));
try {
$file->updateDimensions();
$console->writeOut("%s\n", pht('Done.'));
} catch (Exception $ex) {
$console->writeOut("%s\n", pht('Failed!'));
$console->writeErr("%s\n", (string)$ex);
$failed[] = $file;
}
}
}
if ($failed) {
$console->writeOut("**%s**\n", pht('Failures!'));
$ids = array();
foreach ($failed as $file) {
$ids[] = 'F'.$file->getID();
}
$console->writeOut("%s\n", implode(', ', $ids));
return 1;
} else {
$console->writeOut("**%s**\n", pht('Success!'));
return 0;
}
return 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/management/PhabricatorFilesManagementCatWorkflow.php | src/applications/files/management/PhabricatorFilesManagementCatWorkflow.php | <?php
final class PhabricatorFilesManagementCatWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$this
->setName('cat')
->setSynopsis(pht('Print the contents of a file.'))
->setArguments(
array(
array(
'name' => 'begin',
'param' => 'bytes',
'help' => pht('Begin printing at a specific offset.'),
),
array(
'name' => 'end',
'param' => 'bytes',
'help' => pht('End printing at a specific offset.'),
),
array(
'name' => 'salvage',
'help' => pht(
'DANGEROUS. Attempt to salvage file content even if the '.
'integrity check fails. If an adversary has tampered with '.
'the file, the content may be unsafe.'),
),
array(
'name' => 'names',
'wildcard' => true,
),
));
}
public function execute(PhutilArgumentParser $args) {
$console = PhutilConsole::getConsole();
$names = $args->getArg('names');
if (count($names) > 1) {
throw new PhutilArgumentUsageException(
pht('Specify exactly one file to print, like "%s".', 'F123'));
} else if (!$names) {
throw new PhutilArgumentUsageException(
pht('Specify a file to print, like "%s".', 'F123'));
}
$file = head($this->loadFilesWithNames($names));
$begin = $args->getArg('begin');
$end = $args->getArg('end');
$file->makeEphemeral();
// If we're running in "salvage" mode, wipe out any integrity hash which
// may be present. This makes us read file data without performing an
// integrity check.
$salvage = $args->getArg('salvage');
if ($salvage) {
$file->setIntegrityHash(null);
}
try {
$iterator = $file->getFileDataIterator($begin, $end);
foreach ($iterator as $data) {
echo $data;
}
} catch (PhabricatorFileIntegrityException $ex) {
throw new PhutilArgumentUsageException(
pht(
'File data integrity check failed. Use "--salvage" to bypass '.
'integrity checks. This flag is dangerous, use it at your own '.
'risk. Underlying error: %s',
$ex->getMessage()));
}
return 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/management/PhabricatorFilesManagementEncodeWorkflow.php | src/applications/files/management/PhabricatorFilesManagementEncodeWorkflow.php | <?php
final class PhabricatorFilesManagementEncodeWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$arguments = $this->newIteratorArguments();
$arguments[] = array(
'name' => 'as',
'param' => 'format',
'help' => pht('Select the storage format to use.'),
);
$arguments[] = array(
'name' => 'key',
'param' => 'keyname',
'help' => pht('Select a specific storage key.'),
);
$arguments[] = array(
'name' => 'force',
'help' => pht(
'Re-encode files which are already stored in the target '.
'encoding.'),
);
$this
->setName('encode')
->setSynopsis(
pht('Change the storage encoding of files.'))
->setArguments($arguments);
}
public function execute(PhutilArgumentParser $args) {
$iterator = $this->buildIterator($args);
$force = (bool)$args->getArg('force');
$format_list = PhabricatorFileStorageFormat::getAllFormats();
$format_list = array_keys($format_list);
$format_list = implode(', ', $format_list);
$format_key = $args->getArg('as');
if (!strlen($format_key)) {
throw new PhutilArgumentUsageException(
pht(
'Use --as <format> to select a target encoding format. Available '.
'formats are: %s.',
$format_list));
}
$format = PhabricatorFileStorageFormat::getFormat($format_key);
if (!$format) {
throw new PhutilArgumentUsageException(
pht(
'Storage format "%s" is not valid. Available formats are: %s.',
$format_key,
$format_list));
}
$key_name = $args->getArg('key');
if (strlen($key_name)) {
$format->selectMasterKey($key_name);
}
$engines = PhabricatorFileStorageEngine::loadAllEngines();
$failed = array();
foreach ($iterator as $file) {
$monogram = $file->getMonogram();
$engine_key = $file->getStorageEngine();
$engine = idx($engines, $engine_key);
if (!$engine) {
echo tsprintf(
"%s\n",
pht(
'%s: Uses unknown storage engine "%s".',
$monogram,
$engine_key));
$failed[] = $file;
continue;
}
if ($engine->isChunkEngine()) {
echo tsprintf(
"%s\n",
pht(
'%s: Stored as chunks, no data to encode directly.',
$monogram));
continue;
}
if (($file->getStorageFormat() == $format_key) && !$force) {
echo tsprintf(
"%s\n",
pht(
'%s: Already encoded in target format.',
$monogram));
continue;
}
echo tsprintf(
"%s\n",
pht(
'%s: Changing encoding from "%s" to "%s".',
$monogram,
$file->getStorageFormat(),
$format_key));
try {
$file->migrateToStorageFormat($format);
echo tsprintf(
"%s\n",
pht('Done.'));
} catch (Exception $ex) {
echo tsprintf(
"%B\n",
pht('Failed! %s', (string)$ex));
$failed[] = $file;
}
}
if ($failed) {
$monograms = mpull($failed, 'getMonogram');
echo tsprintf(
"%s\n",
pht('Failures: %s.', implode(', ', $monograms)));
return 1;
}
return 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/management/PhabricatorFilesManagementEnginesWorkflow.php | src/applications/files/management/PhabricatorFilesManagementEnginesWorkflow.php | <?php
final class PhabricatorFilesManagementEnginesWorkflow
extends PhabricatorFilesManagementWorkflow {
protected function didConstruct() {
$this
->setName('engines')
->setSynopsis(pht('List available storage engines.'))
->setArguments(array());
}
public function execute(PhutilArgumentParser $args) {
$console = PhutilConsole::getConsole();
$engines = PhabricatorFile::buildAllEngines();
if (!$engines) {
throw new Exception(pht('No storage engines are available.'));
}
foreach ($engines as $engine) {
$console->writeOut(
"%s\n",
$engine->getEngineIdentifier());
}
return 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/management/PhabricatorFilesManagementWorkflow.php | src/applications/files/management/PhabricatorFilesManagementWorkflow.php | <?php
abstract class PhabricatorFilesManagementWorkflow
extends PhabricatorManagementWorkflow {
protected function newIteratorArguments() {
return array(
array(
'name' => 'all',
'help' => pht('Operate on all files.'),
),
array(
'name' => 'names',
'wildcard' => true,
),
array(
'name' => 'from-engine',
'param' => 'storage-engine',
'help' => pht('Operate on files stored in a specified engine.'),
),
);
}
protected function buildIterator(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$is_all = $args->getArg('all');
$names = $args->getArg('names');
$from_engine = $args->getArg('from-engine');
$any_constraint = ($from_engine || $names);
if (!$is_all && !$any_constraint) {
throw new PhutilArgumentUsageException(
pht(
'Specify which files to operate on, or use "--all" to operate on '.
'all files.'));
}
if ($is_all && $any_constraint) {
throw new PhutilArgumentUsageException(
pht(
'You can not operate on all files with "--all" and also operate '.
'on a subset of files by naming them explicitly or using '.
'constraint flags like "--from-engine".'));
}
// If we're migrating specific named files, convert the names into IDs
// first.
$ids = null;
if ($names) {
$files = $this->loadFilesWithNames($names);
$ids = mpull($files, 'getID');
}
$query = id(new PhabricatorFileQuery())
->setViewer($viewer);
if ($ids) {
$query->withIDs($ids);
}
if ($from_engine) {
$query->withStorageEngines(array($from_engine));
}
return new PhabricatorQueryIterator($query);
}
protected function loadFilesWithNames(array $names) {
$query = id(new PhabricatorObjectQuery())
->setViewer($this->getViewer())
->withNames($names)
->withTypes(array(PhabricatorFileFilePHIDType::TYPECONST));
$query->execute();
$files = $query->getNamedResults();
foreach ($names as $name) {
if (empty($files[$name])) {
throw new PhutilArgumentUsageException(
pht(
'No file "%s" exists.',
$name));
}
}
return array_values($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/worker/FileDeletionWorker.php | src/applications/files/worker/FileDeletionWorker.php | <?php
final class FileDeletionWorker extends PhabricatorWorker {
private function loadFile() {
$phid = idx($this->getTaskData(), 'objectPHID');
if (!$phid) {
throw new PhabricatorWorkerPermanentFailureException(
pht('No "%s" in task data.', 'objectPHID'));
}
$file = id(new PhabricatorFileQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs(array($phid))
->executeOne();
if (!$file) {
throw new PhabricatorWorkerPermanentFailureException(
pht('File "%s" does not exist.', $phid));
}
return $file;
}
protected function doWork() {
$file = $this->loadFile();
$engine = new PhabricatorDestructionEngine();
$engine->destroyObject($file);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/query/PhabricatorFileQuery.php | src/applications/files/query/PhabricatorFileQuery.php | <?php
final class PhabricatorFileQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $authorPHIDs;
private $explicitUploads;
private $transforms;
private $dateCreatedAfter;
private $dateCreatedBefore;
private $contentHashes;
private $minLength;
private $maxLength;
private $names;
private $isPartial;
private $isDeleted;
private $needTransforms;
private $builtinKeys;
private $isBuiltin;
private $storageEngines;
private $attachedObjectPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withAuthorPHIDs(array $phids) {
$this->authorPHIDs = $phids;
return $this;
}
public function withDateCreatedBefore($date_created_before) {
$this->dateCreatedBefore = $date_created_before;
return $this;
}
public function withDateCreatedAfter($date_created_after) {
$this->dateCreatedAfter = $date_created_after;
return $this;
}
public function withContentHashes(array $content_hashes) {
$this->contentHashes = $content_hashes;
return $this;
}
public function withBuiltinKeys(array $keys) {
$this->builtinKeys = $keys;
return $this;
}
public function withIsBuiltin($is_builtin) {
$this->isBuiltin = $is_builtin;
return $this;
}
public function withAttachedObjectPHIDs(array $phids) {
$this->attachedObjectPHIDs = $phids;
return $this;
}
/**
* Select files which are transformations of some other file. For example,
* you can use this query to find previously generated thumbnails of an image
* file.
*
* As a parameter, provide a list of transformation specifications. Each
* specification is a dictionary with the keys `originalPHID` and `transform`.
* The `originalPHID` is the PHID of the original file (the file which was
* transformed) and the `transform` is the name of the transform to query
* for. If you pass `true` as the `transform`, all transformations of the
* file will be selected.
*
* For example:
*
* array(
* array(
* 'originalPHID' => 'PHID-FILE-aaaa',
* 'transform' => 'sepia',
* ),
* array(
* 'originalPHID' => 'PHID-FILE-bbbb',
* 'transform' => true,
* ),
* )
*
* This selects the `"sepia"` transformation of the file with PHID
* `PHID-FILE-aaaa` and all transformations of the file with PHID
* `PHID-FILE-bbbb`.
*
* @param list<dict> List of transform specifications, described above.
* @return this
*/
public function withTransforms(array $specs) {
foreach ($specs as $spec) {
if (!is_array($spec) ||
empty($spec['originalPHID']) ||
empty($spec['transform'])) {
throw new Exception(
pht(
"Transform specification must be a dictionary with keys ".
"'%s' and '%s'!",
'originalPHID',
'transform'));
}
}
$this->transforms = $specs;
return $this;
}
public function withLengthBetween($min, $max) {
$this->minLength = $min;
$this->maxLength = $max;
return $this;
}
public function withNames(array $names) {
$this->names = $names;
return $this;
}
public function withIsPartial($partial) {
$this->isPartial = $partial;
return $this;
}
public function withIsDeleted($deleted) {
$this->isDeleted = $deleted;
return $this;
}
public function withNameNgrams($ngrams) {
return $this->withNgramsConstraint(
id(new PhabricatorFileNameNgrams()),
$ngrams);
}
public function withStorageEngines(array $engines) {
$this->storageEngines = $engines;
return $this;
}
public function showOnlyExplicitUploads($explicit_uploads) {
$this->explicitUploads = $explicit_uploads;
return $this;
}
public function needTransforms(array $transforms) {
$this->needTransforms = $transforms;
return $this;
}
public function newResultObject() {
return new PhabricatorFile();
}
protected function loadPage() {
$files = $this->loadStandardPage($this->newResultObject());
if (!$files) {
return $files;
}
// Figure out which files we need to load attached objects for. In most
// cases, we need to load attached objects to perform policy checks for
// files.
// However, in some special cases where we know files will always be
// visible, we skip this. See T8478 and T13106.
$need_objects = array();
$need_xforms = array();
foreach ($files as $file) {
$always_visible = false;
if ($file->getIsProfileImage()) {
$always_visible = true;
}
if ($file->isBuiltin()) {
$always_visible = true;
}
if ($always_visible) {
// We just treat these files as though they aren't attached to
// anything. This saves a query in common cases when we're loading
// profile images or builtins. We could be slightly more nuanced
// about this and distinguish between "not attached to anything" and
// "might be attached but policy checks don't need to care".
$file->attachObjectPHIDs(array());
continue;
}
$need_objects[] = $file;
$need_xforms[] = $file;
}
$viewer = $this->getViewer();
$is_omnipotent = $viewer->isOmnipotent();
// If we have any files left which do need objects, load the edges now.
$object_phids = array();
if ($need_objects) {
$attachments_map = $this->newAttachmentsMap($need_objects);
foreach ($need_objects as $file) {
$file_phid = $file->getPHID();
$phids = $attachments_map[$file_phid];
$file->attachObjectPHIDs($phids);
if ($is_omnipotent) {
// If the viewer is omnipotent, we don't need to load the associated
// objects either since the viewer can certainly see the object.
// Skipping this can improve performance and prevent cycles. This
// could possibly become part of the profile/builtin code above which
// short circuits attacment policy checks in cases where we know them
// to be unnecessary.
continue;
}
foreach ($phids as $phid) {
$object_phids[$phid] = true;
}
}
}
// If this file is a transform of another file, load that file too. If you
// can see the original file, you can see the thumbnail.
// TODO: It might be nice to put this directly on PhabricatorFile and
// remove the PhabricatorTransformedFile table, which would be a little
// simpler.
if ($need_xforms) {
$xforms = id(new PhabricatorTransformedFile())->loadAllWhere(
'transformedPHID IN (%Ls)',
mpull($need_xforms, 'getPHID'));
$xform_phids = mpull($xforms, 'getOriginalPHID', 'getTransformedPHID');
foreach ($xform_phids as $derived_phid => $original_phid) {
$object_phids[$original_phid] = true;
}
} else {
$xform_phids = array();
}
$object_phids = array_keys($object_phids);
// Now, load the objects.
$objects = array();
if ($object_phids) {
// NOTE: We're explicitly turning policy exceptions off, since the rule
// here is "you can see the file if you can see ANY associated object".
// Without this explicit flag, we'll incorrectly throw unless you can
// see ALL associated objects.
$objects = id(new PhabricatorObjectQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($object_phids)
->setRaisePolicyExceptions(false)
->execute();
$objects = mpull($objects, null, 'getPHID');
}
foreach ($files as $file) {
$file_objects = array_select_keys($objects, $file->getObjectPHIDs());
$file->attachObjects($file_objects);
}
foreach ($files as $key => $file) {
$original_phid = idx($xform_phids, $file->getPHID());
if ($original_phid == PhabricatorPHIDConstants::PHID_VOID) {
// This is a special case for builtin files, which are handled
// oddly.
$original = null;
} else if ($original_phid) {
$original = idx($objects, $original_phid);
if (!$original) {
// If the viewer can't see the original file, also prevent them from
// seeing the transformed file.
$this->didRejectResult($file);
unset($files[$key]);
continue;
}
} else {
$original = null;
}
$file->attachOriginalFile($original);
}
return $files;
}
private function newAttachmentsMap(array $files) {
$file_phids = mpull($files, 'getPHID');
$attachments_table = new PhabricatorFileAttachment();
$attachments_conn = $attachments_table->establishConnection('r');
$attachments = queryfx_all(
$attachments_conn,
'SELECT filePHID, objectPHID FROM %R WHERE filePHID IN (%Ls)
AND attachmentMode IN (%Ls)',
$attachments_table,
$file_phids,
array(
PhabricatorFileAttachment::MODE_ATTACH,
));
$attachments_map = array_fill_keys($file_phids, array());
foreach ($attachments as $row) {
$file_phid = $row['filePHID'];
$object_phid = $row['objectPHID'];
$attachments_map[$file_phid][] = $object_phid;
}
return $attachments_map;
}
protected function didFilterPage(array $files) {
$xform_keys = $this->needTransforms;
if ($xform_keys !== null) {
$xforms = id(new PhabricatorTransformedFile())->loadAllWhere(
'originalPHID IN (%Ls) AND transform IN (%Ls)',
mpull($files, 'getPHID'),
$xform_keys);
if ($xforms) {
$xfiles = id(new PhabricatorFile())->loadAllWhere(
'phid IN (%Ls)',
mpull($xforms, 'getTransformedPHID'));
$xfiles = mpull($xfiles, null, 'getPHID');
}
$xform_map = array();
foreach ($xforms as $xform) {
$xfile = idx($xfiles, $xform->getTransformedPHID());
if (!$xfile) {
continue;
}
$original_phid = $xform->getOriginalPHID();
$xform_key = $xform->getTransform();
$xform_map[$original_phid][$xform_key] = $xfile;
}
$default_xforms = array_fill_keys($xform_keys, null);
foreach ($files as $file) {
$file_xforms = idx($xform_map, $file->getPHID(), array());
$file_xforms += $default_xforms;
$file->attachTransforms($file_xforms);
}
}
return $files;
}
protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) {
$joins = parent::buildJoinClauseParts($conn);
if ($this->transforms) {
$joins[] = qsprintf(
$conn,
'JOIN %T t ON t.transformedPHID = f.phid',
id(new PhabricatorTransformedFile())->getTableName());
}
if ($this->shouldJoinAttachmentsTable()) {
$joins[] = qsprintf(
$conn,
'JOIN %R attachments ON attachments.filePHID = f.phid
AND attachmentMode IN (%Ls)',
new PhabricatorFileAttachment(),
array(
PhabricatorFileAttachment::MODE_ATTACH,
));
}
return $joins;
}
private function shouldJoinAttachmentsTable() {
return ($this->attachedObjectPHIDs !== null);
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'f.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'f.phid IN (%Ls)',
$this->phids);
}
if ($this->authorPHIDs !== null) {
$where[] = qsprintf(
$conn,
'f.authorPHID IN (%Ls)',
$this->authorPHIDs);
}
if ($this->explicitUploads !== null) {
$where[] = qsprintf(
$conn,
'f.isExplicitUpload = %d',
(int)$this->explicitUploads);
}
if ($this->transforms !== null) {
$clauses = array();
foreach ($this->transforms as $transform) {
if ($transform['transform'] === true) {
$clauses[] = qsprintf(
$conn,
'(t.originalPHID = %s)',
$transform['originalPHID']);
} else {
$clauses[] = qsprintf(
$conn,
'(t.originalPHID = %s AND t.transform = %s)',
$transform['originalPHID'],
$transform['transform']);
}
}
$where[] = qsprintf($conn, '%LO', $clauses);
}
if ($this->dateCreatedAfter !== null) {
$where[] = qsprintf(
$conn,
'f.dateCreated >= %d',
$this->dateCreatedAfter);
}
if ($this->dateCreatedBefore !== null) {
$where[] = qsprintf(
$conn,
'f.dateCreated <= %d',
$this->dateCreatedBefore);
}
if ($this->contentHashes !== null) {
$where[] = qsprintf(
$conn,
'f.contentHash IN (%Ls)',
$this->contentHashes);
}
if ($this->minLength !== null) {
$where[] = qsprintf(
$conn,
'byteSize >= %d',
$this->minLength);
}
if ($this->maxLength !== null) {
$where[] = qsprintf(
$conn,
'byteSize <= %d',
$this->maxLength);
}
if ($this->names !== null) {
$where[] = qsprintf(
$conn,
'name in (%Ls)',
$this->names);
}
if ($this->isPartial !== null) {
$where[] = qsprintf(
$conn,
'isPartial = %d',
(int)$this->isPartial);
}
if ($this->isDeleted !== null) {
$where[] = qsprintf(
$conn,
'isDeleted = %d',
(int)$this->isDeleted);
}
if ($this->builtinKeys !== null) {
$where[] = qsprintf(
$conn,
'builtinKey IN (%Ls)',
$this->builtinKeys);
}
if ($this->isBuiltin !== null) {
if ($this->isBuiltin) {
$where[] = qsprintf(
$conn,
'builtinKey IS NOT NULL');
} else {
$where[] = qsprintf(
$conn,
'builtinKey IS NULL');
}
}
if ($this->storageEngines !== null) {
$where[] = qsprintf(
$conn,
'storageEngine IN (%Ls)',
$this->storageEngines);
}
if ($this->attachedObjectPHIDs !== null) {
$where[] = qsprintf(
$conn,
'attachments.objectPHID IN (%Ls)',
$this->attachedObjectPHIDs);
}
return $where;
}
protected function getPrimaryTableAlias() {
return 'f';
}
public function getQueryApplicationClass() {
return 'PhabricatorFilesApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/query/PhabricatorFileTransactionQuery.php | src/applications/files/query/PhabricatorFileTransactionQuery.php | <?php
final class PhabricatorFileTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new PhabricatorFileTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/query/PhabricatorFileChunkQuery.php | src/applications/files/query/PhabricatorFileChunkQuery.php | <?php
final class PhabricatorFileChunkQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $chunkHandles;
private $rangeStart;
private $rangeEnd;
private $isComplete;
private $needDataFiles;
public function withChunkHandles(array $handles) {
$this->chunkHandles = $handles;
return $this;
}
public function withByteRange($start, $end) {
$this->rangeStart = $start;
$this->rangeEnd = $end;
return $this;
}
public function withIsComplete($complete) {
$this->isComplete = $complete;
return $this;
}
public function needDataFiles($need) {
$this->needDataFiles = $need;
return $this;
}
protected function loadPage() {
$table = new PhabricatorFileChunk();
$conn_r = $table->establishConnection('r');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T %Q %Q %Q',
$table->getTableName(),
$this->buildWhereClause($conn_r),
$this->buildOrderClause($conn_r),
$this->buildLimitClause($conn_r));
return $table->loadAllFromArray($data);
}
protected function willFilterPage(array $chunks) {
if ($this->needDataFiles) {
$file_phids = mpull($chunks, 'getDataFilePHID');
$file_phids = array_filter($file_phids);
if ($file_phids) {
$files = id(new PhabricatorFileQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($file_phids)
->execute();
$files = mpull($files, null, 'getPHID');
} else {
$files = array();
}
foreach ($chunks as $key => $chunk) {
$data_phid = $chunk->getDataFilePHID();
if (!$data_phid) {
$chunk->attachDataFile(null);
continue;
}
$file = idx($files, $data_phid);
if (!$file) {
unset($chunks[$key]);
$this->didRejectResult($chunk);
continue;
}
$chunk->attachDataFile($file);
}
if (!$chunks) {
return $chunks;
}
}
return $chunks;
}
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$where = array();
if ($this->chunkHandles !== null) {
$where[] = qsprintf(
$conn,
'chunkHandle IN (%Ls)',
$this->chunkHandles);
}
if ($this->rangeStart !== null) {
$where[] = qsprintf(
$conn,
'byteEnd > %d',
$this->rangeStart);
}
if ($this->rangeEnd !== null) {
$where[] = qsprintf(
$conn,
'byteStart < %d',
$this->rangeEnd);
}
if ($this->isComplete !== null) {
if ($this->isComplete) {
$where[] = qsprintf(
$conn,
'dataFilePHID IS NOT NULL');
} else {
$where[] = qsprintf(
$conn,
'dataFilePHID IS NULL');
}
}
$where[] = $this->buildPagingClause($conn);
return $this->formatWhereClause($conn, $where);
}
public function getQueryApplicationClass() {
return 'PhabricatorFilesApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/query/PhabricatorFileBundleLoader.php | src/applications/files/query/PhabricatorFileBundleLoader.php | <?php
/**
* Callback provider for loading @{class@arcanist:ArcanistBundle} file data
* stored in the Files application.
*/
final class PhabricatorFileBundleLoader extends Phobject {
private $viewer;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function loadFileData($phid) {
$file = id(new PhabricatorFileQuery())
->setViewer($this->viewer)
->withPHIDs(array($phid))
->executeOne();
if (!$file) {
return null;
}
return $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/query/PhabricatorFileSearchEngine.php | src/applications/files/query/PhabricatorFileSearchEngine.php | <?php
final class PhabricatorFileSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Files');
}
public function getApplicationClassName() {
return 'PhabricatorFilesApplication';
}
public function canUseInPanelContext() {
return false;
}
public function newQuery() {
$query = new PhabricatorFileQuery();
$query->withIsDeleted(false);
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorUsersSearchField())
->setKey('authorPHIDs')
->setAliases(array('author', 'authors'))
->setLabel(pht('Authors')),
id(new PhabricatorSearchThreeStateField())
->setKey('explicit')
->setLabel(pht('Upload Source'))
->setOptions(
pht('(Show All)'),
pht('Show Only Manually Uploaded Files'),
pht('Hide Manually Uploaded Files')),
id(new PhabricatorSearchDateField())
->setKey('createdStart')
->setLabel(pht('Created After')),
id(new PhabricatorSearchDateField())
->setKey('createdEnd')
->setLabel(pht('Created Before')),
id(new PhabricatorSearchTextField())
->setLabel(pht('Name Contains'))
->setKey('name')
->setDescription(pht('Search for files by name substring.')),
);
}
protected function getDefaultFieldOrder() {
return array(
'...',
'createdStart',
'createdEnd',
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['authorPHIDs']) {
$query->withAuthorPHIDs($map['authorPHIDs']);
}
if ($map['explicit'] !== null) {
$query->showOnlyExplicitUploads($map['explicit']);
}
if ($map['createdStart']) {
$query->withDateCreatedAfter($map['createdStart']);
}
if ($map['createdEnd']) {
$query->withDateCreatedBefore($map['createdEnd']);
}
if ($map['name'] !== null) {
$query->withNameNgrams($map['name']);
}
return $query;
}
protected function getURI($path) {
return '/file/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array();
if ($this->requireViewer()->isLoggedIn()) {
$names['authored'] = pht('Authored');
}
$names += array(
'all' => pht('All'),
);
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
case 'authored':
$author_phid = array($this->requireViewer()->getPHID());
return $query
->setParameter('authorPHIDs', $author_phid)
->setParameter('explicit', true);
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function getRequiredHandlePHIDsForResultList(
array $files,
PhabricatorSavedQuery $query) {
return mpull($files, 'getAuthorPHID');
}
protected function renderResultList(
array $files,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($files, 'PhabricatorFile');
$request = $this->getRequest();
if ($request) {
$highlighted_ids = $request->getStrList('h');
} else {
$highlighted_ids = array();
}
$viewer = $this->requireViewer();
$highlighted_ids = array_fill_keys($highlighted_ids, true);
$list_view = id(new PHUIObjectItemListView())
->setUser($viewer);
foreach ($files as $file) {
$id = $file->getID();
$phid = $file->getPHID();
$name = $file->getName();
$file_uri = $this->getApplicationURI("/info/{$phid}/");
$date_created = phabricator_date($file->getDateCreated(), $viewer);
$author_phid = $file->getAuthorPHID();
if ($author_phid) {
$author_link = $handles[$author_phid]->renderLink();
$uploaded = pht('Uploaded by %s on %s', $author_link, $date_created);
} else {
$uploaded = pht('Uploaded on %s', $date_created);
}
$item = id(new PHUIObjectItemView())
->setObject($file)
->setObjectName("F{$id}")
->setHeader($name)
->setHref($file_uri)
->addAttribute($uploaded)
->addIcon('none', phutil_format_bytes($file->getByteSize()));
$ttl = $file->getTTL();
if ($ttl !== null) {
$item->addIcon('blame', pht('Temporary'));
}
if ($file->getIsPartial()) {
$item->addIcon('fa-exclamation-triangle orange', pht('Partial'));
}
if (isset($highlighted_ids[$id])) {
$item->setEffect('highlighted');
}
$list_view->addItem($item);
}
$list_view->appendChild(id(new PhabricatorGlobalUploadTargetView())
->setUser($viewer));
$result = new PhabricatorApplicationSearchResultView();
$result->setContent($list_view);
return $result;
}
protected function getNewUserBody() {
$create_button = id(new PHUIButtonView())
->setTag('a')
->setText(pht('Upload a File'))
->setHref('/file/upload/')
->setColor(PHUIButtonView::GREEN);
$icon = $this->getApplication()->getIcon();
$app_name = $this->getApplication()->getName();
$view = id(new PHUIBigInfoView())
->setIcon($icon)
->setTitle(pht('Welcome to %s', $app_name))
->setDescription(
pht('Just a place for files.'))
->addAction($create_button);
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/files/query/PhabricatorFileAttachmentQuery.php | src/applications/files/query/PhabricatorFileAttachmentQuery.php | <?php
final class PhabricatorFileAttachmentQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $objectPHIDs;
private $filePHIDs;
private $needFiles;
private $visibleFiles;
public function withObjectPHIDs(array $object_phids) {
$this->objectPHIDs = $object_phids;
return $this;
}
public function withFilePHIDs(array $file_phids) {
$this->filePHIDs = $file_phids;
return $this;
}
public function withVisibleFiles($visible_files) {
$this->visibleFiles = $visible_files;
return $this;
}
public function needFiles($need) {
$this->needFiles = $need;
return $this;
}
public function newResultObject() {
return new PhabricatorFileAttachment();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->objectPHIDs !== null) {
$where[] = qsprintf(
$conn,
'attachments.objectPHID IN (%Ls)',
$this->objectPHIDs);
}
if ($this->filePHIDs !== null) {
$where[] = qsprintf(
$conn,
'attachments.filePHID IN (%Ls)',
$this->filePHIDs);
}
return $where;
}
protected function willFilterPage(array $attachments) {
$viewer = $this->getViewer();
$object_phids = array();
foreach ($attachments as $attachment) {
$object_phid = $attachment->getObjectPHID();
$object_phids[$object_phid] = $object_phid;
}
if ($object_phids) {
$objects = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->setParentQuery($this)
->withPHIDs($object_phids)
->execute();
$objects = mpull($objects, null, 'getPHID');
} else {
$objects = array();
}
foreach ($attachments as $key => $attachment) {
$object_phid = $attachment->getObjectPHID();
$object = idx($objects, $object_phid);
if (!$object) {
$this->didRejectResult($attachment);
unset($attachments[$key]);
continue;
}
$attachment->attachObject($object);
}
if ($this->needFiles) {
$file_phids = array();
foreach ($attachments as $attachment) {
$file_phid = $attachment->getFilePHID();
$file_phids[$file_phid] = $file_phid;
}
if ($file_phids) {
$files = id(new PhabricatorFileQuery())
->setViewer($viewer)
->setParentQuery($this)
->withPHIDs($file_phids)
->execute();
$files = mpull($files, null, 'getPHID');
} else {
$files = array();
}
foreach ($attachments as $key => $attachment) {
$file_phid = $attachment->getFilePHID();
$file = idx($files, $file_phid);
if ($this->visibleFiles && !$file) {
$this->didRejectResult($attachment);
unset($attachments[$key]);
continue;
}
$attachment->attachFile($file);
}
}
return $attachments;
}
protected function getPrimaryTableAlias() {
return 'attachments';
}
public function getQueryApplicationClass() {
return 'PhabricatorFilesApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/favicon/PhabricatorFaviconRefQuery.php | src/applications/files/favicon/PhabricatorFaviconRefQuery.php | <?php
final class PhabricatorFaviconRefQuery extends Phobject {
private $refs;
public function withRefs(array $refs) {
assert_instances_of($refs, 'PhabricatorFaviconRef');
$this->refs = $refs;
return $this;
}
public function execute() {
$viewer = PhabricatorUser::getOmnipotentUser();
$refs = $this->refs;
$config_digest = PhabricatorFaviconRef::newConfigurationDigest();
$ref_map = array();
foreach ($refs as $ref) {
$ref_digest = $ref->newDigest();
$ref_key = "favicon({$config_digest},{$ref_digest},8)";
$ref
->setViewer($viewer)
->setCacheKey($ref_key);
$ref_map[$ref_key] = $ref;
}
$cache = PhabricatorCaches::getImmutableCache();
$ref_hits = $cache->getKeys(array_keys($ref_map));
foreach ($ref_hits as $ref_key => $ref_uri) {
$ref_map[$ref_key]->setURI($ref_uri);
unset($ref_map[$ref_key]);
}
if ($ref_map) {
$new_map = array();
foreach ($ref_map as $ref_key => $ref) {
$ref_uri = $ref->newURI();
$ref->setURI($ref_uri);
$new_map[$ref_key] = $ref_uri;
}
$cache->setKeys($new_map);
}
return $refs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/favicon/PhabricatorFaviconRef.php | src/applications/files/favicon/PhabricatorFaviconRef.php | <?php
final class PhabricatorFaviconRef extends Phobject {
private $viewer;
private $width;
private $height;
private $emblems;
private $uri;
private $cacheKey;
public function __construct() {
$this->emblems = array(null, null, null, null);
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setWidth($width) {
$this->width = $width;
return $this;
}
public function getWidth() {
return $this->width;
}
public function setHeight($height) {
$this->height = $height;
return $this;
}
public function getHeight() {
return $this->height;
}
public function setEmblems(array $emblems) {
if (count($emblems) !== 4) {
throw new Exception(
pht(
'Expected four elements in icon emblem list. To omit an emblem, '.
'pass "null".'));
}
$this->emblems = $emblems;
return $this;
}
public function getEmblems() {
return $this->emblems;
}
public function setURI($uri) {
$this->uri = $uri;
return $this;
}
public function getURI() {
return $this->uri;
}
public function setCacheKey($cache_key) {
$this->cacheKey = $cache_key;
return $this;
}
public function getCacheKey() {
return $this->cacheKey;
}
public function newDigest() {
return PhabricatorHash::digestForIndex(serialize($this->toDictionary()));
}
public function toDictionary() {
return array(
'width' => $this->width,
'height' => $this->height,
'emblems' => $this->emblems,
);
}
public static function newConfigurationDigest() {
$all_resources = self::getAllResources();
// Because we need to access this cache on every page, it's very sticky.
// Try to dirty it automatically if any relevant configuration changes.
$inputs = array(
'resources' => $all_resources,
'prod' => PhabricatorEnv::getProductionURI('/'),
'cdn' => PhabricatorEnv::getEnvConfig('security.alternate-file-domain'),
'havepng' => function_exists('imagepng'),
);
return PhabricatorHash::digestForIndex(serialize($inputs));
}
private static function getAllResources() {
$custom_resources = PhabricatorEnv::getEnvConfig('ui.favicons');
foreach ($custom_resources as $key => $custom_resource) {
$custom_resources[$key] = array(
'source-type' => 'file',
'default' => false,
) + $custom_resource;
}
$builtin_resources = self::getBuiltinResources();
return array_merge($builtin_resources, $custom_resources);
}
private static function getBuiltinResources() {
return array(
array(
'source-type' => 'builtin',
'source' => 'favicon/default-76x76.png',
'version' => 1,
'width' => 76,
'height' => 76,
'default' => true,
),
array(
'source-type' => 'builtin',
'source' => 'favicon/default-120x120.png',
'version' => 1,
'width' => 120,
'height' => 120,
'default' => true,
),
array(
'source-type' => 'builtin',
'source' => 'favicon/default-128x128.png',
'version' => 1,
'width' => 128,
'height' => 128,
'default' => true,
),
array(
'source-type' => 'builtin',
'source' => 'favicon/default-152x152.png',
'version' => 1,
'width' => 152,
'height' => 152,
'default' => true,
),
array(
'source-type' => 'builtin',
'source' => 'favicon/dot-pink-64x64.png',
'version' => 1,
'width' => 64,
'height' => 64,
'emblem' => 'dot-pink',
'default' => true,
),
array(
'source-type' => 'builtin',
'source' => 'favicon/dot-red-64x64.png',
'version' => 1,
'width' => 64,
'height' => 64,
'emblem' => 'dot-red',
'default' => true,
),
);
}
public function newURI() {
$dst_w = $this->getWidth();
$dst_h = $this->getHeight();
$template = $this->newTemplateFile(null, $dst_w, $dst_h);
$template_file = $template['file'];
$cache = $this->loadCachedFile($template_file);
if ($cache) {
return $cache->getViewURI();
}
$data = $this->newCompositedFavicon($template);
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$caught = null;
try {
$favicon_file = $this->newFaviconFile($data);
$xform = id(new PhabricatorTransformedFile())
->setOriginalPHID($template_file->getPHID())
->setTransformedPHID($favicon_file->getPHID())
->setTransform($this->getCacheKey());
try {
$xform->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
unset($unguarded);
$cache = $this->loadCachedFile($template_file);
if (!$cache) {
throw $ex;
}
id(new PhabricatorDestructionEngine())
->destroyObject($favicon_file);
return $cache->getViewURI();
}
} catch (Exception $ex) {
$caught = $ex;
}
unset($unguarded);
if ($caught) {
throw $caught;
}
return $favicon_file->getViewURI();
}
private function loadCachedFile(PhabricatorFile $template_file) {
$viewer = $this->getViewer();
$xform = id(new PhabricatorTransformedFile())->loadOneWhere(
'originalPHID = %s AND transform = %s',
$template_file->getPHID(),
$this->getCacheKey());
if (!$xform) {
return null;
}
return id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($xform->getTransformedPHID()))
->executeOne();
}
private function newCompositedFavicon($template) {
$dst_w = $this->getWidth();
$dst_h = $this->getHeight();
$src_w = $template['width'];
$src_h = $template['height'];
try {
$template_data = $template['file']->loadFileData();
} catch (Exception $ex) {
// In rare cases, we can end up with a corrupted or inaccessible file.
// If we do, just give up: otherwise, it's impossible to get pages to
// generate and not obvious how to fix it.
return null;
}
if (!function_exists('imagecreatefromstring')) {
return $template_data;
}
$src = @imagecreatefromstring($template_data);
if (!$src) {
return $template_data;
}
$dst = imagecreatetruecolor($dst_w, $dst_h);
imagesavealpha($dst, true);
$transparent = imagecolorallocatealpha($dst, 0, 255, 0, 127);
imagefill($dst, 0, 0, $transparent);
imagecopyresampled(
$dst,
$src,
0,
0,
0,
0,
$dst_w,
$dst_h,
$src_w,
$src_h);
// Now, copy any icon emblems on top of the image. These are dots or other
// marks used to indicate status information.
$emblem_w = (int)floor(min($dst_w, $dst_h) / 2);
$emblem_h = $emblem_w;
foreach ($this->emblems as $key => $emblem) {
if ($emblem === null) {
continue;
}
$emblem_template = $this->newTemplateFile(
$emblem,
$emblem_w,
$emblem_h);
switch ($key) {
case 0:
$emblem_x = $dst_w - $emblem_w;
$emblem_y = 0;
break;
case 1:
$emblem_x = $dst_w - $emblem_w;
$emblem_y = $dst_h - $emblem_h;
break;
case 2:
$emblem_x = 0;
$emblem_y = $dst_h - $emblem_h;
break;
case 3:
$emblem_x = 0;
$emblem_y = 0;
break;
}
$emblem_data = $emblem_template['file']->loadFileData();
$src = @imagecreatefromstring($emblem_data);
if (!$src) {
continue;
}
imagecopyresampled(
$dst,
$src,
$emblem_x,
$emblem_y,
0,
0,
$emblem_w,
$emblem_h,
$emblem_template['width'],
$emblem_template['height']);
}
return PhabricatorImageTransformer::saveImageDataInAnyFormat(
$dst,
'image/png');
}
private function newTemplateFile($emblem, $width, $height) {
$all_resources = self::getAllResources();
$scores = array();
$ratio = $width / $height;
foreach ($all_resources as $key => $resource) {
// We can't use an emblem resource for a different emblem, nor for an
// icon base. We also can't use an icon base as an emblem. That is, if
// we're looking for a picture of a red dot, we have to actually find
// a red dot, not just any image which happens to have a similar size.
if (idx($resource, 'emblem') !== $emblem) {
continue;
}
$resource_width = $resource['width'];
$resource_height = $resource['height'];
// Never use a resource with a different aspect ratio.
if (($resource_width / $resource_height) !== $ratio) {
continue;
}
// Try to use custom resources instead of default resources.
if ($resource['default']) {
$default_score = 1;
} else {
$default_score = 0;
}
$width_diff = ($resource_width - $width);
// If we have to resize an image, we'd rather scale a larger image down
// than scale a smaller image up.
if ($width_diff < 0) {
$scale_score = 1;
} else {
$scale_score = 0;
}
// Otherwise, we'd rather scale an image a little bit (ideally, zero)
// than scale an image a lot.
$width_score = abs($width_diff);
$scores[$key] = id(new PhutilSortVector())
->addInt($default_score)
->addInt($scale_score)
->addInt($width_score);
}
if (!$scores) {
if ($emblem === null) {
throw new Exception(
pht(
'Found no background template resource for dimensions %dx%d.',
$width,
$height));
} else {
throw new Exception(
pht(
'Found no template resource (for emblem "%s") with dimensions '.
'%dx%d.',
$emblem,
$width,
$height));
}
}
$scores = msortv($scores, 'getSelf');
$best_score = head_key($scores);
$viewer = $this->getViewer();
$resource = $all_resources[$best_score];
if ($resource['source-type'] === 'builtin') {
$file = PhabricatorFile::loadBuiltin($viewer, $resource['source']);
if (!$file) {
throw new Exception(
pht(
'Failed to load favicon template builtin "%s".',
$resource['source']));
}
} else {
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($resource['source']))
->executeOne();
if (!$file) {
throw new Exception(
pht(
'Failed to load favicon template with PHID "%s".',
$resource['source']));
}
}
return array(
'width' => $resource['width'],
'height' => $resource['height'],
'file' => $file,
);
}
private function newFaviconFile($data) {
return PhabricatorFile::newFromFileData(
$data,
array(
'name' => 'favicon',
'canCDN' => 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/mail/FileCreateMailReceiver.php | src/applications/files/mail/FileCreateMailReceiver.php | <?php
final class FileCreateMailReceiver
extends PhabricatorApplicationMailReceiver {
protected function newApplication() {
return new PhabricatorFilesApplication();
}
protected function processReceivedMail(
PhabricatorMetaMTAReceivedMail $mail,
PhutilEmailAddress $target) {
$author = $this->getAuthor();
$attachment_phids = $mail->getAttachments();
if (empty($attachment_phids)) {
throw new PhabricatorMetaMTAReceivedMailProcessingException(
MetaMTAReceivedMailStatus::STATUS_UNHANDLED_EXCEPTION,
pht(
'Ignoring email to create files that did not include attachments.'));
}
$first_phid = head($attachment_phids);
$mail->setRelatedPHID($first_phid);
$sender = $this->getSender();
if (!$sender) {
return;
}
$attachment_count = count($attachment_phids);
if ($attachment_count > 1) {
$subject = pht('You successfully uploaded %d files.', $attachment_count);
} else {
$subject = pht('You successfully uploaded a file.');
}
$subject_prefix = pht('[File]');
$file_uris = array();
foreach ($attachment_phids as $phid) {
$file_uris[] =
PhabricatorEnv::getProductionURI('/file/info/'.$phid.'/');
}
$body = new PhabricatorMetaMTAMailBody();
$body->addRawSection($subject);
$body->addTextSection(pht('FILE LINKS'), implode("\n", $file_uris));
id(new PhabricatorMetaMTAMail())
->addTos(array($sender->getPHID()))
->setSubject($subject)
->setSubjectPrefix($subject_prefix)
->setFrom($sender->getPHID())
->setRelatedPHID($first_phid)
->setBody($body->render())
->saveAndSend();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/mail/FileMailReceiver.php | src/applications/files/mail/FileMailReceiver.php | <?php
final class FileMailReceiver extends PhabricatorObjectMailReceiver {
public function isEnabled() {
return PhabricatorApplication::isClassInstalled(
'PhabricatorFilesApplication');
}
protected function getObjectPattern() {
return 'F[1-9]\d*';
}
protected function loadObject($pattern, PhabricatorUser $viewer) {
$id = (int)substr($pattern, 1);
return id(new PhabricatorFileQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
}
protected function getTransactionReplyHandler() {
return new FileReplyHandler();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/mail/FileReplyHandler.php | src/applications/files/mail/FileReplyHandler.php | <?php
final class FileReplyHandler
extends PhabricatorApplicationTransactionReplyHandler {
public function validateMailReceiver($mail_receiver) {
if (!($mail_receiver instanceof PhabricatorFile)) {
throw new Exception(pht('Mail receiver is not a %s.', 'PhabricatorFile'));
}
}
public function getObjectPrefix() {
return 'F';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/keyring/PhabricatorKeyringConfigOptionType.php | src/applications/files/keyring/PhabricatorKeyringConfigOptionType.php | <?php
final class PhabricatorKeyringConfigOptionType
extends PhabricatorConfigJSONOptionType {
public function validateOption(PhabricatorConfigOption $option, $value) {
if (!is_array($value)) {
throw new Exception(
pht(
'Keyring configuration is not valid: value must be a '.
'list of encryption keys.'));
}
foreach ($value as $index => $spec) {
if (!is_array($spec)) {
throw new Exception(
pht(
'Keyring configuration is not valid: each entry in the list must '.
'be a dictionary describing an encryption key, but the value '.
'with index "%s" is not a dictionary.',
$index));
}
}
$map = array();
$defaults = array();
foreach ($value as $index => $spec) {
try {
PhutilTypeSpec::checkMap(
$spec,
array(
'name' => 'string',
'type' => 'string',
'material.base64' => 'string',
'default' => 'optional bool',
));
} catch (Exception $ex) {
throw new Exception(
pht(
'Keyring configuration has an invalid key specification (at '.
'index "%s"): %s.',
$index,
$ex->getMessage()));
}
$name = $spec['name'];
if (isset($map[$name])) {
throw new Exception(
pht(
'Keyring configuration is invalid: it describes multiple keys '.
'with the same name ("%s"). Each key must have a unique name.',
$name));
}
$map[$name] = true;
if (idx($spec, 'default')) {
$defaults[] = $name;
}
$type = $spec['type'];
switch ($type) {
case 'aes-256-cbc':
if (!function_exists('openssl_encrypt')) {
throw new Exception(
pht(
'Keyring is configured with a "%s" key, but the PHP OpenSSL '.
'extension is not installed. Install the OpenSSL extension '.
'to enable encryption.',
$type));
}
$material = $spec['material.base64'];
$material = base64_decode($material, true);
if ($material === false) {
throw new Exception(
pht(
'Keyring specifies an invalid key ("%s"): key material '.
'should be base64 encoded.',
$name));
}
if (strlen($material) != 32) {
throw new Exception(
pht(
'Keyring specifies an invalid key ("%s"): key material '.
'should be 32 bytes (256 bits) but has length %s.',
$name,
new PhutilNumber(strlen($material))));
}
break;
default:
throw new Exception(
pht(
'Keyring configuration is invalid: it describes a key with '.
'type "%s", but this type is unknown.',
$type));
}
}
if (count($defaults) > 1) {
throw new Exception(
pht(
'Keyring configuration is invalid: it describes multiple default '.
'encryption keys. No more than one key may be the default key. '.
'Keys currently configured as defaults: %s.',
implode(', ', $defaults)));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/keyring/PhabricatorKeyring.php | src/applications/files/keyring/PhabricatorKeyring.php | <?php
final class PhabricatorKeyring extends Phobject {
private static $hasReadConfiguration;
private static $keyRing = array();
public static function addKey($spec) {
self::$keyRing[$spec['name']] = $spec;
}
public static function getKey($name, $type) {
self::readConfiguration();
if (empty(self::$keyRing[$name])) {
throw new Exception(
pht(
'No key "%s" exists in keyring.',
$name));
}
$spec = self::$keyRing[$name];
$material = base64_decode($spec['material.base64'], true);
return new PhutilOpaqueEnvelope($material);
}
public static function getDefaultKeyName($type) {
self::readConfiguration();
foreach (self::$keyRing as $name => $key) {
if (!empty($key['default'])) {
return $name;
}
}
return null;
}
private static function readConfiguration() {
if (self::$hasReadConfiguration) {
return true;
}
self::$hasReadConfiguration = true;
foreach (PhabricatorEnv::getEnvConfig('keyring') as $spec) {
self::addKey($spec);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/action/PhabricatorFilesOutboundRequestAction.php | src/applications/files/action/PhabricatorFilesOutboundRequestAction.php | <?php
final class PhabricatorFilesOutboundRequestAction
extends PhabricatorSystemAction {
const TYPECONST = 'files.outbound';
public function getScoreThreshold() {
return 60 / phutil_units('1 hour in seconds');
}
public function getLimitExplanation() {
return pht(
'You have initiated too many outbound requests to fetch remote URIs '.
'recently.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/editor/PhabricatorFileEditor.php | src/applications/files/editor/PhabricatorFileEditor.php | <?php
final class PhabricatorFileEditor
extends PhabricatorApplicationTransactionEditor {
public function getEditorApplicationClass() {
return 'PhabricatorFilesApplication';
}
public function getEditorObjectsDescription() {
return pht('Files');
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorTransactions::TYPE_COMMENT;
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
return $types;
}
protected function shouldSendMail(
PhabricatorLiskDAO $object,
array $xactions) {
return true;
}
protected function getMailSubjectPrefix() {
return pht('[File]');
}
protected function getMailTo(PhabricatorLiskDAO $object) {
return array(
$object->getAuthorPHID(),
$this->requireActor()->getPHID(),
);
}
protected function buildReplyHandler(PhabricatorLiskDAO $object) {
return id(new FileReplyHandler())
->setMailReceiver($object);
}
protected function buildMailTemplate(PhabricatorLiskDAO $object) {
$id = $object->getID();
$name = $object->getName();
return id(new PhabricatorMetaMTAMail())
->setSubject("F{$id}: {$name}");
}
protected function buildMailBody(
PhabricatorLiskDAO $object,
array $xactions) {
$body = parent::buildMailBody($object, $xactions);
$body->addTextSection(
pht('FILE DETAIL'),
PhabricatorEnv::getProductionURI($object->getInfoURI()));
return $body;
}
protected function shouldPublishFeedStory(
PhabricatorLiskDAO $object,
array $xactions) {
return true;
}
protected function supportsSearch() {
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/editor/PhabricatorFileEditEngine.php | src/applications/files/editor/PhabricatorFileEditEngine.php | <?php
final class PhabricatorFileEditEngine
extends PhabricatorEditEngine {
const ENGINECONST = 'files.file';
public function getEngineName() {
return pht('Files');
}
protected function supportsEditEngineConfiguration() {
return false;
}
protected function getCreateNewObjectPolicy() {
// TODO: For now, this EditEngine can only edit objects, since there is
// a lot of complexity in dealing with file data during file creation.
return PhabricatorPolicies::POLICY_NOONE;
}
public function getSummaryHeader() {
return pht('Configure Files Forms');
}
public function getSummaryText() {
return pht('Configure creation and editing forms in Files.');
}
public function getEngineApplicationClass() {
return 'PhabricatorFilesApplication';
}
protected function newEditableObject() {
return PhabricatorFile::initializeNewFile();
}
protected function newObjectQuery() {
$query = new PhabricatorFileQuery();
$query->withIsDeleted(false);
return $query;
}
protected function getObjectCreateTitleText($object) {
return pht('Create New File');
}
protected function getObjectEditTitleText($object) {
return pht('Edit File: %s', $object->getName());
}
protected function getObjectEditShortText($object) {
return $object->getMonogram();
}
protected function getObjectCreateShortText() {
return pht('Create File');
}
protected function getObjectName() {
return pht('File');
}
protected function getObjectViewURI($object) {
return $object->getURI();
}
protected function buildCustomEditFields($object) {
return array(
id(new PhabricatorTextEditField())
->setKey('name')
->setLabel(pht('Name'))
->setTransactionType(PhabricatorFileNameTransaction::TRANSACTIONTYPE)
->setDescription(pht('The name of the file.'))
->setConduitDescription(pht('Rename the file.'))
->setConduitTypeDescription(pht('New file name.'))
->setValue($object->getName()),
id(new PhabricatorTextEditField())
->setKey('alt')
->setLabel(pht('Alt Text'))
->setTransactionType(PhabricatorFileAltTextTransaction::TRANSACTIONTYPE)
->setDescription(pht('Human-readable file description.'))
->setConduitDescription(pht('Set the file alt text.'))
->setConduitTypeDescription(pht('New alt text.'))
->setValue($object->getCustomAltText()),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/xaction/PhabricatorFileDeleteTransaction.php | src/applications/files/xaction/PhabricatorFileDeleteTransaction.php | <?php
final class PhabricatorFileDeleteTransaction
extends PhabricatorFileTransactionType {
const TRANSACTIONTYPE = 'file:delete';
public function generateOldValue($object) {
return PhabricatorFile::STATUS_ACTIVE;
}
public function applyInternalEffects($object, $value) {
$file = $object;
// Mark the file for deletion, save it, and schedule a worker to
// sweep by later and pick it up.
$file->setIsDeleted(true);
PhabricatorWorker::scheduleTask(
'FileDeletionWorker',
array('objectPHID' => $file->getPHID()),
array('priority' => PhabricatorWorker::PRIORITY_BULK));
}
public function getIcon() {
return 'fa-ban';
}
public function getColor() {
return 'red';
}
public function getTitle() {
return pht(
'%s deleted this file.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s deleted %s.',
$this->renderAuthor(),
$this->renderObject());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/xaction/PhabricatorFileAltTextTransaction.php | src/applications/files/xaction/PhabricatorFileAltTextTransaction.php | <?php
final class PhabricatorFileAltTextTransaction
extends PhabricatorFileTransactionType {
const TRANSACTIONTYPE = 'file:alt';
public function generateOldValue($object) {
return $object->getCustomAltText();
}
public function generateNewValue($object, $value) {
$value = phutil_string_cast($value);
if (!strlen($value)) {
$value = null;
}
return $value;
}
public function applyInternalEffects($object, $value) {
$object->setCustomAltText($value);
}
public function getTitle() {
$old_value = $this->getOldValue();
$new_value = $this->getNewValue();
if ($old_value == null || !strlen($old_value)) {
return pht(
'%s set the alternate text for this file to %s.',
$this->renderAuthor(),
$this->renderNewValue());
} else if ($new_value === null || !strlen($new_value)) {
return pht(
'%s removed the alternate text for this file (was %s).',
$this->renderAuthor(),
$this->renderOldValue());
} else {
return pht(
'%s changed the alternate text for this file from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
public function getTitleForFeed() {
$old_value = $this->getOldValue();
$new_value = $this->getNewValue();
if ($old_value === null || !strlen($old_value)) {
return pht(
'%s set the alternate text for %s to %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderNewValue());
} else if ($new_value === null || !strlen($new_value)) {
return pht(
'%s removed the alternate text for %s (was %s).',
$this->renderAuthor(),
$this->renderObject(),
$this->renderOldValue());
} else {
return pht(
'%s changed the alternate text for %s from %s to %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$max_length = 1024;
foreach ($xactions as $xaction) {
$new_value = $xaction->getNewValue();
$new_length = strlen($new_value);
if ($new_length > $max_length) {
$errors[] = $this->newInvalidError(
pht(
'File alternate text must not be longer than %s character(s).',
new PhutilNumber($max_length)));
}
}
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/files/xaction/PhabricatorFileTransactionType.php | src/applications/files/xaction/PhabricatorFileTransactionType.php | <?php
abstract class PhabricatorFileTransactionType
extends PhabricatorModularTransactionType {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/xaction/PhabricatorFileNameTransaction.php | src/applications/files/xaction/PhabricatorFileNameTransaction.php | <?php
final class PhabricatorFileNameTransaction
extends PhabricatorFileTransactionType {
const TRANSACTIONTYPE = 'file:name';
public function generateOldValue($object) {
return $object->getName();
}
public function applyInternalEffects($object, $value) {
$object->setName($value);
}
public function getTitle() {
return pht(
'%s updated the name for this file from "%s" to "%s".',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
public function getTitleForFeed() {
return pht(
'%s updated the name of %s from "%s" to "%s".',
$this->renderAuthor(),
$this->renderObject(),
$this->renderOldValue(),
$this->renderNewValue());
}
public function validateTransactions($object, array $xactions) {
$errors = array();
if ($this->isEmptyTextTransaction($object->getName(), $xactions)) {
$errors[] = $this->newRequiredError(pht('Files must have a name.'));
}
$max_length = $object->getColumnMaximumByteLength('name');
foreach ($xactions as $xaction) {
$new_value = $xaction->getNewValue();
$new_length = strlen($new_value);
if ($new_length > $max_length) {
$errors[] = $this->newInvalidError(
pht(
'File names must not be longer than %s character(s).',
new PhutilNumber($max_length)));
}
}
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/files/exception/PhabricatorFileIntegrityException.php | src/applications/files/exception/PhabricatorFileIntegrityException.php | <?php
final class PhabricatorFileIntegrityException
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/exception/PhabricatorFileUploadException.php | src/applications/files/exception/PhabricatorFileUploadException.php | <?php
final class PhabricatorFileUploadException extends Exception {
public function __construct($code) {
$map = array(
UPLOAD_ERR_INI_SIZE => pht(
"Uploaded file is too large: current limit is %s. To adjust ".
"this limit change '%s' in php.ini.",
ini_get('upload_max_filesize'),
'upload_max_filesize'),
UPLOAD_ERR_FORM_SIZE => pht(
'File is too large.'),
UPLOAD_ERR_PARTIAL => pht(
'File was only partially transferred, upload did not complete.'),
UPLOAD_ERR_NO_FILE => pht(
'No file was uploaded.'),
UPLOAD_ERR_NO_TMP_DIR => pht(
'Unable to write file: temporary directory does not exist.'),
UPLOAD_ERR_CANT_WRITE => pht(
'Unable to write file: failed to write to temporary directory.'),
UPLOAD_ERR_EXTENSION => pht(
'Unable to upload: a PHP extension stopped the upload.'),
);
$message = idx(
$map,
$code,
pht('Upload failed: unknown error (%s).', $code));
parent::__construct($message, $code);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/exception/PhabricatorFileStorageConfigurationException.php | src/applications/files/exception/PhabricatorFileStorageConfigurationException.php | <?php
/**
* Thrown by storage engines to indicate an configuration error which should
* abort the storage attempt, as opposed to a transient storage error which
* should be retried on other engines.
*/
final class PhabricatorFileStorageConfigurationException 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/builtin/PhabricatorFilesComposeAvatarBuiltinFile.php | src/applications/files/builtin/PhabricatorFilesComposeAvatarBuiltinFile.php | <?php
final class PhabricatorFilesComposeAvatarBuiltinFile
extends PhabricatorFilesBuiltinFile {
private $icon;
private $color;
private $border;
private $maps = array();
const VERSION = 'v1';
public function updateUser(PhabricatorUser $user) {
$username = $user->getUsername();
$image_map = $this->getMap('image');
$initial = phutil_utf8_strtoupper(substr($username, 0, 1));
$pack = $this->pickMap('pack', $username);
$icon = "alphanumeric/{$pack}/{$initial}.png";
if (!isset($image_map[$icon])) {
$icon = "alphanumeric/{$pack}/_default.png";
}
$border = $this->pickMap('border', $username);
$color = $this->pickMap('color', $username);
$data = $this->composeImage($color, $icon, $border);
$name = $this->getImageDisplayName($color, $icon, $border);
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$file = PhabricatorFile::newFromFileData(
$data,
array(
'name' => $name,
'profile' => true,
'canCDN' => true,
));
$user
->setDefaultProfileImagePHID($file->getPHID())
->setDefaultProfileImageVersion(self::VERSION)
->saveWithoutIndex();
unset($unguarded);
return $file;
}
private function getMap($map_key) {
if (!isset($this->maps[$map_key])) {
switch ($map_key) {
case 'pack':
$map = $this->newPackMap();
break;
case 'image':
$map = $this->newImageMap();
break;
case 'color':
$map = $this->newColorMap();
break;
case 'border':
$map = $this->newBorderMap();
break;
default:
throw new Exception(pht('Unknown map "%s".', $map_key));
}
$this->maps[$map_key] = $map;
}
return $this->maps[$map_key];
}
private function pickMap($map_key, $username) {
$map = $this->getMap($map_key);
$seed = $username.'_'.$map_key;
$key = PhabricatorHash::digestToRange($seed, 0, count($map) - 1);
return $map[$key];
}
public function setIcon($icon) {
$this->icon = $icon;
return $this;
}
public function getIcon() {
return $this->icon;
}
public function setColor($color) {
$this->color = $color;
return $this;
}
public function getColor() {
return $this->color;
}
public function setBorder($border) {
$this->border = $border;
return $this;
}
public function getBorder() {
return $this->border;
}
public function getBuiltinFileKey() {
$icon = $this->getIcon();
$color = $this->getColor();
$border = implode(',', $this->getBorder());
$desc = "compose(icon={$icon}, color={$color}, border={$border}";
$hash = PhabricatorHash::digestToLength($desc, 40);
return "builtin:{$hash}";
}
public function getBuiltinDisplayName() {
return $this->getImageDisplayName(
$this->getIcon(),
$this->getColor(),
$this->getBorder());
}
private function getImageDisplayName($icon, $color, $border) {
$border = implode(',', $border);
return "{$icon}-{$color}-{$border}.png";
}
public function loadBuiltinFileData() {
return $this->composeImage(
$this->getColor(),
$this->getIcon(),
$this->getBorder());
}
private function composeImage($color, $image, $border) {
// If we don't have the GD extension installed, just return a static
// default profile image rather than trying to compose a dynamic one.
if (!function_exists('imagecreatefromstring')) {
$root = dirname(phutil_get_library_root('phabricator'));
$default_path = $root.'/resources/builtin/profile.png';
return Filesystem::readFile($default_path);
}
$color_const = hexdec(trim($color, '#'));
$true_border = self::rgba2gd($border);
$image_map = $this->getMap('image');
$data = Filesystem::readFile($image_map[$image]);
$img = imagecreatefromstring($data);
// 4 pixel border at 50x50, 32 pixel border at 400x400
$canvas = imagecreatetruecolor(400, 400);
$image_fill = imagefill($canvas, 0, 0, $color_const);
if (!$image_fill) {
throw new Exception(
pht('Failed to save builtin avatar image data (imagefill).'));
}
$border_thickness = imagesetthickness($canvas, 64);
if (!$border_thickness) {
throw new Exception(
pht('Failed to save builtin avatar image data (imagesetthickness).'));
}
$image_rectangle = imagerectangle($canvas, 0, 0, 400, 400, $true_border);
if (!$image_rectangle) {
throw new Exception(
pht('Failed to save builtin avatar image data (imagerectangle).'));
}
$image_copy = imagecopy($canvas, $img, 0, 0, 0, 0, 400, 400);
if (!$image_copy) {
throw new Exception(
pht('Failed to save builtin avatar image data (imagecopy).'));
}
return PhabricatorImageTransformer::saveImageDataInAnyFormat(
$canvas,
'image/png');
}
private static function rgba2gd(array $rgba) {
$r = (int)$rgba[0];
$g = (int)$rgba[1];
$b = (int)$rgba[2];
$a = (int)$rgba[3];
$a = (1 - $a) * 255;
return ($a << 24) | ($r << 16) | ($g << 8) | $b;
}
private function newImageMap() {
$root = dirname(phutil_get_library_root('phabricator'));
$root = $root.'/resources/builtin/alphanumeric/';
$map = array();
$list = id(new FileFinder($root))
->withType('f')
->withFollowSymlinks(true)
->find();
foreach ($list as $file) {
$map['alphanumeric/'.$file] = $root.$file;
}
return $map;
}
private function newPackMap() {
$root = dirname(phutil_get_library_root('phabricator'));
$root = $root.'/resources/builtin/alphanumeric/';
$map = id(new FileFinder($root))
->withType('d')
->withFollowSymlinks(false)
->find();
$map = array_values($map);
return $map;
}
private function newBorderMap() {
return array(
array(0, 0, 0, 0),
array(0, 0, 0, 0.3),
array(255, 255, 255, 0.4),
array(255, 255, 255, 0.7),
);
}
private function newColorMap() {
// Via: http://tools.medialab.sciences-po.fr/iwanthue/
return array(
'#335862',
'#2d5192',
'#3c5da0',
'#99cd86',
'#704889',
'#5ac59e',
'#984060',
'#33d4d1',
'#9c4050',
'#20d8fd',
'#944937',
'#4bd0e3',
'#a25542',
'#4eb4f3',
'#6da8ec',
'#545608',
'#829ce5',
'#68681d',
'#607bc2',
'#4b69ad',
'#236ead',
'#31a0de',
'#4f8ed0',
'#846f2a',
'#bdb0f0',
'#518342',
'#9166aa',
'#5e904e',
'#f79dcc',
'#158e6b',
'#e189b7',
'#3ba984',
'#a85582',
'#4cccb7',
'#863d67',
'#84c08c',
'#7f4c7f',
'#a1bb7a',
'#65558f',
'#445082',
'#c9ca8e',
'#265582',
'#f4b189',
'#265582',
'#40b8e1',
'#814a28',
'#80c8f6',
'#cf7b5d',
'#1db5c7',
'#c0606e',
'#299a89',
'#ef8ead',
'#296437',
'#d39edb',
'#507436',
'#b888c9',
'#476025',
'#9987c5',
'#7867a3',
'#769b5a',
'#c46e9d',
'#437d4e',
'#d17492',
'#115e41',
'#ec8794',
'#297153',
'#d67381',
'#57c2c3',
'#bc607f',
'#86ceac',
'#7e3e53',
'#72c8b8',
'#884349',
'#45a998',
'#faa38c',
'#265582',
'#265582',
'#e4b788',
'#265582',
'#bbbc81',
'#265582',
'#ccb781',
'#265582',
'#eb957f',
'#15729c',
'#cf996f',
'#369bc5',
'#b6685d',
'#2da0a1',
'#d38275',
'#217e70',
'#ec9da1',
'#146268',
'#e8aa95',
'#3c6796',
'#8da667',
'#935f93',
'#69a573',
'#ae78ad',
'#569160',
'#d898be',
'#8eb4e8',
'#5e622c',
'#929ad3',
'#6c8548',
'#576196',
'#aed0a0',
'#694e79',
'#9abb8d',
'#8c5175',
'#6bb391',
'#8b4a5f',
'#519878',
'#ae7196',
'#3d8465',
'#e69eb3',
'#48663d',
'#cdaede',
'#71743d',
'#63acda',
'#7b5d30',
'#66bed6',
'#3585b0',
'#5880b0',
'#739acc',
'#48a3ba',
'#9d565b',
'#7fc4ca',
'#99566b',
'#94cabf',
'#7b4b49',
'#b1c8eb',
'#4e5632',
'#ecb2c3',
'#2d6158',
'#cf8287',
'#25889f',
'#b2696d',
'#6bafb6',
'#8c5744',
'#84b9d6',
'#9db3d6',
'#777cad',
'#826693',
'#86a779',
'#9d7fad',
'#b193c2',
'#547348',
'#d5adcb',
'#3f674d',
'#c98398',
'#66865a',
'#b2add6',
'#5a623d',
'#9793bb',
'#3c5472',
'#d5c5a1',
'#5e5a7f',
'#2c647e',
'#d8b194',
'#49607f',
'#c7b794',
'#335862',
'#e3aba7',
'#335862',
'#d9b9ad',
'#335862',
'#c48975',
'#347b81',
'#ad697e',
'#799a6d',
'#916b88',
'#69536b',
'#b4c4ad',
'#845865',
'#96b89d',
'#706d92',
'#9aa27a',
'#5b7292',
'#bc967b',
'#417792',
'#ce9793',
'#335862',
'#c898a5',
'#527a5f',
'#b38ba9',
'#648d72',
'#986b78',
'#79afa4',
'#966461',
'#50959b',
'#b27d7a',
'#335862',
'#335862',
'#bcadc4',
'#706343',
'#749ebc',
'#8c6a50',
'#92b8c4',
'#758cad',
'#868e67',
'#335862',
'#335862',
'#335862',
'#ac7e8b',
'#77a185',
'#807288',
'#636f51',
'#a192a9',
'#467a70',
'#9b7d73',
'#335862',
'#335862',
'#8c9c85',
'#335862',
'#81645a',
'#5f9489',
'#335862',
'#789da8',
'#335862',
'#72826c',
'#335862',
'#5c8596',
'#335862',
'#456a74',
'#335862',
'#335862',
'#335862',
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/builtin/PhabricatorFilesComposeIconBuiltinFile.php | src/applications/files/builtin/PhabricatorFilesComposeIconBuiltinFile.php | <?php
final class PhabricatorFilesComposeIconBuiltinFile
extends PhabricatorFilesBuiltinFile {
private $icon;
private $color;
public function setIcon($icon) {
$this->icon = $icon;
return $this;
}
public function getIcon() {
return $this->icon;
}
public function setColor($color) {
$this->color = $color;
return $this;
}
public function getColor() {
return $this->color;
}
public function getBuiltinFileKey() {
$icon = $this->getIcon();
$color = $this->getColor();
$desc = "compose(icon={$icon}, color={$color})";
$hash = PhabricatorHash::digestToLength($desc, 40);
return "builtin:{$hash}";
}
public function getBuiltinDisplayName() {
$icon = $this->getIcon();
$color = $this->getColor();
return "{$icon}-{$color}.png";
}
public function loadBuiltinFileData() {
return $this->composeImage($this->getColor(), $this->getIcon());
}
public static function getAllIcons() {
$root = dirname(phutil_get_library_root('phabricator'));
$root = $root.'/resources/builtin/projects/';
$quips = self::getIconQuips();
$map = array();
$list = Filesystem::listDirectory($root, $include_hidden = false);
foreach ($list as $file) {
$short = preg_replace('/\.png$/', '', $file);
$map[$short] = array(
'path' => $root.$file,
'quip' => idx($quips, $short, $short),
);
}
return $map;
}
public static function getAllColors() {
$colors = id(new CelerityResourceTransformer())
->getCSSVariableMap();
$colors = array_select_keys(
$colors,
array(
'red',
'orange',
'yellow',
'green',
'blue',
'sky',
'indigo',
'violet',
'pink',
'charcoal',
'backdrop',
));
$quips = self::getColorQuips();
$map = array();
foreach ($colors as $name => $color) {
$map[$name] = array(
'color' => $color,
'quip' => idx($quips, $name, $name),
);
}
return $map;
}
private function composeImage($color, $icon) {
$color_map = self::getAllColors();
$color = idx($color_map, $color);
if (!$color) {
$fallback = 'backdrop';
$color = idx($color_map, $fallback);
if (!$color) {
throw new Exception(
pht(
'Fallback compose color ("%s") does not exist!',
$fallback));
}
}
$color_hex = idx($color, 'color');
$color_const = hexdec(trim($color_hex, '#'));
$icon_map = self::getAllIcons();
$icon = idx($icon_map, $icon);
if (!$icon) {
$fallback = 'fa-umbrella';
$icon = idx($icon_map, $fallback);
if (!$icon) {
throw new Exception(
pht(
'Fallback compose icon ("%s") does not exist!',
$fallback));
}
}
$path = idx($icon, 'path');
$data = Filesystem::readFile($path);
$icon_img = imagecreatefromstring($data);
$canvas = imagecreatetruecolor(200, 200);
imagefill($canvas, 0, 0, $color_const);
imagecopy($canvas, $icon_img, 0, 0, 0, 0, 200, 200);
return PhabricatorImageTransformer::saveImageDataInAnyFormat(
$canvas,
'image/png');
}
private static function getIconQuips() {
return array(
'fa-android' => pht('Friendly Robot'),
'fa-apple' => pht('Friendly Fruit'),
'fa-beer' => pht('Liquid Carbs'),
'fa-bomb' => pht('Boom!'),
'fa-book' => pht('Read Me'),
'fa-briefcase' => pht('Briefcase'),
'fa-bug' => pht('Bug'),
'fa-building' => pht('Company'),
'fa-calendar' => pht('Deadline'),
'fa-camera-retro' => pht('Leica Enthusiast'),
'fa-chrome' => pht('Shiny'),
'fa-cloud' => pht('The Cloud'),
'fa-coffee' => pht('Go Juice'),
'fa-comments' => pht('Cartoon Captions'),
'fa-credit-card' => pht('Accounting'),
'fa-database' => pht('Stack of Pancakes'),
'fa-desktop' => pht('Cardboard Box'),
'fa-diamond' => pht('Isometric-Hexoctahedral'),
'fa-empire' => pht('Bad Guys'),
'fa-envelope' => pht('Communication'),
'fa-facebook' => pht('College Site'),
'fa-fax' => pht('Communication Device'),
'fa-film' => pht('Physical Film'),
'fa-firefox' => pht('Blake Ross'),
'fa-flag-checkered' => pht('Goal'),
'fa-flask' => pht('Experimental'),
'fa-folder' => pht('Folder'),
'fa-gamepad' => pht('Half-Life 3 Confirmed'),
'fa-gears' => pht('Mechanical'),
'fa-google' => pht('Car Company'),
'fa-hand-peace-o' => pht('Peace'),
'fa-hashtag' => pht('Not Slack'),
'fa-heart' => pht('Myocardial Infarction'),
'fa-internet-explorer' => pht('Now Just Edge'),
'fa-key' => pht('Primitive Security'),
'fa-legal' => pht('Hired Protection'),
'fa-linux' => pht('M\'Lady'),
'fa-lock' => pht('Policy'),
'fa-map-marker' => pht('Destination Beacon'),
'fa-microphone' => pht('Podcasting'),
'fa-mobile' => pht('Tiny Pocket Cat Meme Machine'),
'fa-money' => pht('1 of 99 Problems'),
'fa-phone' => pht('Grandma Uses This'),
'fa-pie-chart' => pht('Not Actually Edible'),
'fa-rebel' => pht('Good Guys'),
'fa-reddit-alien' => pht('Updoot In 5 Seconds'),
'fa-safari' => pht('Fruit Exploration'),
'fa-search' => pht('Dust Detector'),
'fa-server' => pht('Heating Units'),
'fa-shopping-cart' => pht('Buy Stuff'),
'fa-sitemap' => pht('Sitemap'),
'fa-star' => pht('The More You Know'),
'fa-tablet' => pht('Cellular Telephone For Giants'),
'fa-tag' => pht('You\'re It'),
'fa-tags' => pht('Tags'),
'fa-trash-o' => pht('Garbage'),
'fa-truck' => pht('Release'),
'fa-twitter' => pht('Bird Stencil'),
'fa-umbrella' => pht('An Umbrella'),
'fa-university' => pht('School'),
'fa-user-secret' => pht('Shhh'),
'fa-user' => pht('Individual'),
'fa-users' => pht('Team'),
'fa-warning' => pht('No Caution Required, Everything Looks Safe'),
'fa-wheelchair' => pht('Accessibility'),
'fa-windows' => pht('Windows'),
);
}
private static function getColorQuips() {
return array(
'red' => pht('Verbillion'),
'orange' => pht('Navel Orange'),
'yellow' => pht('Prim Goldenrod'),
'green' => pht('Lustrous Verdant'),
'blue' => pht('Tropical Deep'),
'sky' => pht('Wide Open Sky'),
'indigo' => pht('Pleated Khaki'),
'violet' => pht('Aged Merlot'),
'pink' => pht('Easter Bunny'),
'charcoal' => pht('Gemstone'),
'backdrop' => pht('Driven Snow'),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/builtin/PhabricatorFilesOnDiskBuiltinFile.php | src/applications/files/builtin/PhabricatorFilesOnDiskBuiltinFile.php | <?php
final class PhabricatorFilesOnDiskBuiltinFile
extends PhabricatorFilesBuiltinFile {
private $name;
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
if ($this->name === null) {
throw new PhutilInvalidStateException('setName');
}
return $this->name;
}
public function getBuiltinDisplayName() {
return $this->getName();
}
public function getBuiltinFileKey() {
$name = $this->getName();
$desc = "disk(name={$name})";
$hash = PhabricatorHash::digestToLength($desc, 40);
return "builtin:{$hash}";
}
public function loadBuiltinFileData() {
$name = $this->getName();
$available = $this->getAllBuiltinFiles();
if (empty($available[$name])) {
throw new Exception(pht('Builtin "%s" does not exist!', $name));
}
return Filesystem::readFile($available[$name]);
}
private function getAllBuiltinFiles() {
$root = dirname(phutil_get_library_root('phabricator'));
$root = $root.'/resources/builtin/';
$map = array();
$list = id(new FileFinder($root))
->withType('f')
->withFollowSymlinks(true)
->find();
foreach ($list as $file) {
$map[$file] = $root.$file;
}
return $map;
}
public function getProjectBuiltinFiles() {
$root = dirname(phutil_get_library_root('phabricator'));
$root = $root.'/resources/builtin/projects/';
$map = array();
$list = id(new FileFinder($root))
->withType('f')
->withFollowSymlinks(true)
->find();
foreach ($list as $file) {
$map[$file] = $root.$file;
}
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/builtin/PhabricatorFilesBuiltinFile.php | src/applications/files/builtin/PhabricatorFilesBuiltinFile.php | <?php
abstract class PhabricatorFilesBuiltinFile extends Phobject {
abstract public function getBuiltinFileKey();
abstract public function getBuiltinDisplayName();
abstract public function loadBuiltinFileData();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/iconset/PhabricatorIconSet.php | src/applications/files/iconset/PhabricatorIconSet.php | <?php
abstract class PhabricatorIconSet
extends Phobject {
final public function getIconSetKey() {
return $this->getPhobjectClassConstant('ICONSETKEY');
}
public function getChooseButtonText() {
return pht('Choose Icon...');
}
public function getSelectIconTitleText() {
return pht('Choose Icon');
}
public function getSelectURI() {
$key = $this->getIconSetKey();
return "/file/iconset/{$key}/select/";
}
final public function getIcons() {
$icons = $this->newIcons();
// TODO: Validate icons.
$icons = mpull($icons, null, 'getKey');
return $icons;
}
final public function getIcon($key) {
$icons = $this->getIcons();
return idx($icons, $key);
}
final public function getIconLabel($key) {
$icon = $this->getIcon($key);
if ($icon) {
return $icon->getLabel();
}
return $key;
}
final public function renderIconForControl(PhabricatorIconSetIcon $icon) {
return phutil_tag(
'span',
array(),
array(
id(new PHUIIconView())->setIcon($icon->getIcon()),
' ',
$icon->getLabel(),
));
}
final public static function getIconSetByKey($key) {
$sets = self::getAllIconSets();
return idx($sets, $key);
}
final public static function getAllIconSets() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getIconSetKey')
->execute();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/files/iconset/PhabricatorIconSetIcon.php | src/applications/files/iconset/PhabricatorIconSetIcon.php | <?php
final class PhabricatorIconSetIcon
extends Phobject {
private $key;
private $icon;
private $label;
private $isDisabled;
public function setKey($key) {
$this->key = $key;
return $this;
}
public function getKey() {
return $this->key;
}
public function setIcon($icon) {
$this->icon = $icon;
return $this;
}
public function getIcon() {
if ($this->icon === null) {
return $this->getKey();
}
return $this->icon;
}
public function setIsDisabled($is_disabled) {
$this->isDisabled = $is_disabled;
return $this;
}
public function getIsDisabled() {
return $this->isDisabled;
}
public function setLabel($label) {
$this->label = $label;
return $this;
}
public function getLabel() {
return $this->label;
}
}
| 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.