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/differential/management/PhabricatorDifferentialAttachCommitWorkflow.php | src/applications/differential/management/PhabricatorDifferentialAttachCommitWorkflow.php | <?php
final class PhabricatorDifferentialAttachCommitWorkflow
extends PhabricatorDifferentialManagementWorkflow {
protected function didConstruct() {
$this
->setName('attach-commit')
->setExamples('**attach-commit** __commit__ __revision__')
->setSynopsis(pht('Forcefully attach a commit to a revision.'))
->setArguments(
array(
array(
'name' => 'argv',
'wildcard' => true,
'help' => pht('Commit, and a revision to attach it to.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$argv = $args->getArg('argv');
if (count($argv) !== 2) {
throw new PhutilArgumentUsageException(
pht('Specify a commit and a revision to attach it to.'));
}
$commit_name = head($argv);
$revision_name = last($argv);
$commit = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withIdentifiers(array($commit_name))
->executeOne();
if (!$commit) {
throw new PhutilArgumentUsageException(
pht('Commit "%s" does not exist.', $commit_name));
}
$revision = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withNames(array($revision_name))
->executeOne();
if (!$revision) {
throw new PhutilArgumentUsageException(
pht('Revision "%s" does not exist.', $revision_name));
}
if (!($revision instanceof DifferentialRevision)) {
throw new PhutilArgumentUsageException(
pht('Object "%s" must be a Differential revision.', $revision_name));
}
// Reload the revision to get the active diff.
$revision = id(new DifferentialRevisionQuery())
->setViewer($viewer)
->withIDs(array($revision->getID()))
->needActiveDiffs(true)
->executeOne();
$differential_phid = id(new PhabricatorDifferentialApplication())
->getPHID();
$extraction_engine = id(new DifferentialDiffExtractionEngine())
->setViewer($viewer)
->setAuthorPHID($differential_phid);
$content_source = $this->newContentSource();
$extraction_engine->updateRevisionWithCommit(
$revision,
$commit,
array(),
$content_source);
echo tsprintf(
"%s\n",
pht(
'Attached "%s" to "%s".',
$commit->getMonogram(),
$revision->getMonogram()));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/management/PhabricatorDifferentialManagementWorkflow.php | src/applications/differential/management/PhabricatorDifferentialManagementWorkflow.php | <?php
abstract class PhabricatorDifferentialManagementWorkflow
extends PhabricatorManagementWorkflow {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/management/PhabricatorDifferentialExtractWorkflow.php | src/applications/differential/management/PhabricatorDifferentialExtractWorkflow.php | <?php
final class PhabricatorDifferentialExtractWorkflow
extends PhabricatorDifferentialManagementWorkflow {
protected function didConstruct() {
$this
->setName('extract')
->setExamples('**extract** __commit__')
->setSynopsis(pht('Extract a diff from a commit.'))
->setArguments(
array(
array(
'name' => 'extract',
'wildcard' => true,
'help' => pht('Commit to extract.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$viewer = $this->getViewer();
$extract = $args->getArg('extract');
if (!$extract) {
throw new PhutilArgumentUsageException(
pht('Specify a commit to extract the diff from.'));
}
if (count($extract) > 1) {
throw new PhutilArgumentUsageException(
pht('Specify exactly one commit to extract.'));
}
$extract = head($extract);
$commit = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withIdentifiers(array($extract))
->executeOne();
if (!$commit) {
throw new PhutilArgumentUsageException(
pht(
'Commit "%s" is not valid.',
$extract));
}
$diff = id(new DifferentialDiffExtractionEngine())
->setViewer($viewer)
->newDiffFromCommit($commit);
$uri = PhabricatorEnv::getProductionURI($diff->getURI());
echo tsprintf(
"%s\n\n %s\n",
pht('Extracted diff from "%s":', $extract),
$uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/management/PhabricatorDifferentialMigrateHunkWorkflow.php | src/applications/differential/management/PhabricatorDifferentialMigrateHunkWorkflow.php | <?php
final class PhabricatorDifferentialMigrateHunkWorkflow
extends PhabricatorDifferentialManagementWorkflow {
protected function didConstruct() {
$this
->setName('migrate-hunk')
->setExamples(
"**migrate-hunk** --id __hunk__ --to __storage__\n".
"**migrate-hunk** --all")
->setSynopsis(pht('Migrate storage engines for a hunk.'))
->setArguments(
array(
array(
'name' => 'id',
'param' => 'id',
'help' => pht('Hunk ID to migrate.'),
),
array(
'name' => 'to',
'param' => 'storage',
'help' => pht('Storage engine to migrate to.'),
),
array(
'name' => 'all',
'help' => pht('Migrate all hunks.'),
),
array(
'name' => 'auto',
'help' => pht('Select storage format automatically.'),
),
array(
'name' => 'dry-run',
'help' => pht('Show planned writes but do not perform them.'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$is_dry_run = $args->getArg('dry-run');
$id = $args->getArg('id');
$is_all = $args->getArg('all');
if ($is_all && $id) {
throw new PhutilArgumentUsageException(
pht(
'Options "--all" (to migrate all hunks) and "--id" (to migrate a '.
'specific hunk) are mutually exclusive.'));
} else if (!$is_all && !$id) {
throw new PhutilArgumentUsageException(
pht(
'Specify a hunk to migrate with "--id", or migrate all hunks '.
'with "--all".'));
}
$is_auto = $args->getArg('auto');
$storage = $args->getArg('to');
if ($is_auto && $storage) {
throw new PhutilArgumentUsageException(
pht(
'Options "--to" (to choose a specific storage format) and "--auto" '.
'(to select a storage format automatically) are mutually '.
'exclusive.'));
} else if (!$is_auto && !$storage) {
throw new PhutilArgumentUsageException(
pht(
'Use "--to" to choose a storage format, or "--auto" to select a '.
'format automatically.'));
}
$types = array(
DifferentialHunk::DATATYPE_TEXT,
DifferentialHunk::DATATYPE_FILE,
);
$types = array_fuse($types);
if (strlen($storage)) {
if (!isset($types[$storage])) {
throw new PhutilArgumentUsageException(
pht(
'Storage type "%s" is unknown. Supported types are: %s.',
$storage,
implode(', ', array_keys($types))));
}
}
if ($id) {
$hunk = $this->loadHunk($id);
$hunks = array($hunk);
} else {
$hunks = new LiskMigrationIterator(new DifferentialHunk());
}
foreach ($hunks as $hunk) {
try {
$this->migrateHunk($hunk, $storage, $is_auto, $is_dry_run);
} catch (Exception $ex) {
// If we're migrating a single hunk, just throw the exception. If
// we're migrating multiple hunks, warn but continue.
if ($id) {
throw $ex;
}
$this->logWarn(
pht('WARN'),
pht(
'Failed to migrate hunk %d: %s',
$hunk->getID(),
$ex->getMessage()));
}
}
return 0;
}
private function loadHunk($id) {
$hunk = id(new DifferentialHunk())->load($id);
if (!$hunk) {
throw new PhutilArgumentUsageException(
pht(
'No hunk exists with ID "%s".',
$id));
}
return $hunk;
}
private function migrateHunk(
DifferentialHunk $hunk,
$type,
$is_auto,
$is_dry_run) {
$old_type = $hunk->getDataType();
if ($is_auto) {
// By default, we're just going to keep hunks in the same storage
// engine. In the future, we could perhaps select large hunks stored in
// text engine and move them into file storage.
$new_type = $old_type;
} else {
$new_type = $type;
}
// Figure out if the storage format (e.g., plain text vs compressed)
// would change if we wrote this hunk anew today.
$old_format = $hunk->getDataFormat();
$new_format = $hunk->getAutomaticDataFormat();
$same_type = ($old_type === $new_type);
$same_format = ($old_format === $new_format);
// If we aren't going to change the storage engine and aren't going to
// change the storage format, just bail out.
if ($same_type && $same_format) {
$this->logInfo(
pht('SKIP'),
pht(
'Hunk %d is already stored in the preferred engine ("%s") '.
'with the preferred format ("%s").',
$hunk->getID(),
$new_type,
$new_format));
return;
}
if ($is_dry_run) {
$this->logOkay(
pht('DRY RUN'),
pht(
'Hunk %d would be rewritten (storage: "%s" -> "%s"; '.
'format: "%s" -> "%s").',
$hunk->getID(),
$old_type,
$new_type,
$old_format,
$new_format));
return;
}
$old_data = $hunk->getChanges();
switch ($new_type) {
case DifferentialHunk::DATATYPE_TEXT:
$hunk->saveAsText();
break;
case DifferentialHunk::DATATYPE_FILE:
$hunk->saveAsFile();
break;
}
$this->logOkay(
pht('MIGRATE'),
pht(
'Converted hunk %d to "%s" storage (with format "%s").',
$hunk->getID(),
$new_type,
$hunk->getDataFormat()));
$hunk = $this->loadHunk($hunk->getID());
$new_data = $hunk->getChanges();
if ($old_data !== $new_data) {
throw new Exception(
pht(
'Integrity check failed: new file data differs from old data!'));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialDiffInlineCommentQuery.php | src/applications/differential/query/DifferentialDiffInlineCommentQuery.php | <?php
final class DifferentialDiffInlineCommentQuery
extends PhabricatorDiffInlineCommentQuery {
private $revisionPHIDs;
protected function newApplicationTransactionCommentTemplate() {
return new DifferentialTransactionComment();
}
public function withRevisionPHIDs(array $phids) {
$this->revisionPHIDs = $phids;
return $this;
}
public function withObjectPHIDs(array $phids) {
return $this->withRevisionPHIDs($phids);
}
protected function buildInlineCommentWhereClauseParts(
AphrontDatabaseConnection $conn) {
$where = array();
$alias = $this->getPrimaryTableAlias();
$where[] = qsprintf(
$conn,
'changesetID IS NOT NULL');
return $where;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
$alias = $this->getPrimaryTableAlias();
if ($this->revisionPHIDs !== null) {
$where[] = qsprintf(
$conn,
'%T.revisionPHID IN (%Ls)',
$alias,
$this->revisionPHIDs);
}
return $where;
}
protected function loadHiddenCommentIDs(
$viewer_phid,
array $comments) {
$table = new DifferentialHiddenComment();
$conn = $table->establishConnection('r');
$rows = queryfx_all(
$conn,
'SELECT commentID FROM %R
WHERE userPHID = %s
AND commentID IN (%Ld)',
$table,
$viewer_phid,
mpull($comments, 'getID'));
$id_map = ipull($rows, 'commentID');
$id_map = array_fuse($id_map);
return $id_map;
}
protected function newInlineContextFromCacheData(array $map) {
return PhabricatorDiffInlineCommentContext::newFromCacheData($map);
}
protected function newInlineContextMap(array $inlines) {
$viewer = $this->getViewer();
$map = array();
$changeset_ids = mpull($inlines, 'getChangesetID');
$changesets = id(new DifferentialChangesetQuery())
->setViewer($viewer)
->withIDs($changeset_ids)
->needHunks(true)
->execute();
$changesets = mpull($changesets, null, 'getID');
foreach ($inlines as $key => $inline) {
$changeset = idx($changesets, $inline->getChangesetID());
if (!$changeset) {
continue;
}
$hunks = $changeset->getHunks();
$is_simple =
(count($hunks) === 1) &&
((int)head($hunks)->getOldOffset() <= 1) &&
((int)head($hunks)->getNewOffset() <= 1);
if (!$is_simple) {
continue;
}
if ($inline->getIsNewFile()) {
$vector = $changeset->getNewStatePathVector();
$filename = last($vector);
$corpus = $changeset->makeNewFile();
} else {
$vector = $changeset->getOldStatePathVector();
$filename = last($vector);
$corpus = $changeset->makeOldFile();
}
$corpus = phutil_split_lines($corpus);
// Adjust the line number into a 0-based offset.
$offset = $inline->getLineNumber();
$offset = $offset - 1;
// Adjust the inclusive range length into a row count.
$length = $inline->getLineLength();
$length = $length + 1;
$head_min = max(0, $offset - 3);
$head_max = $offset;
$head_len = $head_max - $head_min;
if ($head_len) {
$head = array_slice($corpus, $head_min, $head_len, true);
$head = $this->simplifyContext($head, true);
} else {
$head = array();
}
$body = array_slice($corpus, $offset, $length, true);
$tail = array_slice($corpus, $offset + $length, 3, true);
$tail = $this->simplifyContext($tail, false);
$context = id(new PhabricatorDiffInlineCommentContext())
->setFilename($filename)
->setHeadLines($head)
->setBodyLines($body)
->setTailLines($tail);
$map[$key] = $context;
}
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/differential/query/DifferentialDiffQuery.php | src/applications/differential/query/DifferentialDiffQuery.php | <?php
final class DifferentialDiffQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $revisionIDs;
private $revisionPHIDs;
private $commitPHIDs;
private $hasRevision;
private $needChangesets = false;
private $needProperties;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withRevisionIDs(array $revision_ids) {
$this->revisionIDs = $revision_ids;
return $this;
}
public function withRevisionPHIDs(array $revision_phids) {
$this->revisionPHIDs = $revision_phids;
return $this;
}
public function withCommitPHIDs(array $phids) {
$this->commitPHIDs = $phids;
return $this;
}
public function withHasRevision($has_revision) {
$this->hasRevision = $has_revision;
return $this;
}
public function needChangesets($bool) {
$this->needChangesets = $bool;
return $this;
}
public function needProperties($need_properties) {
$this->needProperties = $need_properties;
return $this;
}
public function newResultObject() {
return new DifferentialDiff();
}
protected function willFilterPage(array $diffs) {
$revision_ids = array_filter(mpull($diffs, 'getRevisionID'));
$revisions = array();
if ($revision_ids) {
$revisions = id(new DifferentialRevisionQuery())
->setViewer($this->getViewer())
->withIDs($revision_ids)
->execute();
}
foreach ($diffs as $key => $diff) {
if (!$diff->getRevisionID()) {
continue;
}
$revision = idx($revisions, $diff->getRevisionID());
if ($revision) {
$diff->attachRevision($revision);
continue;
}
unset($diffs[$key]);
}
if ($diffs && $this->needChangesets) {
$diffs = $this->loadChangesets($diffs);
}
return $diffs;
}
protected function didFilterPage(array $diffs) {
if ($this->needProperties) {
$properties = id(new DifferentialDiffProperty())->loadAllWhere(
'diffID IN (%Ld)',
mpull($diffs, 'getID'));
$properties = mgroup($properties, 'getDiffID');
foreach ($diffs as $diff) {
$map = idx($properties, $diff->getID(), array());
$map = mpull($map, 'getData', 'getName');
$diff->attachDiffProperties($map);
}
}
return $diffs;
}
private function loadChangesets(array $diffs) {
id(new DifferentialChangesetQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withDiffs($diffs)
->needAttachToDiffs(true)
->needHunks(true)
->execute();
return $diffs;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->revisionIDs !== null) {
$where[] = qsprintf(
$conn,
'revisionID IN (%Ld)',
$this->revisionIDs);
}
if ($this->commitPHIDs !== null) {
$where[] = qsprintf(
$conn,
'commitPHID IN (%Ls)',
$this->commitPHIDs);
}
if ($this->hasRevision !== null) {
if ($this->hasRevision) {
$where[] = qsprintf(
$conn,
'revisionID IS NOT NULL');
} else {
$where[] = qsprintf(
$conn,
'revisionID IS NULL');
}
}
if ($this->revisionPHIDs !== null) {
$viewer = $this->getViewer();
$revisions = id(new DifferentialRevisionQuery())
->setViewer($viewer)
->setParentQuery($this)
->withPHIDs($this->revisionPHIDs)
->execute();
$revision_ids = mpull($revisions, 'getID');
if (!$revision_ids) {
throw new PhabricatorEmptyQueryException();
}
$where[] = qsprintf(
$conn,
'revisionID IN (%Ls)',
$revision_ids);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialChangesetSearchEngine.php | src/applications/differential/query/DifferentialChangesetSearchEngine.php | <?php
final class DifferentialChangesetSearchEngine
extends PhabricatorApplicationSearchEngine {
private $diff;
public function setDiff(DifferentialDiff $diff) {
$this->diff = $diff;
return $this;
}
public function getDiff() {
return $this->diff;
}
public function getResultTypeDescription() {
return pht('Differential Changesets');
}
public function getApplicationClassName() {
return 'PhabricatorDifferentialApplication';
}
public function canUseInPanelContext() {
return false;
}
public function newQuery() {
$query = id(new DifferentialChangesetQuery());
if ($this->diff) {
$query->withDiffs(array($this->diff));
}
return $query;
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['diffPHIDs']) {
$query->withDiffPHIDs($map['diffPHIDs']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Diffs'))
->setKey('diffPHIDs')
->setAliases(array('diff', 'diffs', 'diffPHID'))
->setDescription(
pht('Find changesets attached to a particular diff.')),
);
}
protected function getURI($path) {
$diff = $this->getDiff();
if ($diff) {
return '/differential/diff/'.$diff->getID().'/changesets/'.$path;
}
throw new PhutilMethodNotImplementedException();
}
protected function getBuiltinQueryNames() {
$names = array();
$names['all'] = pht('All Changesets');
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
$viewer = $this->requireViewer();
switch ($query_key) {
case 'all':
return $query->setParameter('order', 'oldest');
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $changesets,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($changesets, 'DifferentialChangeset');
$viewer = $this->requireViewer();
$rows = array();
foreach ($changesets as $changeset) {
$link = phutil_tag(
'a',
array(
'href' => '/differential/changeset/?ref='.$changeset->getID(),
),
$changeset->getDisplayFilename());
$type = $changeset->getChangeType();
$title = DifferentialChangeType::getFullNameForChangeType($type);
$add_lines = $changeset->getAddLines();
if (!$add_lines) {
$add_lines = null;
} else {
$add_lines = '+'.$add_lines;
}
$rem_lines = $changeset->getDelLines();
if (!$rem_lines) {
$rem_lines = null;
} else {
$rem_lines = '-'.$rem_lines;
}
$rows[] = array(
$changeset->newFileTreeIcon(),
$title,
$link,
);
}
$table = id(new AphrontTableView($rows))
->setHeaders(
array(
null,
pht('Change'),
pht('Path'),
))
->setColumnClasses(
array(
null,
null,
'pri wide',
));
return id(new PhabricatorApplicationSearchResultView())
->setTable($table);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialTransactionQuery.php | src/applications/differential/query/DifferentialTransactionQuery.php | <?php
final class DifferentialTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new DifferentialTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialRepositoryLookup.php | src/applications/differential/query/DifferentialRepositoryLookup.php | <?php
/**
* Guess which tracked repository a diff comes from.
*/
final class DifferentialRepositoryLookup extends Phobject {
private $viewer;
private $diff;
public function setDiff(DifferentialDiff $diff) {
$this->diff = $diff;
return $this;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function lookupRepository() {
$viewer = $this->viewer;
$diff = $this->diff;
// Look for a repository UUID.
if ($diff->getRepositoryUUID()) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withUUIDs(array($diff->getRepositoryUUID()))
->execute();
if ($repositories) {
return head($repositories);
}
}
// Look for the base commit in Git and Mercurial.
$vcs = $diff->getSourceControlSystem();
$vcs_git = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT;
$vcs_hg = PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL;
if ($vcs == $vcs_git || $vcs == $vcs_hg) {
$base = $diff->getSourceControlBaseRevision();
if ($base) {
$commits = id(new DiffusionCommitQuery())
->setViewer($viewer)
->withIdentifiers(array($base))
->execute();
$commits = mgroup($commits, 'getRepositoryID');
if (count($commits) == 1) {
$repository_id = key($commits);
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->withIDs(array($repository_id))
->execute();
if ($repositories) {
return head($repositories);
}
}
}
}
// TODO: Compare SVN remote URIs? Compare Git/Hg remote URIs? Add
// an explicit option to `.arcconfig`?
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialRevisionRequiredActionResultBucket.php | src/applications/differential/query/DifferentialRevisionRequiredActionResultBucket.php | <?php
final class DifferentialRevisionRequiredActionResultBucket
extends DifferentialRevisionResultBucket {
const BUCKETKEY = 'action';
const KEY_MUSTREVIEW = 'must-review';
const KEY_SHOULDREVIEW = 'should-review';
private $objects;
public function getResultBucketName() {
return pht('Bucket by Required Action');
}
protected function buildResultGroups(
PhabricatorSavedQuery $query,
array $objects) {
$this->objects = $objects;
$phids = $query->getEvaluatedParameter('responsiblePHIDs');
if (!$phids) {
throw new Exception(
pht(
'You can not bucket results by required action without '.
'specifying "Responsible Users".'));
}
$phids = array_fuse($phids);
// Before continuing, throw away any revisions which responsible users
// have explicitly resigned from.
// The goal is to allow users to resign from revisions they don't want to
// review to get these revisions off their dashboard, even if there are
// other project or package reviewers which they have authority over.
$this->filterResigned($phids);
// We also throw away draft revisions which you aren't the author of.
$this->filterOtherDrafts($phids);
$groups = array();
$groups[] = $this->newGroup()
->setName(pht('Must Review'))
->setKey(self::KEY_MUSTREVIEW)
->setNoDataString(pht('No revisions are blocked on your review.'))
->setObjects($this->filterMustReview($phids));
$groups[] = $this->newGroup()
->setName(pht('Ready to Review'))
->setKey(self::KEY_SHOULDREVIEW)
->setNoDataString(pht('No revisions are waiting on you to review them.'))
->setObjects($this->filterShouldReview($phids));
$groups[] = $this->newGroup()
->setName(pht('Ready to Land'))
->setNoDataString(pht('No revisions are ready to land.'))
->setObjects($this->filterShouldLand($phids));
$groups[] = $this->newGroup()
->setName(pht('Ready to Update'))
->setNoDataString(pht('No revisions are waiting for updates.'))
->setObjects($this->filterShouldUpdate($phids));
$groups[] = $this->newGroup()
->setName(pht('Drafts'))
->setNoDataString(pht('You have no draft revisions.'))
->setObjects($this->filterDrafts($phids));
$groups[] = $this->newGroup()
->setName(pht('Waiting on Review'))
->setNoDataString(pht('None of your revisions are waiting on review.'))
->setObjects($this->filterWaitingForReview($phids));
$groups[] = $this->newGroup()
->setName(pht('Waiting on Authors'))
->setNoDataString(pht('No revisions are waiting on author action.'))
->setObjects($this->filterWaitingOnAuthors($phids));
$groups[] = $this->newGroup()
->setName(pht('Waiting on Other Reviewers'))
->setNoDataString(pht('No revisions are waiting for other reviewers.'))
->setObjects($this->filterWaitingOnOtherReviewers($phids));
// Because you can apply these buckets to queries which include revisions
// that have been closed, add an "Other" bucket if we still have stuff
// that didn't get filtered into any of the previous buckets.
if ($this->objects) {
$groups[] = $this->newGroup()
->setName(pht('Other Revisions'))
->setObjects($this->objects);
}
return $groups;
}
private function filterMustReview(array $phids) {
$blocking = array(
DifferentialReviewerStatus::STATUS_BLOCKING,
DifferentialReviewerStatus::STATUS_REJECTED,
DifferentialReviewerStatus::STATUS_REJECTED_OLDER,
);
$blocking = array_fuse($blocking);
$objects = $this->getRevisionsUnderReview($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (!$this->hasReviewersWithStatus($object, $phids, $blocking)) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterShouldReview(array $phids) {
$reviewing = array(
DifferentialReviewerStatus::STATUS_ADDED,
DifferentialReviewerStatus::STATUS_COMMENTED,
// If an author has used "Request Review" to put an accepted revision
// back into the "Needs Review" state, include "Accepted" reviewers
// whose reviews have been voided in the "Should Review" bucket.
// If we don't do this, they end up in "Waiting on Other Reviewers",
// even if there are no other reviewers.
DifferentialReviewerStatus::STATUS_ACCEPTED,
);
$reviewing = array_fuse($reviewing);
$objects = $this->getRevisionsUnderReview($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (!$this->hasReviewersWithStatus($object, $phids, $reviewing, true)) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterShouldLand(array $phids) {
$objects = $this->getRevisionsAuthored($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (!$object->isAccepted()) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterShouldUpdate(array $phids) {
$statuses = array(
DifferentialRevisionStatus::NEEDS_REVISION,
DifferentialRevisionStatus::CHANGES_PLANNED,
);
$statuses = array_fuse($statuses);
$objects = $this->getRevisionsAuthored($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (empty($statuses[$object->getModernRevisionStatus()])) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterWaitingForReview(array $phids) {
$objects = $this->getRevisionsAuthored($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (!$object->isNeedsReview()) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterWaitingOnAuthors(array $phids) {
$statuses = array(
DifferentialRevisionStatus::ACCEPTED,
DifferentialRevisionStatus::NEEDS_REVISION,
DifferentialRevisionStatus::CHANGES_PLANNED,
);
$statuses = array_fuse($statuses);
$objects = $this->getRevisionsNotAuthored($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (empty($statuses[$object->getModernRevisionStatus()])) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterWaitingOnOtherReviewers(array $phids) {
$objects = $this->getRevisionsNotAuthored($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (!$object->isNeedsReview()) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterResigned(array $phids) {
$resigned = array(
DifferentialReviewerStatus::STATUS_RESIGNED,
);
$resigned = array_fuse($resigned);
$objects = $this->getRevisionsNotAuthored($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (!$this->hasReviewersWithStatus($object, $phids, $resigned)) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterOtherDrafts(array $phids) {
$objects = $this->getRevisionsNotAuthored($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (!$object->isDraft()) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
return $results;
}
private function filterDrafts(array $phids) {
$objects = $this->getRevisionsAuthored($this->objects, $phids);
$results = array();
foreach ($objects as $key => $object) {
if (!$object->isDraft()) {
continue;
}
$results[$key] = $object;
unset($this->objects[$key]);
}
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/differential/query/DifferentialRevisionQuery.php | src/applications/differential/query/DifferentialRevisionQuery.php | <?php
/**
* @task config Query Configuration
* @task exec Query Execution
* @task internal Internals
*/
final class DifferentialRevisionQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $authors = array();
private $draftAuthors = array();
private $ccs = array();
private $reviewers = array();
private $revIDs = array();
private $commitHashes = array();
private $phids = array();
private $responsibles = array();
private $branches = array();
private $repositoryPHIDs;
private $updatedEpochMin;
private $updatedEpochMax;
private $statuses;
private $isOpen;
private $createdEpochMin;
private $createdEpochMax;
private $noReviewers;
private $paths;
const ORDER_MODIFIED = 'order-modified';
const ORDER_CREATED = 'order-created';
private $needActiveDiffs = false;
private $needDiffIDs = false;
private $needCommitPHIDs = false;
private $needHashes = false;
private $needReviewers = false;
private $needReviewerAuthority;
private $needDrafts;
private $needFlags;
/* -( Query Configuration )------------------------------------------------ */
/**
* Find revisions affecting one or more items in a list of paths.
*
* @param list<string> List of file paths.
* @return this
* @task config
*/
public function withPaths(array $paths) {
$this->paths = $paths;
return $this;
}
/**
* Filter results to revisions authored by one of the given PHIDs. Calling
* this function will clear anything set by previous calls to
* @{method:withAuthors}.
*
* @param array List of PHIDs of authors
* @return this
* @task config
*/
public function withAuthors(array $author_phids) {
$this->authors = $author_phids;
return $this;
}
/**
* Filter results to revisions which CC one of the listed people. Calling this
* function will clear anything set by previous calls to @{method:withCCs}.
*
* @param array List of PHIDs of subscribers.
* @return this
* @task config
*/
public function withCCs(array $cc_phids) {
$this->ccs = $cc_phids;
return $this;
}
/**
* Filter results to revisions that have one of the provided PHIDs as
* reviewers. Calling this function will clear anything set by previous calls
* to @{method:withReviewers}.
*
* @param array List of PHIDs of reviewers
* @return this
* @task config
*/
public function withReviewers(array $reviewer_phids) {
if ($reviewer_phids === array()) {
throw new Exception(
pht(
'Empty "withReviewers()" constraint is invalid. Provide one or '.
'more values, or remove the constraint.'));
}
$with_none = false;
foreach ($reviewer_phids as $key => $phid) {
switch ($phid) {
case DifferentialNoReviewersDatasource::FUNCTION_TOKEN:
$with_none = true;
unset($reviewer_phids[$key]);
break;
default:
break;
}
}
$this->noReviewers = $with_none;
if ($reviewer_phids) {
$this->reviewers = array_values($reviewer_phids);
}
return $this;
}
/**
* Filter results to revisions that have one of the provided commit hashes.
* Calling this function will clear anything set by previous calls to
* @{method:withCommitHashes}.
*
* @param array List of pairs <Class
* ArcanistDifferentialRevisionHash::HASH_$type constant,
* hash>
* @return this
* @task config
*/
public function withCommitHashes(array $commit_hashes) {
$this->commitHashes = $commit_hashes;
return $this;
}
public function withStatuses(array $statuses) {
$this->statuses = $statuses;
return $this;
}
public function withIsOpen($is_open) {
$this->isOpen = $is_open;
return $this;
}
/**
* Filter results to revisions on given branches.
*
* @param list List of branch names.
* @return this
* @task config
*/
public function withBranches(array $branches) {
$this->branches = $branches;
return $this;
}
/**
* Filter results to only return revisions whose ids are in the given set.
*
* @param array List of revision ids
* @return this
* @task config
*/
public function withIDs(array $ids) {
$this->revIDs = $ids;
return $this;
}
/**
* Filter results to only return revisions whose PHIDs are in the given set.
*
* @param array List of revision PHIDs
* @return this
* @task config
*/
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
/**
* Given a set of users, filter results to return only revisions they are
* responsible for (i.e., they are either authors or reviewers).
*
* @param array List of user PHIDs.
* @return this
* @task config
*/
public function withResponsibleUsers(array $responsible_phids) {
$this->responsibles = $responsible_phids;
return $this;
}
public function withRepositoryPHIDs(array $repository_phids) {
$this->repositoryPHIDs = $repository_phids;
return $this;
}
public function withUpdatedEpochBetween($min, $max) {
$this->updatedEpochMin = $min;
$this->updatedEpochMax = $max;
return $this;
}
public function withCreatedEpochBetween($min, $max) {
$this->createdEpochMin = $min;
$this->createdEpochMax = $max;
return $this;
}
/**
* Set whether or not the query should load the active diff for each
* revision.
*
* @param bool True to load and attach diffs.
* @return this
* @task config
*/
public function needActiveDiffs($need_active_diffs) {
$this->needActiveDiffs = $need_active_diffs;
return $this;
}
/**
* Set whether or not the query should load the associated commit PHIDs for
* each revision.
*
* @param bool True to load and attach diffs.
* @return this
* @task config
*/
public function needCommitPHIDs($need_commit_phids) {
$this->needCommitPHIDs = $need_commit_phids;
return $this;
}
/**
* Set whether or not the query should load associated diff IDs for each
* revision.
*
* @param bool True to load and attach diff IDs.
* @return this
* @task config
*/
public function needDiffIDs($need_diff_ids) {
$this->needDiffIDs = $need_diff_ids;
return $this;
}
/**
* Set whether or not the query should load associated commit hashes for each
* revision.
*
* @param bool True to load and attach commit hashes.
* @return this
* @task config
*/
public function needHashes($need_hashes) {
$this->needHashes = $need_hashes;
return $this;
}
/**
* Set whether or not the query should load associated reviewers.
*
* @param bool True to load and attach reviewers.
* @return this
* @task config
*/
public function needReviewers($need_reviewers) {
$this->needReviewers = $need_reviewers;
return $this;
}
/**
* Request information about the viewer's authority to act on behalf of each
* reviewer. In particular, they have authority to act on behalf of projects
* they are a member of.
*
* @param bool True to load and attach authority.
* @return this
* @task config
*/
public function needReviewerAuthority($need_reviewer_authority) {
$this->needReviewerAuthority = $need_reviewer_authority;
return $this;
}
public function needFlags($need_flags) {
$this->needFlags = $need_flags;
return $this;
}
public function needDrafts($need_drafts) {
$this->needDrafts = $need_drafts;
return $this;
}
/* -( Query Execution )---------------------------------------------------- */
public function newResultObject() {
return new DifferentialRevision();
}
/**
* Execute the query as configured, returning matching
* @{class:DifferentialRevision} objects.
*
* @return list List of matching DifferentialRevision objects.
* @task exec
*/
protected function loadPage() {
$data = $this->loadData();
$data = $this->didLoadRawRows($data);
$table = $this->newResultObject();
return $table->loadAllFromArray($data);
}
protected function willFilterPage(array $revisions) {
$viewer = $this->getViewer();
$repository_phids = mpull($revisions, 'getRepositoryPHID');
$repository_phids = array_filter($repository_phids);
$repositories = array();
if ($repository_phids) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($this->getViewer())
->withPHIDs($repository_phids)
->execute();
$repositories = mpull($repositories, null, 'getPHID');
}
// If a revision is associated with a repository:
//
// - the viewer must be able to see the repository; or
// - the viewer must have an automatic view capability.
//
// In the latter case, we'll load the revision but not load the repository.
$can_view = PhabricatorPolicyCapability::CAN_VIEW;
foreach ($revisions as $key => $revision) {
$repo_phid = $revision->getRepositoryPHID();
if (!$repo_phid) {
// The revision has no associated repository. Attach `null` and move on.
$revision->attachRepository(null);
continue;
}
$repository = idx($repositories, $repo_phid);
if ($repository) {
// The revision has an associated repository, and the viewer can see
// it. Attach it and move on.
$revision->attachRepository($repository);
continue;
}
if ($revision->hasAutomaticCapability($can_view, $viewer)) {
// The revision has an associated repository which the viewer can not
// see, but the viewer has an automatic capability on this revision.
// Load the revision without attaching a repository.
$revision->attachRepository(null);
continue;
}
if ($this->getViewer()->isOmnipotent()) {
// The viewer is omnipotent. Allow the revision to load even without
// a repository.
$revision->attachRepository(null);
continue;
}
// The revision has an associated repository, and the viewer can't see
// it, and the viewer has no special capabilities. Filter out this
// revision.
$this->didRejectResult($revision);
unset($revisions[$key]);
}
if (!$revisions) {
return array();
}
$table = new DifferentialRevision();
$conn_r = $table->establishConnection('r');
if ($this->needCommitPHIDs) {
$this->loadCommitPHIDs($revisions);
}
$need_active = $this->needActiveDiffs;
$need_ids = $need_active || $this->needDiffIDs;
if ($need_ids) {
$this->loadDiffIDs($conn_r, $revisions);
}
if ($need_active) {
$this->loadActiveDiffs($conn_r, $revisions);
}
if ($this->needHashes) {
$this->loadHashes($conn_r, $revisions);
}
if ($this->needReviewers || $this->needReviewerAuthority) {
$this->loadReviewers($conn_r, $revisions);
}
return $revisions;
}
protected function didFilterPage(array $revisions) {
$viewer = $this->getViewer();
if ($this->needFlags) {
$flags = id(new PhabricatorFlagQuery())
->setViewer($viewer)
->withOwnerPHIDs(array($viewer->getPHID()))
->withObjectPHIDs(mpull($revisions, 'getPHID'))
->execute();
$flags = mpull($flags, null, 'getObjectPHID');
foreach ($revisions as $revision) {
$revision->attachFlag(
$viewer,
idx($flags, $revision->getPHID()));
}
}
if ($this->needDrafts) {
PhabricatorDraftEngine::attachDrafts(
$viewer,
$revisions);
}
return $revisions;
}
private function loadData() {
$table = $this->newResultObject();
$conn = $table->establishConnection('r');
$selects = array();
// NOTE: If the query includes "responsiblePHIDs", we execute it as a
// UNION of revisions they own and revisions they're reviewing. This has
// much better performance than doing it with JOIN/WHERE.
if ($this->responsibles) {
$basic_authors = $this->authors;
$basic_reviewers = $this->reviewers;
try {
// Build the query where the responsible users are authors.
$this->authors = array_merge($basic_authors, $this->responsibles);
$this->reviewers = $basic_reviewers;
$selects[] = $this->buildSelectStatement($conn);
// Build the query where the responsible users are reviewers, or
// projects they are members of are reviewers.
$this->authors = $basic_authors;
$this->reviewers = array_merge($basic_reviewers, $this->responsibles);
$selects[] = $this->buildSelectStatement($conn);
// Put everything back like it was.
$this->authors = $basic_authors;
$this->reviewers = $basic_reviewers;
} catch (Exception $ex) {
$this->authors = $basic_authors;
$this->reviewers = $basic_reviewers;
throw $ex;
}
} else {
$selects[] = $this->buildSelectStatement($conn);
}
if (count($selects) > 1) {
$unions = null;
foreach ($selects as $select) {
if (!$unions) {
$unions = $select;
continue;
}
$unions = qsprintf(
$conn,
'%Q UNION DISTINCT %Q',
$unions,
$select);
}
$query = qsprintf(
$conn,
'%Q %Q %Q',
$unions,
$this->buildOrderClause($conn, true),
$this->buildLimitClause($conn));
} else {
$query = head($selects);
}
return queryfx_all($conn, '%Q', $query);
}
private function buildSelectStatement(AphrontDatabaseConnection $conn_r) {
$table = new DifferentialRevision();
$select = $this->buildSelectClause($conn_r);
$from = qsprintf(
$conn_r,
'FROM %T r',
$table->getTableName());
$joins = $this->buildJoinsClause($conn_r);
$where = $this->buildWhereClause($conn_r);
$group_by = $this->buildGroupClause($conn_r);
$having = $this->buildHavingClause($conn_r);
$order_by = $this->buildOrderClause($conn_r);
$limit = $this->buildLimitClause($conn_r);
return qsprintf(
$conn_r,
'(%Q %Q %Q %Q %Q %Q %Q %Q)',
$select,
$from,
$joins,
$where,
$group_by,
$having,
$order_by,
$limit);
}
/* -( Internals )---------------------------------------------------------- */
/**
* @task internal
*/
private function buildJoinsClause(AphrontDatabaseConnection $conn) {
$joins = array();
if ($this->paths) {
$path_table = new DifferentialAffectedPath();
$joins[] = qsprintf(
$conn,
'JOIN %R paths ON paths.revisionID = r.id',
$path_table);
}
if ($this->commitHashes) {
$joins[] = qsprintf(
$conn,
'JOIN %T hash_rel ON hash_rel.revisionID = r.id',
ArcanistDifferentialRevisionHash::TABLE_NAME);
}
if ($this->ccs) {
$joins[] = qsprintf(
$conn,
'JOIN %T e_ccs ON e_ccs.src = r.phid '.
'AND e_ccs.type = %s '.
'AND e_ccs.dst in (%Ls)',
PhabricatorEdgeConfig::TABLE_NAME_EDGE,
PhabricatorObjectHasSubscriberEdgeType::EDGECONST,
$this->ccs);
}
if ($this->reviewers) {
$joins[] = qsprintf(
$conn,
'LEFT JOIN %T reviewer ON reviewer.revisionPHID = r.phid
AND reviewer.reviewerStatus != %s
AND reviewer.reviewerPHID in (%Ls)',
id(new DifferentialReviewer())->getTableName(),
DifferentialReviewerStatus::STATUS_RESIGNED,
$this->reviewers);
}
if ($this->noReviewers) {
$joins[] = qsprintf(
$conn,
'LEFT JOIN %T no_reviewer ON no_reviewer.revisionPHID = r.phid
AND no_reviewer.reviewerStatus != %s',
id(new DifferentialReviewer())->getTableName(),
DifferentialReviewerStatus::STATUS_RESIGNED);
}
if ($this->draftAuthors) {
$joins[] = qsprintf(
$conn,
'JOIN %T has_draft ON has_draft.srcPHID = r.phid
AND has_draft.type = %s
AND has_draft.dstPHID IN (%Ls)',
PhabricatorEdgeConfig::TABLE_NAME_EDGE,
PhabricatorObjectHasDraftEdgeType::EDGECONST,
$this->draftAuthors);
}
$joins[] = $this->buildJoinClauseParts($conn);
return $this->formatJoinClause($conn, $joins);
}
/**
* @task internal
*/
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$viewer = $this->getViewer();
$where = array();
if ($this->paths !== null) {
$paths = $this->paths;
$path_map = id(new DiffusionPathIDQuery($paths))
->loadPathIDs();
if (!$path_map) {
// If none of the paths have entries in the PathID table, we can not
// possibly find any revisions affecting them.
throw new PhabricatorEmptyQueryException();
}
$where[] = qsprintf(
$conn,
'paths.pathID IN (%Ld)',
array_fuse($path_map));
// If we have repository PHIDs, additionally constrain this query to
// try to help MySQL execute it efficiently.
if ($this->repositoryPHIDs !== null) {
$repositories = id(new PhabricatorRepositoryQuery())
->setViewer($viewer)
->setParentQuery($this)
->withPHIDs($this->repositoryPHIDs)
->execute();
if (!$repositories) {
throw new PhabricatorEmptyQueryException();
}
$repository_ids = mpull($repositories, 'getID');
$where[] = qsprintf(
$conn,
'paths.repositoryID IN (%Ld)',
$repository_ids);
}
}
if ($this->authors) {
$where[] = qsprintf(
$conn,
'r.authorPHID IN (%Ls)',
$this->authors);
}
if ($this->revIDs) {
$where[] = qsprintf(
$conn,
'r.id IN (%Ld)',
$this->revIDs);
}
if ($this->repositoryPHIDs) {
$where[] = qsprintf(
$conn,
'r.repositoryPHID IN (%Ls)',
$this->repositoryPHIDs);
}
if ($this->commitHashes) {
$hash_clauses = array();
foreach ($this->commitHashes as $info) {
list($type, $hash) = $info;
$hash_clauses[] = qsprintf(
$conn,
'(hash_rel.type = %s AND hash_rel.hash = %s)',
$type,
$hash);
}
$hash_clauses = qsprintf($conn, '%LO', $hash_clauses);
$where[] = $hash_clauses;
}
if ($this->phids) {
$where[] = qsprintf(
$conn,
'r.phid IN (%Ls)',
$this->phids);
}
if ($this->branches) {
$where[] = qsprintf(
$conn,
'r.branchName in (%Ls)',
$this->branches);
}
if ($this->updatedEpochMin !== null) {
$where[] = qsprintf(
$conn,
'r.dateModified >= %d',
$this->updatedEpochMin);
}
if ($this->updatedEpochMax !== null) {
$where[] = qsprintf(
$conn,
'r.dateModified <= %d',
$this->updatedEpochMax);
}
if ($this->createdEpochMin !== null) {
$where[] = qsprintf(
$conn,
'r.dateCreated >= %d',
$this->createdEpochMin);
}
if ($this->createdEpochMax !== null) {
$where[] = qsprintf(
$conn,
'r.dateCreated <= %d',
$this->createdEpochMax);
}
if ($this->statuses !== null) {
$where[] = qsprintf(
$conn,
'r.status in (%Ls)',
$this->statuses);
}
if ($this->isOpen !== null) {
if ($this->isOpen) {
$statuses = DifferentialLegacyQuery::getModernValues(
DifferentialLegacyQuery::STATUS_OPEN);
} else {
$statuses = DifferentialLegacyQuery::getModernValues(
DifferentialLegacyQuery::STATUS_CLOSED);
}
$where[] = qsprintf(
$conn,
'r.status in (%Ls)',
$statuses);
}
$reviewer_subclauses = array();
if ($this->noReviewers) {
$reviewer_subclauses[] = qsprintf(
$conn,
'no_reviewer.reviewerPHID IS NULL');
}
if ($this->reviewers) {
$reviewer_subclauses[] = qsprintf(
$conn,
'reviewer.reviewerPHID IS NOT NULL');
}
if ($reviewer_subclauses) {
$where[] = qsprintf($conn, '%LO', $reviewer_subclauses);
}
$where[] = $this->buildWhereClauseParts($conn);
return $this->formatWhereClause($conn, $where);
}
/**
* @task internal
*/
protected function shouldGroupQueryResultRows() {
if ($this->paths) {
// (If we have exactly one repository and exactly one path, we don't
// technically need to group, but it's simpler to always group.)
return true;
}
if (count($this->ccs) > 1) {
return true;
}
if (count($this->reviewers) > 1) {
return true;
}
if (count($this->commitHashes) > 1) {
return true;
}
if ($this->noReviewers) {
return true;
}
return parent::shouldGroupQueryResultRows();
}
public function getBuiltinOrders() {
$orders = parent::getBuiltinOrders() + array(
'updated' => array(
'vector' => array('updated', 'id'),
'name' => pht('Date Updated (Latest First)'),
'aliases' => array(self::ORDER_MODIFIED),
),
'outdated' => array(
'vector' => array('-updated', '-id'),
'name' => pht('Date Updated (Oldest First)'),
),
);
// Alias the "newest" builtin to the historical key for it.
$orders['newest']['aliases'][] = self::ORDER_CREATED;
return $orders;
}
protected function getDefaultOrderVector() {
return array('updated', 'id');
}
public function getOrderableColumns() {
return array(
'updated' => array(
'table' => $this->getPrimaryTableAlias(),
'column' => 'dateModified',
'type' => 'int',
),
) + parent::getOrderableColumns();
}
protected function newPagingMapFromPartialObject($object) {
return array(
'id' => (int)$object->getID(),
'updated' => (int)$object->getDateModified(),
);
}
private function loadCommitPHIDs(array $revisions) {
assert_instances_of($revisions, 'DifferentialRevision');
if (!$revisions) {
return;
}
$revisions = mpull($revisions, null, 'getPHID');
$edge_query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(array_keys($revisions))
->withEdgeTypes(
array(
DifferentialRevisionHasCommitEdgeType::EDGECONST,
));
$edge_query->execute();
foreach ($revisions as $phid => $revision) {
$commit_phids = $edge_query->getDestinationPHIDs(array($phid));
$revision->attachCommitPHIDs($commit_phids);
}
}
private function loadDiffIDs($conn_r, array $revisions) {
assert_instances_of($revisions, 'DifferentialRevision');
$diff_table = new DifferentialDiff();
$diff_ids = queryfx_all(
$conn_r,
'SELECT revisionID, id FROM %T WHERE revisionID IN (%Ld)
ORDER BY id DESC',
$diff_table->getTableName(),
mpull($revisions, 'getID'));
$diff_ids = igroup($diff_ids, 'revisionID');
foreach ($revisions as $revision) {
$ids = idx($diff_ids, $revision->getID(), array());
$ids = ipull($ids, 'id');
$revision->attachDiffIDs($ids);
}
}
private function loadActiveDiffs($conn_r, array $revisions) {
assert_instances_of($revisions, 'DifferentialRevision');
$diff_table = new DifferentialDiff();
$load_ids = array();
foreach ($revisions as $revision) {
$diffs = $revision->getDiffIDs();
if ($diffs) {
$load_ids[] = max($diffs);
}
}
$active_diffs = array();
if ($load_ids) {
$active_diffs = $diff_table->loadAllWhere(
'id IN (%Ld)',
$load_ids);
}
$active_diffs = mpull($active_diffs, null, 'getRevisionID');
foreach ($revisions as $revision) {
$revision->attachActiveDiff(idx($active_diffs, $revision->getID()));
}
}
private function loadHashes(
AphrontDatabaseConnection $conn_r,
array $revisions) {
assert_instances_of($revisions, 'DifferentialRevision');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T WHERE revisionID IN (%Ld)',
'differential_revisionhash',
mpull($revisions, 'getID'));
$data = igroup($data, 'revisionID');
foreach ($revisions as $revision) {
$hashes = idx($data, $revision->getID(), array());
$list = array();
foreach ($hashes as $hash) {
$list[] = array($hash['type'], $hash['hash']);
}
$revision->attachHashes($list);
}
}
private function loadReviewers(
AphrontDatabaseConnection $conn,
array $revisions) {
assert_instances_of($revisions, 'DifferentialRevision');
$reviewer_table = new DifferentialReviewer();
$reviewer_rows = queryfx_all(
$conn,
'SELECT * FROM %T WHERE revisionPHID IN (%Ls)
ORDER BY id ASC',
$reviewer_table->getTableName(),
mpull($revisions, 'getPHID'));
$reviewer_list = $reviewer_table->loadAllFromArray($reviewer_rows);
$reviewer_map = mgroup($reviewer_list, 'getRevisionPHID');
foreach ($reviewer_map as $key => $reviewers) {
$reviewer_map[$key] = mpull($reviewers, null, 'getReviewerPHID');
}
$viewer = $this->getViewer();
$viewer_phid = $viewer->getPHID();
$allow_key = 'differential.allow-self-accept';
$allow_self = PhabricatorEnv::getEnvConfig($allow_key);
// Figure out which of these reviewers the viewer has authority to act as.
if ($this->needReviewerAuthority && $viewer_phid) {
$authority = $this->loadReviewerAuthority(
$revisions,
$reviewer_map,
$allow_self);
}
foreach ($revisions as $revision) {
$reviewers = idx($reviewer_map, $revision->getPHID(), array());
foreach ($reviewers as $reviewer_phid => $reviewer) {
if ($this->needReviewerAuthority) {
if (!$viewer_phid) {
// Logged-out users never have authority.
$has_authority = false;
} else if ((!$allow_self) &&
($revision->getAuthorPHID() == $viewer_phid)) {
// The author can never have authority unless we allow self-accept.
$has_authority = false;
} else {
// Otherwise, look up whether the viewer has authority.
$has_authority = isset($authority[$reviewer_phid]);
}
$reviewer->attachAuthority($viewer, $has_authority);
}
$reviewers[$reviewer_phid] = $reviewer;
}
$revision->attachReviewers($reviewers);
}
}
private function loadReviewerAuthority(
array $revisions,
array $reviewers,
$allow_self) {
$revision_map = mpull($revisions, null, 'getPHID');
$viewer_phid = $this->getViewer()->getPHID();
// Find all the project/package reviewers which the user may have authority
// over.
$project_phids = array();
$package_phids = array();
$project_type = PhabricatorProjectProjectPHIDType::TYPECONST;
$package_type = PhabricatorOwnersPackagePHIDType::TYPECONST;
foreach ($reviewers as $revision_phid => $reviewer_list) {
if (!$allow_self) {
if ($revision_map[$revision_phid]->getAuthorPHID() == $viewer_phid) {
// If self-review isn't permitted, the user will never have
// authority over projects on revisions they authored because you
// can't accept your own revisions, so we don't need to load any
// data about these reviewers.
continue;
}
}
foreach ($reviewer_list as $reviewer_phid => $reviewer) {
$phid_type = phid_get_type($reviewer_phid);
if ($phid_type == $project_type) {
$project_phids[] = $reviewer_phid;
}
if ($phid_type == $package_type) {
$package_phids[] = $reviewer_phid;
}
}
}
// The viewer has authority over themselves.
$user_authority = array_fuse(array($viewer_phid));
// And over any projects they are a member of.
$project_authority = array();
if ($project_phids) {
$project_authority = id(new PhabricatorProjectQuery())
->setViewer($this->getViewer())
->withPHIDs($project_phids)
->withMemberPHIDs(array($viewer_phid))
->execute();
$project_authority = mpull($project_authority, 'getPHID');
$project_authority = array_fuse($project_authority);
}
// And over any packages they own.
$package_authority = array();
if ($package_phids) {
$package_authority = id(new PhabricatorOwnersPackageQuery())
->setViewer($this->getViewer())
->withPHIDs($package_phids)
->withAuthorityPHIDs(array($viewer_phid))
->execute();
$package_authority = mpull($package_authority, 'getPHID');
$package_authority = array_fuse($package_authority);
}
return $user_authority + $project_authority + $package_authority;
}
public function getQueryApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
protected function getPrimaryTableAlias() {
return 'r';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialRevisionSearchEngine.php | src/applications/differential/query/DifferentialRevisionSearchEngine.php | <?php
final class DifferentialRevisionSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Differential Revisions');
}
public function getApplicationClassName() {
return 'PhabricatorDifferentialApplication';
}
protected function newResultBuckets() {
return DifferentialRevisionResultBucket::getAllResultBuckets();
}
public function newQuery() {
return id(new DifferentialRevisionQuery())
->needFlags(true)
->needDrafts(true)
->needReviewers(true);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['responsiblePHIDs']) {
$query->withResponsibleUsers($map['responsiblePHIDs']);
}
if ($map['authorPHIDs']) {
$query->withAuthors($map['authorPHIDs']);
}
if ($map['reviewerPHIDs']) {
$query->withReviewers($map['reviewerPHIDs']);
}
if ($map['repositoryPHIDs']) {
$query->withRepositoryPHIDs($map['repositoryPHIDs']);
}
if ($map['statuses']) {
$query->withStatuses($map['statuses']);
}
if ($map['createdStart'] || $map['createdEnd']) {
$query->withCreatedEpochBetween(
$map['createdStart'],
$map['createdEnd']);
}
if ($map['modifiedStart'] || $map['modifiedEnd']) {
$query->withUpdatedEpochBetween(
$map['modifiedStart'],
$map['modifiedEnd']);
}
if ($map['affectedPaths']) {
$query->withPaths($map['affectedPaths']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Responsible Users'))
->setKey('responsiblePHIDs')
->setAliases(array('responsiblePHID', 'responsibles', 'responsible'))
->setDatasource(new DifferentialResponsibleDatasource())
->setDescription(
pht('Find revisions that a given user is responsible for.')),
id(new PhabricatorUsersSearchField())
->setLabel(pht('Authors'))
->setKey('authorPHIDs')
->setAliases(array('author', 'authors', 'authorPHID'))
->setDescription(
pht('Find revisions with specific authors.')),
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Reviewers'))
->setKey('reviewerPHIDs')
->setAliases(array('reviewer', 'reviewers', 'reviewerPHID'))
->setDatasource(new DifferentialReviewerFunctionDatasource())
->setDescription(
pht('Find revisions with specific reviewers.')),
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Repositories'))
->setKey('repositoryPHIDs')
->setAliases(array('repository', 'repositories', 'repositoryPHID'))
->setDatasource(new DiffusionRepositoryFunctionDatasource())
->setDescription(
pht('Find revisions from specific repositories.')),
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Statuses'))
->setKey('statuses')
->setAliases(array('status'))
->setDatasource(new DifferentialRevisionStatusFunctionDatasource())
->setDescription(
pht('Find revisions with particular statuses.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Created After'))
->setKey('createdStart')
->setDescription(
pht('Find revisions created at or after a particular time.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Created Before'))
->setKey('createdEnd')
->setDescription(
pht('Find revisions created at or before a particular time.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Modified After'))
->setKey('modifiedStart')
->setIsHidden(true)
->setDescription(
pht('Find revisions modified at or after a particular time.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Modified Before'))
->setKey('modifiedEnd')
->setIsHidden(true)
->setDescription(
pht('Find revisions modified at or before a particular time.')),
id(new PhabricatorSearchStringListField())
->setKey('affectedPaths')
->setLabel(pht('Affected Paths'))
->setDescription(
pht('Search for revisions affecting particular paths.'))
->setIsHidden(true),
);
}
protected function getURI($path) {
return '/differential/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array();
if ($this->requireViewer()->isLoggedIn()) {
$names['active'] = pht('Active Revisions');
$names['authored'] = pht('Authored');
}
$names['all'] = pht('All Revisions');
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
$viewer = $this->requireViewer();
switch ($query_key) {
case 'active':
$bucket_key = DifferentialRevisionRequiredActionResultBucket::BUCKETKEY;
return $query
->setParameter('responsiblePHIDs', array($viewer->getPHID()))
->setParameter('statuses', array('open()'))
->setParameter('bucket', $bucket_key);
case 'authored':
return $query
->setParameter('authorPHIDs', array($viewer->getPHID()));
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
private function getStatusOptions() {
return array(
DifferentialLegacyQuery::STATUS_ANY => pht('All'),
DifferentialLegacyQuery::STATUS_OPEN => pht('Open'),
DifferentialLegacyQuery::STATUS_ACCEPTED => pht('Accepted'),
DifferentialLegacyQuery::STATUS_NEEDS_REVIEW => pht('Needs Review'),
DifferentialLegacyQuery::STATUS_NEEDS_REVISION => pht('Needs Revision'),
DifferentialLegacyQuery::STATUS_CLOSED => pht('Closed'),
DifferentialLegacyQuery::STATUS_ABANDONED => pht('Abandoned'),
);
}
protected function renderResultList(
array $revisions,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($revisions, 'DifferentialRevision');
$viewer = $this->requireViewer();
$template = id(new DifferentialRevisionListView())
->setViewer($viewer)
->setNoBox($this->isPanelContext());
$bucket = $this->getResultBucket($query);
$unlanded = $this->loadUnlandedDependencies($revisions);
$views = array();
if ($bucket) {
$bucket->setViewer($viewer);
try {
$groups = $bucket->newResultGroups($query, $revisions);
foreach ($groups as $group) {
// Don't show groups in Dashboard Panels
if ($group->getObjects() || !$this->isPanelContext()) {
$views[] = id(clone $template)
->setHeader($group->getName())
->setNoDataString($group->getNoDataString())
->setRevisions($group->getObjects());
}
}
} catch (Exception $ex) {
$this->addError($ex->getMessage());
}
} else {
$views[] = id(clone $template)
->setRevisions($revisions);
}
if (!$views) {
$views[] = id(new DifferentialRevisionListView())
->setViewer($viewer)
->setNoDataString(pht('No revisions found.'));
}
foreach ($views as $view) {
$view->setUnlandedDependencies($unlanded);
}
if (count($views) == 1) {
// Reduce this to a PHUIObjectItemListView so we can get the free
// support from ApplicationSearch.
$list = head($views)->render();
} else {
$list = $views;
}
$result = new PhabricatorApplicationSearchResultView();
$result->setContent($list);
return $result;
}
protected function getNewUserBody() {
$create_button = id(new PHUIButtonView())
->setTag('a')
->setText(pht('Create a Diff'))
->setHref('/differential/diff/create/')
->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('Pre-commit code review. Revisions that are waiting on your input '.
'will appear here.'))
->addAction($create_button);
return $view;
}
private function loadUnlandedDependencies(array $revisions) {
$phids = array();
foreach ($revisions as $revision) {
if (!$revision->isAccepted()) {
continue;
}
$phids[] = $revision->getPHID();
}
if (!$phids) {
return array();
}
$query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs($phids)
->withEdgeTypes(
array(
DifferentialRevisionDependsOnRevisionEdgeType::EDGECONST,
));
$query->execute();
$revision_phids = $query->getDestinationPHIDs();
if (!$revision_phids) {
return array();
}
$viewer = $this->requireViewer();
$blocking_revisions = id(new DifferentialRevisionQuery())
->setViewer($viewer)
->withPHIDs($revision_phids)
->withIsOpen(true)
->execute();
$blocking_revisions = mpull($blocking_revisions, null, 'getPHID');
$result = array();
foreach ($revisions as $revision) {
$revision_phid = $revision->getPHID();
$blocking_phids = $query->getDestinationPHIDs(array($revision_phid));
$blocking = array_select_keys($blocking_revisions, $blocking_phids);
if ($blocking) {
$result[$revision_phid] = $blocking;
}
}
return $result;
}
protected function newExportFields() {
$fields = array(
id(new PhabricatorStringExportField())
->setKey('monogram')
->setLabel(pht('Monogram')),
id(new PhabricatorPHIDExportField())
->setKey('authorPHID')
->setLabel(pht('Author PHID')),
id(new PhabricatorStringExportField())
->setKey('author')
->setLabel(pht('Author')),
id(new PhabricatorStringExportField())
->setKey('status')
->setLabel(pht('Status')),
id(new PhabricatorStringExportField())
->setKey('statusName')
->setLabel(pht('Status Name')),
id(new PhabricatorURIExportField())
->setKey('uri')
->setLabel(pht('URI')),
id(new PhabricatorStringExportField())
->setKey('title')
->setLabel(pht('Title')),
id(new PhabricatorStringExportField())
->setKey('summary')
->setLabel(pht('Summary')),
id(new PhabricatorStringExportField())
->setKey('testPlan')
->setLabel(pht('Test Plan')),
);
return $fields;
}
protected function newExportData(array $revisions) {
$viewer = $this->requireViewer();
$phids = array();
foreach ($revisions as $revision) {
$phids[] = $revision->getAuthorPHID();
}
$handles = $viewer->loadHandles($phids);
$export = array();
foreach ($revisions as $revision) {
$author_phid = $revision->getAuthorPHID();
if ($author_phid) {
$author_name = $handles[$author_phid]->getName();
} else {
$author_name = null;
}
$status = $revision->getStatusObject();
$status_name = $status->getDisplayName();
$status_value = $status->getKey();
$export[] = array(
'monogram' => $revision->getMonogram(),
'authorPHID' => $author_phid,
'author' => $author_name,
'status' => $status_value,
'statusName' => $status_name,
'uri' => PhabricatorEnv::getProductionURI($revision->getURI()),
'title' => (string)$revision->getTitle(),
'summary' => (string)$revision->getSummary(),
'testPlan' => (string)$revision->getTestPlan(),
);
}
return $export;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialDiffTransactionQuery.php | src/applications/differential/query/DifferentialDiffTransactionQuery.php | <?php
final class DifferentialDiffTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new DifferentialDiffTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialViewStateQuery.php | src/applications/differential/query/DifferentialViewStateQuery.php | <?php
final class DifferentialViewStateQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $viewerPHIDs;
private $objectPHIDs;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withViewerPHIDs(array $phids) {
$this->viewerPHIDs = $phids;
return $this;
}
public function withObjectPHIDs(array $phids) {
$this->objectPHIDs = $phids;
return $this;
}
public function newResultObject() {
return new DifferentialViewState();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->viewerPHIDs !== null) {
$where[] = qsprintf(
$conn,
'viewerPHID IN (%Ls)',
$this->viewerPHIDs);
}
if ($this->objectPHIDs !== null) {
$where[] = qsprintf(
$conn,
'objectPHID IN (%Ls)',
$this->objectPHIDs);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialHunkQuery.php | src/applications/differential/query/DifferentialHunkQuery.php | <?php
final class DifferentialHunkQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $changesets;
private $shouldAttachToChangesets;
public function withChangesets(array $changesets) {
assert_instances_of($changesets, 'DifferentialChangeset');
$this->changesets = $changesets;
return $this;
}
public function needAttachToChangesets($attach) {
$this->shouldAttachToChangesets = $attach;
return $this;
}
protected function willExecute() {
// If we fail to load any hunks at all (for example, because all of
// the requested changesets are directories or empty files and have no
// hunks) we'll never call didFilterPage(), and thus never have an
// opportunity to attach hunks. Attach empty hunk lists now so that we
// end up with the right result.
if ($this->shouldAttachToChangesets) {
foreach ($this->changesets as $changeset) {
$changeset->attachHunks(array());
}
}
}
public function newResultObject() {
return new DifferentialHunk();
}
protected function willFilterPage(array $hunks) {
$changesets = mpull($this->changesets, null, 'getID');
foreach ($hunks as $key => $hunk) {
$changeset = idx($changesets, $hunk->getChangesetID());
if (!$changeset) {
unset($hunks[$key]);
}
$hunk->attachChangeset($changeset);
}
return $hunks;
}
protected function didFilterPage(array $hunks) {
if ($this->shouldAttachToChangesets) {
$hunk_groups = mgroup($hunks, 'getChangesetID');
foreach ($this->changesets as $changeset) {
$hunks = idx($hunk_groups, $changeset->getID(), array());
$changeset->attachHunks($hunks);
}
}
return $hunks;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if (!$this->changesets) {
throw new Exception(
pht(
'You must load hunks via changesets, with %s!',
'withChangesets()'));
}
$where[] = qsprintf(
$conn,
'changesetID IN (%Ld)',
mpull($this->changesets, 'getID'));
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
protected function getDefaultOrderVector() {
// TODO: Do we need this?
return array('-id');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialChangesetQuery.php | src/applications/differential/query/DifferentialChangesetQuery.php | <?php
final class DifferentialChangesetQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $diffPHIDs;
private $diffs;
private $needAttachToDiffs;
private $needHunks;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withDiffs(array $diffs) {
assert_instances_of($diffs, 'DifferentialDiff');
$this->diffs = $diffs;
return $this;
}
public function withDiffPHIDs(array $phids) {
$this->diffPHIDs = $phids;
return $this;
}
public function needAttachToDiffs($attach) {
$this->needAttachToDiffs = $attach;
return $this;
}
public function needHunks($need) {
$this->needHunks = $need;
return $this;
}
protected function willExecute() {
// If we fail to load any changesets (which is possible in the case of an
// empty commit) we'll never call didFilterPage(). Attach empty changeset
// lists now so that we end up with the right result.
if ($this->needAttachToDiffs) {
foreach ($this->diffs as $diff) {
$diff->attachChangesets(array());
}
}
}
public function newResultObject() {
return new DifferentialChangeset();
}
protected function willFilterPage(array $changesets) {
// First, attach all the diffs we already have. We can just do this
// directly without worrying about querying for them. When we don't have
// a diff, record that we need to load it.
if ($this->diffs) {
$have_diffs = mpull($this->diffs, null, 'getID');
} else {
$have_diffs = array();
}
$must_load = array();
foreach ($changesets as $key => $changeset) {
$diff_id = $changeset->getDiffID();
if (isset($have_diffs[$diff_id])) {
$changeset->attachDiff($have_diffs[$diff_id]);
} else {
$must_load[$key] = $changeset;
}
}
// Load all the diffs we don't have.
$need_diff_ids = mpull($must_load, 'getDiffID');
$more_diffs = array();
if ($need_diff_ids) {
$more_diffs = id(new DifferentialDiffQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withIDs($need_diff_ids)
->execute();
$more_diffs = mpull($more_diffs, null, 'getID');
}
// Attach the diffs we loaded.
foreach ($must_load as $key => $changeset) {
$diff_id = $changeset->getDiffID();
if (isset($more_diffs[$diff_id])) {
$changeset->attachDiff($more_diffs[$diff_id]);
} else {
// We didn't have the diff, and could not load it (it does not exist,
// or we can't see it), so filter this result out.
unset($changesets[$key]);
}
}
return $changesets;
}
protected function didFilterPage(array $changesets) {
if ($this->needAttachToDiffs) {
$changeset_groups = mgroup($changesets, 'getDiffID');
foreach ($this->diffs as $diff) {
$diff_changesets = idx($changeset_groups, $diff->getID(), array());
$diff->attachChangesets($diff_changesets);
}
}
if ($this->needHunks) {
id(new DifferentialHunkQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withChangesets($changesets)
->needAttachToChangesets(true)
->execute();
}
return $changesets;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->diffs !== null) {
$where[] = qsprintf(
$conn,
'diffID IN (%Ld)',
mpull($this->diffs, 'getID'));
}
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->diffPHIDs !== null) {
$diff_ids = queryfx_all(
$conn,
'SELECT id FROM %R WHERE phid IN (%Ls)',
new DifferentialDiff(),
$this->diffPHIDs);
$diff_ids = ipull($diff_ids, 'id', null);
if (!$diff_ids) {
throw new PhabricatorEmptyQueryException();
}
$where[] = qsprintf(
$conn,
'diffID IN (%Ld)',
$diff_ids);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialDiffSearchEngine.php | src/applications/differential/query/DifferentialDiffSearchEngine.php | <?php
final class DifferentialDiffSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Differential Diffs');
}
public function getApplicationClassName() {
return 'PhabricatorDifferentialApplication';
}
public function newQuery() {
return new DifferentialDiffQuery();
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['revisionPHIDs']) {
$query->withRevisionPHIDs($map['revisionPHIDs']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorPHIDsSearchField())
->setLabel(pht('Revisions'))
->setKey('revisionPHIDs')
->setAliases(array('revision', 'revisions', 'revisionPHID'))
->setDescription(
pht('Find diffs attached to a particular revision.')),
);
}
protected function getURI($path) {
return '/differential/diff/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array();
$names['all'] = pht('All Diffs');
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
$viewer = $this->requireViewer();
switch ($query_key) {
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $revisions,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($revisions, 'DifferentialDiff');
$viewer = $this->requireViewer();
// NOTE: This is only exposed to Conduit, so we don't currently render
// results.
return id(new PhabricatorApplicationSearchResultView());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/query/DifferentialRevisionResultBucket.php | src/applications/differential/query/DifferentialRevisionResultBucket.php | <?php
abstract class DifferentialRevisionResultBucket
extends PhabricatorSearchResultBucket {
public static function getAllResultBuckets() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getResultBucketKey')
->execute();
}
protected function getRevisionsUnderReview(array $objects, array $phids) {
$results = array();
$objects = $this->getRevisionsNotAuthored($objects, $phids);
foreach ($objects as $key => $object) {
if (!$object->isNeedsReview()) {
continue;
}
$results[$key] = $object;
}
return $results;
}
protected function getRevisionsAuthored(array $objects, array $phids) {
$results = array();
foreach ($objects as $key => $object) {
if (isset($phids[$object->getAuthorPHID()])) {
$results[$key] = $object;
}
}
return $results;
}
protected function getRevisionsNotAuthored(array $objects, array $phids) {
$results = array();
foreach ($objects as $key => $object) {
if (empty($phids[$object->getAuthorPHID()])) {
$results[$key] = $object;
}
}
return $results;
}
protected function hasReviewersWithStatus(
DifferentialRevision $revision,
array $phids,
array $statuses,
$include_voided = null) {
foreach ($revision->getReviewers() as $reviewer) {
$reviewer_phid = $reviewer->getReviewerPHID();
if (empty($phids[$reviewer_phid])) {
continue;
}
$status = $reviewer->getReviewerStatus();
if (empty($statuses[$status])) {
continue;
}
if ($include_voided !== null) {
if ($status == DifferentialReviewerStatus::STATUS_ACCEPTED) {
$is_voided = (bool)$reviewer->getVoidedPHID();
if ($is_voided !== $include_voided) {
continue;
}
}
}
return true;
}
return false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/doorkeeper/DifferentialDoorkeeperRevisionFeedStoryPublisher.php | src/applications/differential/doorkeeper/DifferentialDoorkeeperRevisionFeedStoryPublisher.php | <?php
final class DifferentialDoorkeeperRevisionFeedStoryPublisher
extends DoorkeeperFeedStoryPublisher {
public function canPublishStory(PhabricatorFeedStory $story, $object) {
return ($object instanceof DifferentialRevision);
}
public function isStoryAboutObjectCreation($object) {
$story = $this->getFeedStory();
$action = $story->getStoryData()->getValue('action');
return ($action == DifferentialAction::ACTION_CREATE);
}
public function isStoryAboutObjectClosure($object) {
$story = $this->getFeedStory();
$action = $story->getStoryData()->getValue('action');
return ($action == DifferentialAction::ACTION_CLOSE) ||
($action == DifferentialAction::ACTION_ABANDON);
}
public function willPublishStory($object) {
return id(new DifferentialRevisionQuery())
->setViewer($this->getViewer())
->withIDs(array($object->getID()))
->needReviewers(true)
->executeOne();
}
public function getOwnerPHID($object) {
return $object->getAuthorPHID();
}
public function getActiveUserPHIDs($object) {
if ($object->isNeedsReview()) {
return $object->getReviewerPHIDs();
} else {
return array();
}
}
public function getPassiveUserPHIDs($object) {
if ($object->isNeedsReview()) {
return array();
} else {
return $object->getReviewerPHIDs();
}
}
public function getCCUserPHIDs($object) {
return PhabricatorSubscribersQuery::loadSubscribersForPHID(
$object->getPHID());
}
public function getObjectTitle($object) {
$id = $object->getID();
$title = $object->getTitle();
return "D{$id}: {$title}";
}
public function getObjectURI($object) {
return PhabricatorEnv::getProductionURI('/D'.$object->getID());
}
public function getObjectDescription($object) {
return $object->getSummary();
}
public function isObjectClosed($object) {
return $object->isClosed();
}
public function getResponsibilityTitle($object) {
$prefix = $this->getTitlePrefix($object);
return pht('%s Review Request', $prefix);
}
private function getTitlePrefix(DifferentialRevision $revision) {
return pht('[Differential]');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/harbormaster/DifferentialBuildableEngine.php | src/applications/differential/harbormaster/DifferentialBuildableEngine.php | <?php
final class DifferentialBuildableEngine
extends HarbormasterBuildableEngine {
protected function getPublishableObject() {
$object = $this->getObject();
if ($object instanceof DifferentialDiff) {
if ($object->getRevisionID()) {
return $object->getRevision();
} else {
return null;
}
}
return $object;
}
public function publishBuildable(
HarbormasterBuildable $old,
HarbormasterBuildable $new) {
// If we're publishing to a diff that is not actually attached to a
// revision, we have nothing to publish to, so just bail out.
$revision = $this->getPublishableObject();
if (!$revision) {
return;
}
// Don't publish manual buildables.
if ($new->getIsManualBuildable()) {
return;
}
// Don't publish anything if the buildable is still building. Differential
// treats more buildables as "building" than Harbormaster does, but the
// Differential definition is a superset of the Harbormaster definition.
if ($new->isBuilding()) {
return;
}
$viewer = $this->getViewer();
$old_status = $revision->getBuildableStatus($new->getPHID());
$new_status = $revision->newBuildableStatus($viewer, $new->getPHID());
if ($old_status === $new_status) {
return;
}
$buildable_type = DifferentialRevisionBuildableTransaction::TRANSACTIONTYPE;
$xaction = $this->newTransaction()
->setMetadataValue('harbormaster:buildablePHID', $new->getPHID())
->setTransactionType($buildable_type)
->setNewValue($new_status);
$this->applyTransactions(array($xaction));
}
public function getAuthorIdentity() {
$object = $this->getObject();
if ($object instanceof DifferentialRevision) {
$object = $object->loadActiveDiff();
}
$authorship = $object->getDiffAuthorshipDict();
if (!isset($authorship['authorName'])) {
return null;
}
$name = $authorship['authorName'];
$address = idx($authorship, 'authorEmail');
$full = id(new PhutilEmailAddress())
->setDisplayName($name)
->setAddress($address);
return id(new PhabricatorRepositoryIdentity())
->setIdentityName((string)$full)
->makeEphemeral();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/mail/DifferentialChangeDetailMailView.php | src/applications/differential/mail/DifferentialChangeDetailMailView.php | <?php
final class DifferentialChangeDetailMailView
extends DifferentialMailView {
private $viewer;
private $diff;
private $patch;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setDiff(DifferentialDiff $diff) {
$this->diff = $diff;
return $this;
}
public function getDiff() {
return $this->diff;
}
public function setPatch($patch) {
$this->patch = $patch;
return $this;
}
public function getPatch() {
return $this->patch;
}
public function buildMailSection() {
$viewer = $this->getViewer();
$diff = $this->getDiff();
$engine = new PhabricatorMarkupEngine();
$viewstate = new PhabricatorChangesetViewState();
$out = array();
foreach ($diff->getChangesets() as $changeset) {
$parser = id(new DifferentialChangesetParser())
->setViewer($viewer)
->setViewState($viewstate)
->setChangeset($changeset)
->setLinesOfContext(2)
->setMarkupEngine($engine);
$parser->setRenderer(new DifferentialChangesetOneUpMailRenderer());
$block = $parser->render();
$filename = $changeset->getFilename();
$filename = $this->renderHeaderBold($filename);
$header = $this->renderHeaderBlock($filename);
$out[] = $this->renderContentBox(
array(
$header,
$this->renderCodeBlock($block),
));
}
$out = phutil_implode_html(phutil_tag('br'), $out);
$patch_html = $out;
$patch_text = $this->getPatch();
return id(new PhabricatorMetaMTAMailSection())
->addPlaintextFragment($patch_text)
->addHTMLFragment($patch_html);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/mail/DifferentialCreateMailReceiver.php | src/applications/differential/mail/DifferentialCreateMailReceiver.php | <?php
final class DifferentialCreateMailReceiver
extends PhabricatorApplicationMailReceiver {
protected function newApplication() {
return new PhabricatorDifferentialApplication();
}
protected function processReceivedMail(
PhabricatorMetaMTAReceivedMail $mail,
PhutilEmailAddress $target) {
$author = $this->getAuthor();
$attachments = $mail->getAttachments();
$files = array();
$errors = array();
if ($attachments) {
$files = id(new PhabricatorFileQuery())
->setViewer($author)
->withPHIDs($attachments)
->execute();
foreach ($files as $index => $file) {
if ($file->getMimeType() != 'text/plain') {
$errors[] = pht(
'Could not parse file %s; only files with mimetype text/plain '.
'can be parsed via email.',
$file->getName());
unset($files[$index]);
}
}
}
$diffs = array();
foreach ($files as $file) {
$call = new ConduitCall(
'differential.createrawdiff',
array(
'diff' => $file->loadFileData(),
));
$call->setUser($author);
try {
$result = $call->execute();
$diffs[$file->getName()] = $result['uri'];
} catch (Exception $e) {
$errors[] = pht(
'Could not parse attachment %s; only attachments (and mail bodies) '.
'generated via "diff" commands can be parsed.',
$file->getName());
}
}
$body = $mail->getCleanTextBody();
if ($body) {
$call = new ConduitCall(
'differential.createrawdiff',
array(
'diff' => $body,
));
$call->setUser($author);
try {
$result = $call->execute();
$diffs[pht('Mail Body')] = $result['uri'];
} catch (Exception $e) {
$errors[] = pht(
'Could not parse mail body; only mail bodies (and attachments) '.
'generated via "diff" commands can be parsed.');
}
}
$subject_prefix = pht('[Differential]');
if (count($diffs)) {
$subject = pht(
'You successfully created %d diff(s).',
count($diffs));
} else {
$subject = pht(
'Diff creation failed; see body for %s error(s).',
phutil_count($errors));
}
$body = new PhabricatorMetaMTAMailBody();
$body->addRawSection($subject);
if (count($diffs)) {
$text_body = '';
$html_body = array();
$body_label = pht('%s DIFF LINK(S)', phutil_count($diffs));
foreach ($diffs as $filename => $diff_uri) {
$text_body .= $filename.': '.$diff_uri."\n";
$html_body[] = phutil_tag(
'a',
array(
'href' => $diff_uri,
),
$filename);
$html_body[] = phutil_tag('br');
}
$body->addTextSection($body_label, $text_body);
$body->addHTMLSection($body_label, $html_body);
}
if (count($errors)) {
$body_section = new PhabricatorMetaMTAMailSection();
$body_label = pht('%s ERROR(S)', phutil_count($errors));
foreach ($errors as $error) {
$body_section->addFragment($error);
}
$body->addTextSection($body_label, $body_section);
}
id(new PhabricatorMetaMTAMail())
->addTos(array($author->getPHID()))
->setSubject($subject)
->setSubjectPrefix($subject_prefix)
->setFrom($author->getPHID())
->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/differential/mail/DifferentialReplyHandler.php | src/applications/differential/mail/DifferentialReplyHandler.php | <?php
final class DifferentialReplyHandler
extends PhabricatorApplicationTransactionReplyHandler {
public function validateMailReceiver($mail_receiver) {
if (!($mail_receiver instanceof DifferentialRevision)) {
throw new Exception(pht('Receiver is not a %s!', 'DifferentialRevision'));
}
}
public function getObjectPrefix() {
return 'D';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/mail/DifferentialMailView.php | src/applications/differential/mail/DifferentialMailView.php | <?php
abstract class DifferentialMailView
extends Phobject {
protected function renderCodeBlock($block) {
$style = array(
'font: 11px/15px "Menlo", "Consolas", "Monaco", monospace;',
'white-space: pre-wrap;',
'clear: both;',
'padding: 4px 0;',
'margin: 0;',
);
return phutil_tag(
'div',
array(
'style' => implode(' ', $style),
),
$block);
}
protected function renderHeaderBlock($block) {
$style = array(
'color: #74777d;',
'background: #eff2f4;',
'padding: 6px 8px;',
'overflow: hidden;',
);
return phutil_tag(
'div',
array(
'style' => implode(' ', $style),
),
$block);
}
protected function renderHeaderBold($content) {
return phutil_tag(
'span',
array(
'style' => 'color: #4b4d51; font-weight: bold;',
),
$content);
}
protected function renderContentBox($content) {
$style = array(
'border: 1px solid #C7CCD9;',
'border-radius: 3px;',
);
return phutil_tag(
'div',
array(
'style' => implode(' ', $style),
),
$content);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/mail/DifferentialRevisionMailReceiver.php | src/applications/differential/mail/DifferentialRevisionMailReceiver.php | <?php
final class DifferentialRevisionMailReceiver
extends PhabricatorObjectMailReceiver {
public function isEnabled() {
return PhabricatorApplication::isClassInstalled(
'PhabricatorDifferentialApplication');
}
protected function getObjectPattern() {
return 'D[1-9]\d*';
}
protected function loadObject($pattern, PhabricatorUser $viewer) {
$id = (int)substr($pattern, 1);
return id(new DifferentialRevisionQuery())
->setViewer($viewer)
->withIDs(array($id))
->needReviewers(true)
->needReviewerAuthority(true)
->needActiveDiffs(true)
->executeOne();
}
protected function getTransactionReplyHandler() {
return new DifferentialReplyHandler();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/mail/DifferentialInlineCommentMailView.php | src/applications/differential/mail/DifferentialInlineCommentMailView.php | <?php
final class DifferentialInlineCommentMailView
extends DifferentialMailView {
private $viewer;
private $inlines;
private $changesets;
private $authors;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setInlines($inlines) {
$this->inlines = $inlines;
return $this;
}
public function getInlines() {
return $this->inlines;
}
public function buildMailSection() {
$inlines = $this->getInlines();
$comments = mpull($inlines, 'getComment');
$comments = mpull($comments, null, 'getPHID');
$parents = $this->loadParents($comments);
$all_comments = $comments + $parents;
$this->changesets = $this->loadChangesets($all_comments);
$this->authors = $this->loadAuthors($all_comments);
$groups = $this->groupInlines($inlines);
$hunk_parser = new DifferentialHunkParser();
$spacer_text = null;
$spacer_html = phutil_tag('br');
$section = new PhabricatorMetaMTAMailSection();
$last_group_key = last_key($groups);
foreach ($groups as $changeset_id => $group) {
$changeset = $this->getChangeset($changeset_id);
if (!$changeset) {
continue;
}
$is_last_group = ($changeset_id == $last_group_key);
$last_inline_key = last_key($group);
foreach ($group as $inline_key => $inline) {
$comment = $inline->getComment();
$parent_phid = $comment->getReplyToCommentPHID();
$inline_object = $comment->newInlineCommentObject();
$document_engine_key = $inline_object->getDocumentEngineKey();
$is_last_inline = ($inline_key == $last_inline_key);
$context_text = null;
$context_html = null;
if ($parent_phid) {
$parent = idx($parents, $parent_phid);
if ($parent) {
$context_text = $this->renderInline($parent, false, true);
$context_html = $this->renderInline($parent, true, true);
}
} else if ($document_engine_key !== null) {
// See T13513. If an inline was left on a rendered document, don't
// include the patch context. Document engines currently can not
// render to mail targets, and using the line numbers as raw source
// lines produces misleading context.
$patch_text = null;
$context_text = $this->renderPatch($comment, $patch_text, false);
$patch_html = null;
$context_html = $this->renderPatch($comment, $patch_html, true);
} else {
$patch_text = $this->getPatch($hunk_parser, $comment, false);
$context_text = $this->renderPatch($comment, $patch_text, false);
$patch_html = $this->getPatch($hunk_parser, $comment, true);
$context_html = $this->renderPatch($comment, $patch_html, true);
}
$render_text = $this->renderInline($comment, false, false);
$render_html = $this->renderInline($comment, true, false);
$section->addPlaintextFragment($context_text);
$section->addPlaintextFragment($spacer_text);
$section->addPlaintextFragment($render_text);
$html_fragment = $this->renderContentBox(
array(
$context_html,
$render_html,
));
$section->addHTMLFragment($html_fragment);
if (!$is_last_group || !$is_last_inline) {
$section->addPlaintextFragment($spacer_text);
$section->addHTMLFragment($spacer_html);
}
}
}
return $section;
}
private function loadChangesets(array $comments) {
if (!$comments) {
return array();
}
$ids = array();
foreach ($comments as $comment) {
$ids[] = $comment->getChangesetID();
}
$changesets = id(new DifferentialChangesetQuery())
->setViewer($this->getViewer())
->withIDs($ids)
->needHunks(true)
->execute();
return mpull($changesets, null, 'getID');
}
private function loadParents(array $comments) {
$viewer = $this->getViewer();
$phids = array();
foreach ($comments as $comment) {
$parent_phid = $comment->getReplyToCommentPHID();
if (!$parent_phid) {
continue;
}
$phids[] = $parent_phid;
}
if (!$phids) {
return array();
}
$parents = id(new DifferentialDiffInlineCommentQuery())
->setViewer($viewer)
->withPHIDs($phids)
->execute();
return mpull($parents, null, 'getPHID');
}
private function loadAuthors(array $comments) {
$viewer = $this->getViewer();
$phids = array();
foreach ($comments as $comment) {
$author_phid = $comment->getAuthorPHID();
if (!$author_phid) {
continue;
}
$phids[] = $author_phid;
}
if (!$phids) {
return array();
}
return $viewer->loadHandles($phids);
}
private function groupInlines(array $inlines) {
return DifferentialTransactionComment::sortAndGroupInlines(
$inlines,
$this->changesets);
}
private function renderInline(
DifferentialTransactionComment $comment,
$is_html,
$is_quote) {
$changeset = $this->getChangeset($comment->getChangesetID());
if (!$changeset) {
return null;
}
$content = $comment->getContent();
$content = $this->renderRemarkupContent($content, $is_html);
if ($is_quote) {
$header = $this->renderHeader($comment, $is_html, true);
} else {
$header = null;
}
if ($is_html) {
$style = array(
'margin: 8px 0;',
'padding: 0 12px;',
);
if ($is_quote) {
$style[] = 'color: #74777D;';
}
$content = phutil_tag(
'div',
array(
'style' => implode(' ', $style),
),
$content);
}
$parts = array(
$header,
"\n",
$content,
);
if (!$is_html) {
$parts = implode('', $parts);
$parts = trim($parts);
}
if ($is_quote) {
if ($is_html) {
$parts = $this->quoteHTML($parts);
} else {
$parts = $this->quoteText($parts);
}
}
return $parts;
}
private function renderRemarkupContent($content, $is_html) {
$viewer = $this->getViewer();
$production_uri = PhabricatorEnv::getProductionURI('/');
if ($is_html) {
$mode = PhutilRemarkupEngine::MODE_HTML_MAIL;
} else {
$mode = PhutilRemarkupEngine::MODE_TEXT;
}
$attributes = array(
'style' => 'padding: 0; margin: 8px;',
);
$engine = PhabricatorMarkupEngine::newMarkupEngine(array())
->setConfig('viewer', $viewer)
->setConfig('uri.base', $production_uri)
->setConfig('default.p.attributes', $attributes)
->setMode($mode);
try {
return $engine->markupText($content);
} catch (Exception $ex) {
return $content;
}
}
private function getChangeset($id) {
return idx($this->changesets, $id);
}
private function getAuthor($phid) {
if (isset($this->authors[$phid])) {
return $this->authors[$phid];
}
return null;
}
private function quoteText($block) {
$block = phutil_split_lines($block);
foreach ($block as $key => $line) {
$block[$key] = '> '.$line;
}
return implode('', $block);
}
private function quoteHTML($block) {
$styles = array(
'padding: 0;',
'background: #F7F7F7;',
'border-color: #e3e4e8;',
'border-style: solid;',
'border-width: 0 0 1px 0;',
'margin: 0;',
);
$styles = implode(' ', $styles);
return phutil_tag(
'div',
array(
'style' => $styles,
),
$block);
}
private function getPatch(
DifferentialHunkParser $parser,
DifferentialTransactionComment $comment,
$is_html) {
$changeset = $this->getChangeset($comment->getChangesetID());
$is_new = $comment->getIsNewFile();
$start = $comment->getLineNumber();
$length = $comment->getLineLength();
// By default, show one line of context around the target inline.
$context = 1;
// If the inline is at least 3 lines long, don't show any extra context.
if ($length >= 2) {
$context = 0;
}
// If the inline is more than 7 lines long, only show the first 7 lines.
if ($length >= 6) {
$length = 6;
}
if (!$is_html) {
$hunks = $changeset->getHunks();
$patch = $parser->makeContextDiff(
$hunks,
$is_new,
$start,
$length,
$context);
$patch = phutil_split_lines($patch);
// Remove the "@@ -x,y +u,v @@" line.
array_shift($patch);
return implode('', $patch);
}
$viewer = $this->getViewer();
$engine = new PhabricatorMarkupEngine();
if ($is_new) {
$offset_mode = 'new';
} else {
$offset_mode = 'old';
}
// See PHI894. Use the parse cache since we can end up with a large
// rendering cost otherwise when users or bots leave hundreds of inline
// comments on diffs with long recipient lists.
$cache_key = $changeset->getID();
$viewstate = new PhabricatorChangesetViewState();
$parser = id(new DifferentialChangesetParser())
->setRenderCacheKey($cache_key)
->setViewer($viewer)
->setViewstate($viewstate)
->setChangeset($changeset)
->setOffsetMode($offset_mode)
->setMarkupEngine($engine);
$parser->setRenderer(new DifferentialChangesetOneUpMailRenderer());
return $parser->render(
$start - $context,
$length + (2 * $context),
array());
}
private function renderPatch(
DifferentialTransactionComment $comment,
$patch,
$is_html) {
if ($is_html) {
if ($patch !== null) {
$patch = $this->renderCodeBlock($patch);
}
}
$header = $this->renderHeader($comment, $is_html, false);
if ($patch === null) {
$patch = array(
$header,
);
} else {
$patch = array(
$header,
"\n",
$patch,
);
}
if (!$is_html) {
$patch = implode('', $patch);
$patch = $this->quoteText($patch);
} else {
$patch = $this->quoteHTML($patch);
}
return $patch;
}
private function renderHeader(
DifferentialTransactionComment $comment,
$is_html,
$with_author) {
$changeset = $this->getChangeset($comment->getChangesetID());
$path = $changeset->getFilename();
// Only show the filename.
$path = basename($path);
$start = $comment->getLineNumber();
$length = $comment->getLineLength();
if ($length) {
$range = pht('%s-%s', $start, $start + $length);
} else {
$range = $start;
}
$header = "{$path}:{$range}";
if ($is_html) {
$header = $this->renderHeaderBold($header);
}
if ($with_author) {
$author = $this->getAuthor($comment->getAuthorPHID());
} else {
$author = null;
}
if ($author) {
$byline = $author->getName();
if ($is_html) {
$byline = $this->renderHeaderBold($byline);
}
$header = pht('%s wrote in %s', $byline, $header);
}
if ($is_html) {
$link_href = $this->getInlineURI($comment);
if ($link_href) {
$link_style = array(
'float: right;',
'text-decoration: none;',
);
$link = phutil_tag(
'a',
array(
'style' => implode(' ', $link_style),
'href' => $link_href,
),
array(
pht('View Inline'),
// See PHI920. Add a space after the link so we render this into
// the document:
//
// View Inline filename.txt
//
// Otherwise, we render "Inlinefilename.txt" and double-clicking
// the file name selects the word "Inline" as well.
' ',
));
} else {
$link = null;
}
$header = $this->renderHeaderBlock(array($link, $header));
}
return $header;
}
private function getInlineURI(DifferentialTransactionComment $comment) {
$changeset = $this->getChangeset($comment->getChangesetID());
if (!$changeset) {
return null;
}
$diff = $changeset->getDiff();
if (!$diff) {
return null;
}
$revision = $diff->getRevision();
if (!$revision) {
return null;
}
$link_href = '/'.$revision->getMonogram().'#inline-'.$comment->getID();
$link_href = PhabricatorEnv::getProductionURI($link_href);
return $link_href;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/command/DifferentialActionEmailCommand.php | src/applications/differential/command/DifferentialActionEmailCommand.php | <?php
final class DifferentialActionEmailCommand
extends MetaMTAEmailTransactionCommand {
private $command;
private $action;
private $aliases;
private $commandSummary;
private $commandDescription;
public function getCommand() {
return $this->command;
}
private function setCommand($command) {
$this->command = $command;
return $this;
}
private function setAction($action) {
$this->action = $action;
return $this;
}
private function getAction() {
return $this->action;
}
private function setCommandAliases(array $aliases) {
$this->aliases = $aliases;
return $this;
}
public function getCommandAliases() {
return $this->aliases;
}
public function setCommandSummary($command_summary) {
$this->commandSummary = $command_summary;
return $this;
}
public function getCommandSummary() {
return $this->commandSummary;
}
public function setCommandDescription($command_description) {
$this->commandDescription = $command_description;
return $this;
}
public function getCommandDescription() {
return $this->commandDescription;
}
public function getCommandObjects() {
$actions = DifferentialRevisionActionTransaction::loadAllActions();
$actions = msortv($actions, 'getRevisionActionOrderVector');
$objects = array();
foreach ($actions as $action) {
$keyword = $action->getCommandKeyword();
if ($keyword === null) {
continue;
}
$aliases = $action->getCommandAliases();
$summary = $action->getCommandSummary();
$object = id(new self())
->setCommand($keyword)
->setCommandAliases($aliases)
->setAction($action->getTransactionTypeConstant())
->setCommandSummary($summary);
$objects[] = $object;
}
return $objects;
}
public function isCommandSupportedForObject(
PhabricatorApplicationTransactionInterface $object) {
return ($object instanceof DifferentialRevision);
}
public function buildTransactions(
PhabricatorUser $viewer,
PhabricatorApplicationTransactionInterface $object,
PhabricatorMetaMTAReceivedMail $mail,
$command,
array $argv) {
$xactions = array();
$xactions[] = $object->getApplicationTransactionTemplate()
->setTransactionType($this->getAction())
->setNewValue(true);
return $xactions;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialPathField.php | src/applications/differential/customfield/DifferentialPathField.php | <?php
final class DifferentialPathField
extends DifferentialCustomField {
public function getFieldKey() {
return 'differential:path';
}
public function getFieldName() {
return pht('Path');
}
public function getFieldDescription() {
return pht('Shows the local path where the diff came from.');
}
public function shouldDisableByDefault() {
return true;
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewValue(array $handles) {
return null;
}
public function shouldAppearInDiffPropertyView() {
return true;
}
public function renderDiffPropertyViewLabel(DifferentialDiff $diff) {
return $this->getFieldName();
}
public function renderDiffPropertyViewValue(DifferentialDiff $diff) {
$path = $diff->getSourcePath();
if (!$path) {
return null;
}
return $path;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialAuditorsField.php | src/applications/differential/customfield/DifferentialAuditorsField.php | <?php
final class DifferentialAuditorsField
extends DifferentialStoredCustomField {
public function getFieldKey() {
return 'phabricator:auditors';
}
public function getFieldName() {
return pht('Auditors');
}
public function getFieldDescription() {
return pht('Allows commits to trigger audits explicitly.');
}
public function getValueForStorage() {
return phutil_json_encode($this->getValue());
}
public function setValueFromStorage($value) {
try {
$this->setValue(phutil_json_decode($value));
} catch (PhutilJSONParserException $ex) {
$this->setValue(array());
}
return $this;
}
public function canDisableField() {
return false;
}
public function shouldAppearInEditEngine() {
return true;
}
public function shouldAppearInConduitTransactions() {
return true;
}
protected function newConduitEditParameterType() {
return new ConduitPHIDListParameterType();
}
public function shouldAppearInApplicationTransactions() {
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/differential/customfield/DifferentialHostField.php | src/applications/differential/customfield/DifferentialHostField.php | <?php
final class DifferentialHostField
extends DifferentialCustomField {
public function getFieldKey() {
return 'differential:host';
}
public function getFieldName() {
return pht('Host');
}
public function getFieldDescription() {
return pht('Shows the local host where the diff came from.');
}
public function shouldDisableByDefault() {
return true;
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewValue(array $handles) {
return null;
}
public function shouldAppearInDiffPropertyView() {
return true;
}
public function renderDiffPropertyViewLabel(DifferentialDiff $diff) {
return $this->getFieldName();
}
public function renderDiffPropertyViewValue(DifferentialDiff $diff) {
$host = $diff->getSourceMachine();
if (!$host) {
return null;
}
return $host;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialRepositoryField.php | src/applications/differential/customfield/DifferentialRepositoryField.php | <?php
final class DifferentialRepositoryField
extends DifferentialCoreCustomField {
public function getFieldKey() {
return 'differential:repository';
}
public function getFieldName() {
return pht('Repository');
}
public function getFieldDescription() {
return pht('Associates a revision with a repository.');
}
protected function readValueFromRevision(
DifferentialRevision $revision) {
return $revision->getRepositoryPHID();
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewValue(array $handles) {
return null;
}
public function shouldAppearInDiffPropertyView() {
return true;
}
public function renderDiffPropertyViewLabel(DifferentialDiff $diff) {
return $this->getFieldName();
}
public function renderDiffPropertyViewValue(DifferentialDiff $diff) {
if (!$diff->getRepositoryPHID()) {
return null;
}
return $this->getViewer()->renderHandle($diff->getRepositoryPHID());
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
$repository = $this->getObject()->getRepository();
if ($repository === null) {
return;
}
$body->addTextSection(
pht('REPOSITORY'),
$repository->getMonogram().' '.$repository->getName());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialRequiredSignaturesField.php | src/applications/differential/customfield/DifferentialRequiredSignaturesField.php | <?php
final class DifferentialRequiredSignaturesField
extends DifferentialCoreCustomField {
public function getFieldKey() {
return 'differential:required-signatures';
}
public function getFieldName() {
return pht('Required Signatures');
}
public function getFieldDescription() {
return pht('Display required legal agreements.');
}
public function shouldAppearInPropertyView() {
return true;
}
protected function readValueFromRevision(DifferentialRevision $revision) {
return self::loadForRevision($revision);
}
public static function loadForRevision($revision) {
$app_legalpad = 'PhabricatorLegalpadApplication';
if (!PhabricatorApplication::isClassInstalled($app_legalpad)) {
return array();
}
if (!$revision->getPHID()) {
return array();
}
$phids = PhabricatorEdgeQuery::loadDestinationPHIDs(
$revision->getPHID(),
LegalpadObjectNeedsSignatureEdgeType::EDGECONST);
if ($phids) {
// NOTE: We're bypassing permissions to pull these. We have to expose
// some information about signature status in order to implement this
// field meaningfully (otherwise, we could not tell reviewers that they
// can't accept the revision yet), but that's OK because the only way to
// require signatures is with a "Global" Herald rule, which requires a
// high level of access.
$signatures = id(new LegalpadDocumentSignatureQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withDocumentPHIDs($phids)
->withSignerPHIDs(array($revision->getAuthorPHID()))
->execute();
$signatures = mpull($signatures, null, 'getDocumentPHID');
$phids = array_fuse($phids);
foreach ($phids as $phid) {
$phids[$phid] = isset($signatures[$phid]);
}
}
return $phids;
}
public function getRequiredHandlePHIDsForPropertyView() {
return array_keys($this->getValue());
}
public function renderPropertyViewValue(array $handles) {
if (!$handles) {
return null;
}
$author_phid = $this->getObject()->getAuthorPHID();
$viewer_phid = $this->getViewer()->getPHID();
$viewer_is_author = ($author_phid == $viewer_phid);
$view = new PHUIStatusListView();
foreach ($handles as $handle) {
$item = id(new PHUIStatusItemView())
->setTarget($handle->renderLink());
// NOTE: If the viewer isn't the author, we just show generic document
// icons, because the granular information isn't very useful and there
// is no need to disclose it.
// If the viewer is the author, we show exactly what they need to sign.
if (!$viewer_is_author) {
$item->setIcon('fa-file-text-o bluegrey');
} else {
if (idx($this->getValue(), $handle->getPHID())) {
$item->setIcon('fa-check-square-o green');
} else {
$item->setIcon('fa-times red');
}
}
$view->addItem($item);
}
return $view;
}
public function getWarningsForDetailView() {
if (!$this->haveAnyUnsignedDocuments()) {
return array();
}
return array(
pht(
'The author of this revision has not signed all the required '.
'legal documents. The revision can not be accepted until the '.
'documents are signed.'),
);
}
private function haveAnyUnsignedDocuments() {
foreach ($this->getValue() as $phid => $signed) {
if (!$signed) {
return true;
}
}
return false;
}
public function getWarningsForRevisionHeader(array $handles) {
if (!$this->haveAnyUnsignedDocuments()) {
return array();
}
return array(
pht(
'This revision can not be accepted until the required legal '.
'agreements have been signed.'),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialHarbormasterField.php | src/applications/differential/customfield/DifferentialHarbormasterField.php | <?php
abstract class DifferentialHarbormasterField
extends DifferentialCustomField {
abstract protected function getDiffPropertyKeys();
abstract protected function loadHarbormasterTargetMessages(
array $target_phids);
abstract protected function getLegacyProperty();
abstract protected function newModernMessage(array $message);
abstract protected function renderHarbormasterStatus(
DifferentialDiff $diff,
array $messages);
abstract protected function newHarbormasterMessageView(array $messages);
public function renderDiffPropertyViewValue(DifferentialDiff $diff) {
// TODO: This load is slightly inefficient, but most of this is moving
// to Harbormaster and this simplifies the transition. Eat 1-2 extra
// queries for now.
$keys = $this->getDiffPropertyKeys();
$properties = id(new DifferentialDiffProperty())->loadAllWhere(
'diffID = %d AND name IN (%Ls)',
$diff->getID(),
$keys);
$properties = mpull($properties, 'getData', 'getName');
foreach ($keys as $key) {
$diff->attachProperty($key, idx($properties, $key));
}
$target_phids = $diff->getBuildTargetPHIDs();
if ($target_phids) {
$messages = $this->loadHarbormasterTargetMessages($target_phids);
} else {
$messages = array();
}
if (!$messages) {
// No Harbormaster messages, so look for legacy messages and make them
// look like modern messages.
$legacy_messages = $diff->getProperty($this->getLegacyProperty());
if ($legacy_messages) {
// Show the top 100 legacy lint messages. Previously, we showed some
// by default and let the user toggle the rest. With modern messages,
// we can send the user to the Harbormaster detail page. Just show
// "a lot" of messages in legacy cases to try to strike a balance
// between implementation simplicity and compatibility.
$legacy_messages = array_slice($legacy_messages, 0, 100);
foreach ($legacy_messages as $message) {
try {
$modern = $this->newModernMessage($message);
$messages[] = $modern;
} catch (Exception $ex) {
// Ignore any poorly formatted messages.
}
}
}
}
$status = $this->renderHarbormasterStatus($diff, $messages);
if ($messages) {
$path_map = mpull($diff->loadChangesets(), 'getID', 'getFilename');
foreach ($path_map as $path => $id) {
$href = '#C'.$id.'NL';
// TODO: When the diff is not the right-hand-size diff, we should
// ideally adjust this URI to be absolute.
$path_map[$path] = $href;
}
$view = $this->newHarbormasterMessageView($messages);
if ($view) {
$view->setPathURIMap($path_map);
}
} else {
$view = null;
}
if ($view) {
$view = phutil_tag(
'div',
array(
'class' => 'differential-harbormaster-table-view',
),
$view);
}
return array(
$status,
$view,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialReviewersField.php | src/applications/differential/customfield/DifferentialReviewersField.php | <?php
final class DifferentialReviewersField
extends DifferentialCoreCustomField {
public function getFieldKey() {
return 'differential:reviewers';
}
public function getFieldName() {
return pht('Reviewers');
}
public function getFieldDescription() {
return pht('Manage reviewers.');
}
protected function readValueFromRevision(
DifferentialRevision $revision) {
return $revision->getReviewers();
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function getRequiredHandlePHIDsForPropertyView() {
return mpull($this->getUserReviewers(), 'getReviewerPHID');
}
public function renderPropertyViewValue(array $handles) {
$reviewers = $this->getUserReviewers();
if (!$reviewers) {
return phutil_tag('em', array(), pht('None'));
}
$view = id(new DifferentialReviewersView())
->setUser($this->getViewer())
->setReviewers($reviewers)
->setHandles($handles);
$diff = $this->getActiveDiff();
if ($diff) {
$view->setActiveDiff($diff);
}
return $view;
}
private function getUserReviewers() {
$reviewers = array();
foreach ($this->getObject()->getReviewers() as $reviewer) {
if ($reviewer->isUser()) {
$reviewers[] = $reviewer;
}
}
return $reviewers;
}
public function getRequiredHandlePHIDsForRevisionHeaderWarnings() {
return mpull($this->getValue(), 'getReviewerPHID');
}
public function getWarningsForRevisionHeader(array $handles) {
$revision = $this->getObject();
if (!$revision->isNeedsReview()) {
return array();
}
$viewer = $this->getViewer();
PhabricatorPolicyFilterSet::loadHandleViewCapabilities(
$viewer,
$handles,
array($revision));
$all_resigned = true;
$all_disabled = true;
$any_reviewers = false;
$all_exiled = true;
foreach ($this->getValue() as $reviewer) {
$reviewer_phid = $reviewer->getReviewerPHID();
$handle = $handles[$reviewer_phid];
$any_reviewers = true;
if (!$handle->isDisabled()) {
$all_disabled = false;
}
if (!$reviewer->isResigned()) {
$all_resigned = false;
}
if (!$handle->hasCapabilities()) {
$all_exiled = false;
} else {
if ($handle->hasViewCapability($revision)) {
$all_exiled = false;
}
}
}
$warnings = array();
if (!$any_reviewers) {
$warnings[] = pht(
'This revision needs review, but there are no reviewers specified.');
} else if ($all_disabled) {
$warnings[] = pht(
'This revision needs review, but all specified reviewers are '.
'disabled or inactive.');
} else if ($all_resigned) {
$warnings[] = pht(
'This revision needs review, but all reviewers have resigned.');
} else if ($all_exiled) {
$warnings[] = pht(
'This revision needs review, but no reviewers have permission '.
'to view it.');
}
return $warnings;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialDraftField.php | src/applications/differential/customfield/DifferentialDraftField.php | <?php
final class DifferentialDraftField
extends DifferentialCoreCustomField {
public function getFieldKey() {
return 'differential:draft';
}
public function getFieldName() {
return pht('Draft');
}
public function getFieldDescription() {
return pht('Show a warning about draft revisions.');
}
protected function readValueFromRevision(
DifferentialRevision $revision) {
return null;
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewValue(array $handles) {
return null;
}
public function getWarningsForRevisionHeader(array $handles) {
$viewer = $this->getViewer();
$revision = $this->getObject();
if (!$revision->isDraft()) {
return array();
}
// If the author has held this revision as a draft explicitly, don't
// show any misleading messages about it autosubmitting later. We do show
// reminder text.
if ($revision->getHoldAsDraft()) {
return array(
pht(
'This is a draft revision that has not yet been submitted for '.
'review.'),
);
}
$warnings = array();
$blocking_map = array(
HarbormasterBuildStatus::STATUS_FAILED,
HarbormasterBuildStatus::STATUS_ABORTED,
HarbormasterBuildStatus::STATUS_ERROR,
HarbormasterBuildStatus::STATUS_PAUSED,
HarbormasterBuildStatus::STATUS_DEADLOCKED,
);
$blocking_map = array_fuse($blocking_map);
$builds = $revision->loadImpactfulBuilds($viewer);
$waiting = array();
$blocking = array();
foreach ($builds as $build) {
if (isset($blocking_map[$build->getBuildStatus()])) {
$blocking[] = $build;
} else {
$waiting[] = $build;
}
}
$blocking_list = $viewer->renderHandleList(mpull($blocking, 'getPHID'))
->setAsInline(true);
$waiting_list = $viewer->renderHandleList(mpull($waiting, 'getPHID'))
->setAsInline(true);
if ($blocking) {
$warnings[] = pht(
'This draft revision will not be submitted for review because %s '.
'build(s) failed: %s.',
phutil_count($blocking),
$blocking_list);
$warnings[] = pht(
'Fix build failures and update the revision.');
} else if ($waiting) {
$warnings[] = pht(
'This draft revision will be sent for review once %s '.
'build(s) pass: %s.',
phutil_count($waiting),
$waiting_list);
} else {
$warnings[] = pht(
'This is a draft revision that has not yet been submitted for '.
'review.');
}
return $warnings;
}
public function getWarningsForDetailView() {
$revision = $this->getObject();
if ($revision->getShouldBroadcast()) {
return array();
}
return array(
pht(
'This revision is currently a draft. You can leave comments, but '.
'no one will be notified until the revision is submitted for '.
'review.'),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialLintField.php | src/applications/differential/customfield/DifferentialLintField.php | <?php
final class DifferentialLintField
extends DifferentialHarbormasterField {
public function getFieldKey() {
return 'differential:lint';
}
public function getFieldName() {
return pht('Lint');
}
public function getFieldDescription() {
return pht('Shows lint results.');
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewValue(array $handles) {
return null;
}
public function shouldAppearInDiffPropertyView() {
return true;
}
public function renderDiffPropertyViewLabel(DifferentialDiff $diff) {
return $this->getFieldName();
}
protected function getLegacyProperty() {
return 'arc:lint';
}
protected function getDiffPropertyKeys() {
return array(
'arc:lint',
);
}
protected function loadHarbormasterTargetMessages(array $target_phids) {
return id(new HarbormasterBuildLintMessage())->loadAllWhere(
'buildTargetPHID IN (%Ls) LIMIT 25',
$target_phids);
}
protected function newHarbormasterMessageView(array $messages) {
return id(new HarbormasterLintPropertyView())
->setLimit(25)
->setLintMessages($messages);
}
protected function newModernMessage(array $message) {
return HarbormasterBuildLintMessage::newFromDictionary(
new HarbormasterBuildTarget(),
$this->getModernLintMessageDictionary($message));
}
public function getWarningsForDetailView() {
$status = $this->getObject()->getActiveDiff()->getLintStatus();
if ($status < DifferentialLintStatus::LINT_WARN) {
return array();
}
if ($status == DifferentialLintStatus::LINT_AUTO_SKIP) {
return array();
}
$warnings = array();
if ($status == DifferentialLintStatus::LINT_SKIP) {
$warnings[] = pht(
'Lint was skipped when generating these changes.');
} else {
$warnings[] = pht('These changes have lint problems.');
}
return $warnings;
}
protected function renderHarbormasterStatus(
DifferentialDiff $diff,
array $messages) {
$status_value = $diff->getLintStatus();
$status = DifferentialLintStatus::newStatusFromValue($status_value);
$status_icon = $status->getIconIcon();
$status_color = $status->getIconColor();
$status_name = $status->getName();
$status = id(new PHUIStatusListView())
->addItem(
id(new PHUIStatusItemView())
->setIcon($status_icon, $status_color)
->setTarget($status_name));
return $status;
}
private function getModernLintMessageDictionary(array $map) {
// Strip out `null` values to satisfy stricter typechecks.
foreach ($map as $key => $value) {
if ($value === null) {
unset($map[$key]);
}
}
// TODO: We might need to remap some stuff here?
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/differential/customfield/DifferentialAsanaRepresentationField.php | src/applications/differential/customfield/DifferentialAsanaRepresentationField.php | <?php
final class DifferentialAsanaRepresentationField
extends DifferentialCustomField {
public function getFieldKey() {
return 'differential:asana-representation';
}
public function getFieldName() {
return pht('In Asana');
}
public function canDisableField() {
return false;
}
public function getFieldDescription() {
return pht('Shows revision representation in Asana.');
}
public function shouldAppearInPropertyView() {
return (bool)PhabricatorEnv::getEnvConfig('asana.workspace-id');
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function renderPropertyViewValue(array $handles) {
$viewer = $this->getViewer();
$src_phid = $this->getObject()->getPHID();
$edge_type = PhabricatorObjectHasAsanaTaskEdgeType::EDGECONST;
$query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(array($src_phid))
->withEdgeTypes(array($edge_type))
->needEdgeData(true);
$edges = $query->execute();
if (!$edges) {
return null;
}
$edge = head($edges[$src_phid][$edge_type]);
if (!$edge) {
return null;
}
if (!empty($edge['data']['gone'])) {
return phutil_tag(
'em',
array(),
pht('Asana Task Deleted'));
}
$ref = id(new DoorkeeperImportEngine())
->setViewer($viewer)
->withPHIDs(array($edge['dst']))
->needLocalOnly(true)
->executeOne();
if (!$ref) {
return null;
}
return id(new DoorkeeperTagView())
->setExternalObject($ref->getExternalObject());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialTestPlanField.php | src/applications/differential/customfield/DifferentialTestPlanField.php | <?php
final class DifferentialTestPlanField
extends DifferentialCoreCustomField {
public function getFieldKey() {
return 'differential:test-plan';
}
public function getFieldName() {
return pht('Test Plan');
}
public function getFieldDescription() {
return pht('Actions performed to verify the behavior of the change.');
}
protected function readValueFromRevision(
DifferentialRevision $revision) {
if (!$revision->getID()) {
return null;
}
return $revision->getTestPlan();
}
public function canDisableField() {
return true;
}
public function shouldAppearInGlobalSearch() {
return true;
}
public function updateAbstractDocument(
PhabricatorSearchAbstractDocument $document) {
if (strlen($this->getValue())) {
$document->addField('plan', $this->getValue());
}
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function getStyleForPropertyView() {
return 'block';
}
public function getIconForPropertyView() {
return PHUIPropertyListView::ICON_TESTPLAN;
}
public function renderPropertyViewValue(array $handles) {
if (!strlen($this->getValue())) {
return null;
}
return new PHUIRemarkupView($this->getViewer(), $this->getValue());
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
if (!$editor->isFirstBroadcast()) {
return;
}
$test_plan = $this->getValue();
if (!strlen(trim($test_plan))) {
return;
}
$body->addRemarkupSection(pht('TEST PLAN'), $test_plan);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialCustomField.php | src/applications/differential/customfield/DifferentialCustomField.php | <?php
/**
* @task commitmessage Integration with Commit Messages
* @task diff Integration with Diff Properties
*/
abstract class DifferentialCustomField
extends PhabricatorCustomField {
/**
* TODO: It would be nice to remove this, but a lot of different code is
* bound together by it. Until everything is modernized, retaining the old
* field keys is the only reasonable way to update things one piece
* at a time.
*/
public function getFieldKeyForConduit() {
return $this->getFieldKey();
}
// TODO: As above.
public function getModernFieldKey() {
return $this->getFieldKeyForConduit();
}
protected function parseObjectList(
$value,
array $types,
$allow_partial = false,
array $suffixes = array()) {
return id(new PhabricatorObjectListQuery())
->setViewer($this->getViewer())
->setAllowedTypes($types)
->setObjectList($value)
->setAllowPartialResults($allow_partial)
->setSuffixes($suffixes)
->execute();
}
protected function renderObjectList(
array $handles,
array $suffixes = array()) {
if (!$handles) {
return null;
}
$out = array();
foreach ($handles as $handle) {
$phid = $handle->getPHID();
if ($handle->getPolicyFiltered()) {
$token = $phid;
} else if ($handle->isComplete()) {
$token = $handle->getCommandLineObjectName();
}
$suffix = idx($suffixes, $phid);
$token = $token.$suffix;
$out[] = $token;
}
return implode(', ', $out);
}
public function getWarningsForDetailView() {
if ($this->getProxy()) {
return $this->getProxy()->getWarningsForDetailView();
}
return array();
}
protected function getActiveDiff() {
$object = $this->getObject();
try {
return $object->getActiveDiff();
} catch (Exception $ex) {
return null;
}
}
public function getRequiredHandlePHIDsForRevisionHeaderWarnings() {
return array();
}
public function getWarningsForRevisionHeader(array $handles) {
return array();
}
/* -( Integration with Commit Messages )----------------------------------- */
/**
* @task commitmessage
*/
public function getProTips() {
if ($this->getProxy()) {
return $this->getProxy()->getProTips();
}
return array();
}
/* -( Integration with Diff Properties )----------------------------------- */
/**
* @task diff
*/
public function shouldAppearInDiffPropertyView() {
if ($this->getProxy()) {
return $this->getProxy()->shouldAppearInDiffPropertyView();
}
return false;
}
/**
* @task diff
*/
public function renderDiffPropertyViewLabel(DifferentialDiff $diff) {
if ($this->getProxy()) {
return $this->getProxy()->renderDiffPropertyViewLabel($diff);
}
return $this->getFieldName();
}
/**
* @task diff
*/
public function renderDiffPropertyViewValue(DifferentialDiff $diff) {
if ($this->getProxy()) {
return $this->getProxy()->renderDiffPropertyViewValue($diff);
}
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialSummaryField.php | src/applications/differential/customfield/DifferentialSummaryField.php | <?php
final class DifferentialSummaryField
extends DifferentialCoreCustomField {
public function getFieldKey() {
return 'differential:summary';
}
public function getFieldName() {
return pht('Summary');
}
public function getFieldDescription() {
return pht('Stores a summary of the revision.');
}
protected function readValueFromRevision(
DifferentialRevision $revision) {
if (!$revision->getID()) {
return null;
}
return $revision->getSummary();
}
public function shouldAppearInGlobalSearch() {
return true;
}
public function updateAbstractDocument(
PhabricatorSearchAbstractDocument $document) {
if (strlen($this->getValue())) {
$document->addField('body', $this->getValue());
}
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function getStyleForPropertyView() {
return 'block';
}
public function getIconForPropertyView() {
return PHUIPropertyListView::ICON_SUMMARY;
}
public function renderPropertyViewValue(array $handles) {
if (!strlen($this->getValue())) {
return null;
}
return new PHUIRemarkupView($this->getViewer(), $this->getValue());
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
if (!$editor->isFirstBroadcast()) {
return;
}
$summary = $this->getValue();
if (!strlen(trim($summary))) {
return;
}
$body->addRemarkupSection(pht('REVISION SUMMARY'), $summary);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialBlameRevisionField.php | src/applications/differential/customfield/DifferentialBlameRevisionField.php | <?php
final class DifferentialBlameRevisionField
extends DifferentialStoredCustomField {
public function getFieldKey() {
return 'phabricator:blame-revision';
}
public function getFieldKeyForConduit() {
return 'blameRevision';
}
public function getFieldName() {
return pht('Blame Revision');
}
public function getFieldDescription() {
return pht('Stores a reference to what this fixes.');
}
public function shouldDisableByDefault() {
return true;
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function renderPropertyViewValue(array $handles) {
if (!strlen($this->getValue())) {
return null;
}
return $this->getValue();
}
public function shouldAppearInEditView() {
return true;
}
public function shouldAppearInApplicationTransactions() {
return true;
}
public function getOldValueForApplicationTransactions() {
return $this->getValue();
}
public function getNewValueForApplicationTransactions() {
return $this->getValue();
}
public function readValueFromRequest(AphrontRequest $request) {
$this->setValue($request->getStr($this->getFieldKey()));
}
public function renderEditControl(array $handles) {
return id(new AphrontFormTextControl())
->setName($this->getFieldKey())
->setValue($this->getValue())
->setLabel($this->getFieldName());
}
public function getApplicationTransactionTitle(
PhabricatorApplicationTransaction $xaction) {
$author_phid = $xaction->getAuthorPHID();
$old = $xaction->getOldValue();
$new = $xaction->getNewValue();
return pht(
'%s updated the blame revision for this revision.',
$xaction->renderHandleLink($author_phid));
}
public function getApplicationTransactionTitleForFeed(
PhabricatorApplicationTransaction $xaction) {
$object_phid = $xaction->getObjectPHID();
$author_phid = $xaction->getAuthorPHID();
$old = $xaction->getOldValue();
$new = $xaction->getNewValue();
return pht(
'%s updated the blame revision for %s.',
$xaction->renderHandleLink($author_phid),
$xaction->renderHandleLink($object_phid));
}
public function shouldAppearInConduitDictionary() {
return true;
}
public function shouldAppearInConduitTransactions() {
return true;
}
protected function newConduitEditParameterType() {
return new ConduitStringParameterType();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialStoredCustomField.php | src/applications/differential/customfield/DifferentialStoredCustomField.php | <?php
abstract class DifferentialStoredCustomField
extends DifferentialCustomField {
private $value;
public function setValue($value) {
$this->value = $value;
return $this;
}
public function getValue() {
return $this->value;
}
public function shouldUseStorage() {
return true;
}
public function newStorageObject() {
return new DifferentialCustomFieldStorage();
}
protected function newStringIndexStorage() {
return new DifferentialCustomFieldStringIndex();
}
protected function newNumericIndexStorage() {
return new DifferentialCustomFieldNumericIndex();
}
public function getValueForStorage() {
return $this->value;
}
public function setValueFromStorage($value) {
$this->value = $value;
return $this;
}
public function setValueFromApplicationTransactions($value) {
$this->setValue($value);
return $this;
}
public function getConduitDictionaryValue() {
return $this->getValue();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialProjectReviewersField.php | src/applications/differential/customfield/DifferentialProjectReviewersField.php | <?php
final class DifferentialProjectReviewersField
extends DifferentialCustomField {
public function getFieldKey() {
return 'differential:project-reviewers';
}
public function getFieldName() {
return pht('Group Reviewers');
}
public function getFieldDescription() {
return pht('Display project reviewers.');
}
public function shouldAppearInPropertyView() {
return true;
}
public function canDisableField() {
return false;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function getRequiredHandlePHIDsForPropertyView() {
return mpull($this->getProjectReviewers(), 'getReviewerPHID');
}
public function renderPropertyViewValue(array $handles) {
$reviewers = $this->getProjectReviewers();
if (!$reviewers) {
return null;
}
$view = id(new DifferentialReviewersView())
->setUser($this->getViewer())
->setReviewers($reviewers)
->setHandles($handles);
$diff = $this->getActiveDiff();
if ($diff) {
$view->setActiveDiff($diff);
}
return $view;
}
private function getProjectReviewers() {
$reviewers = array();
foreach ($this->getObject()->getReviewers() as $reviewer) {
if (!$reviewer->isUser()) {
$reviewers[] = $reviewer;
}
}
return $reviewers;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialBranchField.php | src/applications/differential/customfield/DifferentialBranchField.php | <?php
final class DifferentialBranchField
extends DifferentialCustomField {
public function getFieldKey() {
return 'differential:branch';
}
public function getFieldName() {
return pht('Branch');
}
public function getFieldDescription() {
return pht('Shows the branch a diff came from.');
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewValue(array $handles) {
return null;
}
public function shouldAppearInDiffPropertyView() {
return true;
}
public function renderDiffPropertyViewLabel(DifferentialDiff $diff) {
return $this->getFieldName();
}
public function renderDiffPropertyViewValue(DifferentialDiff $diff) {
return $this->getBranchDescription($diff);
}
private function getBranchDescription(DifferentialDiff $diff) {
$branch = $diff->getBranch();
$bookmark = $diff->getBookmark();
if ($branch === null) {
$branch = '';
}
if ($bookmark === null) {
$bookmark = '';
}
if (strlen($branch) && strlen($bookmark)) {
return pht('%s (bookmark) on %s (branch)', $bookmark, $branch);
} else if (strlen($bookmark)) {
return pht('%s (bookmark)', $bookmark);
} else if (strlen($branch)) {
$onto = $diff->loadTargetBranch();
if ($onto !== null && strlen($onto) && ($onto !== $branch)) {
return pht(
'%s (branched from %s)',
$branch,
$onto);
} else {
return $branch;
}
} else {
return null;
}
}
public function getProTips() {
return array(
pht(
'In Git and Mercurial, use a branch like "%s" to automatically '.
'associate changes with the corresponding task.',
'T123'),
);
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
$revision = $this->getObject();
// Show the "BRANCH" section only if there's a new diff or the revision
// is "Accepted".
$is_update = (bool)$editor->getDiffUpdateTransaction($xactions);
$is_accepted = $revision->isAccepted();
if (!$is_update && !$is_accepted) {
return;
}
$branch = $this->getBranchDescription($revision->getActiveDiff());
if ($branch === null) {
return;
}
$body->addTextSection(pht('BRANCH'), $branch);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialJIRAIssuesField.php | src/applications/differential/customfield/DifferentialJIRAIssuesField.php | <?php
final class DifferentialJIRAIssuesField
extends DifferentialStoredCustomField {
private $error;
public function getFieldKey() {
return 'phabricator:jira-issues';
}
public function getFieldKeyForConduit() {
return 'jira.issues';
}
public function isFieldEnabled() {
return (bool)PhabricatorJIRAAuthProvider::getJIRAProvider();
}
public function canDisableField() {
return false;
}
public function getValueForStorage() {
return json_encode($this->getValue());
}
public function setValueFromStorage($value) {
try {
$this->setValue(phutil_json_decode($value));
} catch (PhutilJSONParserException $ex) {
$this->setValue(array());
}
return $this;
}
public function getFieldName() {
return pht('JIRA Issues');
}
public function getFieldDescription() {
return pht('Lists associated JIRA issues.');
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function renderPropertyViewValue(array $handles) {
$xobjs = $this->loadDoorkeeperExternalObjects($this->getValue());
if (!$xobjs) {
return null;
}
$links = array();
foreach ($xobjs as $xobj) {
$links[] = id(new DoorkeeperTagView())
->setExternalObject($xobj);
}
return phutil_implode_html(phutil_tag('br'), $links);
}
private function buildDoorkeeperRefs($value) {
$provider = PhabricatorJIRAAuthProvider::getJIRAProvider();
$refs = array();
if ($value) {
foreach ($value as $jira_key) {
$refs[] = id(new DoorkeeperObjectRef())
->setApplicationType(DoorkeeperBridgeJIRA::APPTYPE_JIRA)
->setApplicationDomain($provider->getProviderDomain())
->setObjectType(DoorkeeperBridgeJIRA::OBJTYPE_ISSUE)
->setObjectID($jira_key);
}
}
return $refs;
}
private function loadDoorkeeperExternalObjects($value) {
$refs = $this->buildDoorkeeperRefs($value);
if (!$refs) {
return array();
}
$xobjs = id(new DoorkeeperExternalObjectQuery())
->setViewer($this->getViewer())
->withObjectKeys(mpull($refs, 'getObjectKey'))
->execute();
return $xobjs;
}
public function shouldAppearInEditView() {
return PhabricatorJIRAAuthProvider::getJIRAProvider();
}
public function shouldAppearInApplicationTransactions() {
return PhabricatorJIRAAuthProvider::getJIRAProvider();
}
public function readValueFromRequest(AphrontRequest $request) {
$this->setValue($request->getStrList($this->getFieldKey()));
return $this;
}
public function renderEditControl(array $handles) {
return id(new AphrontFormTextControl())
->setLabel(pht('JIRA Issues'))
->setCaption(
pht('Example: %s', phutil_tag('tt', array(), 'JIS-3, JIS-9')))
->setName($this->getFieldKey())
->setValue(implode(', ', nonempty($this->getValue(), array())))
->setError($this->error);
}
public function getOldValueForApplicationTransactions() {
return array_unique(nonempty($this->getValue(), array()));
}
public function getNewValueForApplicationTransactions() {
return array_unique(nonempty($this->getValue(), array()));
}
public function validateApplicationTransactions(
PhabricatorApplicationTransactionEditor $editor,
$type,
array $xactions) {
$this->error = null;
$errors = parent::validateApplicationTransactions(
$editor,
$type,
$xactions);
$transaction = null;
foreach ($xactions as $xaction) {
$old = $xaction->getOldValue();
$new = $xaction->getNewValue();
$add = array_diff($new, $old);
if (!$add) {
continue;
}
// Only check that the actor can see newly added JIRA refs. You're
// allowed to remove refs or make no-op changes even if you aren't
// linked to JIRA.
try {
$refs = id(new DoorkeeperImportEngine())
->setViewer($this->getViewer())
->setRefs($this->buildDoorkeeperRefs($add))
->setThrowOnMissingLink(true)
->execute();
} catch (DoorkeeperMissingLinkException $ex) {
$this->error = pht('Not Linked');
$errors[] = new PhabricatorApplicationTransactionValidationError(
$type,
pht('Not Linked'),
pht(
'You can not add JIRA issues (%s) to this revision because your '.
'%s account is not linked to a JIRA account.',
implode(', ', $add),
PlatformSymbols::getPlatformServerName()),
$xaction);
continue;
}
$bad = array();
foreach ($refs as $ref) {
if (!$ref->getIsVisible()) {
$bad[] = $ref->getObjectID();
}
}
if ($bad) {
$bad = implode(', ', $bad);
$this->error = pht('Invalid');
$errors[] = new PhabricatorApplicationTransactionValidationError(
$type,
pht('Invalid'),
pht(
'Some JIRA issues could not be loaded. They may not exist, or '.
'you may not have permission to view them: %s',
$bad),
$xaction);
}
}
return $errors;
}
public function getApplicationTransactionTitle(
PhabricatorApplicationTransaction $xaction) {
$old = $xaction->getOldValue();
if (!is_array($old)) {
$old = array();
}
$new = $xaction->getNewValue();
if (!is_array($new)) {
$new = array();
}
$add = array_diff($new, $old);
$rem = array_diff($old, $new);
$author_phid = $xaction->getAuthorPHID();
if ($add && $rem) {
return pht(
'%s updated JIRA issue(s): added %d %s; removed %d %s.',
$xaction->renderHandleLink($author_phid),
phutil_count($add),
implode(', ', $add),
phutil_count($rem),
implode(', ', $rem));
} else if ($add) {
return pht(
'%s added %d JIRA issue(s): %s.',
$xaction->renderHandleLink($author_phid),
phutil_count($add),
implode(', ', $add));
} else if ($rem) {
return pht(
'%s removed %d JIRA issue(s): %s.',
$xaction->renderHandleLink($author_phid),
phutil_count($rem),
implode(', ', $rem));
}
return parent::getApplicationTransactionTitle($xaction);
}
public function applyApplicationTransactionExternalEffects(
PhabricatorApplicationTransaction $xaction) {
// Update the CustomField storage.
parent::applyApplicationTransactionExternalEffects($xaction);
// Now, synchronize the Doorkeeper edges.
$revision = $this->getObject();
$revision_phid = $revision->getPHID();
$edge_type = PhabricatorJiraIssueHasObjectEdgeType::EDGECONST;
$xobjs = $this->loadDoorkeeperExternalObjects($xaction->getNewValue());
$edge_dsts = mpull($xobjs, 'getPHID');
$edges = PhabricatorEdgeQuery::loadDestinationPHIDs(
$revision_phid,
$edge_type);
$editor = new PhabricatorEdgeEditor();
foreach (array_diff($edges, $edge_dsts) as $rem_edge) {
$editor->removeEdge($revision_phid, $edge_type, $rem_edge);
}
foreach (array_diff($edge_dsts, $edges) as $add_edge) {
$editor->addEdge($revision_phid, $edge_type, $add_edge);
}
$editor->save();
}
public function shouldAppearInConduitDictionary() {
return true;
}
public function shouldAppearInConduitTransactions() {
return true;
}
protected function newConduitEditParameterType() {
return new ConduitStringListParameterType();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialCommitsField.php | src/applications/differential/customfield/DifferentialCommitsField.php | <?php
final class DifferentialCommitsField
extends DifferentialCustomField {
public function getFieldKey() {
return 'differential:commits';
}
public function getFieldName() {
return pht('Commits');
}
public function canDisableField() {
return false;
}
public function getFieldDescription() {
return pht('Shows associated commits.');
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function getRequiredHandlePHIDsForPropertyView() {
return $this->getObject()->getCommitPHIDs();
}
public function renderPropertyViewValue(array $handles) {
return $this->renderHandleList($handles);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialUnitField.php | src/applications/differential/customfield/DifferentialUnitField.php | <?php
final class DifferentialUnitField
extends DifferentialCustomField {
public function getFieldKey() {
return 'differential:unit';
}
public function getFieldName() {
return pht('Unit');
}
public function getFieldDescription() {
return pht('Shows unit test results.');
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewValue(array $handles) {
return null;
}
public function shouldAppearInDiffPropertyView() {
return true;
}
public function renderDiffPropertyViewLabel(DifferentialDiff $diff) {
return $this->getFieldName();
}
public function getWarningsForDetailView() {
$warnings = array();
$viewer = $this->getViewer();
$diff = $this->getObject()->getActiveDiff();
$buildable = id(new HarbormasterBuildableQuery())
->setViewer($viewer)
->withBuildablePHIDs(array($diff->getPHID()))
->withManualBuildables(false)
->executeOne();
if ($buildable) {
switch ($buildable->getBuildableStatus()) {
case HarbormasterBuildableStatus::STATUS_BUILDING:
$warnings[] = pht(
'These changes have not finished building yet and may have build '.
'failures.');
break;
case HarbormasterBuildableStatus::STATUS_FAILED:
$warnings[] = pht(
'These changes have failed to build.');
break;
}
}
$status = $this->getObject()->getActiveDiff()->getUnitStatus();
if ($status < DifferentialUnitStatus::UNIT_WARN) {
// Don't show any warnings.
} else if ($status == DifferentialUnitStatus::UNIT_AUTO_SKIP) {
// Don't show any warnings.
} else if ($status == DifferentialUnitStatus::UNIT_SKIP) {
$warnings[] = pht(
'Unit tests were skipped when generating these changes.');
} else {
$warnings[] = pht('These changes have unit test problems.');
}
return $warnings;
}
public function renderDiffPropertyViewValue(DifferentialDiff $diff) {
$status_value = $diff->getUnitStatus();
$status = DifferentialUnitStatus::newStatusFromValue($status_value);
$status_icon = $status->getIconIcon();
$status_color = $status->getIconColor();
$status_name = $status->getName();
$status = id(new PHUIStatusListView())
->addItem(
id(new PHUIStatusItemView())
->setIcon($status_icon, $status_color)
->setTarget($status_name));
return $status;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialRevertPlanField.php | src/applications/differential/customfield/DifferentialRevertPlanField.php | <?php
final class DifferentialRevertPlanField
extends DifferentialStoredCustomField {
public function getFieldKey() {
return 'phabricator:revert-plan';
}
public function getFieldKeyForConduit() {
return 'revertPlan';
}
public function getFieldName() {
return pht('Revert Plan');
}
public function getFieldDescription() {
return pht('Instructions for reverting/undoing this change.');
}
public function shouldDisableByDefault() {
return true;
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
public function getStyleForPropertyView() {
return 'block';
}
public function getIconForPropertyView() {
return PHUIPropertyListView::ICON_TESTPLAN;
}
public function renderPropertyViewValue(array $handles) {
if (!strlen($this->getValue())) {
return null;
}
return new PHUIRemarkupView($this->getViewer(), $this->getValue());
}
public function shouldAppearInGlobalSearch() {
return true;
}
public function updateAbstractDocument(
PhabricatorSearchAbstractDocument $document) {
if (strlen($this->getValue())) {
$document->addField('rvrt', $this->getValue());
}
}
public function shouldAppearInEditView() {
return true;
}
public function shouldAppearInApplicationTransactions() {
return true;
}
public function getOldValueForApplicationTransactions() {
return $this->getValue();
}
public function getNewValueForApplicationTransactions() {
return $this->getValue();
}
public function readValueFromRequest(AphrontRequest $request) {
$this->setValue($request->getStr($this->getFieldKey()));
}
public function renderEditControl(array $handles) {
return id(new PhabricatorRemarkupControl())
->setUser($this->getViewer())
->setName($this->getFieldKey())
->setValue($this->getValue())
->setLabel($this->getFieldName());
}
public function getApplicationTransactionTitle(
PhabricatorApplicationTransaction $xaction) {
$author_phid = $xaction->getAuthorPHID();
$old = $xaction->getOldValue();
$new = $xaction->getNewValue();
return pht(
'%s updated the revert plan for this revision.',
$xaction->renderHandleLink($author_phid));
}
public function getApplicationTransactionTitleForFeed(
PhabricatorApplicationTransaction $xaction) {
$object_phid = $xaction->getObjectPHID();
$author_phid = $xaction->getAuthorPHID();
$old = $xaction->getOldValue();
$new = $xaction->getNewValue();
return pht(
'%s updated the revert plan for %s.',
$xaction->renderHandleLink($author_phid),
$xaction->renderHandleLink($object_phid));
}
public function getApplicationTransactionHasChangeDetails(
PhabricatorApplicationTransaction $xaction) {
return true;
}
public function getApplicationTransactionChangeDetails(
PhabricatorApplicationTransaction $xaction,
PhabricatorUser $viewer) {
return $xaction->renderTextCorpusChangeDetails(
$viewer,
$xaction->getOldValue(),
$xaction->getNewValue());
}
public function getApplicationTransactionRemarkupBlocks(
PhabricatorApplicationTransaction $xaction) {
return array($xaction->getNewValue());
}
public function shouldAppearInConduitDictionary() {
return true;
}
public function shouldAppearInConduitTransactions() {
return true;
}
protected function newConduitEditParameterType() {
return new ConduitStringParameterType();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialCoreCustomField.php | src/applications/differential/customfield/DifferentialCoreCustomField.php | <?php
/**
* Base class for Differential fields with storage on the revision object
* itself. This mostly wraps reading/writing field values to and from the
* object.
*/
abstract class DifferentialCoreCustomField
extends DifferentialCustomField {
private $value;
private $fieldError;
private $fieldParser;
abstract protected function readValueFromRevision(
DifferentialRevision $revision);
protected function writeValueToRevision(
DifferentialRevision $revision,
$value) {
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
protected function isCoreFieldRequired() {
return false;
}
protected function isCoreFieldValueEmpty($value) {
if (is_array($value)) {
return !$value;
}
return !strlen(trim($value));
}
protected function getCoreFieldRequiredErrorString() {
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
public function validateApplicationTransactions(
PhabricatorApplicationTransactionEditor $editor,
$type,
array $xactions) {
$this->setFieldError(null);
$errors = parent::validateApplicationTransactions(
$editor,
$type,
$xactions);
$transaction = null;
foreach ($xactions as $xaction) {
$value = $xaction->getNewValue();
if ($this->isCoreFieldRequired()) {
if ($this->isCoreFieldValueEmpty($value)) {
$error = new PhabricatorApplicationTransactionValidationError(
$type,
pht('Required'),
$this->getCoreFieldRequiredErrorString(),
$xaction);
$error->setIsMissingFieldError(true);
$errors[] = $error;
$this->setFieldError(pht('Required'));
continue;
}
}
}
return $errors;
}
public function canDisableField() {
return false;
}
public function shouldAppearInApplicationTransactions() {
return true;
}
public function readValueFromObject(PhabricatorCustomFieldInterface $object) {
if ($this->isCoreFieldRequired()) {
$this->setFieldError(true);
}
$this->setValue($this->readValueFromRevision($object));
}
public function getOldValueForApplicationTransactions() {
return $this->readValueFromRevision($this->getObject());
}
public function getNewValueForApplicationTransactions() {
return $this->getValue();
}
public function applyApplicationTransactionInternalEffects(
PhabricatorApplicationTransaction $xaction) {
$this->writeValueToRevision($this->getObject(), $xaction->getNewValue());
}
public function setFieldError($field_error) {
$this->fieldError = $field_error;
return $this;
}
public function getFieldError() {
return $this->fieldError;
}
public function setValue($value) {
$this->value = $value;
return $this;
}
public function getValue() {
return $this->value;
}
public function getConduitDictionaryValue() {
return $this->getValue();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialManiphestTasksField.php | src/applications/differential/customfield/DifferentialManiphestTasksField.php | <?php
final class DifferentialManiphestTasksField
extends DifferentialCoreCustomField {
public function getFieldKey() {
return 'differential:maniphest-tasks';
}
public function canDisableField() {
return false;
}
public function getFieldName() {
return pht('Maniphest Tasks');
}
public function getFieldDescription() {
return pht('Lists associated tasks.');
}
public function shouldAppearInPropertyView() {
return true;
}
public function renderPropertyViewLabel() {
return $this->getFieldName();
}
protected function readValueFromRevision(DifferentialRevision $revision) {
if (!$revision->getPHID()) {
return array();
}
return PhabricatorEdgeQuery::loadDestinationPHIDs(
$revision->getPHID(),
DifferentialRevisionHasTaskEdgeType::EDGECONST);
}
public function getRequiredHandlePHIDsForPropertyView() {
return $this->getValue();
}
public function renderPropertyViewValue(array $handles) {
return $this->renderHandleList($handles);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/customfield/DifferentialChangesSinceLastUpdateField.php | src/applications/differential/customfield/DifferentialChangesSinceLastUpdateField.php | <?php
final class DifferentialChangesSinceLastUpdateField
extends DifferentialCustomField {
public function getFieldKey() {
return 'differential:changes-since-last-update';
}
public function getFieldName() {
return pht('Changes Since Last Update');
}
public function getFieldDescription() {
return pht('Links to changes since the last update in email.');
}
public function shouldAppearInTransactionMail() {
return true;
}
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
if ($editor->isFirstBroadcast()) {
return;
}
if ($editor->getIsCloseByCommit()) {
return;
}
$xaction = $editor->getDiffUpdateTransaction($xactions);
if (!$xaction) {
return;
}
$original = id(new DifferentialDiffQuery())
->setViewer($this->getViewer())
->withPHIDs(array($xaction->getOldValue()))
->executeOne();
if (!$original) {
return;
}
$revision = $this->getObject();
$current = $revision->getActiveDiff();
$old_id = $original->getID();
$new_id = $current->getID();
$uri = '/'.$revision->getMonogram().'?vs='.$old_id.'&id='.$new_id;
$uri = PhabricatorEnv::getProductionURI($uri);
$body->addLinkSection(pht('CHANGES SINCE LAST UPDATE'), $uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/editor/DifferentialDiffEditor.php | src/applications/differential/editor/DifferentialDiffEditor.php | <?php
final class DifferentialDiffEditor
extends PhabricatorApplicationTransactionEditor {
private $diffDataDict;
private $lookupRepository = true;
public function setLookupRepository($bool) {
$this->lookupRepository = $bool;
return $this;
}
public function getEditorApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getEditorObjectsDescription() {
return pht('Differential Diffs');
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
$types[] = DifferentialDiffTransaction::TYPE_DIFF_CREATE;
return $types;
}
protected function getCustomTransactionOldValue(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialDiffTransaction::TYPE_DIFF_CREATE:
return null;
}
return parent::getCustomTransactionOldValue($object, $xaction);
}
protected function getCustomTransactionNewValue(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialDiffTransaction::TYPE_DIFF_CREATE:
$this->diffDataDict = $xaction->getNewValue();
return true;
}
return parent::getCustomTransactionNewValue($object, $xaction);
}
protected function applyCustomInternalTransaction(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialDiffTransaction::TYPE_DIFF_CREATE:
$dict = $this->diffDataDict;
$this->updateDiffFromDict($object, $dict);
return;
}
return parent::applyCustomInternalTransaction($object, $xaction);
}
protected function applyCustomExternalTransaction(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialDiffTransaction::TYPE_DIFF_CREATE:
return;
}
return parent::applyCustomExternalTransaction($object, $xaction);
}
protected function applyFinalEffects(
PhabricatorLiskDAO $object,
array $xactions) {
// If we didn't get an explicit `repositoryPHID` (which means the client
// is old, or couldn't figure out which repository the working copy
// belongs to), apply heuristics to try to figure it out.
if ($this->lookupRepository && !$object->getRepositoryPHID()) {
$repository = id(new DifferentialRepositoryLookup())
->setDiff($object)
->setViewer($this->getActor())
->lookupRepository();
if ($repository) {
$object->setRepositoryPHID($repository->getPHID());
$object->setRepositoryUUID($repository->getUUID());
$object->save();
}
}
return $xactions;
}
/**
* We run Herald as part of transaction validation because Herald can
* block diff creation for Differential diffs. Its important to do this
* separately so no Herald logs are saved; these logs could expose
* information the Herald rules are intended to block.
*/
protected function validateTransaction(
PhabricatorLiskDAO $object,
$type,
array $xactions) {
$errors = parent::validateTransaction($object, $type, $xactions);
foreach ($xactions as $xaction) {
switch ($type) {
case DifferentialDiffTransaction::TYPE_DIFF_CREATE:
$diff = clone $object;
$diff = $this->updateDiffFromDict($diff, $xaction->getNewValue());
$adapter = $this->buildHeraldAdapter($diff, $xactions);
$adapter->setContentSource($this->getContentSource());
$adapter->setIsNewObject($this->getIsNewObject());
$engine = new HeraldEngine();
$rules = $engine->loadRulesForAdapter($adapter);
$rules = mpull($rules, null, 'getID');
$effects = $engine->applyRules($rules, $adapter);
$action_block = DifferentialBlockHeraldAction::ACTIONCONST;
$blocking_effect = null;
foreach ($effects as $effect) {
if ($effect->getAction() == $action_block) {
$blocking_effect = $effect;
break;
}
}
if ($blocking_effect) {
$rule = $blocking_effect->getRule();
$message = $effect->getTarget();
if (!strlen($message)) {
$message = pht('(None.)');
}
$errors[] = new PhabricatorApplicationTransactionValidationError(
$type,
pht('Rejected by Herald'),
pht(
"Creation of this diff was rejected by Herald rule %s.\n".
" Rule: %s\n".
"Reason: %s",
$rule->getMonogram(),
$rule->getName(),
$message));
}
break;
}
}
return $errors;
}
protected function shouldPublishFeedStory(
PhabricatorLiskDAO $object,
array $xactions) {
return false;
}
protected function shouldSendMail(
PhabricatorLiskDAO $object,
array $xactions) {
return false;
}
protected function supportsSearch() {
return false;
}
/* -( Herald Integration )------------------------------------------------- */
/**
* See @{method:validateTransaction}. The only Herald action is to block
* the creation of Diffs. We thus have to be careful not to save any
* data and do this validation very early.
*/
protected function shouldApplyHeraldRules(
PhabricatorLiskDAO $object,
array $xactions) {
return false;
}
protected function buildHeraldAdapter(
PhabricatorLiskDAO $object,
array $xactions) {
$adapter = id(new HeraldDifferentialDiffAdapter())
->setDiff($object);
return $adapter;
}
private function updateDiffFromDict(DifferentialDiff $diff, $dict) {
$diff
->setSourcePath(idx($dict, 'sourcePath'))
->setSourceMachine(idx($dict, 'sourceMachine'))
->setBranch(idx($dict, 'branch'))
->setCreationMethod(idx($dict, 'creationMethod'))
->setAuthorPHID(idx($dict, 'authorPHID', $this->getActor()))
->setBookmark(idx($dict, 'bookmark'))
->setRepositoryPHID(idx($dict, 'repositoryPHID'))
->setRepositoryUUID(idx($dict, 'repositoryUUID'))
->setSourceControlSystem(idx($dict, 'sourceControlSystem'))
->setSourceControlPath(idx($dict, 'sourceControlPath'))
->setSourceControlBaseRevision(idx($dict, 'sourceControlBaseRevision'))
->setLintStatus(idx($dict, 'lintStatus'))
->setUnitStatus(idx($dict, 'unitStatus'));
return $diff;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/editor/DifferentialRevisionEditEngine.php | src/applications/differential/editor/DifferentialRevisionEditEngine.php | <?php
final class DifferentialRevisionEditEngine
extends PhabricatorEditEngine {
private $diff;
const ENGINECONST = 'differential.revision';
const ACTIONGROUP_REVIEW = 'review';
const ACTIONGROUP_REVISION = 'revision';
public function getEngineName() {
return pht('Revisions');
}
public function getSummaryHeader() {
return pht('Configure Revision Forms');
}
public function getSummaryText() {
return pht(
'Configure creation and editing revision forms in Differential.');
}
public function getEngineApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function isEngineConfigurable() {
return false;
}
protected function newEditableObject() {
$viewer = $this->getViewer();
return DifferentialRevision::initializeNewRevision($viewer);
}
protected function newObjectQuery() {
return id(new DifferentialRevisionQuery())
->needActiveDiffs(true)
->needReviewers(true)
->needReviewerAuthority(true);
}
protected function getObjectCreateTitleText($object) {
return pht('Create New Revision');
}
protected function getObjectEditTitleText($object) {
$monogram = $object->getMonogram();
$title = $object->getTitle();
$diff = $this->getDiff();
if ($diff) {
return pht('Update Revision %s: %s', $monogram, $title);
} else {
return pht('Edit Revision %s: %s', $monogram, $title);
}
}
protected function getObjectEditShortText($object) {
return $object->getMonogram();
}
public function getCreateURI($form_key) {
return '/differential/diff/create/';
}
protected function getObjectCreateShortText() {
return pht('Create Revision');
}
protected function getObjectName() {
return pht('Revision');
}
protected function getCommentViewButtonText($object) {
if ($object->isDraft()) {
return pht('Submit Quietly');
}
return parent::getCommentViewButtonText($object);
}
protected function getObjectViewURI($object) {
return $object->getURI();
}
protected function getEditorURI() {
return $this->getApplication()->getApplicationURI('revision/edit/');
}
public function setDiff(DifferentialDiff $diff) {
$this->diff = $diff;
return $this;
}
public function getDiff() {
return $this->diff;
}
protected function newCommentActionGroups() {
return array(
id(new PhabricatorEditEngineCommentActionGroup())
->setKey(self::ACTIONGROUP_REVIEW)
->setLabel(pht('Review Actions')),
id(new PhabricatorEditEngineCommentActionGroup())
->setKey(self::ACTIONGROUP_REVISION)
->setLabel(pht('Revision Actions')),
);
}
protected function buildCustomEditFields($object) {
$viewer = $this->getViewer();
$plan_required = PhabricatorEnv::getEnvConfig(
'differential.require-test-plan-field');
$plan_enabled = $this->isCustomFieldEnabled(
$object,
'differential:test-plan');
$diff = $this->getDiff();
if ($diff) {
$diff_phid = $diff->getPHID();
} else {
$diff_phid = null;
}
$is_create = $this->getIsCreate();
$is_update = ($diff && !$is_create);
$fields = array();
$fields[] = id(new PhabricatorHandlesEditField())
->setKey(DifferentialRevisionUpdateTransaction::EDITKEY)
->setLabel(pht('Update Diff'))
->setDescription(pht('New diff to create or update the revision with.'))
->setConduitDescription(pht('Create or update a revision with a diff.'))
->setConduitTypeDescription(pht('PHID of the diff.'))
->setTransactionType(
DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE)
->setHandleParameterType(new AphrontPHIDListHTTPParameterType())
->setSingleValue($diff_phid)
->setIsFormField((bool)$diff)
->setIsReorderable(false)
->setIsDefaultable(false)
->setIsInvisible(true)
->setIsLockable(false);
if ($is_update) {
$fields[] = id(new PhabricatorInstructionsEditField())
->setKey('update.help')
->setValue(pht('Describe the updates you have made to the diff.'));
$fields[] = id(new PhabricatorCommentEditField())
->setKey('update.comment')
->setLabel(pht('Comment'))
->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)
->setIsWebOnly(true)
->setDescription(pht('Comments providing context for the update.'));
$fields[] = id(new PhabricatorSubmitEditField())
->setKey('update.submit')
->setValue($this->getObjectEditButtonText($object));
$fields[] = id(new PhabricatorDividerEditField())
->setKey('update.note');
}
$fields[] = id(new PhabricatorTextEditField())
->setKey(DifferentialRevisionTitleTransaction::EDITKEY)
->setLabel(pht('Title'))
->setIsRequired(true)
->setTransactionType(
DifferentialRevisionTitleTransaction::TRANSACTIONTYPE)
->setDescription(pht('The title of the revision.'))
->setConduitDescription(pht('Retitle the revision.'))
->setConduitTypeDescription(pht('New revision title.'))
->setValue($object->getTitle());
$author_field = id(new PhabricatorDatasourceEditField())
->setKey(DifferentialRevisionAuthorTransaction::EDITKEY)
->setLabel(pht('Author'))
->setDatasource(new PhabricatorPeopleDatasource())
->setTransactionType(
DifferentialRevisionAuthorTransaction::TRANSACTIONTYPE)
->setDescription(pht('Foist this revision upon someone else.'))
->setConduitDescription(pht('Foist this revision upon another user.'))
->setConduitTypeDescription(pht('New author.'))
->setSingleValue($object->getAuthorPHID());
// Don't show the "Author" field when creating a revision using the web
// workflow, since it adds more noise than signal to this workflow.
if ($this->getIsCreate()) {
$author_field->setIsHidden(true);
}
// Only show the "Foist Upon" comment action to the current revision
// author. Other users can use "Edit Revision", it's just very unlikley
// that they're interested in this action.
if ($viewer->getPHID() === $object->getAuthorPHID()) {
$author_field->setCommentActionLabel(pht('Foist Upon'));
}
$fields[] = $author_field;
$fields[] = id(new PhabricatorRemarkupEditField())
->setKey(DifferentialRevisionSummaryTransaction::EDITKEY)
->setLabel(pht('Summary'))
->setTransactionType(
DifferentialRevisionSummaryTransaction::TRANSACTIONTYPE)
->setDescription(pht('The summary of the revision.'))
->setConduitDescription(pht('Change the revision summary.'))
->setConduitTypeDescription(pht('New revision summary.'))
->setValue($object->getSummary());
if ($plan_enabled) {
$fields[] = id(new PhabricatorRemarkupEditField())
->setKey(DifferentialRevisionTestPlanTransaction::EDITKEY)
->setLabel(pht('Test Plan'))
->setIsRequired($plan_required)
->setTransactionType(
DifferentialRevisionTestPlanTransaction::TRANSACTIONTYPE)
->setDescription(
pht('Actions performed to verify the behavior of the change.'))
->setConduitDescription(pht('Update the revision test plan.'))
->setConduitTypeDescription(pht('New test plan.'))
->setValue($object->getTestPlan());
}
$fields[] = id(new PhabricatorDatasourceEditField())
->setKey(DifferentialRevisionReviewersTransaction::EDITKEY)
->setLabel(pht('Reviewers'))
->setDatasource(new DifferentialReviewerDatasource())
->setUseEdgeTransactions(true)
->setTransactionType(
DifferentialRevisionReviewersTransaction::TRANSACTIONTYPE)
->setCommentActionLabel(pht('Change Reviewers'))
->setDescription(pht('Reviewers for this revision.'))
->setConduitDescription(pht('Change the reviewers for this revision.'))
->setConduitTypeDescription(pht('New reviewers.'))
->setValue($object->getReviewerPHIDsForEdit());
$fields[] = id(new PhabricatorDatasourceEditField())
->setKey('repositoryPHID')
->setLabel(pht('Repository'))
->setDatasource(new DiffusionRepositoryDatasource())
->setTransactionType(
DifferentialRevisionRepositoryTransaction::TRANSACTIONTYPE)
->setDescription(pht('The repository the revision belongs to.'))
->setConduitDescription(pht('Change the repository for this revision.'))
->setConduitTypeDescription(pht('New repository.'))
->setSingleValue($object->getRepositoryPHID());
// This is a little flimsy, but allows "Maniphest Tasks: ..." to continue
// working properly in commit messages until we fully sort out T5873.
$fields[] = id(new PhabricatorHandlesEditField())
->setKey('tasks')
->setUseEdgeTransactions(true)
->setIsFormField(false)
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue(
'edge:type',
DifferentialRevisionHasTaskEdgeType::EDGECONST)
->setDescription(pht('Tasks associated with this revision.'))
->setConduitDescription(pht('Change associated tasks.'))
->setConduitTypeDescription(pht('List of tasks.'))
->setValue(array());
$fields[] = id(new PhabricatorHandlesEditField())
->setKey('parents')
->setUseEdgeTransactions(true)
->setIsFormField(false)
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue(
'edge:type',
DifferentialRevisionDependsOnRevisionEdgeType::EDGECONST)
->setDescription(pht('Parent revisions of this revision.'))
->setConduitDescription(pht('Change associated parent revisions.'))
->setConduitTypeDescription(pht('List of revisions.'))
->setValue(array());
$fields[] = id(new PhabricatorHandlesEditField())
->setKey('children')
->setUseEdgeTransactions(true)
->setIsFormField(false)
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue(
'edge:type',
DifferentialRevisionDependedOnByRevisionEdgeType::EDGECONST)
->setDescription(pht('Child revisions of this revision.'))
->setConduitDescription(pht('Change associated child revisions.'))
->setConduitTypeDescription(pht('List of revisions.'))
->setValue(array());
$actions = DifferentialRevisionActionTransaction::loadAllActions();
$actions = msortv($actions, 'getRevisionActionOrderVector');
foreach ($actions as $key => $action) {
$fields[] = $action->newEditField($object, $viewer);
}
$fields[] = id(new PhabricatorBoolEditField())
->setKey('draft')
->setLabel(pht('Hold as Draft'))
->setIsFormField(false)
->setOptions(
pht('Autosubmit Once Builds Finish'),
pht('Hold as Draft'))
->setTransactionType(
DifferentialRevisionHoldDraftTransaction::TRANSACTIONTYPE)
->setDescription(pht('Hold revision as as draft.'))
->setConduitDescription(
pht(
'Change autosubmission from draft state after builds finish.'))
->setConduitTypeDescription(pht('New "Hold as Draft" setting.'))
->setValue($object->getHoldAsDraft());
return $fields;
}
private function isCustomFieldEnabled(DifferentialRevision $revision, $key) {
$field_list = PhabricatorCustomField::getObjectFields(
$revision,
PhabricatorCustomField::ROLE_VIEW);
$fields = $field_list->getFields();
return isset($fields[$key]);
}
protected function newAutomaticCommentTransactions($object) {
$viewer = $this->getViewer();
$editor = $object->getApplicationTransactionEditor()
->setActor($viewer);
$xactions = $editor->newAutomaticInlineTransactions(
$object,
DifferentialTransaction::TYPE_INLINE,
new DifferentialDiffInlineCommentQuery());
return $xactions;
}
protected function newCommentPreviewContent($object, array $xactions) {
$viewer = $this->getViewer();
$type_inline = DifferentialTransaction::TYPE_INLINE;
$inlines = array();
foreach ($xactions as $xaction) {
if ($xaction->getTransactionType() === $type_inline) {
$inlines[] = $xaction->getComment();
}
}
$content = array();
if ($inlines) {
// Reload inlines to get inline context.
$inlines = id(new DifferentialDiffInlineCommentQuery())
->setViewer($viewer)
->withIDs(mpull($inlines, 'getID'))
->needInlineContext(true)
->execute();
$inline_preview = id(new PHUIDiffInlineCommentPreviewListView())
->setViewer($viewer)
->setInlineComments($inlines);
$content[] = phutil_tag(
'div',
array(
'id' => 'inline-comment-preview',
),
$inline_preview);
}
return $content;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/editor/DifferentialTransactionEditor.php | src/applications/differential/editor/DifferentialTransactionEditor.php | <?php
final class DifferentialTransactionEditor
extends PhabricatorApplicationTransactionEditor {
private $changedPriorToCommitURI;
private $isCloseByCommit;
private $repositoryPHIDOverride = false;
private $didExpandInlineState = false;
private $firstBroadcast = false;
private $wasBroadcasting;
private $isDraftDemotion;
private $ownersDiff;
private $ownersChangesets;
public function getEditorApplicationClass() {
return 'PhabricatorDifferentialApplication';
}
public function getEditorObjectsDescription() {
return pht('Differential Revisions');
}
public function getCreateObjectTitle($author, $object) {
return pht('%s created this revision.', $author);
}
public function getCreateObjectTitleForFeed($author, $object) {
return pht('%s created %s.', $author, $object);
}
public function isFirstBroadcast() {
return $this->firstBroadcast;
}
public function getDiffUpdateTransaction(array $xactions) {
$type_update = DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE;
foreach ($xactions as $xaction) {
if ($xaction->getTransactionType() == $type_update) {
return $xaction;
}
}
return null;
}
public function setIsCloseByCommit($is_close_by_commit) {
$this->isCloseByCommit = $is_close_by_commit;
return $this;
}
public function getIsCloseByCommit() {
return $this->isCloseByCommit;
}
public function setChangedPriorToCommitURI($uri) {
$this->changedPriorToCommitURI = $uri;
return $this;
}
public function getChangedPriorToCommitURI() {
return $this->changedPriorToCommitURI;
}
public function setRepositoryPHIDOverride($phid_or_null) {
$this->repositoryPHIDOverride = $phid_or_null;
return $this;
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorTransactions::TYPE_COMMENT;
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
$types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;
$types[] = PhabricatorTransactions::TYPE_INLINESTATE;
$types[] = DifferentialTransaction::TYPE_INLINE;
return $types;
}
protected function getCustomTransactionOldValue(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialTransaction::TYPE_INLINE:
return null;
}
return parent::getCustomTransactionOldValue($object, $xaction);
}
protected function getCustomTransactionNewValue(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialTransaction::TYPE_INLINE:
return null;
}
return parent::getCustomTransactionNewValue($object, $xaction);
}
protected function applyCustomInternalTransaction(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialTransaction::TYPE_INLINE:
$comment = $xaction->getComment();
$comment->setAttribute('editing', false);
PhabricatorVersionedDraft::purgeDrafts(
$comment->getPHID(),
$this->getActingAsPHID());
return;
}
return parent::applyCustomInternalTransaction($object, $xaction);
}
protected function expandTransactions(
PhabricatorLiskDAO $object,
array $xactions) {
foreach ($xactions as $xaction) {
switch ($xaction->getTransactionType()) {
case PhabricatorTransactions::TYPE_INLINESTATE:
// If we have an "Inline State" transaction already, the caller
// built it for us so we don't need to expand it again.
$this->didExpandInlineState = true;
break;
case DifferentialRevisionPlanChangesTransaction::TRANSACTIONTYPE:
if ($xaction->getMetadataValue('draft.demote')) {
$this->isDraftDemotion = true;
}
break;
}
}
$this->wasBroadcasting = $object->getShouldBroadcast();
return parent::expandTransactions($object, $xactions);
}
protected function expandTransaction(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
$results = parent::expandTransaction($object, $xaction);
$actor = $this->getActor();
$actor_phid = $this->getActingAsPHID();
$type_edge = PhabricatorTransactions::TYPE_EDGE;
$edge_ref_task = DifferentialRevisionHasTaskEdgeType::EDGECONST;
$want_downgrade = array();
$must_downgrade = array();
if ($this->getIsCloseByCommit()) {
// Never downgrade reviewers when we're closing a revision after a
// commit.
} else {
switch ($xaction->getTransactionType()) {
case DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE:
$want_downgrade[] = DifferentialReviewerStatus::STATUS_ACCEPTED;
$want_downgrade[] = DifferentialReviewerStatus::STATUS_REJECTED;
break;
case DifferentialRevisionRequestReviewTransaction::TRANSACTIONTYPE:
if (!$object->isChangePlanned()) {
// If the old state isn't "Changes Planned", downgrade the accepts
// even if they're sticky.
// We don't downgrade for "Changes Planned" to allow an author to
// undo a "Plan Changes" by immediately following it up with a
// "Request Review".
$want_downgrade[] = DifferentialReviewerStatus::STATUS_ACCEPTED;
$must_downgrade[] = DifferentialReviewerStatus::STATUS_ACCEPTED;
}
$want_downgrade[] = DifferentialReviewerStatus::STATUS_REJECTED;
break;
}
}
if ($want_downgrade) {
$void_type = DifferentialRevisionVoidTransaction::TRANSACTIONTYPE;
$results[] = id(new DifferentialTransaction())
->setTransactionType($void_type)
->setIgnoreOnNoEffect(true)
->setMetadataValue('void.force', $must_downgrade)
->setNewValue($want_downgrade);
}
$new_author_phid = null;
switch ($xaction->getTransactionType()) {
case DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE:
if ($this->getIsCloseByCommit()) {
// Don't bother with any of this if this update is a side effect of
// commit detection.
break;
}
// When a revision is updated and the diff comes from a branch named
// "T123" or similar, automatically associate the commit with the
// task that the branch names.
$maniphest = 'PhabricatorManiphestApplication';
if (PhabricatorApplication::isClassInstalled($maniphest)) {
$diff = $this->requireDiff($xaction->getNewValue());
$branch = $diff->getBranch();
// No "$", to allow for branches like T123_demo.
$match = null;
if ($branch !== null && preg_match('/^T(\d+)/i', $branch, $match)) {
$task_id = $match[1];
$tasks = id(new ManiphestTaskQuery())
->setViewer($this->getActor())
->withIDs(array($task_id))
->execute();
if ($tasks) {
$task = head($tasks);
$task_phid = $task->getPHID();
$results[] = id(new DifferentialTransaction())
->setTransactionType($type_edge)
->setMetadataValue('edge:type', $edge_ref_task)
->setIgnoreOnNoEffect(true)
->setNewValue(array('+' => array($task_phid => $task_phid)));
}
}
}
break;
case DifferentialRevisionCommandeerTransaction::TRANSACTIONTYPE:
$new_author_phid = $actor_phid;
break;
case DifferentialRevisionAuthorTransaction::TRANSACTIONTYPE:
$new_author_phid = $xaction->getNewValue();
break;
}
if ($new_author_phid) {
$swap_xaction = $this->newSwapReviewersTransaction(
$object,
$new_author_phid);
if ($swap_xaction) {
$results[] = $swap_xaction;
}
}
if (!$this->didExpandInlineState) {
switch ($xaction->getTransactionType()) {
case PhabricatorTransactions::TYPE_COMMENT:
case DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE:
case DifferentialTransaction::TYPE_INLINE:
$this->didExpandInlineState = true;
$query_template = id(new DifferentialDiffInlineCommentQuery())
->withRevisionPHIDs(array($object->getPHID()));
$state_xaction = $this->newInlineStateTransaction(
$object,
$query_template);
if ($state_xaction) {
$results[] = $state_xaction;
}
break;
}
}
return $results;
}
protected function applyCustomExternalTransaction(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialTransaction::TYPE_INLINE:
$reply = $xaction->getComment()->getReplyToComment();
if ($reply && !$reply->getHasReplies()) {
$reply->setHasReplies(1)->save();
}
return;
}
return parent::applyCustomExternalTransaction($object, $xaction);
}
protected function applyBuiltinExternalTransaction(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case PhabricatorTransactions::TYPE_INLINESTATE:
$table = new DifferentialTransactionComment();
$conn_w = $table->establishConnection('w');
foreach ($xaction->getNewValue() as $phid => $state) {
queryfx(
$conn_w,
'UPDATE %T SET fixedState = %s WHERE phid = %s',
$table->getTableName(),
$state,
$phid);
}
break;
}
return parent::applyBuiltinExternalTransaction($object, $xaction);
}
protected function applyFinalEffects(
PhabricatorLiskDAO $object,
array $xactions) {
// Load the most up-to-date version of the revision and its reviewers,
// so we don't need to try to deduce the state of reviewers by examining
// all the changes made by the transactions. Then, update the reviewers
// on the object to make sure we're acting on the current reviewer set
// (and, for example, sending mail to the right people).
$new_revision = id(new DifferentialRevisionQuery())
->setViewer($this->getActor())
->needReviewers(true)
->needActiveDiffs(true)
->withIDs(array($object->getID()))
->executeOne();
if (!$new_revision) {
throw new Exception(
pht('Failed to load revision from transaction finalization.'));
}
$active_diff = $new_revision->getActiveDiff();
$new_diff_phid = $active_diff->getPHID();
$object->attachReviewers($new_revision->getReviewers());
$object->attachActiveDiff($active_diff);
$object->attachRepository($new_revision->getRepository());
$has_new_diff = false;
$should_index_paths = false;
$should_index_hashes = false;
$need_changesets = false;
foreach ($xactions as $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE:
$need_changesets = true;
$new_diff_phid = $xaction->getNewValue();
$has_new_diff = true;
$should_index_paths = true;
$should_index_hashes = true;
break;
case DifferentialRevisionRepositoryTransaction::TRANSACTIONTYPE:
// The "AffectedPath" table denormalizes the repository, so we
// want to update the index if the repository changes.
$need_changesets = true;
$should_index_paths = true;
break;
}
}
if ($need_changesets) {
$new_diff = $this->requireDiff($new_diff_phid, true);
if ($should_index_paths) {
id(new DifferentialAffectedPathEngine())
->setRevision($object)
->setDiff($new_diff)
->updateAffectedPaths();
}
if ($should_index_hashes) {
$this->updateRevisionHashTable($object, $new_diff);
}
if ($has_new_diff) {
$this->ownersDiff = $new_diff;
$this->ownersChangesets = $new_diff->getChangesets();
}
}
$xactions = $this->updateReviewStatus($object, $xactions);
$this->markReviewerComments($object, $xactions);
return $xactions;
}
private function updateReviewStatus(
DifferentialRevision $revision,
array $xactions) {
$was_accepted = $revision->isAccepted();
$was_revision = $revision->isNeedsRevision();
$was_review = $revision->isNeedsReview();
if (!$was_accepted && !$was_revision && !$was_review) {
// Revisions can't transition out of other statuses (like closed or
// abandoned) as a side effect of reviewer status changes.
return $xactions;
}
// Try to move a revision to "accepted". We look for:
//
// - at least one accepting reviewer who is a user; and
// - no rejects; and
// - no rejects of older diffs; and
// - no blocking reviewers.
$has_accepting_user = false;
$has_rejecting_reviewer = false;
$has_rejecting_older_reviewer = false;
$has_blocking_reviewer = false;
$active_diff = $revision->getActiveDiff();
foreach ($revision->getReviewers() as $reviewer) {
$reviewer_status = $reviewer->getReviewerStatus();
switch ($reviewer_status) {
case DifferentialReviewerStatus::STATUS_REJECTED:
$active_phid = $active_diff->getPHID();
if ($reviewer->isRejected($active_phid)) {
$has_rejecting_reviewer = true;
} else {
$has_rejecting_older_reviewer = true;
}
break;
case DifferentialReviewerStatus::STATUS_REJECTED_OLDER:
$has_rejecting_older_reviewer = true;
break;
case DifferentialReviewerStatus::STATUS_BLOCKING:
$has_blocking_reviewer = true;
break;
case DifferentialReviewerStatus::STATUS_ACCEPTED:
if ($reviewer->isUser()) {
$active_phid = $active_diff->getPHID();
if ($reviewer->isAccepted($active_phid)) {
$has_accepting_user = true;
}
}
break;
}
}
$new_status = null;
if ($has_accepting_user &&
!$has_rejecting_reviewer &&
!$has_rejecting_older_reviewer &&
!$has_blocking_reviewer) {
$new_status = DifferentialRevisionStatus::ACCEPTED;
} else if ($has_rejecting_reviewer) {
// This isn't accepted, and there's at least one rejecting reviewer,
// so the revision needs changes. This usually happens after a
// "reject".
$new_status = DifferentialRevisionStatus::NEEDS_REVISION;
} else if ($was_accepted) {
// This revision was accepted, but it no longer satisfies the
// conditions for acceptance. This usually happens after an accepting
// reviewer resigns or is removed.
$new_status = DifferentialRevisionStatus::NEEDS_REVIEW;
} else if ($was_revision) {
// This revision was "Needs Revision", but no longer has any rejecting
// reviewers. This usually happens after the last rejecting reviewer
// resigns or is removed. Put the revision back in "Needs Review".
$new_status = DifferentialRevisionStatus::NEEDS_REVIEW;
}
if ($new_status === null) {
return $xactions;
}
$old_status = $revision->getModernRevisionStatus();
if ($new_status == $old_status) {
return $xactions;
}
$xaction = id(new DifferentialTransaction())
->setTransactionType(
DifferentialRevisionStatusTransaction::TRANSACTIONTYPE)
->setOldValue($old_status)
->setNewValue($new_status);
$xaction = $this->populateTransaction($revision, $xaction)
->save();
$xactions[] = $xaction;
// Save the status adjustment we made earlier.
$revision
->setModernRevisionStatus($new_status)
->save();
return $xactions;
}
protected function sortTransactions(array $xactions) {
$xactions = parent::sortTransactions($xactions);
$head = array();
$tail = array();
foreach ($xactions as $xaction) {
$type = $xaction->getTransactionType();
if ($type == DifferentialTransaction::TYPE_INLINE) {
$tail[] = $xaction;
} else {
$head[] = $xaction;
}
}
return array_values(array_merge($head, $tail));
}
protected function shouldPublishFeedStory(
PhabricatorLiskDAO $object,
array $xactions) {
if (!$object->getShouldBroadcast()) {
return false;
}
return true;
}
protected function shouldSendMail(
PhabricatorLiskDAO $object,
array $xactions) {
return true;
}
protected function getMailTo(PhabricatorLiskDAO $object) {
if ($object->getShouldBroadcast()) {
$this->requireReviewers($object);
$phids = array();
$phids[] = $object->getAuthorPHID();
foreach ($object->getReviewers() as $reviewer) {
if ($reviewer->isResigned()) {
continue;
}
$phids[] = $reviewer->getReviewerPHID();
}
return $phids;
}
// If we're demoting a draft after a build failure, just notify the author.
if ($this->isDraftDemotion) {
$author_phid = $object->getAuthorPHID();
return array(
$author_phid,
);
}
return array();
}
protected function getMailCC(PhabricatorLiskDAO $object) {
if (!$object->getShouldBroadcast()) {
return array();
}
return parent::getMailCC($object);
}
protected function newMailUnexpandablePHIDs(PhabricatorLiskDAO $object) {
$this->requireReviewers($object);
$phids = array();
foreach ($object->getReviewers() as $reviewer) {
if ($reviewer->isResigned()) {
$phids[] = $reviewer->getReviewerPHID();
}
}
return $phids;
}
protected function getMailAction(
PhabricatorLiskDAO $object,
array $xactions) {
$show_lines = false;
if ($this->isFirstBroadcast()) {
$action = pht('Request');
$show_lines = true;
} else {
$action = parent::getMailAction($object, $xactions);
$strongest = $this->getStrongestAction($object, $xactions);
$type_update = DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE;
if ($strongest->getTransactionType() == $type_update) {
$show_lines = true;
}
}
if ($show_lines) {
$count = new PhutilNumber($object->getLineCount());
$action = pht('%s] [%s', $action, $object->getRevisionScaleGlyphs());
}
return $action;
}
protected function getMailSubjectPrefix() {
return pht('[Differential]');
}
protected function getMailThreadID(PhabricatorLiskDAO $object) {
// This is nonstandard, but retains threading with older messages.
$phid = $object->getPHID();
return "differential-rev-{$phid}-req";
}
protected function buildReplyHandler(PhabricatorLiskDAO $object) {
return id(new DifferentialReplyHandler())
->setMailReceiver($object);
}
protected function buildMailTemplate(PhabricatorLiskDAO $object) {
$monogram = $object->getMonogram();
$title = $object->getTitle();
return id(new PhabricatorMetaMTAMail())
->setSubject(pht('%s: %s', $monogram, $title))
->setMustEncryptSubject(pht('%s: Revision Updated', $monogram))
->setMustEncryptURI($object->getURI());
}
protected function getTransactionsForMail(
PhabricatorLiskDAO $object,
array $xactions) {
// If this is the first time we're sending mail about this revision, we
// generate mail for all prior transactions, not just whatever is being
// applied now. This gets the "added reviewers" lines and other relevant
// information into the mail.
if ($this->isFirstBroadcast()) {
return $this->loadUnbroadcastTransactions($object);
}
return $xactions;
}
protected function getObjectLinkButtonLabelForMail(
PhabricatorLiskDAO $object) {
return pht('View Revision');
}
protected function buildMailBody(
PhabricatorLiskDAO $object,
array $xactions) {
$viewer = $this->requireActor();
$body = id(new PhabricatorMetaMTAMailBody())
->setViewer($viewer);
$revision_uri = $this->getObjectLinkButtonURIForMail($object);
$new_uri = $revision_uri.'/new/';
$this->addHeadersAndCommentsToMailBody(
$body,
$xactions,
$this->getObjectLinkButtonLabelForMail($object),
$revision_uri);
$type_inline = DifferentialTransaction::TYPE_INLINE;
$inlines = array();
foreach ($xactions as $xaction) {
if ($xaction->getTransactionType() == $type_inline) {
$inlines[] = $xaction;
}
}
if ($inlines) {
$this->appendInlineCommentsForMail($object, $inlines, $body);
}
$update_xaction = null;
foreach ($xactions as $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE:
$update_xaction = $xaction;
break;
}
}
if ($update_xaction) {
$diff = $this->requireDiff($update_xaction->getNewValue(), true);
} else {
$diff = null;
}
$changed_uri = $this->getChangedPriorToCommitURI();
if ($changed_uri) {
$body->addLinkSection(
pht('CHANGED PRIOR TO COMMIT'),
$changed_uri);
}
$this->addCustomFieldsToMailBody($body, $object, $xactions);
if (!$this->isFirstBroadcast()) {
$body->addLinkSection(pht('CHANGES SINCE LAST ACTION'), $new_uri);
}
$body->addLinkSection(
pht('REVISION DETAIL'),
$revision_uri);
if ($update_xaction) {
$body->addTextSection(
pht('AFFECTED FILES'),
$this->renderAffectedFilesForMail($diff));
$config_key_inline = 'metamta.differential.inline-patches';
$config_inline = PhabricatorEnv::getEnvConfig($config_key_inline);
$config_key_attach = 'metamta.differential.attach-patches';
$config_attach = PhabricatorEnv::getEnvConfig($config_key_attach);
if ($config_inline || $config_attach) {
$body_limit = PhabricatorEnv::getEnvConfig('metamta.email-body-limit');
try {
$patch = $this->buildPatchForMail($diff, $body_limit);
} catch (ArcanistDiffByteSizeException $ex) {
$patch = null;
}
if (($patch !== null) && $config_inline) {
$lines = substr_count($patch, "\n");
$bytes = strlen($patch);
// Limit the patch size to the smaller of 256 bytes per line or
// the mail body limit. This prevents degenerate behavior for patches
// with one line that is 10MB long. See T11748.
$byte_limits = array();
$byte_limits[] = (256 * $config_inline);
$byte_limits[] = $body_limit;
$byte_limit = min($byte_limits);
$lines_ok = ($lines <= $config_inline);
$bytes_ok = ($bytes <= $byte_limit);
if ($lines_ok && $bytes_ok) {
$this->appendChangeDetailsForMail($object, $diff, $patch, $body);
} else {
// TODO: Provide a helpful message about the patch being too
// large or lengthy here.
}
}
if (($patch !== null) && $config_attach) {
// See T12033, T11767, and PHI55. This is a crude fix to stop the
// major concrete problems that lackluster email size limits cause.
if (strlen($patch) < $body_limit) {
$name = pht('D%s.%s.patch', $object->getID(), $diff->getID());
$mime_type = 'text/x-patch; charset=utf-8';
$body->addAttachment(
new PhabricatorMailAttachment($patch, $name, $mime_type));
}
}
}
}
return $body;
}
public function getMailTagsMap() {
return array(
DifferentialTransaction::MAILTAG_REVIEW_REQUEST =>
pht('A revision is created.'),
DifferentialTransaction::MAILTAG_UPDATED =>
pht('A revision is updated.'),
DifferentialTransaction::MAILTAG_COMMENT =>
pht('Someone comments on a revision.'),
DifferentialTransaction::MAILTAG_CLOSED =>
pht('A revision is closed.'),
DifferentialTransaction::MAILTAG_REVIEWERS =>
pht("A revision's reviewers change."),
DifferentialTransaction::MAILTAG_CC =>
pht("A revision's CCs change."),
DifferentialTransaction::MAILTAG_OTHER =>
pht('Other revision activity not listed above occurs.'),
);
}
protected function supportsSearch() {
return true;
}
protected function expandCustomRemarkupBlockTransactions(
PhabricatorLiskDAO $object,
array $xactions,
array $changes,
PhutilMarkupEngine $engine) {
// For "Fixes ..." and "Depends on ...", we're only going to look at
// content blocks which are part of the revision itself (like "Summary"
// and "Test Plan"), not comments.
$content_parts = array();
foreach ($changes as $change) {
if ($change->getTransaction()->isCommentTransaction()) {
continue;
}
$content_parts[] = $change->getNewValue();
}
if (!$content_parts) {
return array();
}
$content_block = implode("\n\n", $content_parts);
$task_map = array();
$task_refs = id(new ManiphestCustomFieldStatusParser())
->parseCorpus($content_block);
foreach ($task_refs as $match) {
foreach ($match['monograms'] as $monogram) {
$task_id = (int)trim($monogram, 'tT');
$task_map[$task_id] = true;
}
}
$rev_map = array();
$rev_refs = id(new DifferentialCustomFieldDependsOnParser())
->parseCorpus($content_block);
foreach ($rev_refs as $match) {
foreach ($match['monograms'] as $monogram) {
$rev_id = (int)trim($monogram, 'dD');
$rev_map[$rev_id] = true;
}
}
$edges = array();
$task_phids = array();
$rev_phids = array();
if ($task_map) {
$tasks = id(new ManiphestTaskQuery())
->setViewer($this->getActor())
->withIDs(array_keys($task_map))
->execute();
if ($tasks) {
$task_phids = mpull($tasks, 'getPHID', 'getPHID');
$edge_related = DifferentialRevisionHasTaskEdgeType::EDGECONST;
$edges[$edge_related] = $task_phids;
}
}
if ($rev_map) {
$revs = id(new DifferentialRevisionQuery())
->setViewer($this->getActor())
->withIDs(array_keys($rev_map))
->execute();
$rev_phids = mpull($revs, 'getPHID', 'getPHID');
// NOTE: Skip any write attempts if a user cleverly implies a revision
// depends upon itself.
unset($rev_phids[$object->getPHID()]);
if ($revs) {
$depends = DifferentialRevisionDependsOnRevisionEdgeType::EDGECONST;
$edges[$depends] = $rev_phids;
}
}
$revert_refs = id(new DifferentialCustomFieldRevertsParser())
->parseCorpus($content_block);
$revert_monograms = array();
foreach ($revert_refs as $match) {
foreach ($match['monograms'] as $monogram) {
$revert_monograms[] = $monogram;
}
}
if ($revert_monograms) {
$revert_objects = DiffusionCommitRevisionQuery::loadRevertedObjects(
$this->getActor(),
$object,
$revert_monograms,
null);
$revert_phids = mpull($revert_objects, 'getPHID', 'getPHID');
$revert_type = DiffusionCommitRevertsCommitEdgeType::EDGECONST;
$edges[$revert_type] = $revert_phids;
} else {
$revert_phids = array();
}
$this->addUnmentionablePHIDs($task_phids);
$this->addUnmentionablePHIDs($rev_phids);
$this->addUnmentionablePHIDs($revert_phids);
$result = array();
foreach ($edges as $type => $specs) {
$result[] = id(new DifferentialTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue('edge:type', $type)
->setNewValue(array('+' => $specs));
}
return $result;
}
private function appendInlineCommentsForMail(
PhabricatorLiskDAO $object,
array $inlines,
PhabricatorMetaMTAMailBody $body) {
$limit = 100;
$limit_note = null;
if (count($inlines) > $limit) {
$limit_note = pht(
'(Showing first %s of %s inline comments.)',
new PhutilNumber($limit),
phutil_count($inlines));
$inlines = array_slice($inlines, 0, $limit, true);
}
$section = id(new DifferentialInlineCommentMailView())
->setViewer($this->getActor())
->setInlines($inlines)
->buildMailSection();
$header = pht('INLINE COMMENTS');
$section_text = "\n".$section->getPlaintext();
if ($limit_note) {
$section_text = $limit_note."\n".$section_text;
}
$style = array(
'margin: 6px 0 12px 0;',
);
$section_html = phutil_tag(
'div',
array(
'style' => implode(' ', $style),
),
$section->getHTML());
if ($limit_note) {
$section_html = array(
phutil_tag(
'em',
array(),
$limit_note),
$section_html,
);
}
$body->addPlaintextSection($header, $section_text, false);
$body->addHTMLSection($header, $section_html);
}
private function appendChangeDetailsForMail(
PhabricatorLiskDAO $object,
DifferentialDiff $diff,
$patch,
PhabricatorMetaMTAMailBody $body) {
$section = id(new DifferentialChangeDetailMailView())
->setViewer($this->getActor())
->setDiff($diff)
->setPatch($patch)
->buildMailSection();
$header = pht('CHANGE DETAILS');
$section_text = "\n".$section->getPlaintext();
$style = array(
'margin: 6px 0 12px 0;',
);
$section_html = phutil_tag(
'div',
array(
'style' => implode(' ', $style),
),
$section->getHTML());
$body->addPlaintextSection($header, $section_text, false);
$body->addHTMLSection($header, $section_html);
}
private function loadDiff($phid, $need_changesets = false) {
$query = id(new DifferentialDiffQuery())
->withPHIDs(array($phid))
->setViewer($this->getActor());
if ($need_changesets) {
$query->needChangesets(true);
}
return $query->executeOne();
}
public function requireDiff($phid, $need_changesets = false) {
$diff = $this->loadDiff($phid, $need_changesets);
if (!$diff) {
throw new Exception(pht('Diff "%s" does not exist!', $phid));
}
return $diff;
}
/* -( Herald Integration )------------------------------------------------- */
protected function shouldApplyHeraldRules(
PhabricatorLiskDAO $object,
array $xactions) {
return true;
}
protected function didApplyHeraldRules(
PhabricatorLiskDAO $object,
HeraldAdapter $adapter,
HeraldTranscript $transcript) {
$repository = $object->getRepository();
if (!$repository) {
return array();
}
$diff = $this->ownersDiff;
$changesets = $this->ownersChangesets;
$this->ownersDiff = null;
$this->ownersChangesets = null;
if (!$changesets) {
return array();
}
$packages = PhabricatorOwnersPackage::loadAffectedPackagesForChangesets(
$repository,
$diff,
$changesets);
if (!$packages) {
return array();
}
// Identify the packages with "Non-Owner Author" review rules and remove
// them if the author has authority over the package.
$autoreview_map = PhabricatorOwnersPackage::getAutoreviewOptionsMap();
$need_authority = array();
foreach ($packages as $package) {
$autoreview_setting = $package->getAutoReview();
$spec = idx($autoreview_map, $autoreview_setting);
if (!$spec) {
continue;
}
if (idx($spec, 'authority')) {
$need_authority[$package->getPHID()] = $package->getPHID();
}
}
if ($need_authority) {
$authority = id(new PhabricatorOwnersPackageQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs($need_authority)
->withAuthorityPHIDs(array($object->getAuthorPHID()))
->execute();
$authority = mpull($authority, null, 'getPHID');
foreach ($packages as $key => $package) {
$package_phid = $package->getPHID();
if (isset($authority[$package_phid])) {
unset($packages[$key]);
continue;
}
}
if (!$packages) {
return array();
}
}
$auto_subscribe = array();
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionTransactionType.php | src/applications/differential/xaction/DifferentialRevisionTransactionType.php | <?php
abstract class DifferentialRevisionTransactionType
extends PhabricatorModularTransactionType {
protected function validateCommitMessageCorpusTransactions(
$object,
array $xactions,
$field_name) {
$errors = array();
foreach ($xactions as $xaction) {
$error = $this->validateMessageCorpus($xaction, $field_name);
if ($error) {
$errors[] = $error;
}
}
return $errors;
}
private function validateMessageCorpus($xaction, $field_name) {
$value = $xaction->getNewValue();
if (!strlen($value)) {
return null;
}
// Put a placeholder title on the message, because the first line of a
// message is now always parsed as a title.
$value = "<placeholder>\n".$value;
$viewer = $this->getActor();
$parser = DifferentialCommitMessageParser::newStandardParser($viewer);
// Set custom title and summary keys so we can detect the presence of
// "Summary:" in, e.g., a test plan.
$parser->setTitleKey('__title__');
$parser->setSummaryKey('__summary__');
$result = $parser->parseCorpus($value);
unset($result['__title__']);
unset($result['__summary__']);
if (!$result) {
return null;
}
return $this->newInvalidError(
pht(
'The value you have entered in "%s" can not be parsed '.
'unambiguously when rendered in a commit message. Edit the '.
'message so that keywords like "Summary:" and "Test Plan:" do '.
'not appear at the beginning of lines. Parsed keys: %s.',
$field_name,
implode(', ', array_keys($result))),
$xaction);
}
protected function getActiveDiffPHID(DifferentialRevision $revision) {
try {
$diff = $revision->getActiveDiff();
if (!$diff) {
return null;
}
return $diff->getPHID();
} catch (Exception $ex) {
return null;
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionWrongBuildsTransaction.php | src/applications/differential/xaction/DifferentialRevisionWrongBuildsTransaction.php | <?php
final class DifferentialRevisionWrongBuildsTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.builds.wrong';
public function generateOldValue($object) {
return null;
}
public function generateNewValue($object, $value) {
return $value;
}
public function applyInternalEffects($object, $value) {
$object->setProperty(DifferentialRevision::PROPERTY_WRONG_BUILDS, true);
}
public function getIcon() {
return 'fa-exclamation';
}
public function getColor() {
return 'pink';
}
public function getActionStrength() {
return 400;
}
public function getTitle() {
return pht(
'This revision was landed with ongoing or failed builds.');
}
public function shouldHideForFeed() {
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/differential/xaction/DifferentialRevisionStatusTransaction.php | src/applications/differential/xaction/DifferentialRevisionStatusTransaction.php | <?php
final class DifferentialRevisionStatusTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.status';
public function generateOldValue($object) {
return $object->getModernRevisionStatus();
}
public function applyInternalEffects($object, $value) {
$object->setModernRevisionStatus($value);
}
public function getTitle() {
$status = $this->newStatusObject();
if ($status->isAccepted()) {
return pht('This revision is now accepted and ready to land.');
}
if ($status->isNeedsRevision()) {
return pht('This revision now requires changes to proceed.');
}
if ($status->isNeedsReview()) {
return pht('This revision now requires review to proceed.');
}
return null;
}
public function getTitleForFeed() {
$status = $this->newStatusObject();
if ($status->isAccepted()) {
return pht(
'%s is now accepted and ready to land.',
$this->renderObject());
}
if ($status->isNeedsRevision()) {
return pht(
'%s now requires changes to proceed.',
$this->renderObject());
}
if ($status->isNeedsReview()) {
return pht(
'%s now requires review to proceed.',
$this->renderObject());
}
return null;
}
public function getIcon() {
$status = $this->newStatusObject();
return $status->getTimelineIcon();
}
public function getColor() {
$status = $this->newStatusObject();
return $status->getTimelineColor();
}
private function newStatusObject() {
$new = $this->getNewValue();
return DifferentialRevisionStatus::newForStatus($new);
}
public function getTransactionTypeForConduit($xaction) {
return 'status';
}
public function getFieldValuesForConduit($xaction, $data) {
return array(
'old' => $xaction->getOldValue(),
'new' => $xaction->getNewValue(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionAuthorTransaction.php | src/applications/differential/xaction/DifferentialRevisionAuthorTransaction.php | <?php
final class DifferentialRevisionAuthorTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.author';
const EDITKEY = 'author';
public function generateOldValue($object) {
return $object->getAuthorPHID();
}
public function generateNewValue($object, $value) {
return $value;
}
public function applyInternalEffects($object, $value) {
$object->setAuthorPHID($value);
}
public function validateTransactions($object, array $xactions) {
$actor = $this->getActor();
$errors = array();
if (!$xactions) {
return $errors;
}
foreach ($xactions as $xaction) {
$old = $xaction->generateOldValue($object);
$new = $xaction->getNewValue();
if ($old === $new) {
continue;
}
if (!$new) {
$errors[] = $this->newInvalidError(
pht('Revisions must have an assigned author.'),
$xaction);
continue;
}
$author_objects = id(new PhabricatorPeopleQuery())
->setViewer($actor)
->withPHIDs(array($new))
->execute();
if (!$author_objects) {
$errors[] = $this->newInvalidError(
pht('Author "%s" is not a valid user.', $new),
$xaction);
continue;
}
}
return $errors;
}
public function getIcon() {
$author_phid = $this->getAuthorPHID();
$old_phid = $this->getOldValue();
$new_phid = $this->getNewValue();
$is_commandeer = ($author_phid === $new_phid);
$is_foist = ($author_phid === $old_phid);
if ($is_commandeer) {
return 'fa-flag';
}
if ($is_foist) {
return 'fa-gift';
}
return 'fa-user';
}
public function getColor() {
return 'sky';
}
public function getTitle() {
$author_phid = $this->getAuthorPHID();
$old_phid = $this->getOldValue();
$new_phid = $this->getNewValue();
$is_commandeer = ($author_phid === $new_phid);
$is_foist = ($author_phid === $old_phid);
if ($is_commandeer) {
return pht(
'%s commandeered this revision from %s.',
$this->renderAuthor(),
$this->renderOldHandle());
}
if ($is_foist) {
if ($new_phid) {
return pht(
'%s foisted this revision upon %s.',
$this->renderAuthor(),
$this->renderNewHandle());
} else {
// This isn't a valid transaction that can be applied, but happens in
// the preview if you temporarily delete the tokenizer value.
return pht(
'%s foisted this revision upon...',
$this->renderAuthor());
}
}
return pht(
'%s changed the author of this revision from %s to %s.',
$this->renderAuthor(),
$this->renderOldHandle(),
$this->renderNewHandle());
}
public function getTitleForFeed() {
$author_phid = $this->getAuthorPHID();
$old_phid = $this->getOldValue();
$new_phid = $this->getNewValue();
$is_commandeer = ($author_phid === $new_phid);
$is_foist = ($author_phid === $old_phid);
if ($is_commandeer) {
return pht(
'%s commandeered %s from %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderOldHandle());
}
if ($is_foist) {
return pht(
'%s foisted %s upon %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderNewHandle());
}
return pht(
'%s changed the author of %s from %s to %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderOldHandle(),
$this->renderNewHandle());
}
public function getTransactionTypeForConduit($xaction) {
return 'author';
}
public function getFieldValuesForConduit($object, $data) {
return array(
'old' => $object->getOldValue(),
'new' => $object->getNewValue(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionResignTransaction.php | src/applications/differential/xaction/DifferentialRevisionResignTransaction.php | <?php
final class DifferentialRevisionResignTransaction
extends DifferentialRevisionReviewTransaction {
const TRANSACTIONTYPE = 'differential.revision.resign';
const ACTIONKEY = 'resign';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Resign as Reviewer');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('You will resign as a reviewer for this change.');
}
public function getIcon() {
return 'fa-flag';
}
public function getColor() {
return 'orange';
}
protected function getRevisionActionOrder() {
return 700;
}
public function getCommandKeyword() {
return 'resign';
}
public function getActionName() {
return pht('Resigned');
}
public function getCommandAliases() {
return array();
}
public function getCommandSummary() {
return pht('Resign from a revision.');
}
public function generateOldValue($object) {
$actor = $this->getActor();
$resigned = DifferentialReviewerStatus::STATUS_RESIGNED;
return ($this->getViewerReviewerStatus($object, $actor) == $resigned);
}
public function applyExternalEffects($object, $value) {
$status = DifferentialReviewerStatus::STATUS_RESIGNED;
$actor = $this->getActor();
$this->applyReviewerEffect($object, $actor, $value, $status);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if ($object->isClosed()) {
throw new Exception(
pht(
'You can not resign from this revision because it has already '.
'been closed. You can only resign from open revisions.'));
}
$resigned = DifferentialReviewerStatus::STATUS_RESIGNED;
if ($this->getViewerReviewerStatus($object, $viewer) == $resigned) {
throw new Exception(
pht(
'You can not resign from this revision because you have already '.
'resigned.'));
}
if (!$this->isViewerAnyAuthority($object, $viewer)) {
throw new Exception(
pht(
'You can not resign from this revision because you are not a '.
'reviewer, and do not have authority over any reviewer.'));
}
}
public function getTitle() {
return pht(
'%s resigned from this revision.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s resigned from %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getTransactionTypeForConduit($xaction) {
return 'resign';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionAbandonTransaction.php | src/applications/differential/xaction/DifferentialRevisionAbandonTransaction.php | <?php
final class DifferentialRevisionAbandonTransaction
extends DifferentialRevisionActionTransaction {
const TRANSACTIONTYPE = 'differential.revision.abandon';
const ACTIONKEY = 'abandon';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Abandon Revision');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('This revision will be abandoned and closed.');
}
public function getIcon() {
return 'fa-plane';
}
public function getColor() {
return 'indigo';
}
protected function getRevisionActionOrder() {
return 500;
}
public function getActionName() {
return pht('Abandoned');
}
public function getCommandKeyword() {
return 'abandon';
}
public function getCommandAliases() {
return array();
}
public function getCommandSummary() {
return pht('Abandon a revision.');
}
public function generateOldValue($object) {
return $object->isAbandoned();
}
public function applyInternalEffects($object, $value) {
$status_abandoned = DifferentialRevisionStatus::ABANDONED;
$object->setModernRevisionStatus($status_abandoned);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if ($object->isClosed()) {
throw new Exception(
pht(
'You can not abandon this revision because it has already been '.
'closed. Only open revisions can be abandoned.'));
}
$config_key = 'differential.always-allow-abandon';
if (!PhabricatorEnv::getEnvConfig($config_key)) {
if (!$this->isViewerRevisionAuthor($object, $viewer)) {
throw new Exception(
pht(
'You can not abandon this revision because you are not the '.
'author. You can only abandon revisions you own. You can change '.
'this behavior by adjusting the "%s" setting in Config.',
$config_key));
}
}
}
public function getTitle() {
return pht(
'%s abandoned this revision.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s abandoned %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getTransactionTypeForConduit($xaction) {
return 'abandon';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionCloseTransaction.php | src/applications/differential/xaction/DifferentialRevisionCloseTransaction.php | <?php
final class DifferentialRevisionCloseTransaction
extends DifferentialRevisionActionTransaction {
const TRANSACTIONTYPE = 'differential.revision.close';
const ACTIONKEY = 'close';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Close Revision');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('This revision will be closed.');
}
public function getIcon() {
return 'fa-check';
}
public function getColor() {
return 'indigo';
}
protected function getRevisionActionOrder() {
return 300;
}
public function getActionName() {
return pht('Closed');
}
public function generateOldValue($object) {
return $object->isClosed();
}
public function applyInternalEffects($object, $value) {
$was_accepted = $object->isAccepted();
$status_published = DifferentialRevisionStatus::PUBLISHED;
$object->setModernRevisionStatus($status_published);
$object->setProperty(
DifferentialRevision::PROPERTY_CLOSED_FROM_ACCEPTED,
$was_accepted);
// See T13300. When a revision is closed, we promote it out of "Draft"
// immediately. This usually happens when a user creates a draft revision
// and then lands the associated commit before the revision leaves draft.
$object->setShouldBroadcast(true);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if ($this->hasEditor()) {
if ($this->getEditor()->getIsCloseByCommit()) {
// If we're closing a revision because we discovered a commit, we don't
// care what state it was in.
return;
}
}
if ($object->isClosed()) {
throw new Exception(
pht(
'You can not close this revision because it has already been '.
'closed. Only open revisions can be closed.'));
}
if (!$object->isAccepted()) {
throw new Exception(
pht(
'You can not close this revision because it has not been accepted. '.
'Revisions must be accepted before they can be closed.'));
}
$config_key = 'differential.always-allow-close';
if (!PhabricatorEnv::getEnvConfig($config_key)) {
if (!$this->isViewerRevisionAuthor($object, $viewer)) {
throw new Exception(
pht(
'You can not close this revision because you are not the '.
'author. You can only close revisions you own. You can change '.
'this behavior by adjusting the "%s" setting in Config.',
$config_key));
}
}
}
public function getTitle() {
$commit_phid = $this->getMetadataValue('commitPHID');
if ($commit_phid) {
$commit = id(new DiffusionCommitQuery())
->setViewer($this->getViewer())
->withPHIDs(array($commit_phid))
->needIdentities(true)
->executeOne();
} else {
$commit = null;
}
if (!$commit) {
return pht(
'%s closed this revision.',
$this->renderAuthor());
}
$author_phid = null;
if ($commit->hasAuthorIdentity()) {
$identity = $commit->getAuthorIdentity();
$author_phid = $identity->getIdentityDisplayPHID();
}
$committer_phid = null;
if ($commit->hasCommitterIdentity()) {
$identity = $commit->getCommitterIdentity();
$committer_phid = $identity->getIdentityDisplayPHID();
}
if (!$author_phid) {
return pht(
'Closed by commit %s.',
$this->renderHandle($commit_phid));
} else if (!$committer_phid || ($committer_phid === $author_phid)) {
return pht(
'Closed by commit %s (authored by %s).',
$this->renderHandle($commit_phid),
$this->renderHandle($author_phid));
} else {
return pht(
'Closed by commit %s (authored by %s, committed by %s).',
$this->renderHandle($commit_phid),
$this->renderHandle($author_phid),
$this->renderHandle($committer_phid));
}
}
public function getTitleForFeed() {
return pht(
'%s closed %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getTransactionTypeForConduit($xaction) {
return 'close';
}
public function getFieldValuesForConduit($object, $data) {
$commit_phid = $object->getMetadataValue('commitPHID');
if ($commit_phid) {
$commit_phids = array($commit_phid);
} else {
$commit_phids = array();
}
return array(
'commitPHIDs' => $commit_phids,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionTestPlanTransaction.php | src/applications/differential/xaction/DifferentialRevisionTestPlanTransaction.php | <?php
final class DifferentialRevisionTestPlanTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.testplan';
const EDITKEY = 'testPlan';
public function generateOldValue($object) {
return $object->getTestPlan();
}
public function applyInternalEffects($object, $value) {
$object->setTestPlan($value);
}
public function getTitle() {
return pht(
'%s edited the test plan for this revision.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s updated the test plan for %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function hasChangeDetailView() {
return true;
}
public function getMailDiffSectionHeader() {
return pht('CHANGES TO TEST PLAN');
}
public function newChangeDetailView() {
$viewer = $this->getViewer();
return id(new PhabricatorApplicationTransactionTextDiffDetailView())
->setViewer($viewer)
->setOldText($this->getOldValue())
->setNewText($this->getNewValue());
}
public function newRemarkupChanges() {
$changes = array();
$changes[] = $this->newRemarkupChange()
->setOldValue($this->getOldValue())
->setNewValue($this->getNewValue());
return $changes;
}
public function validateTransactions($object, array $xactions) {
$errors = $this->validateCommitMessageCorpusTransactions(
$object,
$xactions,
pht('Test Plan'));
$is_required = PhabricatorEnv::getEnvConfig(
'differential.require-test-plan-field');
if ($is_required) {
if ($this->isEmptyTextTransaction($object->getTestPlan(), $xactions)) {
$errors[] = $this->newRequiredError(
pht(
'You must provide a test plan. Describe the actions you '.
'performed to verify the behavior of this change.'));
}
}
return $errors;
}
public function getTransactionTypeForConduit($xaction) {
return 'testPlan';
}
public function getFieldValuesForConduit($xaction, $data) {
return array(
'old' => $xaction->getOldValue(),
'new' => $xaction->getNewValue(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionActionTransaction.php | src/applications/differential/xaction/DifferentialRevisionActionTransaction.php | <?php
abstract class DifferentialRevisionActionTransaction
extends DifferentialRevisionTransactionType {
final public function getRevisionActionKey() {
return $this->getPhobjectClassConstant('ACTIONKEY', 32);
}
public function isActionAvailable($object, PhabricatorUser $viewer) {
try {
$this->validateAction($object, $viewer);
return true;
} catch (Exception $ex) {
return false;
}
}
abstract protected function validateAction($object, PhabricatorUser $viewer);
abstract protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer);
protected function validateOptionValue($object, $actor, array $value) {
return null;
}
public function getCommandKeyword() {
return null;
}
public function getCommandAliases() {
return array();
}
public function getCommandSummary() {
return null;
}
protected function getRevisionActionOrder() {
return 1000;
}
public function getActionStrength() {
return 300;
}
public function getRevisionActionOrderVector() {
return id(new PhutilSortVector())
->addInt($this->getRevisionActionOrder());
}
protected function getRevisionActionGroupKey() {
return DifferentialRevisionEditEngine::ACTIONGROUP_REVISION;
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return null;
}
protected function getRevisionActionSubmitButtonText(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return null;
}
protected function getRevisionActionMetadata(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return array();
}
public static function loadAllActions() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getRevisionActionKey')
->execute();
}
protected function isViewerRevisionAuthor(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
if (!$viewer->getPHID()) {
return false;
}
return ($viewer->getPHID() === $revision->getAuthorPHID());
}
protected function getActionOptions(
PhabricatorUser $viewer,
DifferentialRevision $revision) {
return array(
array(),
array(),
);
}
public function newEditField(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
// Actions in the "review" group, like "Accept Revision", do not require
// that the actor be able to edit the revision.
$group_review = DifferentialRevisionEditEngine::ACTIONGROUP_REVIEW;
$is_review = ($this->getRevisionActionGroupKey() == $group_review);
$field = id(new PhabricatorApplyEditField())
->setKey($this->getRevisionActionKey())
->setTransactionType($this->getTransactionTypeConstant())
->setCanApplyWithoutEditCapability($is_review)
->setValue(true);
if ($this->isActionAvailable($revision, $viewer)) {
$label = $this->getRevisionActionLabel($revision, $viewer);
if ($label !== null) {
$field->setCommentActionLabel($label);
$description = $this->getRevisionActionDescription($revision, $viewer);
$field->setActionDescription($description);
$group_key = $this->getRevisionActionGroupKey();
$field->setCommentActionGroupKey($group_key);
$button_text = $this->getRevisionActionSubmitButtonText(
$revision,
$viewer);
$field->setActionSubmitButtonText($button_text);
// Currently, every revision action conflicts with every other
// revision action: for example, you can not simultaneously Accept and
// Reject a revision.
// Under some configurations, some combinations of actions are sort of
// technically permissible. For example, you could reasonably Reject
// and Abandon a revision if "anyone can abandon anything" is enabled.
// It's not clear that these combinations are actually useful, so just
// keep things simple for now.
$field->setActionConflictKey('revision.action');
list($options, $value) = $this->getActionOptions($viewer, $revision);
// Show the options if the user can select on behalf of two or more
// reviewers, or can force-accept on behalf of one or more reviewers,
// or can accept on behalf of a reviewer other than themselves (see
// T12533).
$can_multi = (count($options) > 1);
$can_force = (count($value) < count($options));
$not_self = (head_key($options) != $viewer->getPHID());
if ($can_multi || $can_force || $not_self) {
$field->setOptions($options);
$field->setValue($value);
}
$metadata = $this->getRevisionActionMetadata($revision, $viewer);
foreach ($metadata as $metadata_key => $metadata_value) {
$field->setMetadataValue($metadata_key, $metadata_value);
}
}
}
return $field;
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$actor = $this->getActor();
$action_exception = null;
foreach ($xactions as $xaction) {
// If this is a draft demotion action, let it skip all the normal
// validation. This is a little hacky and should perhaps move down
// into the actual action implementations, but currently we can not
// apply this rule in validateAction() because it doesn't operate on
// the actual transaction.
if ($xaction->getMetadataValue('draft.demote')) {
continue;
}
try {
$this->validateAction($object, $actor);
} catch (Exception $ex) {
$action_exception = $ex;
}
break;
}
foreach ($xactions as $xaction) {
if ($action_exception) {
$errors[] = $this->newInvalidError(
$action_exception->getMessage(),
$xaction);
continue;
}
$new = $xaction->getNewValue();
if (!is_array($new)) {
continue;
}
try {
$this->validateOptionValue($object, $actor, $new);
} catch (Exception $ex) {
$errors[] = $this->newInvalidError(
$ex->getMessage(),
$xaction);
}
}
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/differential/xaction/DifferentialRevisionWrongStateTransaction.php | src/applications/differential/xaction/DifferentialRevisionWrongStateTransaction.php | <?php
final class DifferentialRevisionWrongStateTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.wrong';
public function generateOldValue($object) {
return null;
}
public function generateNewValue($object, $value) {
return $value;
}
public function getIcon() {
return 'fa-exclamation';
}
public function getColor() {
return 'pink';
}
public function getActionStrength() {
return 400;
}
public function getTitle() {
$new_value = $this->getNewValue();
$status = DifferentialRevisionStatus::newForStatus($new_value);
return pht(
'This revision was not accepted when it landed; it landed in state %s.',
$this->renderValue($status->getDisplayName()));
}
public function shouldHideForFeed() {
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/differential/xaction/DifferentialRevisionReviewTransaction.php | src/applications/differential/xaction/DifferentialRevisionReviewTransaction.php | <?php
abstract class DifferentialRevisionReviewTransaction
extends DifferentialRevisionActionTransaction {
protected function getRevisionActionGroupKey() {
return DifferentialRevisionEditEngine::ACTIONGROUP_REVIEW;
}
public function generateNewValue($object, $value) {
if (!is_array($value)) {
return true;
}
// If the list of options is the same as the default list, just treat this
// as a "take the default action" transaction.
$viewer = $this->getActor();
list($options, $default) = $this->getActionOptions($viewer, $object);
// Remove reviewers which aren't actionable. In the case of "Accept", we
// may allow the transaction to proceed with some reviewers who have
// already accepted, to avoid race conditions where two reviewers fill
// out the form at the same time and accept on behalf of the same package.
// It's okay for these reviewers to survive validation, but they should
// not survive beyond this point.
$value = array_fuse($value);
$value = array_intersect($value, array_keys($options));
$value = array_values($value);
sort($default);
sort($value);
if ($default === $value) {
return true;
}
return $value;
}
protected function isViewerAnyReviewer(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return ($this->getViewerReviewerStatus($revision, $viewer) !== null);
}
protected function isViewerAnyAuthority(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
$reviewers = $revision->getReviewers();
foreach ($revision->getReviewers() as $reviewer) {
if ($reviewer->hasAuthority($viewer)) {
return true;
}
}
return false;
}
protected function isViewerFullyAccepted(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return $this->isViewerReviewerStatusFully(
$revision,
$viewer,
DifferentialReviewerStatus::STATUS_ACCEPTED);
}
protected function isViewerFullyRejected(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return $this->isViewerReviewerStatusFully(
$revision,
$viewer,
DifferentialReviewerStatus::STATUS_REJECTED);
}
protected function getViewerReviewerStatus(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
if (!$viewer->getPHID()) {
return null;
}
foreach ($revision->getReviewers() as $reviewer) {
if ($reviewer->getReviewerPHID() != $viewer->getPHID()) {
continue;
}
return $reviewer->getReviewerStatus();
}
return null;
}
private function isViewerReviewerStatusFully(
DifferentialRevision $revision,
PhabricatorUser $viewer,
$require_status) {
// If the user themselves is not a reviewer, the reviews they have
// authority over can not all be in any set of states since their own
// personal review has no state.
$status = $this->getViewerReviewerStatus($revision, $viewer);
if ($status === null) {
return false;
}
$active_phid = $this->getActiveDiffPHID($revision);
$status_accepted = DifferentialReviewerStatus::STATUS_ACCEPTED;
$status_rejected = DifferentialReviewerStatus::STATUS_REJECTED;
$is_accepted = ($require_status == $status_accepted);
$is_rejected = ($require_status == $status_rejected);
// Otherwise, check that all reviews they have authority over are in
// the desired set of states.
foreach ($revision->getReviewers() as $reviewer) {
if (!$reviewer->hasAuthority($viewer)) {
$can_force = false;
if ($is_accepted) {
if ($revision->canReviewerForceAccept($viewer, $reviewer)) {
$can_force = true;
}
}
if (!$can_force) {
continue;
}
}
$status = $reviewer->getReviewerStatus();
if ($status != $require_status) {
return false;
}
// Here, we're primarily testing if we can remove a void on the review.
if ($is_accepted) {
if (!$reviewer->isAccepted($active_phid)) {
return false;
}
}
if ($is_rejected) {
if (!$reviewer->isRejected($active_phid)) {
return false;
}
}
// This is a broader check to see if we can update the diff where the
// last action occurred.
if ($reviewer->getLastActionDiffPHID() != $active_phid) {
return false;
}
}
return true;
}
protected function applyReviewerEffect(
DifferentialRevision $revision,
PhabricatorUser $viewer,
$value,
$status,
array $reviewer_options = array()) {
PhutilTypeSpec::checkMap(
$reviewer_options,
array(
'sticky' => 'optional bool',
));
$map = array();
// When you accept or reject, you may accept or reject on behalf of all
// reviewers you have authority for. When you resign, you only affect
// yourself.
$with_authority = ($status != DifferentialReviewerStatus::STATUS_RESIGNED);
$with_force = ($status == DifferentialReviewerStatus::STATUS_ACCEPTED);
if ($with_authority) {
foreach ($revision->getReviewers() as $reviewer) {
if (!$reviewer->hasAuthority($viewer)) {
if (!$with_force) {
continue;
}
if (!$revision->canReviewerForceAccept($viewer, $reviewer)) {
continue;
}
}
$map[$reviewer->getReviewerPHID()] = $status;
}
}
// In all cases, you affect yourself.
$map[$viewer->getPHID()] = $status;
// If we're applying an "accept the defaults" transaction, and this
// transaction type uses checkboxes, replace the value with the list of
// defaults.
if (!is_array($value)) {
list($options, $default) = $this->getActionOptions($viewer, $revision);
if ($options) {
$value = $default;
}
}
// If we have a specific list of reviewers to act on, usually because the
// user has submitted a specific list of reviewers to act as by
// unchecking some checkboxes under "Accept", only affect those reviewers.
if (is_array($value)) {
$map = array_select_keys($map, $value);
}
// Now, do the new write.
if ($map) {
$diff = $this->getEditor()->getActiveDiff($revision);
if ($diff) {
$diff_phid = $diff->getPHID();
} else {
$diff_phid = null;
}
$table = new DifferentialReviewer();
$src_phid = $revision->getPHID();
$reviewers = $table->loadAllWhere(
'revisionPHID = %s AND reviewerPHID IN (%Ls)',
$src_phid,
array_keys($map));
$reviewers = mpull($reviewers, null, 'getReviewerPHID');
foreach (array_keys($map) as $dst_phid) {
$reviewer = idx($reviewers, $dst_phid);
if (!$reviewer) {
$reviewer = id(new DifferentialReviewer())
->setRevisionPHID($src_phid)
->setReviewerPHID($dst_phid);
}
$old_status = $reviewer->getReviewerStatus();
$reviewer->setReviewerStatus($status);
if ($diff_phid) {
$reviewer->setLastActionDiffPHID($diff_phid);
}
if ($old_status !== $status) {
$reviewer->setLastActorPHID($this->getActingAsPHID());
}
// Clear any outstanding void on this reviewer. A void may be placed
// by the author using "Request Review" when a reviewer has already
// accepted.
$reviewer->setVoidedPHID(null);
$reviewer->setOption('sticky', idx($reviewer_options, 'sticky'));
try {
$reviewer->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// At least for now, just ignore it if we lost a race.
}
}
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionRepositoryTransaction.php | src/applications/differential/xaction/DifferentialRevisionRepositoryTransaction.php | <?php
final class DifferentialRevisionRepositoryTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.repository';
public function generateOldValue($object) {
return $object->getRepositoryPHID();
}
public function applyInternalEffects($object, $value) {
$object->setRepositoryPHID($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old && $new) {
return pht(
'%s changed the repository for this revision from %s to %s.',
$this->renderAuthor(),
$this->renderHandle($old),
$this->renderHandle($new));
} else if ($new) {
return pht(
'%s set the repository for this revision to %s.',
$this->renderAuthor(),
$this->renderHandle($new));
} else {
return pht(
'%s removed %s as the repository for this revision.',
$this->renderAuthor(),
$this->renderHandle($old));
}
}
public function getTitleForFeed() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old && $new) {
return pht(
'%s changed the repository for %s from %s to %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderHandle($old),
$this->renderHandle($new));
} else if ($new) {
return pht(
'%s set the repository for %s to %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderHandle($new));
} else {
return pht(
'%s removed %s as the repository for %s.',
$this->renderAuthor(),
$this->renderHandle($old),
$this->renderObject());
}
}
public function validateTransactions($object, array $xactions) {
$actor = $this->getActor();
$errors = array();
$old_value = $object->getRepositoryPHID();
foreach ($xactions as $xaction) {
$new_value = $xaction->getNewValue();
if (!$new_value) {
continue;
}
if ($new_value == $old_value) {
continue;
}
$repository = id(new PhabricatorRepositoryQuery())
->setViewer($actor)
->withPHIDs(array($new_value))
->executeOne();
if (!$repository) {
$errors[] = $this->newInvalidError(
pht(
'Repository "%s" is not a valid repository, or you do not have '.
'permission to view it.',
$new_value),
$xaction);
}
}
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/differential/xaction/DifferentialRevisionReclaimTransaction.php | src/applications/differential/xaction/DifferentialRevisionReclaimTransaction.php | <?php
final class DifferentialRevisionReclaimTransaction
extends DifferentialRevisionActionTransaction {
const TRANSACTIONTYPE = 'differential.revision.reclaim';
const ACTIONKEY = 'reclaim';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Reclaim Revision');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('This revision will be reclaimed and reopened.');
}
public function getIcon() {
return 'fa-bullhorn';
}
public function getColor() {
return 'sky';
}
protected function getRevisionActionOrder() {
return 600;
}
public function getActionName() {
return pht('Reclaimed');
}
public function getCommandKeyword() {
return 'reclaim';
}
public function getCommandAliases() {
return array();
}
public function getCommandSummary() {
return pht('Reclaim a revision.');
}
public function generateOldValue($object) {
return !$object->isAbandoned();
}
public function applyInternalEffects($object, $value) {
if ($object->getShouldBroadcast()) {
$new_status = DifferentialRevisionStatus::NEEDS_REVIEW;
} else {
$new_status = DifferentialRevisionStatus::DRAFT;
}
$object->setModernRevisionStatus($new_status);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if (!$object->isAbandoned()) {
throw new Exception(
pht(
'You can not reclaim this revision because it has not been '.
'abandoned. Only abandoned revisions can be reclaimed.'));
}
if (!$this->isViewerRevisionAuthor($object, $viewer)) {
throw new Exception(
pht(
'You can not reclaim this revision because you are not the '.
'revision author. You can only reclaim revisions you own.'));
}
}
public function getTitle() {
return pht(
'%s reclaimed this revision.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s reclaimed %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getTransactionTypeForConduit($xaction) {
return 'reclaim';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionAcceptTransaction.php | src/applications/differential/xaction/DifferentialRevisionAcceptTransaction.php | <?php
final class DifferentialRevisionAcceptTransaction
extends DifferentialRevisionReviewTransaction {
const TRANSACTIONTYPE = 'differential.revision.accept';
const ACTIONKEY = 'accept';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Accept Revision');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('These changes will be approved.');
}
public function getIcon() {
return 'fa-check-circle-o';
}
public function getColor() {
return 'green';
}
protected function getRevisionActionOrder() {
return 500;
}
public function getActionName() {
return pht('Accepted');
}
public function getCommandKeyword() {
$accept_key = 'differential.enable-email-accept';
$allow_email_accept = PhabricatorEnv::getEnvConfig($accept_key);
if (!$allow_email_accept) {
return null;
}
return 'accept';
}
public function getCommandAliases() {
return array();
}
public function getCommandSummary() {
return pht('Accept a revision.');
}
protected function getActionOptions(
PhabricatorUser $viewer,
DifferentialRevision $revision,
$include_accepted = false) {
$reviewers = $revision->getReviewers();
$options = array();
$value = array();
// Put the viewer's user reviewer first, if it exists, so that "Accept as
// yourself" is always at the top.
$head = array();
$tail = array();
foreach ($reviewers as $key => $reviewer) {
if ($reviewer->isUser()) {
$head[$key] = $reviewer;
} else {
$tail[$key] = $reviewer;
}
}
$reviewers = $head + $tail;
$diff_phid = $this->getActiveDiffPHID($revision);
$reviewer_phids = array();
// If the viewer isn't a reviewer, add them to the list of options first.
// This happens when you navigate to some revision you aren't involved in:
// you can accept and become a reviewer.
$viewer_phid = $viewer->getPHID();
if ($viewer_phid) {
if (!isset($reviewers[$viewer_phid])) {
$reviewer_phids[$viewer_phid] = $viewer_phid;
}
}
$default_unchecked = array();
foreach ($reviewers as $reviewer) {
$reviewer_phid = $reviewer->getReviewerPHID();
if (!$reviewer->hasAuthority($viewer)) {
// If the viewer doesn't have authority to act on behalf of a reviewer,
// we check if they can accept by force.
if ($revision->canReviewerForceAccept($viewer, $reviewer)) {
$default_unchecked[$reviewer_phid] = true;
} else {
continue;
}
}
if (!$include_accepted) {
if ($reviewer->isAccepted($diff_phid)) {
// If a reviewer is already in a full "accepted" state, don't
// include that reviewer as an option unless we're listing all
// reviewers, including reviewers who have already accepted.
continue;
}
}
$reviewer_phids[$reviewer_phid] = $reviewer_phid;
}
$handles = $viewer->loadHandles($reviewer_phids);
$head = array();
$tail = array();
foreach ($reviewer_phids as $reviewer_phid) {
$is_force = isset($default_unchecked[$reviewer_phid]);
if ($is_force) {
$tail[] = $reviewer_phid;
$options[$reviewer_phid] = pht(
'Force accept as %s',
$viewer->renderHandle($reviewer_phid));
} else {
$head[] = $reviewer_phid;
$value[] = $reviewer_phid;
$options[$reviewer_phid] = pht(
'Accept as %s',
$viewer->renderHandle($reviewer_phid));
}
}
// Reorder reviewers so "force accept" reviewers come at the end.
$options =
array_select_keys($options, $head) +
array_select_keys($options, $tail);
return array($options, $value);
}
public function generateOldValue($object) {
$actor = $this->getActor();
return $this->isViewerFullyAccepted($object, $actor);
}
public function applyExternalEffects($object, $value) {
$status = DifferentialReviewerStatus::STATUS_ACCEPTED;
$actor = $this->getActor();
$this->applyReviewerEffect($object, $actor, $value, $status);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if ($object->isClosed()) {
throw new Exception(
pht(
'You can not accept this revision because it has already been '.
'closed. Only open revisions can be accepted.'));
}
if ($object->isDraft() || !$object->getShouldBroadcast()) {
throw new Exception(
pht('You can not accept a draft revision.'));
}
$config_key = 'differential.allow-self-accept';
if (!PhabricatorEnv::getEnvConfig($config_key)) {
if ($this->isViewerRevisionAuthor($object, $viewer)) {
throw new Exception(
pht(
'You can not accept this revision because you are the revision '.
'author. You can only accept revisions you do not own. You can '.
'change this behavior by adjusting the "%s" setting in Config.',
$config_key));
}
}
if ($this->isViewerFullyAccepted($object, $viewer)) {
throw new Exception(
pht(
'You can not accept this revision because you have already '.
'accepted it.'));
}
}
protected function validateOptionValue($object, $actor, array $value) {
if (!$value) {
throw new Exception(
pht(
'When accepting a revision, you must accept on behalf of at '.
'least one reviewer.'));
}
// NOTE: We're including reviewers who have already been accepted in this
// check. Legitimate users may race one another to accept on behalf of
// packages. If we get a form submission which includes a reviewer which
// someone has already accepted, that's fine. See T12757.
list($options) = $this->getActionOptions($actor, $object, true);
foreach ($value as $phid) {
if (!isset($options[$phid])) {
throw new Exception(
pht(
'Reviewer "%s" is not a valid reviewer which you have authority '.
'to accept on behalf of.',
$phid));
}
}
}
public function getTitle() {
$new = $this->getNewValue();
if (is_array($new) && $new) {
return pht(
'%s accepted this revision as %s reviewer(s): %s.',
$this->renderAuthor(),
phutil_count($new),
$this->renderHandleList($new));
} else {
return pht(
'%s accepted this revision.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
return pht(
'%s accepted %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getTransactionTypeForConduit($xaction) {
return 'accept';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionVoidTransaction.php | src/applications/differential/xaction/DifferentialRevisionVoidTransaction.php | <?php
/**
* This is an internal transaction type used to void reviews.
*
* For example, "Request Review" voids any open accepts, so they no longer
* act as current accepts.
*/
final class DifferentialRevisionVoidTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.void';
public function generateOldValue($object) {
return false;
}
public function generateNewValue($object, $value) {
$reviewers = id(new DifferentialReviewer())->loadAllWhere(
'revisionPHID = %s
AND voidedPHID IS NULL
AND reviewerStatus IN (%Ls)',
$object->getPHID(),
$value);
$must_downgrade = $this->getMetadataValue('void.force', array());
$must_downgrade = array_fuse($must_downgrade);
$default = PhabricatorEnv::getEnvConfig('differential.sticky-accept');
foreach ($reviewers as $key => $reviewer) {
$status = $reviewer->getReviewerStatus();
// If this void is forced, always downgrade. For example, this happens
// when an author chooses "Request Review": existing reviews are always
// voided, even if they're sticky.
if (isset($must_downgrade[$status])) {
continue;
}
// Otherwise, if this is a sticky accept, don't void it. Accepts may be
// explicitly sticky or unsticky, or they'll use the default value if
// no value is specified.
$is_sticky = $reviewer->getOption('sticky');
$is_sticky = coalesce($is_sticky, $default);
if ($status === DifferentialReviewerStatus::STATUS_ACCEPTED) {
if ($is_sticky) {
unset($reviewers[$key]);
continue;
}
}
}
return mpull($reviewers, 'getReviewerPHID');
}
public function getTransactionHasEffect($object, $old, $new) {
return (bool)$new;
}
public function applyExternalEffects($object, $value) {
$table = new DifferentialReviewer();
$table_name = $table->getTableName();
$conn = $table->establishConnection('w');
queryfx(
$conn,
'UPDATE %T SET voidedPHID = %s
WHERE revisionPHID = %s
AND voidedPHID IS NULL
AND reviewerPHID IN (%Ls)',
$table_name,
$this->getActingAsPHID(),
$object->getPHID(),
$value);
}
public function shouldHide() {
// This is an internal transaction, so don't show it in feeds or
// transaction logs.
return true;
}
private function getVoidableStatuses() {
return array(
DifferentialReviewerStatus::STATUS_ACCEPTED,
DifferentialReviewerStatus::STATUS_REJECTED,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionInlineTransaction.php | src/applications/differential/xaction/DifferentialRevisionInlineTransaction.php | <?php
final class DifferentialRevisionInlineTransaction
extends PhabricatorModularTransactionType {
// NOTE: This class is NOT an actual Differential modular transaction type!
// It does not extend "DifferentialRevisionTransactionType". Some day it
// should, but for now it's just reducing the amount of hackiness around
// supporting inline comments in the "transaction.search" Conduit API method.
const TRANSACTIONTYPE = 'internal.pretend-inline';
public function getTransactionTypeForConduit($xaction) {
return 'inline';
}
public function loadTransactionTypeConduitData(array $xactions) {
$viewer = $this->getViewer();
$changeset_ids = array();
foreach ($xactions as $xaction) {
$changeset_ids[] = $xaction->getComment()->getChangesetID();
}
$changesets = id(new DifferentialChangesetQuery())
->setViewer($viewer)
->withIDs($changeset_ids)
->execute();
$changesets = mpull($changesets, null, 'getID');
return $changesets;
}
public function getFieldValuesForConduit($object, $data) {
$comment = $object->getComment();
$changeset = $data[$comment->getChangesetID()];
$diff = $changeset->getDiff();
$is_done = false;
switch ($comment->getFixedState()) {
case PhabricatorInlineComment::STATE_DONE:
case PhabricatorInlineComment::STATE_UNDRAFT:
$is_done = true;
break;
}
return array(
'diff' => array(
'id' => (int)$diff->getID(),
'phid' => $diff->getPHID(),
),
'path' => $changeset->getDisplayFilename(),
'line' => (int)$comment->getLineNumber(),
'length' => (int)($comment->getLineLength() + 1),
'replyToCommentPHID' => $comment->getReplyToCommentPHID(),
'isDone' => $is_done,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionSummaryTransaction.php | src/applications/differential/xaction/DifferentialRevisionSummaryTransaction.php | <?php
final class DifferentialRevisionSummaryTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.summary';
const EDITKEY = 'summary';
public function generateOldValue($object) {
return $object->getSummary();
}
public function applyInternalEffects($object, $value) {
$object->setSummary($value);
}
public function getTitle() {
return pht(
'%s edited the summary of this revision.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s updated the summary of %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function hasChangeDetailView() {
return true;
}
public function getMailDiffSectionHeader() {
return pht('CHANGES TO REVISION SUMMARY');
}
public function newChangeDetailView() {
$viewer = $this->getViewer();
return id(new PhabricatorApplicationTransactionTextDiffDetailView())
->setViewer($viewer)
->setOldText($this->getOldValue())
->setNewText($this->getNewValue());
}
public function newRemarkupChanges() {
$changes = array();
$changes[] = $this->newRemarkupChange()
->setOldValue($this->getOldValue())
->setNewValue($this->getNewValue());
return $changes;
}
public function validateTransactions($object, array $xactions) {
return $this->validateCommitMessageCorpusTransactions(
$object,
$xactions,
pht('Summary'));
}
public function getTransactionTypeForConduit($xaction) {
return 'summary';
}
public function getFieldValuesForConduit($xaction, $data) {
return array(
'old' => $xaction->getOldValue(),
'new' => $xaction->getNewValue(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionRejectTransaction.php | src/applications/differential/xaction/DifferentialRevisionRejectTransaction.php | <?php
final class DifferentialRevisionRejectTransaction
extends DifferentialRevisionReviewTransaction {
const TRANSACTIONTYPE = 'differential.revision.reject';
const ACTIONKEY = 'reject';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Request Changes');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('This revision will be returned to the author for updates.');
}
public function getIcon() {
return 'fa-times-circle-o';
}
public function getColor() {
return 'red';
}
protected function getRevisionActionOrder() {
return 600;
}
public function getActionName() {
return pht('Requested Changes');
}
public function getCommandKeyword() {
return 'request';
}
public function getCommandAliases() {
return array(
'reject',
);
}
public function getCommandSummary() {
return pht('Request changes to a revision.');
}
public function generateOldValue($object) {
$actor = $this->getActor();
return $this->isViewerFullyRejected($object, $actor);
}
public function applyExternalEffects($object, $value) {
$status = DifferentialReviewerStatus::STATUS_REJECTED;
$actor = $this->getActor();
$this->applyReviewerEffect($object, $actor, $value, $status);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if ($object->isClosed()) {
throw new Exception(
pht(
'You can not request changes to this revision because it has '.
'already been closed. You can only request changes to open '.
'revisions.'));
}
if ($this->isViewerRevisionAuthor($object, $viewer)) {
throw new Exception(
pht(
'You can not request changes to this revision because you are the '.
'revision author. You can only request changes to revisions you do '.
'not own.'));
}
if ($object->isDraft() || !$object->getShouldBroadcast()) {
throw new Exception(
pht('You can not request changes to a draft revision.'));
}
if ($this->isViewerFullyRejected($object, $viewer)) {
throw new Exception(
pht(
'You can not request changes to this revision because you have '.
'already requested changes.'));
}
}
public function getTitle() {
return pht(
'%s requested changes to this revision.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s requested changes to %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getTransactionTypeForConduit($xaction) {
return 'request-changes';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionPlanChangesTransaction.php | src/applications/differential/xaction/DifferentialRevisionPlanChangesTransaction.php | <?php
final class DifferentialRevisionPlanChangesTransaction
extends DifferentialRevisionActionTransaction {
const TRANSACTIONTYPE = 'differential.revision.plan';
const ACTIONKEY = 'plan-changes';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Plan Changes');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht(
'This revision will be removed from review queues until it is revised.');
}
public function getIcon() {
return 'fa-headphones';
}
public function getColor() {
return 'red';
}
protected function getRevisionActionOrder() {
return 200;
}
public function getActionName() {
return pht('Planned Changes');
}
public function getCommandKeyword() {
return 'planchanges';
}
public function getCommandAliases() {
return array(
'rethink',
);
}
public function getCommandSummary() {
return pht('Plan changes to a revision.');
}
public function generateOldValue($object) {
return $object->isChangePlanned();
}
public function applyInternalEffects($object, $value) {
$status_planned = DifferentialRevisionStatus::CHANGES_PLANNED;
$object->setModernRevisionStatus($status_planned);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if ($object->isDraft()) {
// See PHI346. Until the "Draft" state fully unprototypes, allow drafts
// to be moved to "changes planned" via the API. This preserves the
// behavior of "arc diff --plan-changes". We still prevent this
// transition from the web UI.
// TODO: Remove this once drafts leave prototype.
$editor = $this->getEditor();
$type_web = PhabricatorWebContentSource::SOURCECONST;
if ($editor->getContentSource()->getSource() == $type_web) {
throw new Exception(
pht('You can not plan changes to a draft revision.'));
}
}
if ($object->isChangePlanned()) {
throw new Exception(
pht(
'You can not request review of this revision because this '.
'revision is already under review and the action would have '.
'no effect.'));
}
if ($object->isClosed()) {
throw new Exception(
pht(
'You can not plan changes to this this revision because it has '.
'already been closed.'));
}
if (!$this->isViewerRevisionAuthor($object, $viewer)) {
throw new Exception(
pht(
'You can not plan changes to this revision because you do not '.
'own it. Only the author of a revision can plan changes to it.'));
}
}
public function getTitle() {
if ($this->isDraftDemotion()) {
return pht(
'%s returned this revision to the author for changes because remote '.
'builds failed.',
$this->renderAuthor());
} else {
return pht(
'%s planned changes to this revision.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
return pht(
'%s planned changes to %s.',
$this->renderAuthor(),
$this->renderObject());
}
private function isDraftDemotion() {
return (bool)$this->getMetadataValue('draft.demote');
}
public function getTransactionTypeForConduit($xaction) {
return 'plan-changes';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionRequestReviewTransaction.php | src/applications/differential/xaction/DifferentialRevisionRequestReviewTransaction.php | <?php
final class DifferentialRevisionRequestReviewTransaction
extends DifferentialRevisionActionTransaction {
const TRANSACTIONTYPE = 'differential.revision.request';
const ACTIONKEY = 'request-review';
const SOURCE_HARBORMASTER = 'harbormaster';
const SOURCE_AUTHOR = 'author';
const SOURCE_VIEWER = 'viewer';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
// See PHI1810. Allow non-authors to "Request Review" on draft revisions
// to promote them out of the draft state. This smoothes over the workflow
// where an author asks for review of an urgent change but has not used
// "Request Review" to skip builds.
if ($revision->isDraft()) {
if (!$this->isViewerRevisionAuthor($revision, $viewer)) {
return pht('Begin Review Now');
}
}
return pht('Request Review');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
if ($revision->isDraft()) {
if (!$this->isViewerRevisionAuthor($revision, $viewer)) {
return pht(
'This revision will be moved out of the draft state so you can '.
'review it immediately.');
} else {
return pht(
'This revision will be submitted to reviewers for feedback.');
}
} else {
return pht('This revision will be returned to reviewers for feedback.');
}
}
protected function getRevisionActionMetadata(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
$map = array();
if ($revision->isDraft()) {
$action_source = $this->getActorSourceType(
$revision,
$viewer);
$map['promotion.source'] = $action_source;
}
return $map;
}
protected function getRevisionActionSubmitButtonText(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
// See PHI975. When the action stack will promote the revision out of
// draft, change the button text from "Submit Quietly".
if ($revision->isDraft()) {
return pht('Publish Revision');
}
return null;
}
public function getColor() {
return 'sky';
}
protected function getRevisionActionOrder() {
return 200;
}
public function getActionName() {
return pht('Requested Review');
}
public function generateOldValue($object) {
return $object->isNeedsReview();
}
public function applyInternalEffects($object, $value) {
$status_review = DifferentialRevisionStatus::NEEDS_REVIEW;
$object
->setModernRevisionStatus($status_review)
->setShouldBroadcast(true);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if ($object->isNeedsReview()) {
throw new Exception(
pht(
'You can not request review of this revision because this '.
'revision is already under review and the action would have '.
'no effect.'));
}
if ($object->isClosed()) {
throw new Exception(
pht(
'You can not request review of this revision because it has '.
'already been closed. You can only request review of open '.
'revisions.'));
}
$this->getActorSourceType($object, $viewer);
}
public function getTitle() {
$source = $this->getDraftPromotionSource();
switch ($source) {
case self::SOURCE_HARBORMASTER:
case self::SOURCE_VIEWER:
case self::SOURCE_AUTHOR:
return pht(
'%s published this revision for review.',
$this->renderAuthor());
default:
return pht(
'%s requested review of this revision.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
$source = $this->getDraftPromotionSource();
switch ($source) {
case self::SOURCE_HARBORMASTER:
case self::SOURCE_VIEWER:
case self::SOURCE_AUTHOR:
return pht(
'%s published %s for review.',
$this->renderAuthor(),
$this->renderObject());
default:
return pht(
'%s requested review of %s.',
$this->renderAuthor(),
$this->renderObject());
}
}
public function getTransactionTypeForConduit($xaction) {
return 'request-review';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
private function getDraftPromotionSource() {
return $this->getMetadataValue('promotion.source');
}
private function getActorSourceType(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
$is_harbormaster = $viewer->isOmnipotent();
$is_author = $this->isViewerRevisionAuthor($revision, $viewer);
$is_draft = $revision->isDraft();
if ($is_harbormaster) {
// When revisions automatically promote out of "Draft" after builds
// finish, the viewer may be acting as the Harbormaster application.
$source = self::SOURCE_HARBORMASTER;
} else if ($is_author) {
$source = self::SOURCE_AUTHOR;
} else if ($is_draft) {
// Non-authors are allowed to "Request Review" on draft revisions, to
// force them into review immediately.
$source = self::SOURCE_VIEWER;
} else {
throw new Exception(
pht(
'You can not request review of this revision because you are not '.
'the author of the revision and it is not currently a draft.'));
}
return $source;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionBuildableTransaction.php | src/applications/differential/xaction/DifferentialRevisionBuildableTransaction.php | <?php
final class DifferentialRevisionBuildableTransaction
extends DifferentialRevisionTransactionType {
// NOTE: This uses an older constant for compatibility. We should perhaps
// migrate these at some point.
const TRANSACTIONTYPE = 'harbormaster:buildable';
public function generateNewValue($object, $value) {
return $value;
}
public function generateOldValue($object) {
return $object->getBuildableStatus($this->getBuildablePHID());
}
public function applyInternalEffects($object, $value) {
$object->setBuildableStatus($this->getBuildablePHID(), $value);
}
public function getIcon() {
return $this->newBuildableStatus()->getIcon();
}
public function getColor() {
return $this->newBuildableStatus()->getColor();
}
public function getActionName() {
return $this->newBuildableStatus()->getActionName();
}
public function shouldHideForFeed() {
return !$this->newBuildableStatus()->isFailed();
}
public function shouldHideForMail() {
return !$this->newBuildableStatus()->isFailed();
}
public function getTitle() {
$new = $this->getNewValue();
$buildable_phid = $this->getBuildablePHID();
switch ($new) {
case HarbormasterBuildableStatus::STATUS_PASSED:
return pht(
'%s completed remote builds in %s.',
$this->renderAuthor(),
$this->renderHandle($buildable_phid));
case HarbormasterBuildableStatus::STATUS_FAILED:
return pht(
'%s failed remote builds in %s!',
$this->renderAuthor(),
$this->renderHandle($buildable_phid));
}
return null;
}
public function getTitleForFeed() {
$new = $this->getNewValue();
$buildable_phid = $this->getBuildablePHID();
switch ($new) {
case HarbormasterBuildableStatus::STATUS_PASSED:
return pht(
'%s completed remote builds in %s for %s.',
$this->renderAuthor(),
$this->renderHandle($buildable_phid),
$this->renderObject());
case HarbormasterBuildableStatus::STATUS_FAILED:
return pht(
'%s failed remote builds in %s for %s!',
$this->renderAuthor(),
$this->renderHandle($buildable_phid),
$this->renderObject());
}
return null;
}
private function newBuildableStatus() {
$new = $this->getNewValue();
return HarbormasterBuildableStatus::newBuildableStatusObject($new);
}
private function getBuildablePHID() {
return $this->getMetadataValue('harbormaster:buildablePHID');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionReopenTransaction.php | src/applications/differential/xaction/DifferentialRevisionReopenTransaction.php | <?php
final class DifferentialRevisionReopenTransaction
extends DifferentialRevisionActionTransaction {
const TRANSACTIONTYPE = 'differential.revision.reopen';
const ACTIONKEY = 'reopen';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Reopen Revision');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('This revision will be reopened for review.');
}
public function getIcon() {
return 'fa-bullhorn';
}
public function getColor() {
return 'sky';
}
protected function getRevisionActionOrder() {
return 400;
}
public function getActionName() {
return pht('Reopened');
}
public function generateOldValue($object) {
return !$object->isClosed();
}
public function applyInternalEffects($object, $value) {
$status_review = DifferentialRevisionStatus::NEEDS_REVIEW;
$object->setModernRevisionStatus($status_review);
}
protected function validateAction($object, PhabricatorUser $viewer) {
if (!$object->isPublished()) {
throw new Exception(
pht(
'You can not reopen this revision because it is not closed. '.
'Only closed revisions can be reopened.'));
}
$config_key = 'differential.allow-reopen';
if (!PhabricatorEnv::getEnvConfig($config_key)) {
throw new Exception(
pht(
'You can not reopen this revision because configuration prevents '.
'any revision from being reopened. You can change this behavior '.
'by adjusting the "%s" setting in Config.',
$config_key));
}
}
public function getTitle() {
return pht(
'%s reopened this revision.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s reopened %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getTransactionTypeForConduit($xaction) {
return 'reopen';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionUpdateTransaction.php | src/applications/differential/xaction/DifferentialRevisionUpdateTransaction.php | <?php
final class DifferentialRevisionUpdateTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential:update';
const EDITKEY = 'update';
public function generateOldValue($object) {
return $object->getActiveDiffPHID();
}
public function generateNewValue($object, $value) {
// See T13290. If we're updating the revision in response to a commit but
// the revision is already closed, return the old value so we no-op this
// transaction. We don't want to attach more than one commit-diff to a
// revision.
// Although we can try to bail out earlier so we don't generate this
// transaction in the first place, we may race another worker and end up
// trying to apply it anyway. Here, we have a lock on the object and can
// be certain about the object state.
if ($this->isCommitUpdate()) {
if ($object->isClosed()) {
return $this->generateOldValue($object);
}
}
return $value;
}
public function applyInternalEffects($object, $value) {
$should_review = $this->shouldRequestReviewAfterUpdate($object);
if ($should_review) {
// If we're updating a non-broadcasting revision, put it back in draft
// rather than moving it directly to "Needs Review".
if ($object->getShouldBroadcast()) {
$new_status = DifferentialRevisionStatus::NEEDS_REVIEW;
} else {
$new_status = DifferentialRevisionStatus::DRAFT;
}
$object->setModernRevisionStatus($new_status);
}
$editor = $this->getEditor();
$diff = $editor->requireDiff($value);
$this->updateRevisionLineCounts($object, $diff);
$object->setRepositoryPHID($diff->getRepositoryPHID());
$object->setActiveDiffPHID($diff->getPHID());
$object->attachActiveDiff($diff);
}
private function shouldRequestReviewAfterUpdate($object) {
if ($this->isCommitUpdate()) {
return false;
}
$should_update =
$object->isNeedsRevision() ||
$object->isChangePlanned() ||
$object->isAbandoned();
if ($should_update) {
return true;
}
return false;
}
public function applyExternalEffects($object, $value) {
$editor = $this->getEditor();
$diff = $editor->requireDiff($value);
// TODO: This can race with diff updates, particularly those from
// Harbormaster. See discussion in T8650.
$diff->setRevisionID($object->getID());
$diff->save();
}
public function didCommitTransaction($object, $value) {
$editor = $this->getEditor();
$diff = $editor->requireDiff($value);
$omnipotent = PhabricatorUser::getOmnipotentUser();
// If there are any outstanding buildables for this diff, tell
// Harbormaster that their containers need to be updated. This is
// common, because `arc` creates buildables so it can upload lint
// and unit results.
$buildables = id(new HarbormasterBuildableQuery())
->setViewer($omnipotent)
->withManualBuildables(false)
->withBuildablePHIDs(array($diff->getPHID()))
->execute();
foreach ($buildables as $buildable) {
$buildable->sendMessage(
$this->getActor(),
HarbormasterMessageType::BUILDABLE_CONTAINER,
true);
}
// See T13455. If users have set view properites on a diff and the diff
// is then attached to a revision, attempt to copy their view preferences
// to the revision.
DifferentialViewState::copyViewStatesToObject(
$diff->getPHID(),
$object->getPHID());
}
public function getColor() {
return 'sky';
}
public function getIcon() {
return 'fa-refresh';
}
public function getActionName() {
if ($this->isCreateTransaction()) {
return pht('Request');
} else {
return pht('Updated');
}
}
public function getActionStrength() {
return 200;
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($this->isCommitUpdate()) {
return pht(
'This revision was automatically updated to reflect the '.
'committed changes.');
}
// NOTE: Very, very old update transactions did not have a new value or
// did not use a diff PHID as a new value. This was changed years ago,
// but wasn't migrated. We might consider migrating if this causes issues.
return pht(
'%s updated this revision to %s.',
$this->renderAuthor(),
$this->renderNewHandle());
}
public function getTitleForFeed() {
return pht(
'%s updated the diff for %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$diff_phid = null;
foreach ($xactions as $xaction) {
$diff_phid = $xaction->getNewValue();
$diff = id(new DifferentialDiffQuery())
->withPHIDs(array($diff_phid))
->setViewer($this->getActor())
->executeOne();
if (!$diff) {
$errors[] = $this->newInvalidError(
pht(
'Specified diff ("%s") does not exist.',
$diff_phid),
$xaction);
continue;
}
$is_attached =
($diff->getRevisionID()) &&
($diff->getRevisionID() == $object->getID());
if ($is_attached) {
$is_active = ($diff_phid == $object->getActiveDiffPHID());
} else {
$is_active = false;
}
if ($is_attached) {
if ($is_active) {
// This is a no-op: we're reattaching the current active diff to the
// revision it is already attached to. This is valid and will just
// be dropped later on in the process.
} else {
// At least for now, there's no support for "undoing" a diff and
// reverting to an older proposed change without just creating a
// new diff from whole cloth.
$errors[] = $this->newInvalidError(
pht(
'You can not update this revision with the specified diff '.
'("%s") because this diff is already attached to the revision '.
'as an older version of the change.',
$diff_phid),
$xaction);
continue;
}
} else if ($diff->getRevisionID()) {
$errors[] = $this->newInvalidError(
pht(
'You can not update this revision with the specified diff ("%s") '.
'because the diff is already attached to another revision.',
$diff_phid),
$xaction);
continue;
}
}
if (!$diff_phid && !$object->getActiveDiffPHID()) {
$errors[] = $this->newInvalidError(
pht(
'You must specify an initial diff when creating a revision.'));
}
return $errors;
}
public function isCommitUpdate() {
return (bool)$this->getMetadataValue('isCommitUpdate');
}
private function updateRevisionLineCounts(
DifferentialRevision $revision,
DifferentialDiff $diff) {
$revision->setLineCount($diff->getLineCount());
$conn = $revision->establishConnection('r');
$row = queryfx_one(
$conn,
'SELECT SUM(addLines) A, SUM(delLines) D FROM %T
WHERE diffID = %d',
id(new DifferentialChangeset())->getTableName(),
$diff->getID());
if ($row) {
$revision->setAddedLineCount((int)$row['A']);
$revision->setRemovedLineCount((int)$row['D']);
}
}
public function getTransactionTypeForConduit($xaction) {
return 'update';
}
public function getFieldValuesForConduit($xaction, $data) {
$commit_phids = $xaction->getMetadataValue('commitPHIDs', array());
return array(
'old' => $xaction->getOldValue(),
'new' => $xaction->getNewValue(),
'commitPHIDs' => $commit_phids,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionTitleTransaction.php | src/applications/differential/xaction/DifferentialRevisionTitleTransaction.php | <?php
final class DifferentialRevisionTitleTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.title';
const EDITKEY = 'title';
public function generateOldValue($object) {
return $object->getTitle();
}
public function applyInternalEffects($object, $value) {
$object->setTitle($value);
}
public function getTitle() {
return pht(
'%s retitled this revision from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
public function getTitleForFeed() {
return pht(
'%s retitled %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->getTitle(), $xactions)) {
$errors[] = $this->newRequiredError(
pht('Revisions must have a title.'));
}
$max_length = $object->getColumnMaximumByteLength('title');
foreach ($xactions as $xaction) {
$new_value = $xaction->getNewValue();
$new_length = strlen($new_value);
if ($new_length > $max_length) {
$errors[] = $this->newInvalidError(
pht(
'Revision title is too long: the maximum length of a '.
'revision title is 255 bytes.'),
$xaction);
}
}
return $errors;
}
public function getTransactionTypeForConduit($xaction) {
return 'title';
}
public function getFieldValuesForConduit($xaction, $data) {
return array(
'old' => $xaction->getOldValue(),
'new' => $xaction->getNewValue(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionHoldDraftTransaction.php | src/applications/differential/xaction/DifferentialRevisionHoldDraftTransaction.php | <?php
final class DifferentialRevisionHoldDraftTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'draft';
const EDITKEY = 'draft';
public function generateOldValue($object) {
return (bool)$object->getHoldAsDraft();
}
public function generateNewValue($object, $value) {
return (bool)$value;
}
public function applyInternalEffects($object, $value) {
$object->setHoldAsDraft($value);
// If draft isn't the default state but we're creating a new revision
// and holding it as a draft, put it in draft mode. See PHI206.
// TODO: This can probably be removed once Draft is the universal default.
if ($this->isNewObject()) {
if ($object->isNeedsReview()) {
$object
->setModernRevisionStatus(DifferentialRevisionStatus::DRAFT)
->setShouldBroadcast(false);
}
}
}
public function getTitle() {
if ($this->getNewValue()) {
return pht(
'%s held this revision as a draft.',
$this->renderAuthor());
} else {
return pht(
'%s set this revision to automatically submit once builds complete.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
if ($this->getNewValue()) {
return pht(
'%s held %s as a draft.',
$this->renderAuthor(),
$this->renderObject());
} else {
return pht(
'%s set %s to automatically submit once builds complete.',
$this->renderAuthor(),
$this->renderObject());
}
}
public function getTransactionTypeForConduit($xaction) {
return 'draft';
}
public function getFieldValuesForConduit($xaction, $data) {
return array(
'old' => $xaction->getOldValue(),
'new' => $xaction->getNewValue(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionCommandeerTransaction.php | src/applications/differential/xaction/DifferentialRevisionCommandeerTransaction.php | <?php
final class DifferentialRevisionCommandeerTransaction
extends DifferentialRevisionActionTransaction {
const TRANSACTIONTYPE = 'differential.revision.commandeer';
const ACTIONKEY = 'commandeer';
protected function getRevisionActionLabel(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('Commandeer Revision');
}
protected function getRevisionActionDescription(
DifferentialRevision $revision,
PhabricatorUser $viewer) {
return pht('You will take control of this revision and become its author.');
}
public function getIcon() {
return 'fa-flag';
}
public function getColor() {
return 'sky';
}
protected function getRevisionActionOrder() {
return 700;
}
public function getActionName() {
return pht('Commandeered');
}
public function getCommandKeyword() {
return 'commandeer';
}
public function getCommandAliases() {
return array(
'claim',
);
}
public function getCommandSummary() {
return pht('Commandeer a revision.');
}
public function generateOldValue($object) {
return $object->getAuthorPHID();
}
public function generateNewValue($object, $value) {
$actor = $this->getActor();
return $actor->getPHID();
}
public function applyInternalEffects($object, $value) {
$object->setAuthorPHID($value);
}
protected function validateAction($object, PhabricatorUser $viewer) {
// If a revision has already landed, we generally want to discourage
// reopening and reusing it since this tends to create a big mess (users
// should create a new revision instead). Thus, we stop you from
// commandeering closed revisions.
// See PHI985. If the revision was abandoned, there's no peril in allowing
// the commandeer since the change (likely) never actually landed. So
// it's okay to commandeer abandoned revisions.
if ($object->isClosed() && !$object->isAbandoned()) {
throw new Exception(
pht(
'You can not commandeer this revision because it has already '.
'been closed. You can only commandeer open or abandoned '.
'revisions.'));
}
if ($this->isViewerRevisionAuthor($object, $viewer)) {
throw new Exception(
pht(
'You can not commandeer this revision because you are already '.
'the author.'));
}
}
public function getTitle() {
return pht(
'%s commandeered this revision.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s commandeered %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getTransactionTypeForConduit($xaction) {
return 'commandeer';
}
public function getFieldValuesForConduit($object, $data) {
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/xaction/DifferentialRevisionReviewersTransaction.php | src/applications/differential/xaction/DifferentialRevisionReviewersTransaction.php | <?php
final class DifferentialRevisionReviewersTransaction
extends DifferentialRevisionTransactionType {
const TRANSACTIONTYPE = 'differential.revision.reviewers';
const EDITKEY = 'reviewers';
public function generateOldValue($object) {
$reviewers = $object->getReviewers();
$reviewers = mpull($reviewers, 'getReviewerStatus', 'getReviewerPHID');
return $reviewers;
}
public function generateNewValue($object, $value) {
$actor = $this->getActor();
$datasource = id(new DifferentialBlockingReviewerDatasource())
->setViewer($actor);
$reviewers = $this->generateOldValue($object);
$old_reviewers = $reviewers;
// First, remove any reviewers we're getting rid of.
$rem = idx($value, '-', array());
$rem = $datasource->evaluateTokens($rem);
foreach ($rem as $spec) {
if (!is_array($spec)) {
$phid = $spec;
} else {
$phid = $spec['phid'];
}
unset($reviewers[$phid]);
}
$add = idx($value, '+', array());
$add = $datasource->evaluateTokens($add);
$add_map = array();
foreach ($add as $spec) {
if (!is_array($spec)) {
$phid = $spec;
$status = DifferentialReviewerStatus::STATUS_ADDED;
} else {
$phid = $spec['phid'];
$status = $spec['type'];
}
$add_map[$phid] = $status;
}
$set = idx($value, '=', null);
if ($set !== null) {
$set = $datasource->evaluateTokens($set);
foreach ($set as $spec) {
if (!is_array($spec)) {
$phid = $spec;
$status = DifferentialReviewerStatus::STATUS_ADDED;
} else {
$phid = $spec['phid'];
$status = $spec['type'];
}
$add_map[$phid] = $status;
}
// We treat setting reviewers as though they were being added to an
// empty list, so we can share more code between pathways.
$reviewers = array();
}
$status_blocking = DifferentialReviewerStatus::STATUS_BLOCKING;
foreach ($add_map as $phid => $new_status) {
$old_status = idx($old_reviewers, $phid);
// If we have an old status and this didn't make the reviewer blocking
// or nonblocking, just retain the old status. This makes sure we don't
// throw away rejects, accepts, etc.
if ($old_status) {
$was_blocking = ($old_status == $status_blocking);
$now_blocking = ($new_status == $status_blocking);
$is_block = ($now_blocking && !$was_blocking);
$is_unblock = (!$now_blocking && $was_blocking);
if (!$is_block && !$is_unblock) {
$reviewers[$phid] = $old_status;
continue;
}
}
$reviewers[$phid] = $new_status;
}
return $reviewers;
}
public function getTransactionHasEffect($object, $old, $new) {
// At least for now, we ignore transactions which ONLY reorder reviewers
// without making any actual changes.
ksort($old);
ksort($new);
return ($old !== $new);
}
public function applyExternalEffects($object, $value) {
$src_phid = $object->getPHID();
$old = $this->generateOldValue($object);
$new = $value;
$rem = array_diff_key($old, $new);
$table = new DifferentialReviewer();
$table_name = $table->getTableName();
$conn = $table->establishConnection('w');
if ($rem) {
queryfx(
$conn,
'DELETE FROM %T WHERE revisionPHID = %s AND reviewerPHID IN (%Ls)',
$table_name,
$src_phid,
array_keys($rem));
}
if ($new) {
$reviewers = $table->loadAllWhere(
'revisionPHID = %s AND reviewerPHID IN (%Ls)',
$src_phid,
array_keys($new));
$reviewers = mpull($reviewers, null, 'getReviewerPHID');
foreach ($new as $dst_phid => $status) {
$old_status = idx($old, $dst_phid);
if ($old_status === $status) {
continue;
}
$reviewer = idx($reviewers, $dst_phid);
if (!$reviewer) {
$reviewer = id(new DifferentialReviewer())
->setRevisionPHID($src_phid)
->setReviewerPHID($dst_phid);
}
$reviewer->setReviewerStatus($status);
try {
$reviewer->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// At least for now, just ignore it if we lost a race.
}
}
}
}
public function getTitle() {
return $this->renderReviewerEditTitle(false);
}
public function getTitleForFeed() {
return $this->renderReviewerEditTitle(true);
}
private function renderReviewerEditTitle($is_feed) {
$old = $this->getOldValue();
$new = $this->getNewValue();
$rem = array_diff_key($old, $new);
$add = array_diff_key($new, $old);
$rem_phids = array_keys($rem);
$add_phids = array_keys($add);
$total_count = count($rem) + count($add);
$parts = array();
if ($rem && $add) {
if ($is_feed) {
$parts[] = pht(
'%s edited %s reviewer(s) for %s, added %s: %s; removed %s: %s.',
$this->renderAuthor(),
new PhutilNumber($total_count),
$this->renderObject(),
phutil_count($add_phids),
$this->renderHandleList($add_phids),
phutil_count($rem_phids),
$this->renderHandleList($rem_phids));
} else {
$parts[] = pht(
'%s edited %s reviewer(s), added %s: %s; removed %s: %s.',
$this->renderAuthor(),
new PhutilNumber($total_count),
phutil_count($add_phids),
$this->renderHandleList($add_phids),
phutil_count($rem_phids),
$this->renderHandleList($rem_phids));
}
} else if ($add) {
if ($is_feed) {
$parts[] = pht(
'%s added %s reviewer(s) for %s: %s.',
$this->renderAuthor(),
phutil_count($add_phids),
$this->renderObject(),
$this->renderHandleList($add_phids));
} else {
$parts[] = pht(
'%s added %s reviewer(s): %s.',
$this->renderAuthor(),
phutil_count($add_phids),
$this->renderHandleList($add_phids));
}
} else if ($rem) {
if ($is_feed) {
$parts[] = pht(
'%s removed %s reviewer(s) for %s: %s.',
$this->renderAuthor(),
phutil_count($rem_phids),
$this->renderObject(),
$this->renderHandleList($rem_phids));
} else {
$parts[] = pht(
'%s removed %s reviewer(s): %s.',
$this->renderAuthor(),
phutil_count($rem_phids),
$this->renderHandleList($rem_phids));
}
}
$status_blocking = DifferentialReviewerStatus::STATUS_BLOCKING;
$blocks = array();
$unblocks = array();
foreach ($new as $phid => $new_status) {
$old_status = idx($old, $phid);
if (!$old_status) {
continue;
}
$was_blocking = ($old_status == $status_blocking);
$now_blocking = ($new_status == $status_blocking);
$is_block = ($now_blocking && !$was_blocking);
$is_unblock = (!$now_blocking && $was_blocking);
if ($is_block) {
$blocks[] = $phid;
}
if ($is_unblock) {
$unblocks[] = $phid;
}
}
$total_count = count($blocks) + count($unblocks);
if ($blocks && $unblocks) {
if ($is_feed) {
$parts[] = pht(
'%s changed %s blocking reviewer(s) for %s, added %s: %s; removed '.
'%s: %s.',
$this->renderAuthor(),
new PhutilNumber($total_count),
$this->renderObject(),
phutil_count($blocks),
$this->renderHandleList($blocks),
phutil_count($unblocks),
$this->renderHandleList($unblocks));
} else {
$parts[] = pht(
'%s changed %s blocking reviewer(s), added %s: %s; removed %s: %s.',
$this->renderAuthor(),
new PhutilNumber($total_count),
phutil_count($blocks),
$this->renderHandleList($blocks),
phutil_count($unblocks),
$this->renderHandleList($unblocks));
}
} else if ($blocks) {
if ($is_feed) {
$parts[] = pht(
'%s added %s blocking reviewer(s) for %s: %s.',
$this->renderAuthor(),
phutil_count($blocks),
$this->renderObject(),
$this->renderHandleList($blocks));
} else {
$parts[] = pht(
'%s added %s blocking reviewer(s): %s.',
$this->renderAuthor(),
phutil_count($blocks),
$this->renderHandleList($blocks));
}
} else if ($unblocks) {
if ($is_feed) {
$parts[] = pht(
'%s removed %s blocking reviewer(s) for %s: %s.',
$this->renderAuthor(),
phutil_count($unblocks),
$this->renderObject(),
$this->renderHandleList($unblocks));
} else {
$parts[] = pht(
'%s removed %s blocking reviewer(s): %s.',
$this->renderAuthor(),
phutil_count($unblocks),
$this->renderHandleList($unblocks));
}
}
if ($this->isTextMode()) {
return implode(' ', $parts);
} else {
return phutil_implode_html(' ', $parts);
}
}
public function validateTransactions($object, array $xactions) {
$actor = $this->getActor();
$errors = array();
if (!$xactions) {
// If we aren't applying new reviewer transactions, just bail. We need
// reviewers to be attached to the revision continue validation, and
// they won't always be (for example, when mentioning a revision).
return $errors;
}
$author_phid = $object->getAuthorPHID();
$config_self_accept_key = 'differential.allow-self-accept';
$allow_self_accept = PhabricatorEnv::getEnvConfig($config_self_accept_key);
$old = $this->generateOldValue($object);
foreach ($xactions as $xaction) {
$new = $this->generateNewValue($object, $xaction->getNewValue());
$add = array_diff_key($new, $old);
if (!$add) {
continue;
}
$objects = id(new PhabricatorObjectQuery())
->setViewer($actor)
->withPHIDs(array_keys($add))
->execute();
$objects = mpull($objects, null, 'getPHID');
foreach ($add as $phid => $status) {
if (!isset($objects[$phid])) {
$errors[] = $this->newInvalidError(
pht(
'Reviewer "%s" is not a valid object.',
$phid),
$xaction);
continue;
}
switch (phid_get_type($phid)) {
case PhabricatorPeopleUserPHIDType::TYPECONST:
case PhabricatorOwnersPackagePHIDType::TYPECONST:
case PhabricatorProjectProjectPHIDType::TYPECONST:
break;
default:
$errors[] = $this->newInvalidError(
pht(
'Reviewer "%s" must be a user, a package, or a project.',
$phid),
$xaction);
continue 2;
}
// NOTE: This weird behavior around commandeering is a bit unorthodox,
// but this restriction is an unusual one.
$is_self = ($phid === $author_phid);
if ($is_self && !$allow_self_accept) {
if (!$xaction->getIsCommandeerSideEffect()) {
$errors[] = $this->newInvalidError(
pht('The author of a revision can not be a reviewer.'),
$xaction);
continue;
}
}
}
}
return $errors;
}
public function getTransactionTypeForConduit($xaction) {
return 'reviewers';
}
public function getFieldValuesForConduit($xaction, $data) {
$old_value = $xaction->getOldValue();
$new_value = $xaction->getNewValue();
$status_blocking = DifferentialReviewerStatus::STATUS_BLOCKING;
$add_phids = array_diff_key($new_value, $old_value);
foreach ($add_phids as $add_phid => $value) {
$add_phids[$add_phid] = array(
'operation' => 'add',
'phid' => $add_phid,
'oldStatus' => null,
'newStatus' => $value,
'isBlocking' => ($value === $status_blocking),
);
}
$rem_phids = array_diff_key($old_value, $new_value);
foreach ($rem_phids as $rem_phid => $value) {
$rem_phids[$rem_phid] = array(
'operation' => 'remove',
'phid' => $rem_phid,
'oldStatus' => $value,
'newStatus' => null,
'isBlocking' => false,
);
}
$mod_phids = array_intersect_key($old_value, $new_value);
foreach ($mod_phids as $mod_phid => $ignored) {
$old = $old_value[$mod_phid];
$new = $new_value[$mod_phid];
if ($old === $new) {
unset($mod_phids[$mod_phid]);
continue;
}
$mod_phids[$mod_phid] = array(
'operation' => 'update',
'phid' => $mod_phid,
'oldStatus' => $old,
'newStatus' => $new,
'isBlocking' => ($new === $status_blocking),
);
}
$all_ops = $add_phids + $rem_phids + $mod_phids;
$all_ops = array_select_keys($all_ops, $new_value) + $all_ops;
$all_ops = array_values($all_ops);
return array(
'operations' => $all_ops,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/exception/DifferentialFieldParseException.php | src/applications/differential/exception/DifferentialFieldParseException.php | <?php
final class DifferentialFieldParseException 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/differential/exception/DifferentialFieldValidationException.php | src/applications/differential/exception/DifferentialFieldValidationException.php | <?php
final class DifferentialFieldValidationException 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/differential/relationships/DifferentialRevisionHasTaskRelationship.php | src/applications/differential/relationships/DifferentialRevisionHasTaskRelationship.php | <?php
final class DifferentialRevisionHasTaskRelationship
extends DifferentialRevisionRelationship {
const RELATIONSHIPKEY = 'revision.has-task';
public function getEdgeConstant() {
return DifferentialRevisionHasTaskEdgeType::EDGECONST;
}
protected function getActionName() {
return pht('Edit Tasks');
}
protected function getActionIcon() {
return 'fa-anchor';
}
public function canRelateObjects($src, $dst) {
return ($dst instanceof ManiphestTask);
}
public function getDialogTitleText() {
return pht('Edit Related Tasks');
}
public function getDialogHeaderText() {
return pht('Current Tasks');
}
public function getDialogButtonText() {
return pht('Save Related Tasks');
}
protected function newRelationshipSource() {
return new ManiphestTaskRelationshipSource();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/relationships/DifferentialRevisionHasParentRelationship.php | src/applications/differential/relationships/DifferentialRevisionHasParentRelationship.php | <?php
final class DifferentialRevisionHasParentRelationship
extends DifferentialRevisionRelationship {
const RELATIONSHIPKEY = 'revision.has-parent';
public function getEdgeConstant() {
return DifferentialRevisionDependsOnRevisionEdgeType::EDGECONST;
}
protected function getActionName() {
return pht('Edit Parent Revisions');
}
protected function getActionIcon() {
return 'fa-chevron-circle-up';
}
public function canRelateObjects($src, $dst) {
return ($dst instanceof DifferentialRevision);
}
public function shouldAppearInActionMenu() {
return false;
}
public function getDialogTitleText() {
return pht('Edit Parent Revisions');
}
public function getDialogHeaderText() {
return pht('Current Parent Revisions');
}
public function getDialogButtonText() {
return pht('Save Parent Revisions');
}
protected function newRelationshipSource() {
return new DifferentialRevisionRelationshipSource();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/relationships/DifferentialRevisionHasChildRelationship.php | src/applications/differential/relationships/DifferentialRevisionHasChildRelationship.php | <?php
final class DifferentialRevisionHasChildRelationship
extends DifferentialRevisionRelationship {
const RELATIONSHIPKEY = 'revision.has-child';
public function getEdgeConstant() {
return DifferentialRevisionDependedOnByRevisionEdgeType::EDGECONST;
}
protected function getActionName() {
return pht('Edit Child Revisions');
}
protected function getActionIcon() {
return 'fa-chevron-circle-down';
}
public function canRelateObjects($src, $dst) {
return ($dst instanceof DifferentialRevision);
}
public function shouldAppearInActionMenu() {
return false;
}
public function getDialogTitleText() {
return pht('Edit Child Revisions');
}
public function getDialogHeaderText() {
return pht('Current Child Revisions');
}
public function getDialogButtonText() {
return pht('Save Child Revisions');
}
protected function newRelationshipSource() {
return new DifferentialRevisionRelationshipSource();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/relationships/DifferentialRevisionHasCommitRelationship.php | src/applications/differential/relationships/DifferentialRevisionHasCommitRelationship.php | <?php
final class DifferentialRevisionHasCommitRelationship
extends DifferentialRevisionRelationship {
const RELATIONSHIPKEY = 'revision.has-commit';
public function getEdgeConstant() {
return DifferentialRevisionHasCommitEdgeType::EDGECONST;
}
protected function getActionName() {
return pht('Edit Commits');
}
protected function getActionIcon() {
return 'fa-code';
}
public function canRelateObjects($src, $dst) {
return ($dst instanceof PhabricatorRepositoryCommit);
}
public function getDialogTitleText() {
return pht('Edit Related Commits');
}
public function getDialogHeaderText() {
return pht('Current Commits');
}
public function getDialogButtonText() {
return pht('Save Related Commits');
}
protected function newRelationshipSource() {
return new DiffusionCommitRelationshipSource();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/relationships/DifferentialRevisionRelationship.php | src/applications/differential/relationships/DifferentialRevisionRelationship.php | <?php
abstract class DifferentialRevisionRelationship
extends PhabricatorObjectRelationship {
public function isEnabledForObject($object) {
$viewer = $this->getViewer();
$has_app = PhabricatorApplication::isClassInstalledForViewer(
'PhabricatorDifferentialApplication',
$viewer);
if (!$has_app) {
return false;
}
return ($object instanceof DifferentialRevision);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/application/PhabricatorDifferentialApplication.php | src/applications/differential/application/PhabricatorDifferentialApplication.php | <?php
final class PhabricatorDifferentialApplication
extends PhabricatorApplication {
public function getBaseURI() {
return '/differential/';
}
public function getName() {
return pht('Differential');
}
public function getShortDescription() {
return pht('Pre-Commit Review');
}
public function getIcon() {
return 'fa-cog';
}
public function isPinnedByDefault(PhabricatorUser $viewer) {
return true;
}
public function getHelpDocumentationArticles(PhabricatorUser $viewer) {
return array(
array(
'name' => pht('Differential User Guide'),
'href' => PhabricatorEnv::getDoclink('Differential User Guide'),
),
);
}
public function getTitleGlyph() {
return "\xE2\x9A\x99";
}
public function getOverview() {
return pht(
'Differential is a **code review application** which allows '.
'engineers to review, discuss and approve changes to software.');
}
public function getRoutes() {
return array(
'/D(?P<id>[1-9]\d*)' => array(
'' => 'DifferentialRevisionViewController',
'/(?P<filter>new)/' => 'DifferentialRevisionViewController',
),
'/differential/' => array(
$this->getQueryRoutePattern() => 'DifferentialRevisionListController',
'diff/' => array(
'(?P<id>[1-9]\d*)/' => array(
'' => 'DifferentialDiffViewController',
'changesets/' => array(
$this->getQueryRoutePattern()
=> 'DifferentialChangesetListController',
),
),
'create/' => 'DifferentialDiffCreateController',
),
'changeset/' => 'DifferentialChangesetViewController',
'revision/' => array(
$this->getEditRoutePattern('edit/')
=> 'DifferentialRevisionEditController',
$this->getEditRoutePattern('attach/(?P<diffID>[^/]+)/to/')
=> 'DifferentialRevisionEditController',
'closedetails/(?P<phid>[^/]+)/'
=> 'DifferentialRevisionCloseDetailsController',
'update/(?P<revisionID>[1-9]\d*)/'
=> 'DifferentialDiffCreateController',
'operation/(?P<id>[1-9]\d*)/'
=> 'DifferentialRevisionOperationController',
'inlines/(?P<id>[1-9]\d*)/'
=> 'DifferentialRevisionInlinesController',
'paths/(?P<id>[1-9]\d*)/'
=> 'DifferentialRevisionAffectedPathsController',
),
'comment/' => array(
'inline/' => array(
'edit/(?P<id>[1-9]\d*)/'
=> 'DifferentialInlineCommentEditController',
),
),
'preview/' => 'PhabricatorMarkupPreviewController',
),
);
}
public function getApplicationOrder() {
return 0.100;
}
public function getRemarkupRules() {
return array(
new DifferentialRemarkupRule(),
);
}
public function supportsEmailIntegration() {
return true;
}
public function getAppEmailBlurb() {
return pht(
'Send email to these addresses to create revisions. The body of the '.
'message and / or one or more attachments should be the output of a '.
'"diff" command. %s',
phutil_tag(
'a',
array(
'href' => $this->getInboundEmailSupportLink(),
),
pht('Learn More')));
}
protected function getCustomCapabilities() {
return array(
DifferentialDefaultViewCapability::CAPABILITY => array(
'caption' => pht('Default view policy for newly created revisions.'),
'template' => DifferentialRevisionPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_VIEW,
),
);
}
public function getMailCommandObjects() {
return array(
'revision' => array(
'name' => pht('Email Commands: Revisions'),
'header' => pht('Interacting with Differential Revisions'),
'object' => new DifferentialRevision(),
'summary' => pht(
'This page documents the commands you can use to interact with '.
'revisions in Differential.'),
),
);
}
public function getApplicationSearchDocumentTypes() {
return array(
DifferentialRevisionPHIDType::TYPECONST,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/__tests__/DifferentialParseRenderTestCase.php | src/applications/differential/__tests__/DifferentialParseRenderTestCase.php | <?php
final class DifferentialParseRenderTestCase extends PhabricatorTestCase {
private function getTestDataDirectory() {
return dirname(__FILE__).'/data/';
}
public function testParseRender() {
$dir = $this->getTestDataDirectory();
foreach (Filesystem::listDirectory($dir, $show_hidden = false) as $file) {
if (!preg_match('/\.diff$/', $file)) {
continue;
}
$data = Filesystem::readFile($dir.$file);
// Strip trailing "~" characters from inputs so they may contain
// trailing whitespace.
$data = preg_replace('/~$/m', '', $data);
$opt_file = $dir.$file.'.options';
if (Filesystem::pathExists($opt_file)) {
$options = Filesystem::readFile($opt_file);
try {
$options = phutil_json_decode($options);
} catch (PhutilJSONParserException $ex) {
throw new PhutilProxyException(
pht('Invalid options file: %s.', $opt_file),
$ex);
}
} else {
$options = array();
}
foreach (array('one', 'two') as $type) {
$this->runParser($type, $data, $file, 'expect');
$this->runParser($type, $data, $file, 'unshielded');
}
}
}
private function runParser($type, $data, $file, $extension) {
$dir = $this->getTestDataDirectory();
$test_file = $dir.$file.'.'.$type.'.'.$extension;
if (!Filesystem::pathExists($test_file)) {
return;
}
$unshielded = false;
switch ($extension) {
case 'unshielded':
$unshielded = true;
break;
}
$parsers = $this->buildChangesetParsers($type, $data, $file);
$actual = $this->renderParsers($parsers, $unshielded);
$expect = Filesystem::readFile($test_file);
$this->assertEqual($expect, $actual, basename($test_file));
}
private function renderParsers(array $parsers, $unshield) {
$result = array();
foreach ($parsers as $parser) {
if ($unshield) {
$s_range = 0;
$e_range = 0xFFFF;
} else {
$s_range = null;
$e_range = null;
}
$result[] = $parser->render($s_range, $e_range, array());
}
return implode(str_repeat('~', 80)."\n", $result);
}
private function buildChangesetParsers($type, $data, $file) {
$parser = new ArcanistDiffParser();
$changes = $parser->parseDiff($data);
$diff = DifferentialDiff::newFromRawChanges(
PhabricatorUser::getOmnipotentUser(),
$changes);
$changesets = $diff->getChangesets();
$engine = new PhabricatorMarkupEngine();
$engine->setViewer(new PhabricatorUser());
$viewstate = new PhabricatorChangesetViewState();
$parsers = array();
foreach ($changesets as $changeset) {
$cparser = id(new DifferentialChangesetParser())
->setViewer(new PhabricatorUser())
->setDisableCache(true)
->setChangeset($changeset)
->setMarkupEngine($engine)
->setViewState($viewstate);
if ($type == 'one') {
$cparser->setRenderer(new DifferentialChangesetOneUpTestRenderer());
} else if ($type == 'two') {
$cparser->setRenderer(new DifferentialChangesetTwoUpTestRenderer());
} else {
throw new Exception(pht('Unknown renderer type "%s"!', $type));
}
$parsers[] = $cparser;
}
return $parsers;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/lipsum/PhabricatorDifferentialRevisionTestDataGenerator.php | src/applications/differential/lipsum/PhabricatorDifferentialRevisionTestDataGenerator.php | <?php
final class PhabricatorDifferentialRevisionTestDataGenerator
extends PhabricatorTestDataGenerator {
const GENERATORKEY = 'revisions';
public function getGeneratorName() {
return pht('Differential Revisions');
}
public function generateObject() {
$author = $this->loadPhabricatorUser();
$revision = DifferentialRevision::initializeNewRevision($author);
$revision->attachReviewers(array());
$revision->attachActiveDiff(null);
// This could be a bit richer and more formal than it is.
$revision->setTitle($this->generateTitle());
$revision->setSummary($this->generateDescription());
$revision->setTestPlan($this->generateDescription());
$diff = $this->generateDiff($author);
$type_update = DifferentialRevisionUpdateTransaction::TRANSACTIONTYPE;
$xactions = array();
$xactions[] = id(new DifferentialTransaction())
->setTransactionType($type_update)
->setNewValue($diff->getPHID());
id(new DifferentialTransactionEditor())
->setActor($author)
->setContentSource($this->getLipsumContentSource())
->applyTransactions($revision, $xactions);
return $revision;
}
public function getCCPHIDs() {
$ccs = array();
for ($i = 0; $i < rand(1, 4);$i++) {
$ccs[] = $this->loadPhabricatorUserPHID();
}
return $ccs;
}
public function generateDiff($author) {
$paste_generator = new PhabricatorPasteTestDataGenerator();
$languages = $paste_generator->getSupportedLanguages();
$language = array_rand($languages);
$spec = $languages[$language];
$code = $paste_generator->generateContent($spec);
$altcode = $paste_generator->generateContent($spec);
$newcode = $this->randomlyModify($code, $altcode);
$diff = id(new PhabricatorDifferenceEngine())
->generateRawDiffFromFileContent($code, $newcode);
$call = new ConduitCall(
'differential.createrawdiff',
array(
'diff' => $diff,
));
$call->setUser($author);
$result = $call->execute();
$thediff = id(new DifferentialDiff())->load(
$result['id']);
$thediff->setDescription($this->generateTitle())->save();
return $thediff;
}
public function generateDescription() {
return id(new PhutilLipsumContextFreeGrammar())
->generate(10, 20);
}
public function generateTitle() {
return id(new PhutilLipsumContextFreeGrammar())
->generate();
}
public function randomlyModify($code, $altcode) {
$codearr = explode("\n", $code);
$altcodearr = explode("\n", $altcode);
$no_lines_to_delete = rand(1,
min(count($codearr) - 2, 5));
$randomlines = array_rand($codearr,
count($codearr) - $no_lines_to_delete);
$newcode = array();
foreach ($randomlines as $lineno) {
$newcode[] = $codearr[$lineno];
}
$newlines_count = rand(2,
min(count($codearr) - 2, count($altcodearr) - 2, 5));
$randomlines_orig = array_rand($codearr, $newlines_count);
$randomlines_new = array_rand($altcodearr, $newlines_count);
$newcode2 = array();
$c = 0;
for ($i = 0; $i < count($newcode);$i++) {
$newcode2[] = $newcode[$i];
if (in_array($i, $randomlines_orig)) {
$newcode2[] = $altcodearr[$randomlines_new[$c++]];
}
}
return implode("\n", $newcode2);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/garbagecollector/DifferentialParseCacheGarbageCollector.php | src/applications/differential/garbagecollector/DifferentialParseCacheGarbageCollector.php | <?php
final class DifferentialParseCacheGarbageCollector
extends PhabricatorGarbageCollector {
const COLLECTORCONST = 'differential.parse';
public function getCollectorName() {
return pht('Differential Parse Cache');
}
public function getDefaultRetentionPolicy() {
return phutil_units('14 days in seconds');
}
protected function collectGarbage() {
$table = new DifferentialChangeset();
$conn_w = $table->establishConnection('w');
queryfx(
$conn_w,
'DELETE FROM %T WHERE dateCreated < %d LIMIT 100',
DifferentialChangeset::TABLE_CACHE,
$this->getGarbageEpoch());
return ($conn_w->getAffectedRows() == 100);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/garbagecollector/DifferentialViewStateGarbageCollector.php | src/applications/differential/garbagecollector/DifferentialViewStateGarbageCollector.php | <?php
final class DifferentialViewStateGarbageCollector
extends PhabricatorGarbageCollector {
const COLLECTORCONST = 'differential.viewstate';
public function getCollectorName() {
return pht('Differential View States');
}
public function getDefaultRetentionPolicy() {
return phutil_units('180 days in seconds');
}
protected function collectGarbage() {
$table = new DifferentialViewState();
$conn = $table->establishConnection('w');
queryfx(
$conn,
'DELETE FROM %R WHERE dateModified < %d LIMIT 100',
$table,
$this->getGarbageEpoch());
return ($conn->getAffectedRows() == 100);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/view/DifferentialRevisionListView.php | src/applications/differential/view/DifferentialRevisionListView.php | <?php
/**
* Render a table of Differential revisions.
*/
final class DifferentialRevisionListView extends AphrontView {
private $revisions = array();
private $header;
private $noDataString;
private $noBox;
private $background = null;
private $unlandedDependencies = array();
public function setUnlandedDependencies(array $unlanded_dependencies) {
$this->unlandedDependencies = $unlanded_dependencies;
return $this;
}
public function getUnlandedDependencies() {
return $this->unlandedDependencies;
}
public function setNoDataString($no_data_string) {
$this->noDataString = $no_data_string;
return $this;
}
public function setHeader($header) {
$this->header = $header;
return $this;
}
public function setRevisions(array $revisions) {
assert_instances_of($revisions, 'DifferentialRevision');
$this->revisions = $revisions;
return $this;
}
public function setNoBox($box) {
$this->noBox = $box;
return $this;
}
public function setBackground($background) {
$this->background = $background;
return $this;
}
public function render() {
$viewer = $this->getViewer();
$this->initBehavior('phabricator-tooltips', array());
$this->requireResource('aphront-tooltip-css');
$reviewer_limit = 7;
$reviewer_phids = array();
$reviewer_more = array();
$handle_phids = array();
foreach ($this->revisions as $key => $revision) {
$reviewers = $revision->getReviewers();
// Don't show reviewers who have resigned. The "Reviewers" constraint
// does not respect these reviewers and they largely don't count as
// reviewers.
foreach ($reviewers as $reviewer_key => $reviewer) {
if ($reviewer->isResigned()) {
unset($reviewers[$reviewer_key]);
}
}
if (count($reviewers) > $reviewer_limit) {
$reviewers = array_slice($reviewers, 0, $reviewer_limit);
$reviewer_more[$key] = true;
} else {
$reviewer_more[$key] = false;
}
$phids = mpull($reviewers, 'getReviewerPHID');
$reviewer_phids[$key] = $phids;
foreach ($phids as $phid) {
$handle_phids[$phid] = $phid;
}
$author_phid = $revision->getAuthorPHID();
$handle_phids[$author_phid] = $author_phid;
}
$handles = $viewer->loadHandles($handle_phids);
$list = new PHUIObjectItemListView();
foreach ($this->revisions as $key => $revision) {
$item = id(new PHUIObjectItemView())
->setViewer($viewer);
$icons = array();
$phid = $revision->getPHID();
$flag = $revision->getFlag($viewer);
if ($flag) {
$flag_class = PhabricatorFlagColor::getCSSClass($flag->getColor());
$icons['flag'] = phutil_tag(
'div',
array(
'class' => 'phabricator-flag-icon '.$flag_class,
),
'');
}
$modified = $revision->getDateModified();
if (isset($icons['flag'])) {
$item->addHeadIcon($icons['flag']);
}
$item->setObjectName($revision->getMonogram());
$item->setHeader($revision->getTitle());
$item->setHref($revision->getURI());
$size = $this->renderRevisionSize($revision);
if ($size !== null) {
$item->addAttribute($size);
}
if ($revision->getHasDraft($viewer)) {
$draft = id(new PHUIIconView())
->setIcon('fa-comment yellow')
->addSigil('has-tooltip')
->setMetadata(
array(
'tip' => pht('Unsubmitted Comments'),
));
$item->addAttribute($draft);
}
$author_handle = $handles[$revision->getAuthorPHID()];
$item->addByline(pht('Author: %s', $author_handle->renderLink()));
$unlanded = idx($this->unlandedDependencies, $phid);
if ($unlanded) {
$item->addAttribute(
array(
id(new PHUIIconView())->setIcon('fa-chain-broken', 'red'),
' ',
pht('Open Dependencies'),
));
}
$more = null;
if ($reviewer_more[$key]) {
$more = pht(', ...');
} else {
$more = null;
}
if ($reviewer_phids[$key]) {
$item->addAttribute(
array(
pht('Reviewers:'),
' ',
$viewer->renderHandleList($reviewer_phids[$key])
->setAsInline(true),
$more,
));
} else {
$item->addAttribute(phutil_tag('em', array(), pht('No Reviewers')));
}
$item->setEpoch($revision->getDateModified());
if ($revision->isClosed()) {
$item->setDisabled(true);
}
$icon = $revision->getStatusIcon();
$color = $revision->getStatusIconColor();
$item->setStatusIcon(
"{$icon} {$color}",
$revision->getStatusDisplayName());
$list->addItem($item);
}
$list->setNoDataString($this->noDataString);
if ($this->header && !$this->noBox) {
$list->setFlush(true);
$list = id(new PHUIObjectBoxView())
->setBackground($this->background)
->setObjectList($list);
if ($this->header instanceof PHUIHeaderView) {
$list->setHeader($this->header);
} else {
$list->setHeaderText($this->header);
}
} else {
$list->setHeader($this->header);
}
return $list;
}
private function renderRevisionSize(DifferentialRevision $revision) {
if (!$revision->hasLineCounts()) {
return null;
}
$size = array();
$glyphs = $revision->getRevisionScaleGlyphs();
$plus_count = 0;
for ($ii = 0; $ii < 7; $ii++) {
$c = $glyphs[$ii];
switch ($c) {
case '+':
$size[] = id(new PHUIIconView())
->setIcon('fa-plus');
$plus_count++;
break;
case '-':
$size[] = id(new PHUIIconView())
->setIcon('fa-minus');
break;
default:
$size[] = id(new PHUIIconView())
->setIcon('fa-square-o invisible');
break;
}
}
$n = $revision->getAddedLineCount() + $revision->getRemovedLineCount();
$classes = array();
$classes[] = 'differential-revision-size';
$tip = array();
$tip[] = pht('%s Lines', new PhutilNumber($n));
if ($plus_count <= 1) {
$classes[] = 'differential-revision-small';
$tip[] = pht('Smaller Change');
}
if ($plus_count >= 4) {
$classes[] = 'differential-revision-large';
$tip[] = pht('Larger Change');
}
$tip = phutil_implode_html(" \xC2\xB7 ", $tip);
return javelin_tag(
'span',
array(
'class' => implode(' ', $classes),
'sigil' => 'has-tooltip',
'meta' => array(
'tip' => $tip,
'align' => 'E',
'size' => 400,
),
),
$size);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/view/DifferentialReviewersView.php | src/applications/differential/view/DifferentialReviewersView.php | <?php
final class DifferentialReviewersView extends AphrontView {
private $reviewers;
private $handles;
private $diff;
public function setReviewers(array $reviewers) {
assert_instances_of($reviewers, 'DifferentialReviewer');
$this->reviewers = $reviewers;
return $this;
}
public function setHandles(array $handles) {
assert_instances_of($handles, 'PhabricatorObjectHandle');
$this->handles = $handles;
return $this;
}
public function setActiveDiff(DifferentialDiff $diff) {
$this->diff = $diff;
return $this;
}
public function render() {
$viewer = $this->getUser();
$reviewers = $this->reviewers;
$diff = $this->diff;
$handles = $this->handles;
$view = new PHUIStatusListView();
// Move resigned reviewers to the bottom.
$head = array();
$tail = array();
foreach ($reviewers as $key => $reviewer) {
if ($reviewer->isResigned()) {
$tail[$key] = $reviewer;
} else {
$head[$key] = $reviewer;
}
}
PhabricatorPolicyFilterSet::loadHandleViewCapabilities(
$viewer,
$handles,
array($diff));
$reviewers = $head + $tail;
foreach ($reviewers as $reviewer) {
$phid = $reviewer->getReviewerPHID();
$handle = $handles[$phid];
$action_phid = $reviewer->getLastActionDiffPHID();
$is_current_action = $this->isCurrent($action_phid);
$is_voided = (bool)$reviewer->getVoidedPHID();
$comment_phid = $reviewer->getLastCommentDiffPHID();
$is_current_comment = $this->isCurrent($comment_phid);
$item = new PHUIStatusItemView();
$item->setHighlighted($reviewer->hasAuthority($viewer));
// If someone other than the reviewer acted on the reviewer's behalf,
// show who is responsible for the current state. This is usually a
// user accepting for a package or project.
$authority_phid = $reviewer->getLastActorPHID();
if ($authority_phid && ($authority_phid !== $phid)) {
$authority_name = $viewer->renderHandle($authority_phid)
->setAsText(true);
} else {
$authority_name = null;
}
switch ($reviewer->getReviewerStatus()) {
case DifferentialReviewerStatus::STATUS_ADDED:
if ($comment_phid) {
if ($is_current_comment) {
$icon = 'fa-comment';
$color = 'blue';
$label = pht('Commented');
} else {
$icon = 'fa-comment-o';
$color = 'bluegrey';
$label = pht('Commented Previously');
}
} else {
$icon = PHUIStatusItemView::ICON_OPEN;
$color = 'bluegrey';
$label = pht('Review Requested');
}
break;
case DifferentialReviewerStatus::STATUS_ACCEPTED:
if ($is_current_action && !$is_voided) {
$icon = PHUIStatusItemView::ICON_ACCEPT;
$color = 'green';
if ($authority_name !== null) {
$label = pht('Accepted (by %s)', $authority_name);
} else {
$label = pht('Accepted');
}
} else {
$icon = 'fa-check-circle-o';
$color = 'bluegrey';
if (!$is_current_action && $is_voided) {
// The reviewer accepted the revision, but later the author
// used "Request Review" to request an updated review.
$label = pht('Accepted Earlier');
} else if ($authority_name !== null) {
$label = pht('Accepted Prior Diff (by %s)', $authority_name);
} else {
$label = pht('Accepted Prior Diff');
}
}
break;
case DifferentialReviewerStatus::STATUS_REJECTED:
if ($is_current_action) {
$icon = PHUIStatusItemView::ICON_REJECT;
$color = 'red';
if ($authority_name !== null) {
$label = pht('Requested Changes (by %s)', $authority_name);
} else {
$label = pht('Requested Changes');
}
} else {
$icon = 'fa-times-circle-o';
$color = 'red';
if ($authority_name !== null) {
$label = pht(
'Requested Changes to Prior Diff (by %s)',
$authority_name);
} else {
$label = pht('Requested Changes to Prior Diff');
}
}
break;
case DifferentialReviewerStatus::STATUS_BLOCKING:
$icon = PHUIStatusItemView::ICON_MINUS;
$color = 'red';
$label = pht('Blocking Review');
break;
case DifferentialReviewerStatus::STATUS_RESIGNED:
$icon = 'fa-times';
$color = 'grey';
$label = pht('Resigned');
break;
default:
$icon = PHUIStatusItemView::ICON_QUESTION;
$color = 'bluegrey';
$label = pht('Unknown ("%s")', $reviewer->getReviewerStatus());
break;
}
$item->setIcon($icon, $color, $label);
$item->setTarget(
$handle->renderHovercardLink(
null,
$diff->getPHID()));
if ($reviewer->isPackage()) {
if (!$reviewer->getChangesets()) {
$item->setNote(pht('(Owns No Changed Paths)'));
}
}
if ($handle->hasCapabilities()) {
if (!$handle->hasViewCapability($diff)) {
$item
->setIcon('fa-eye-slash', 'red')
->setNote(pht('No View Permission'))
->setIsExiled(true);
}
}
$view->addItem($item);
}
return $view;
}
private function isCurrent($action_phid) {
if (!$this->diff) {
return true;
}
if (!$action_phid) {
return true;
}
$diff_phid = $this->diff->getPHID();
if (!$diff_phid) {
return true;
}
if ($diff_phid == $action_phid) {
return true;
}
return false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/view/DifferentialChangesetListView.php | src/applications/differential/view/DifferentialChangesetListView.php | <?php
final class DifferentialChangesetListView extends AphrontView {
private $changesets = array();
private $visibleChangesets = array();
private $references = array();
private $inlineURI;
private $renderURI = '/differential/changeset/';
private $background;
private $header;
private $isStandalone;
private $standaloneURI;
private $leftRawFileURI;
private $rightRawFileURI;
private $inlineListURI;
private $symbolIndexes = array();
private $repository;
private $branch;
private $diff;
private $vsMap = array();
private $title;
private $parser;
private $formationView;
public function setParser(DifferentialChangesetParser $parser) {
$this->parser = $parser;
return $this;
}
public function getParser() {
return $this->parser;
}
public function setTitle($title) {
$this->title = $title;
return $this;
}
private function getTitle() {
return $this->title;
}
public function setBranch($branch) {
$this->branch = $branch;
return $this;
}
private function getBranch() {
return $this->branch;
}
public function setChangesets($changesets) {
$this->changesets = $changesets;
return $this;
}
public function setVisibleChangesets($visible_changesets) {
$this->visibleChangesets = $visible_changesets;
return $this;
}
public function setInlineCommentControllerURI($uri) {
$this->inlineURI = $uri;
return $this;
}
public function setInlineListURI($uri) {
$this->inlineListURI = $uri;
return $this;
}
public function getInlineListURI() {
return $this->inlineListURI;
}
public function setRepository(PhabricatorRepository $repository) {
$this->repository = $repository;
return $this;
}
public function getRepository() {
return $this->repository;
}
public function setDiff(DifferentialDiff $diff) {
$this->diff = $diff;
return $this;
}
public function getDiff() {
return $this->diff;
}
public function setRenderingReferences(array $references) {
$this->references = $references;
return $this;
}
public function setSymbolIndexes(array $indexes) {
$this->symbolIndexes = $indexes;
return $this;
}
public function setRenderURI($render_uri) {
$this->renderURI = $render_uri;
return $this;
}
public function setVsMap(array $vs_map) {
$this->vsMap = $vs_map;
return $this;
}
public function getVsMap() {
return $this->vsMap;
}
public function setStandaloneURI($uri) {
$this->standaloneURI = $uri;
return $this;
}
public function setRawFileURIs($l, $r) {
$this->leftRawFileURI = $l;
$this->rightRawFileURI = $r;
return $this;
}
public function setIsStandalone($is_standalone) {
$this->isStandalone = $is_standalone;
return $this;
}
public function getIsStandalone() {
return $this->isStandalone;
}
public function setBackground($background) {
$this->background = $background;
return $this;
}
public function setHeader($header) {
$this->header = $header;
return $this;
}
public function setFormationView(PHUIFormationView $formation_view) {
$this->formationView = $formation_view;
return $this;
}
public function getFormationView() {
return $this->formationView;
}
public function render() {
$viewer = $this->getViewer();
$this->requireResource('differential-changeset-view-css');
$changesets = $this->changesets;
$repository = $this->getRepository();
$diff = $this->getDiff();
$output = array();
$ids = array();
foreach ($changesets as $key => $changeset) {
$file = $changeset->getFilename();
$ref = $this->references[$key];
$detail = id(new DifferentialChangesetDetailView())
->setViewer($viewer);
if ($repository) {
$detail->setRepository($repository);
}
if ($diff) {
$detail->setDiff($diff);
}
$uniq_id = 'diff-'.$changeset->getAnchorName();
$detail->setID($uniq_id);
$view_options = $this->renderViewOptionsDropdown(
$detail,
$ref,
$changeset);
$detail->setChangeset($changeset);
$detail->addButton($view_options);
$detail->setSymbolIndex(idx($this->symbolIndexes, $key));
$detail->setVsChangesetID(idx($this->vsMap, $changeset->getID()));
$detail->setEditable(true);
$detail->setRenderingRef($ref);
$detail->setBranch($this->getBranch());
$detail->setRenderURI($this->renderURI);
$parser = $this->getParser();
if ($parser) {
$response = $parser->newChangesetResponse();
$detail->setChangesetResponse($response);
} else {
$detail->setAutoload(isset($this->visibleChangesets[$key]));
if (isset($this->visibleChangesets[$key])) {
$load = pht('Loading...');
} else {
$load = javelin_tag(
'a',
array(
'class' => 'button button-grey',
'href' => '#'.$uniq_id,
'sigil' => 'differential-load',
'meta' => array(
'id' => $detail->getID(),
'kill' => true,
),
'mustcapture' => true,
),
pht('Load File'));
}
$detail->appendChild(
phutil_tag(
'div',
array(
'id' => $uniq_id,
),
phutil_tag(
'div',
array('class' => 'differential-loading'),
$load)));
}
$output[] = $detail->render();
$ids[] = $detail->getID();
}
$this->requireResource('aphront-tooltip-css');
$formation_id = null;
$formation_view = $this->getFormationView();
if ($formation_view) {
$formation_id = $formation_view->getID();
}
$this->initBehavior(
'differential-populate',
array(
'changesetViewIDs' => $ids,
'formationViewID' => $formation_id,
'inlineURI' => $this->inlineURI,
'inlineListURI' => $this->inlineListURI,
'isStandalone' => $this->getIsStandalone(),
'pht' => array(
'Open in Editor' => pht('Open in Editor'),
'Show All Context' => pht('Show All Context'),
'All Context Shown' => pht('All Context Shown'),
'Expand File' => pht('Expand File'),
'Hide Changeset' => pht('Hide Changeset'),
'Show Path in Repository' => pht('Show Path in Repository'),
'Show Directory in Repository' => pht('Show Directory in Repository'),
'View Standalone' => pht('View Standalone'),
'Show Raw File (Left)' => pht('Show Raw File (Left)'),
'Show Raw File (Right)' => pht('Show Raw File (Right)'),
'Configure Editor' => pht('Configure Editor'),
'Load Changes' => pht('Load Changes'),
'View Side-by-Side Diff' => pht('View Side-by-Side Diff'),
'View Unified Diff' => pht('View Unified Diff'),
'Change Text Encoding...' => pht('Change Text Encoding...'),
'Highlight As...' => pht('Highlight As...'),
'View As Document Type...' => pht('View As Document Type...'),
'Loading...' => pht('Loading...'),
'Editing Comment' => pht('Editing Comment'),
'Jump to next change.' => pht('Jump to next change.'),
'Jump to previous change.' => pht('Jump to previous change.'),
'Jump to next file.' => pht('Jump to next file.'),
'Jump to previous file.' => pht('Jump to previous file.'),
'Jump to next inline comment.' => pht('Jump to next inline comment.'),
'Jump to previous inline comment.' =>
pht('Jump to previous inline comment.'),
'Jump to the table of contents.' =>
pht('Jump to the table of contents.'),
'Edit selected inline comment.' =>
pht('Edit selected inline comment.'),
'You must select a comment to edit.' =>
pht('You must select a comment to edit.'),
'Reply to selected inline comment or change.' =>
pht('Reply to selected inline comment or change.'),
'You must select a comment or change to reply to.' =>
pht('You must select a comment or change to reply to.'),
'Reply and quote selected inline comment.' =>
pht('Reply and quote selected inline comment.'),
'Mark or unmark selected inline comment as done.' =>
pht('Mark or unmark selected inline comment as done.'),
'You must select a comment to mark done.' =>
pht('You must select a comment to mark done.'),
'Collapse or expand inline comment.' =>
pht('Collapse or expand inline comment.'),
'You must select a comment to hide.' =>
pht('You must select a comment to hide.'),
'Jump to next inline comment, including collapsed comments.' =>
pht('Jump to next inline comment, including collapsed comments.'),
'Jump to previous inline comment, including collapsed comments.' =>
pht('Jump to previous inline comment, including collapsed comments.'),
'Hide or show the current changeset.' =>
pht('Hide or show the current changeset.'),
'You must select a file to hide or show.' =>
pht('You must select a file to hide or show.'),
'Unsaved' => pht('Unsaved'),
'Unsubmitted' => pht('Unsubmitted'),
'Comments' => pht('Comments'),
'Hide "Done" Inlines' => pht('Hide "Done" Inlines'),
'Hide Collapsed Inlines' => pht('Hide Collapsed Inlines'),
'Hide Older Inlines' => pht('Hide Older Inlines'),
'Hide All Inlines' => pht('Hide All Inlines'),
'Show All Inlines' => pht('Show All Inlines'),
'List Inline Comments' => pht('List Inline Comments'),
'Display Options' => pht('Display Options'),
'Hide or show all inline comments.' =>
pht('Hide or show all inline comments.'),
'Finish editing inline comments before changing display modes.' =>
pht('Finish editing inline comments before changing display modes.'),
'Open file in external editor.' =>
pht('Open file in external editor.'),
'You must select a file to edit.' =>
pht('You must select a file to edit.'),
'You must select a file to open.' =>
pht('You must select a file to open.'),
'No external editor is configured.' =>
pht('No external editor is configured.'),
'Hide or show the paths panel.' =>
pht('Hide or show the paths panel.'),
'Show path in repository.' =>
pht('Show path in repository.'),
'Show directory in repository.' =>
pht('Show directory in repository.'),
'Jump to the comment area.' =>
pht('Jump to the comment area.'),
'Show Changeset' => pht('Show Changeset'),
'You must select source text to create a new inline comment.' =>
pht('You must select source text to create a new inline comment.'),
'New Inline Comment' => pht('New Inline Comment'),
'Add new inline comment on selected source text.' =>
pht('Add new inline comment on selected source text.'),
'Suggest Edit' => pht('Suggest Edit'),
'Discard Edit' => pht('Discard Edit'),
),
));
if ($this->header) {
$header = $this->header;
} else {
$header = id(new PHUIHeaderView())
->setHeader($this->getTitle());
}
$content = phutil_tag(
'div',
array(
'class' => 'differential-review-stage',
'id' => 'differential-review-stage',
),
$output);
$object_box = id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground($this->background)
->setCollapsed(true)
->appendChild($content);
return $object_box;
}
private function renderViewOptionsDropdown(
DifferentialChangesetDetailView $detail,
$ref,
DifferentialChangeset $changeset) {
$viewer = $this->getViewer();
$meta = array();
$qparams = array(
'ref' => $ref,
);
if ($this->standaloneURI) {
$uri = new PhutilURI($this->standaloneURI);
$uri = $this->appendDefaultQueryParams($uri, $qparams);
$meta['standaloneURI'] = (string)$uri;
}
$change = $changeset->getChangeType();
if ($this->leftRawFileURI) {
if ($change != DifferentialChangeType::TYPE_ADD) {
$uri = new PhutilURI($this->leftRawFileURI);
$uri = $this->appendDefaultQueryParams($uri, $qparams);
$meta['leftURI'] = (string)$uri;
}
}
if ($this->rightRawFileURI) {
if ($change != DifferentialChangeType::TYPE_DELETE &&
$change != DifferentialChangeType::TYPE_MULTICOPY) {
$uri = new PhutilURI($this->rightRawFileURI);
$uri = $this->appendDefaultQueryParams($uri, $qparams);
$meta['rightURI'] = (string)$uri;
}
}
$meta['containerID'] = $detail->getID();
return id(new PHUIButtonView())
->setTag('a')
->setText(pht('View Options'))
->setIcon('fa-bars')
->setColor(PHUIButtonView::GREY)
->setHref(idx($meta, 'detailURI', '#'))
->setMetadata($meta)
->addSigil('differential-view-options');
}
private function appendDefaultQueryParams(PhutilURI $uri, array $params) {
// Add these default query parameters to the query string if they do not
// already exist.
$have = array();
foreach ($uri->getQueryParamsAsPairList() as $pair) {
list($key, $value) = $pair;
$have[$key] = true;
}
foreach ($params as $key => $value) {
if (!isset($have[$key])) {
$uri->appendQueryParam($key, $value);
}
}
return $uri;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/view/DifferentialRevisionUpdateHistoryView.php | src/applications/differential/view/DifferentialRevisionUpdateHistoryView.php | <?php
final class DifferentialRevisionUpdateHistoryView extends AphrontView {
private $diffs = array();
private $selectedVersusDiffID;
private $selectedDiffID;
private $commitsForLinks = array();
private $unitStatus = array();
public function setDiffs(array $diffs) {
assert_instances_of($diffs, 'DifferentialDiff');
$this->diffs = $diffs;
return $this;
}
public function setSelectedVersusDiffID($id) {
$this->selectedVersusDiffID = $id;
return $this;
}
public function setSelectedDiffID($id) {
$this->selectedDiffID = $id;
return $this;
}
public function setCommitsForLinks(array $commits) {
assert_instances_of($commits, 'PhabricatorRepositoryCommit');
$this->commitsForLinks = $commits;
return $this;
}
public function setDiffUnitStatuses(array $unit_status) {
$this->unitStatus = $unit_status;
return $this;
}
public function render() {
$this->requireResource('differential-core-view-css');
$this->requireResource('differential-revision-history-css');
$data = array(
array(
'name' => pht('Base'),
'id' => null,
'desc' => pht('Base'),
'age' => null,
'obj' => null,
),
);
$seq = 0;
foreach ($this->diffs as $diff) {
$data[] = array(
'name' => pht('Diff %d', ++$seq),
'id' => $diff->getID(),
'desc' => $diff->getDescription(),
'age' => $diff->getDateCreated(),
'obj' => $diff,
);
}
$max_id = $diff->getID();
$revision_id = $diff->getRevisionID();
$idx = 0;
$rows = array();
$disable = false;
$radios = array();
$last_base = null;
$rowc = array();
foreach ($data as $row) {
$diff = $row['obj'];
$name = $row['name'];
$id = $row['id'];
$old_class = false;
$new_class = false;
if ($id) {
$new_checked = ($this->selectedDiffID == $id);
$new = javelin_tag(
'input',
array(
'type' => 'radio',
'name' => 'id',
'value' => $id,
'checked' => $new_checked ? 'checked' : null,
'sigil' => 'differential-new-radio',
));
if ($new_checked) {
$new_class = true;
$disable = true;
}
$new = phutil_tag(
'div',
array(
'class' => 'differential-update-history-radio',
),
$new);
} else {
$new = null;
}
if ($max_id != $id) {
$uniq = celerity_generate_unique_node_id();
$old_checked = ($this->selectedVersusDiffID == $id);
$old = phutil_tag(
'input',
array(
'type' => 'radio',
'name' => 'vs',
'value' => $id,
'id' => $uniq,
'checked' => $old_checked ? 'checked' : null,
'disabled' => $disable ? 'disabled' : null,
));
$radios[] = $uniq;
if ($old_checked) {
$old_class = true;
}
$old = phutil_tag(
'div',
array(
'class' => 'differential-update-history-radio',
),
$old);
} else {
$old = null;
}
$desc = $row['desc'];
if ($row['age']) {
$age = phabricator_datetime($row['age'], $this->getUser());
} else {
$age = null;
}
if ($diff) {
$lint = $this->newLintStatusView($diff);
$unit = $this->newUnitStatusView($diff);
$base = $this->renderBaseRevision($diff);
} else {
$lint = null;
$unit = null;
$base = null;
}
if ($last_base !== null && $base !== $last_base) {
// TODO: Render some kind of notice about rebases.
}
$last_base = $base;
if ($revision_id) {
$id_link = phutil_tag(
'a',
array(
'href' => '/D'.$revision_id.'?id='.$id,
),
$id);
} else {
$id_link = phutil_tag(
'a',
array(
'href' => '/differential/diff/'.$id.'/',
),
$id);
}
$rows[] = array(
$name,
$id_link,
$base,
$desc,
$age,
$lint,
$unit,
$old,
$new,
);
$classes = array();
if ($old_class) {
$classes[] = 'differential-update-history-old-now';
}
if ($new_class) {
$classes[] = 'differential-update-history-new-now';
}
$rowc[] = nonempty(implode(' ', $classes), null);
}
Javelin::initBehavior(
'differential-diff-radios',
array(
'radios' => $radios,
));
$table = id(new AphrontTableView($rows));
$table->setHeaders(
array(
pht('Diff'),
pht('ID'),
pht('Base'),
pht('Description'),
pht('Created'),
pht('Lint'),
pht('Unit'),
'',
'',
));
$table->setColumnClasses(
array(
'pri',
'',
'',
'wide',
'date',
'center',
'center',
'center differential-update-history-old',
'center differential-update-history-new',
));
$table->setRowClasses($rowc);
$table->setDeviceVisibility(
array(
true,
true,
false,
true,
false,
false,
false,
true,
true,
));
$show_diff = phutil_tag(
'div',
array(
'class' => 'differential-update-history-footer',
),
array(
phutil_tag(
'button',
array(),
pht('Show Diff')),
));
$content = phabricator_form(
$this->getUser(),
array(
'method' => 'GET',
'action' => '/D'.$revision_id.'#toc',
),
array(
$table,
$show_diff,
));
return $content;
}
private function renderBaseRevision(DifferentialDiff $diff) {
switch ($diff->getSourceControlSystem()) {
case 'git':
$base = $diff->getSourceControlBaseRevision();
if (strpos($base, '@') === false) {
$label = substr($base, 0, 7);
} else {
// The diff is from git-svn
$base = explode('@', $base);
$base = last($base);
$label = $base;
}
break;
case 'svn':
$base = $diff->getSourceControlBaseRevision();
$base = explode('@', $base);
$base = last($base);
$label = $base;
break;
default:
$label = null;
break;
}
$link = null;
if ($label) {
$commit_for_link = idx(
$this->commitsForLinks,
$diff->getSourceControlBaseRevision());
if ($commit_for_link) {
$link = phutil_tag(
'a',
array('href' => $commit_for_link->getURI()),
$label);
} else {
$link = $label;
}
}
return $link;
}
private function newLintStatusView(DifferentialDiff $diff) {
$value = $diff->getLintStatus();
$status = DifferentialLintStatus::newStatusFromValue($value);
$icon = $status->getIconIcon();
$color = $status->getIconColor();
$name = $status->getName();
return $this->newDiffStatusIconView($icon, $color, $name);
}
private function newUnitStatusView(DifferentialDiff $diff) {
$value = $diff->getUnitStatus();
// NOTE: We may be overriding the value on the diff with a value from
// Harbormaster.
$value = idx($this->unitStatus, $diff->getPHID(), $value);
$status = DifferentialUnitStatus::newStatusFromValue($value);
$icon = $status->getIconIcon();
$color = $status->getIconColor();
$name = $status->getName();
return $this->newDiffStatusIconView($icon, $color, $name);
}
private function newDiffStatusIconView($icon, $color, $name) {
return id(new PHUIIconView())
->setIcon($icon, $color)
->addSigil('has-tooltip')
->setMetadata(
array(
'tip' => $name,
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/view/DifferentialLocalCommitsView.php | src/applications/differential/view/DifferentialLocalCommitsView.php | <?php
final class DifferentialLocalCommitsView extends AphrontView {
private $localCommits;
private $commitsForLinks = array();
public function setLocalCommits($local_commits) {
$this->localCommits = $local_commits;
return $this;
}
public function setCommitsForLinks(array $commits) {
assert_instances_of($commits, 'PhabricatorRepositoryCommit');
$this->commitsForLinks = $commits;
return $this;
}
public function render() {
$viewer = $this->getViewer();
$local = $this->localCommits;
if (!$local) {
return null;
}
$has_tree = false;
$has_local = false;
foreach ($local as $commit) {
if (idx($commit, 'tree')) {
$has_tree = true;
}
if (idx($commit, 'local')) {
$has_local = true;
}
}
$rows = array();
foreach ($local as $commit) {
$row = array();
if (idx($commit, 'commit')) {
$commit_link = $this->buildCommitLink($commit['commit']);
} else if (isset($commit['rev'])) {
$commit_link = $this->buildCommitLink($commit['rev']);
} else {
$commit_link = null;
}
$row[] = $commit_link;
if ($has_tree) {
$row[] = $this->buildCommitLink($commit['tree']);
}
if ($has_local) {
$row[] = $this->buildCommitLink($commit['local']);
}
$parents = idx($commit, 'parents', array());
foreach ($parents as $k => $parent) {
if (is_array($parent)) {
$parent = idx($parent, 'rev');
}
$parents[$k] = $this->buildCommitLink($parent);
}
$parents = phutil_implode_html(phutil_tag('br'), $parents);
$row[] = $parents;
$author = nonempty(
idx($commit, 'user'),
idx($commit, 'author'));
$row[] = $author;
$message = idx($commit, 'message');
$summary = idx($commit, 'summary');
$summary = id(new PhutilUTF8StringTruncator())
->setMaximumGlyphs(80)
->truncateString($summary);
$view = new AphrontMoreView();
$view->setSome($summary);
if ($message && (trim($summary) != trim($message))) {
$view->setMore(phutil_escape_html_newlines($message));
}
$row[] = $view->render();
$date = nonempty(
idx($commit, 'date'),
idx($commit, 'time'));
if ($date) {
$date = phabricator_datetime($date, $viewer);
}
$row[] = $date;
$rows[] = $row;
}
$column_classes = array('');
if ($has_tree) {
$column_classes[] = '';
}
if ($has_local) {
$column_classes[] = '';
}
$column_classes[] = '';
$column_classes[] = '';
$column_classes[] = 'wide';
$column_classes[] = 'date';
$table = id(new AphrontTableView($rows))
->setColumnClasses($column_classes);
$headers = array();
$headers[] = pht('Commit');
if ($has_tree) {
$headers[] = pht('Tree');
}
if ($has_local) {
$headers[] = pht('Local');
}
$headers[] = pht('Parents');
$headers[] = pht('Author');
$headers[] = pht('Summary');
$headers[] = pht('Date');
$table->setHeaders($headers);
return $table;
}
private static function formatCommit($commit) {
return substr($commit, 0, 12);
}
private function buildCommitLink($hash) {
$commit_for_link = idx($this->commitsForLinks, $hash);
$commit_hash = self::formatCommit($hash);
if ($commit_for_link) {
$link = phutil_tag(
'a',
array(
'href' => $commit_for_link->getURI(),
),
$commit_hash);
} else {
$link = $commit_hash;
}
return $link;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/view/DifferentialTransactionView.php | src/applications/differential/view/DifferentialTransactionView.php | <?php
final class DifferentialTransactionView
extends PhabricatorApplicationTransactionView {
private $changesets = array();
private $revision;
private $rightDiff;
private $leftDiff;
public function setLeftDiff(DifferentialDiff $left_diff) {
$this->leftDiff = $left_diff;
return $this;
}
public function getLeftDiff() {
return $this->leftDiff;
}
public function setRightDiff(DifferentialDiff $right_diff) {
$this->rightDiff = $right_diff;
return $this;
}
public function getRightDiff() {
return $this->rightDiff;
}
public function setRevision(DifferentialRevision $revision) {
$this->revision = $revision;
return $this;
}
public function getRevision() {
return $this->revision;
}
public function setChangesets(array $changesets) {
assert_instances_of($changesets, 'DifferentialChangeset');
$this->changesets = $changesets;
return $this;
}
public function getChangesets() {
return $this->changesets;
}
// TODO: There's a whole lot of code duplication between this and
// PholioTransactionView to handle inlines. Merge this into the core? Some of
// it can probably be shared, while other parts are trickier.
protected function shouldGroupTransactions(
PhabricatorApplicationTransaction $u,
PhabricatorApplicationTransaction $v) {
if ($u->getAuthorPHID() != $v->getAuthorPHID()) {
// Don't group transactions by different authors.
return false;
}
if (($v->getDateCreated() - $u->getDateCreated()) > 60) {
// Don't group if transactions that happened more than 60s apart.
return false;
}
switch ($u->getTransactionType()) {
case PhabricatorTransactions::TYPE_COMMENT:
case DifferentialTransaction::TYPE_INLINE:
break;
default:
return false;
}
switch ($v->getTransactionType()) {
case DifferentialTransaction::TYPE_INLINE:
return true;
}
return parent::shouldGroupTransactions($u, $v);
}
protected function renderTransactionContent(
PhabricatorApplicationTransaction $xaction) {
$out = array();
$type_inline = DifferentialTransaction::TYPE_INLINE;
$group = $xaction->getTransactionGroup();
if ($xaction->getTransactionType() == $type_inline) {
array_unshift($group, $xaction);
} else {
$out[] = parent::renderTransactionContent($xaction);
}
// If we're rendering a preview, we show the inline comments in a separate
// section underneath the main transaction preview, so we skip rendering
// them in the preview body.
if ($this->getIsPreview()) {
return $out;
}
if (!$group) {
return $out;
}
$inlines = array();
foreach ($group as $xaction) {
switch ($xaction->getTransactionType()) {
case DifferentialTransaction::TYPE_INLINE:
$inlines[] = $xaction;
break;
default:
throw new Exception(pht('Unknown grouped transaction type!'));
}
}
if ($inlines) {
$inline_view = new PhabricatorInlineSummaryView();
$changesets = $this->getChangesets();
$inline_groups = DifferentialTransactionComment::sortAndGroupInlines(
$inlines,
$changesets);
foreach ($inline_groups as $changeset_id => $group) {
$changeset = $changesets[$changeset_id];
$items = array();
foreach ($group as $inline) {
$comment = $inline->getComment();
$item = array(
'id' => $comment->getID(),
'line' => $comment->getLineNumber(),
'length' => $comment->getLineLength(),
'content' => parent::renderTransactionContent($inline),
);
$changeset_diff_id = $changeset->getDiffID();
if ($comment->getIsNewFile()) {
$visible_diff_id = $this->getRightDiff()->getID();
} else {
$visible_diff_id = $this->getLeftDiff()->getID();
}
// TODO: We still get one edge case wrong here, when we have a
// versus diff and the file didn't exist in the old version. The
// comment is visible because we show the left side of the target
// diff when there's no corresponding file in the versus diff, but
// we incorrectly link it off-page.
$is_visible = ($changeset_diff_id == $visible_diff_id);
if (!$is_visible) {
$revision_id = $this->getRevision()->getID();
$comment_id = $comment->getID();
$item['href'] =
'/D'.$revision_id.
'?id='.$changeset_diff_id.
'#inline-'.$comment_id;
$item['where'] = pht('(On Diff #%d)', $changeset_diff_id);
}
$items[] = $item;
}
$inline_view->addCommentGroup(
$changeset->getFilename(),
$items);
}
$out[] = $inline_view;
}
return $out;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/differential/view/DifferentialChangesetDetailView.php | src/applications/differential/view/DifferentialChangesetDetailView.php | <?php
final class DifferentialChangesetDetailView extends AphrontView {
private $changeset;
private $buttons = array();
private $editable;
private $symbolIndex;
private $id;
private $vsChangesetID;
private $renderURI;
private $renderingRef;
private $autoload;
private $repository;
private $diff;
private $changesetResponse;
private $branch;
public function setAutoload($autoload) {
$this->autoload = $autoload;
return $this;
}
public function getAutoload() {
return $this->autoload;
}
public function setRenderingRef($rendering_ref) {
$this->renderingRef = $rendering_ref;
return $this;
}
public function getRenderingRef() {
return $this->renderingRef;
}
public function setChangesetResponse(PhabricatorChangesetResponse $response) {
$this->changesetResponse = $response;
return $this;
}
public function getChangesetResponse() {
return $this->changesetResponse;
}
public function setRenderURI($render_uri) {
$this->renderURI = $render_uri;
return $this;
}
public function getRenderURI() {
return $this->renderURI;
}
public function setChangeset($changeset) {
$this->changeset = $changeset;
return $this;
}
public function addButton($button) {
$this->buttons[] = $button;
return $this;
}
public function setEditable($editable) {
$this->editable = $editable;
return $this;
}
public function setSymbolIndex($symbol_index) {
$this->symbolIndex = $symbol_index;
return $this;
}
public function setBranch($branch) {
$this->branch = $branch;
return $this;
}
public function getBranch() {
return $this->branch;
}
public function getID() {
if (!$this->id) {
$this->id = celerity_generate_unique_node_id();
}
return $this->id;
}
public function setID($id) {
$this->id = $id;
return $this;
}
public function setVsChangesetID($vs_changeset_id) {
$this->vsChangesetID = $vs_changeset_id;
return $this;
}
public function getVsChangesetID() {
return $this->vsChangesetID;
}
public function render() {
$viewer = $this->getViewer();
$this->requireResource('differential-changeset-view-css');
$this->requireResource('syntax-highlighting-css');
Javelin::initBehavior('phabricator-oncopy', array());
$changeset = $this->changeset;
$class = 'differential-changeset';
if (!$this->editable) {
$class .= ' differential-changeset-immutable';
}
$buttons = null;
if ($this->buttons) {
$buttons = phutil_tag(
'div',
array(
'class' => 'differential-changeset-buttons',
),
$this->buttons);
}
$id = $this->getID();
if ($this->symbolIndex) {
Javelin::initBehavior(
'repository-crossreference',
array(
'container' => $id,
) + $this->symbolIndex);
}
$display_filename = $changeset->getDisplayFilename();
$display_icon = FileTypeIcon::getFileIcon($display_filename);
$icon = id(new PHUIIconView())
->setIcon($display_icon);
$changeset_id = $this->changeset->getID();
$vs_id = $this->getVsChangesetID();
if (!$vs_id) {
// Showing a changeset normally.
$left_id = $changeset_id;
$right_id = $changeset_id;
} else if ($vs_id == -1) {
// Showing a synthetic "deleted" changeset for a file which was
// removed between changes.
$left_id = $changeset_id;
$right_id = null;
} else {
// Showing a diff-of-diffs.
$left_id = $vs_id;
$right_id = $changeset_id;
}
// In the persistent banner, emphasize the current filename.
$path_part = dirname($display_filename);
$file_part = basename($display_filename);
$display_parts = array();
if (strlen($path_part)) {
$path_part = $path_part.'/';
$display_parts[] = phutil_tag(
'span',
array(
'class' => 'diff-banner-path',
),
$path_part);
}
$display_parts[] = phutil_tag(
'span',
array(
'class' => 'diff-banner-file',
),
$file_part);
$response = $this->getChangesetResponse();
if ($response) {
$is_loaded = true;
$changeset_markup = $response->getRenderedChangeset();
$changeset_state = $response->getChangesetState();
} else {
$is_loaded = false;
$changeset_markup = null;
$changeset_state = null;
}
$path_parts = trim($display_filename, '/');
$path_parts = explode('/', $path_parts);
$show_path_uri = null;
$show_directory_uri = null;
$repository = $this->getRepository();
if ($repository) {
$diff = $this->getDiff();
if ($diff) {
$repo_path = $changeset->getAbsoluteRepositoryPath($repository, $diff);
$repo_dir = dirname($repo_path);
if ($repo_dir === $repo_path) {
$repo_dir = null;
}
$show_path_uri = $repository->getDiffusionBrowseURIForPath(
$viewer,
$repo_path,
idx($changeset->getMetadata(), 'line:first'),
$this->getBranch());
if ($repo_dir !== null) {
$repo_dir = rtrim($repo_dir, '/').'/';
$show_directory_uri = $repository->getDiffusionBrowseURIForPath(
$viewer,
$repo_dir,
null,
$this->getBranch());
}
}
}
if ($show_path_uri) {
$show_path_uri = phutil_string_cast($show_path_uri);
}
if ($show_directory_uri) {
$show_directory_uri = phutil_string_cast($show_directory_uri);
}
return javelin_tag(
'div',
array(
'sigil' => 'differential-changeset',
'meta' => array(
'left' => $left_id,
'right' => $right_id,
'renderURI' => $this->getRenderURI(),
'ref' => $this->getRenderingRef(),
'autoload' => $this->getAutoload(),
'displayPath' => hsprintf('%s', $display_parts),
'icon' => $display_icon,
'pathParts' => $path_parts,
'symbolPath' => $display_filename,
'pathIconIcon' => $changeset->getPathIconIcon(),
'pathIconColor' => $changeset->getPathIconColor(),
'isLowImportance' => $changeset->getIsLowImportanceChangeset(),
'isOwned' => $changeset->getIsOwnedChangeset(),
'editorURITemplate' => $this->getEditorURITemplate(),
'editorConfigureURI' => $this->getEditorConfigureURI(),
'loaded' => $is_loaded,
'changesetState' => $changeset_state,
'showPathURI' => $show_path_uri,
'showDirectoryURI' => $show_directory_uri,
),
'class' => $class,
'id' => $id,
),
array(
id(new PhabricatorAnchorView())
->setAnchorName($changeset->getAnchorName())
->setNavigationMarker(true)
->render(),
$buttons,
javelin_tag(
'h1',
array(
'class' => 'differential-file-icon-header',
'sigil' => 'changeset-header',
),
array(
$icon,
javelin_tag(
'span',
array(
'class' => 'differential-changeset-path-name',
'sigil' => 'changeset-header-path-name',
),
$display_filename),
)),
javelin_tag(
'div',
array(
'class' => 'changeset-view-content',
'sigil' => 'changeset-view-content',
),
array(
$changeset_markup,
$this->renderChildren(),
)),
));
}
public function setRepository(PhabricatorRepository $repository) {
$this->repository = $repository;
return $this;
}
public function getRepository() {
return $this->repository;
}
public function getChangeset() {
return $this->changeset;
}
public function setDiff(DifferentialDiff $diff) {
$this->diff = $diff;
return $this;
}
public function getDiff() {
return $this->diff;
}
private function getEditorURITemplate() {
$repository = $this->getRepository();
if (!$repository) {
return null;
}
$viewer = $this->getViewer();
$link_engine = PhabricatorEditorURIEngine::newForViewer($viewer);
if (!$link_engine) {
return null;
}
$link_engine->setRepository($repository);
$changeset = $this->getChangeset();
$diff = $this->getDiff();
$path = $changeset->getAbsoluteRepositoryPath($repository, $diff);
$path = ltrim($path, '/');
return $link_engine->getURITokensForPath($path);
}
private function getEditorConfigureURI() {
$viewer = $this->getViewer();
if (!$viewer->isLoggedIn()) {
return null;
}
return '/settings/panel/editor/';
}
}
| 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.