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/infrastructure/customfield/datasource/PhabricatorCustomFieldApplicationSearchNoneFunctionDatasource.php | src/infrastructure/customfield/datasource/PhabricatorCustomFieldApplicationSearchNoneFunctionDatasource.php | <?php
final class PhabricatorCustomFieldApplicationSearchNoneFunctionDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse No Value');
}
public function getPlaceholderText() {
return pht('Type "none()"...');
}
public function getDatasourceApplicationClass() {
return null;
}
public function getDatasourceFunctions() {
return array(
'none' => array(
'name' => pht('No Value'),
'summary' => pht('Find results with no value.'),
'description' => pht(
"This function includes results which have no value. Use a query ".
"like this to find results with no value:\n\n%s\n\n".
'If you combine this function with other constraints, results '.
'which have no value or the specified values will be returned.',
'> any()'),
),
);
}
public function loadResults() {
$results = array(
$this->newNoneFunction(),
);
return $this->filterResultsAgainstTokens($results);
}
protected function evaluateFunction($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = new PhabricatorQueryConstraint(
PhabricatorQueryConstraint::OPERATOR_NULL,
null);
}
return $results;
}
public function renderFunctionTokens($function, array $argv_list) {
$results = array();
foreach ($argv_list as $argv) {
$results[] = PhabricatorTypeaheadTokenView::newFromTypeaheadResult(
$this->newNoneFunction());
}
return $results;
}
private function newNoneFunction() {
$name = pht('No Value');
return $this->newFunctionResult()
->setName($name.' none')
->setDisplayName($name)
->setIcon('fa-ban')
->setPHID('none()')
->setUnique(true)
->addAttribute(pht('Select results with no value.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/datasource/PhabricatorCustomFieldApplicationSearchDatasource.php | src/infrastructure/customfield/datasource/PhabricatorCustomFieldApplicationSearchDatasource.php | <?php
final class PhabricatorCustomFieldApplicationSearchDatasource
extends PhabricatorTypeaheadProxyDatasource {
public function getComponentDatasources() {
$datasources = parent::getComponentDatasources();
$datasources[] =
new PhabricatorCustomFieldApplicationSearchAnyFunctionDatasource();
$datasources[] =
new PhabricatorCustomFieldApplicationSearchNoneFunctionDatasource();
return $datasources;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/interface/PhabricatorCustomFieldInterface.php | src/infrastructure/customfield/interface/PhabricatorCustomFieldInterface.php | <?php
interface PhabricatorCustomFieldInterface {
public function getCustomFieldBaseClass();
public function getCustomFieldSpecificationForRole($role);
public function getCustomFields();
public function attachCustomFields(PhabricatorCustomFieldAttachment $fields);
}
// TEMPLATE IMPLEMENTATION /////////////////////////////////////////////////////
/* -( PhabricatorCustomFieldInterface )------------------------------------ */
/*
private $customFields = self::ATTACHABLE;
public function getCustomFieldSpecificationForRole($role) {
return PhabricatorEnv::getEnvConfig(<<<'application.fields'>>>);
}
public function getCustomFieldBaseClass() {
return <<<<'YourApplicationHereCustomField'>>>>;
}
public function getCustomFields() {
return $this->assertAttached($this->customFields);
}
public function attachCustomFields(PhabricatorCustomFieldAttachment $fields) {
$this->customFields = $fields;
return $this;
}
*/
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/interface/PhabricatorStandardCustomFieldInterface.php | src/infrastructure/customfield/interface/PhabricatorStandardCustomFieldInterface.php | <?php
interface PhabricatorStandardCustomFieldInterface {
public function getStandardCustomFieldNamespace();
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/editor/PhabricatorCustomFieldEditType.php | src/infrastructure/customfield/editor/PhabricatorCustomFieldEditType.php | <?php
final class PhabricatorCustomFieldEditType
extends PhabricatorEditType {
private $customField;
public function setCustomField(PhabricatorCustomField $custom_field) {
$this->customField = $custom_field;
return $this;
}
public function getCustomField() {
return $this->customField;
}
public function getMetadata() {
$field = $this->getCustomField();
return parent::getMetadata() + $field->getApplicationTransactionMetadata();
}
public function generateTransactions(
PhabricatorApplicationTransaction $template,
array $spec) {
$value = idx($spec, 'value');
$xaction = $this->newTransaction($template)
->setNewValue($value);
$custom_type = PhabricatorTransactions::TYPE_CUSTOMFIELD;
if ($xaction->getTransactionType() == $custom_type) {
$field = $this->getCustomField();
$xaction
->setOldValue($field->getOldValueForApplicationTransactions())
->setMetadataValue('customfield:key', $field->getFieldKey());
}
return array($xaction);
}
protected function getTransactionValueFromValue($value) {
$field = $this->getCustomField();
// Avoid changing the value of the field itself, since later calls would
// incorrectly reflect the new value.
$clone = clone $field;
$clone->setValueFromApplicationTransactions($value);
return $clone->getNewValueForApplicationTransactions();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/editor/PhabricatorCustomFieldEditField.php | src/infrastructure/customfield/editor/PhabricatorCustomFieldEditField.php | <?php
final class PhabricatorCustomFieldEditField
extends PhabricatorEditField {
private $customField;
private $httpParameterType;
private $conduitParameterType;
private $bulkParameterType;
private $commentAction;
public function setCustomField(PhabricatorCustomField $custom_field) {
$this->customField = $custom_field;
return $this;
}
public function getCustomField() {
return $this->customField;
}
public function setCustomFieldHTTPParameterType(
AphrontHTTPParameterType $type) {
$this->httpParameterType = $type;
return $this;
}
public function getCustomFieldHTTPParameterType() {
return $this->httpParameterType;
}
public function setCustomFieldConduitParameterType(
ConduitParameterType $type) {
$this->conduitParameterType = $type;
return $this;
}
public function getCustomFieldConduitParameterType() {
return $this->conduitParameterType;
}
public function setCustomFieldBulkParameterType(
BulkParameterType $type) {
$this->bulkParameterType = $type;
return $this;
}
public function getCustomFieldBulkParameterType() {
return $this->bulkParameterType;
}
public function setCustomFieldCommentAction(
PhabricatorEditEngineCommentAction $comment_action) {
$this->commentAction = $comment_action;
return $this;
}
public function getCustomFieldCommentAction() {
return $this->commentAction;
}
protected function buildControl() {
if (!$this->getIsFormField()) {
return null;
}
$field = $this->getCustomField();
$clone = clone $field;
$value = $this->getValue();
$clone->setValueFromApplicationTransactions($value);
return $clone->renderEditControl(array());
}
protected function newEditType() {
return id(new PhabricatorCustomFieldEditType())
->setCustomField($this->getCustomField());
}
public function getValueForTransaction() {
$value = $this->getValue();
$field = $this->getCustomField();
// Avoid changing the value of the field itself, since later calls would
// incorrectly reflect the new value.
$clone = clone $field;
$clone->setValueFromApplicationTransactions($value);
return $clone->getNewValueForApplicationTransactions();
}
protected function getValueForCommentAction($value) {
$field = $this->getCustomField();
$clone = clone $field;
$clone->setValueFromApplicationTransactions($value);
// TODO: This is somewhat bogus because only StandardCustomFields
// implement a getFieldValue() method -- not all CustomFields. Today,
// only StandardCustomFields can ever actually generate a comment action
// so we never reach this method with other field types.
return $clone->getFieldValue();
}
protected function getValueExistsInSubmit(AphrontRequest $request, $key) {
return true;
}
protected function getValueFromSubmit(AphrontRequest $request, $key) {
$field = $this->getCustomField();
$clone = clone $field;
$clone->readValueFromRequest($request);
return $clone->getNewValueForApplicationTransactions();
}
protected function newConduitEditTypes() {
$field = $this->getCustomField();
if (!$field->shouldAppearInConduitTransactions()) {
return array();
}
return parent::newConduitEditTypes();
}
protected function newHTTPParameterType() {
$type = $this->getCustomFieldHTTPParameterType();
if ($type) {
return clone $type;
}
return null;
}
protected function newCommentAction() {
$action = $this->getCustomFieldCommentAction();
if ($action) {
return clone $action;
}
return null;
}
protected function newConduitParameterType() {
$type = $this->getCustomFieldConduitParameterType();
if ($type) {
return clone $type;
}
return null;
}
protected function newBulkParameterType() {
$type = $this->getCustomFieldBulkParameterType();
if ($type) {
return clone $type;
}
return null;
}
public function getAllReadValueFromRequestKeys() {
$keys = array();
// NOTE: This piece of complexity is so we can expose a reasonable key in
// the UI ("custom.x") instead of a crufty internal key ("std:app:x").
// Perhaps we can simplify this some day.
// In the parent, this is just getKey(), but that returns a cumbersome
// key in EditFields. Use the simpler edit type key instead.
$keys[] = $this->getEditTypeKey();
foreach ($this->getAliases() as $alias) {
$keys[] = $alias;
}
return $keys;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/exception/PhabricatorCustomFieldDataNotAvailableException.php | src/infrastructure/customfield/exception/PhabricatorCustomFieldDataNotAvailableException.php | <?php
final class PhabricatorCustomFieldDataNotAvailableException extends Exception {
public function __construct(PhabricatorCustomField $field) {
parent::__construct(
pht(
"Custom field '%s' (with key '%s', of class '%s') is attempting ".
"to access data which is not available in this context.",
$field->getFieldName(),
$field->getFieldKey(),
get_class($field)));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/exception/PhabricatorCustomFieldNotProxyException.php | src/infrastructure/customfield/exception/PhabricatorCustomFieldNotProxyException.php | <?php
final class PhabricatorCustomFieldNotProxyException extends Exception {
public function __construct(PhabricatorCustomField $field) {
parent::__construct(
pht(
"Custom field '%s' (with key '%s', of class '%s') can not have a ".
"proxy set with %s, because it returned %s from %s.",
$field->getFieldName(),
$field->getFieldKey(),
get_class($field),
'setProxy()',
'false',
'canSetProxy()'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/exception/PhabricatorCustomFieldNotAttachedException.php | src/infrastructure/customfield/exception/PhabricatorCustomFieldNotAttachedException.php | <?php
final class PhabricatorCustomFieldNotAttachedException
extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/exception/PhabricatorCustomFieldImplementationIncompleteException.php | src/infrastructure/customfield/exception/PhabricatorCustomFieldImplementationIncompleteException.php | <?php
final class PhabricatorCustomFieldImplementationIncompleteException
extends Exception {
public function __construct(
PhabricatorCustomField $field,
$field_key_is_incomplete = false) {
if ($field_key_is_incomplete) {
$key = pht('<incomplete key>');
$name = pht('<incomplete name>');
} else {
$key = $field->getFieldKey();
$name = $field->getFieldName();
}
parent::__construct(
pht(
"Custom field '%s' (with key '%s', of class '%s') is incompletely ".
"implemented: it claims to support a feature, but does not ".
"implement all of the required methods for that feature.",
$name,
$key,
get_class($field)));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/field/PhabricatorCustomFieldList.php | src/infrastructure/customfield/field/PhabricatorCustomFieldList.php | <?php
/**
* Convenience class to perform operations on an entire field list, like reading
* all values from storage.
*
* $field_list = new PhabricatorCustomFieldList($fields);
*
*/
final class PhabricatorCustomFieldList extends Phobject {
private $fields;
private $viewer;
public function __construct(array $fields) {
assert_instances_of($fields, 'PhabricatorCustomField');
$this->fields = $fields;
}
public function getFields() {
return $this->fields;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
foreach ($this->getFields() as $field) {
$field->setViewer($viewer);
}
return $this;
}
public function readFieldsFromObject(
PhabricatorCustomFieldInterface $object) {
$fields = $this->getFields();
foreach ($fields as $field) {
$field
->setObject($object)
->readValueFromObject($object);
}
return $this;
}
/**
* Read stored values for all fields which support storage.
*
* @param PhabricatorCustomFieldInterface Object to read field values for.
* @return void
*/
public function readFieldsFromStorage(
PhabricatorCustomFieldInterface $object) {
$this->readFieldsFromObject($object);
$fields = $this->getFields();
id(new PhabricatorCustomFieldStorageQuery())
->addFields($fields)
->execute();
return $this;
}
public function appendFieldsToForm(AphrontFormView $form) {
$enabled = array();
foreach ($this->fields as $field) {
if ($field->shouldEnableForRole(PhabricatorCustomField::ROLE_EDIT)) {
$enabled[] = $field;
}
}
$phids = array();
foreach ($enabled as $field_key => $field) {
$phids[$field_key] = $field->getRequiredHandlePHIDsForEdit();
}
$all_phids = array_mergev($phids);
if ($all_phids) {
$handles = id(new PhabricatorHandleQuery())
->setViewer($this->viewer)
->withPHIDs($all_phids)
->execute();
} else {
$handles = array();
}
foreach ($enabled as $field_key => $field) {
$field_handles = array_select_keys($handles, $phids[$field_key]);
$instructions = $field->getInstructionsForEdit();
if ($instructions !== null && strlen($instructions)) {
$form->appendRemarkupInstructions($instructions);
}
$form->appendChild($field->renderEditControl($field_handles));
}
}
public function appendFieldsToPropertyList(
PhabricatorCustomFieldInterface $object,
PhabricatorUser $viewer,
PHUIPropertyListView $view) {
$this->readFieldsFromStorage($object);
$fields = $this->fields;
foreach ($fields as $field) {
$field->setViewer($viewer);
}
// Move all the blocks to the end, regardless of their configuration order,
// because it always looks silly to render a block in the middle of a list
// of properties.
$head = array();
$tail = array();
foreach ($fields as $key => $field) {
$style = $field->getStyleForPropertyView();
switch ($style) {
case 'property':
case 'header':
$head[$key] = $field;
break;
case 'block':
$tail[$key] = $field;
break;
default:
throw new Exception(
pht(
"Unknown field property view style '%s'; valid styles are ".
"'%s' and '%s'.",
$style,
'block',
'property'));
}
}
$fields = $head + $tail;
$add_header = null;
$phids = array();
foreach ($fields as $key => $field) {
$phids[$key] = $field->getRequiredHandlePHIDsForPropertyView();
}
$all_phids = array_mergev($phids);
if ($all_phids) {
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs($all_phids)
->execute();
} else {
$handles = array();
}
foreach ($fields as $key => $field) {
$field_handles = array_select_keys($handles, $phids[$key]);
$label = $field->renderPropertyViewLabel();
$value = $field->renderPropertyViewValue($field_handles);
if ($value !== null) {
switch ($field->getStyleForPropertyView()) {
case 'header':
// We want to hide headers if the fields they're associated with
// don't actually produce any visible properties. For example, in a
// list like this:
//
// Header A
// Prop A: Value A
// Header B
// Prop B: Value B
//
// ...if the "Prop A" field returns `null` when rendering its
// property value and we rendered naively, we'd get this:
//
// Header A
// Header B
// Prop B: Value B
//
// This is silly. Instead, we hide "Header A".
$add_header = $value;
break;
case 'property':
if ($add_header !== null) {
// Add the most recently seen header.
$view->addSectionHeader($add_header);
$add_header = null;
}
$view->addProperty($label, $value);
break;
case 'block':
$icon = $field->getIconForPropertyView();
$view->invokeWillRenderEvent();
if ($label !== null) {
$view->addSectionHeader($label, $icon);
}
$view->addTextContent($value);
break;
}
}
}
}
public function buildFieldTransactionsFromRequest(
PhabricatorApplicationTransaction $template,
AphrontRequest $request) {
$xactions = array();
$role = PhabricatorCustomField::ROLE_APPLICATIONTRANSACTIONS;
foreach ($this->fields as $field) {
if (!$field->shouldEnableForRole($role)) {
continue;
}
$transaction_type = $field->getApplicationTransactionType();
$xaction = id(clone $template)
->setTransactionType($transaction_type);
if ($transaction_type == PhabricatorTransactions::TYPE_CUSTOMFIELD) {
// For TYPE_CUSTOMFIELD transactions only, we provide the old value
// as an input.
$old_value = $field->getOldValueForApplicationTransactions();
$xaction->setOldValue($old_value);
}
$field->readValueFromRequest($request);
$xaction
->setNewValue($field->getNewValueForApplicationTransactions());
if ($transaction_type == PhabricatorTransactions::TYPE_CUSTOMFIELD) {
// For TYPE_CUSTOMFIELD transactions, add the field key in metadata.
$xaction->setMetadataValue('customfield:key', $field->getFieldKey());
}
$metadata = $field->getApplicationTransactionMetadata();
foreach ($metadata as $key => $value) {
$xaction->setMetadataValue($key, $value);
}
$xactions[] = $xaction;
}
return $xactions;
}
/**
* Publish field indexes into index tables, so ApplicationSearch can search
* them.
*
* @return void
*/
public function rebuildIndexes(PhabricatorCustomFieldInterface $object) {
$indexes = array();
$index_keys = array();
$phid = $object->getPHID();
$role = PhabricatorCustomField::ROLE_APPLICATIONSEARCH;
foreach ($this->fields as $field) {
if (!$field->shouldEnableForRole($role)) {
continue;
}
$index_keys[$field->getFieldIndex()] = true;
foreach ($field->buildFieldIndexes() as $index) {
$index->setObjectPHID($phid);
$indexes[$index->getTableName()][] = $index;
}
}
if (!$indexes) {
return;
}
$any_index = head(head($indexes));
$conn_w = $any_index->establishConnection('w');
foreach ($indexes as $table => $index_list) {
$sql = array();
foreach ($index_list as $index) {
$sql[] = $index->formatForInsert($conn_w);
}
$indexes[$table] = $sql;
}
$any_index->openTransaction();
foreach ($indexes as $table => $sql_list) {
queryfx(
$conn_w,
'DELETE FROM %T WHERE objectPHID = %s AND indexKey IN (%Ls)',
$table,
$phid,
array_keys($index_keys));
if (!$sql_list) {
continue;
}
foreach (PhabricatorLiskDAO::chunkSQL($sql_list) as $chunk) {
queryfx(
$conn_w,
'INSERT INTO %T (objectPHID, indexKey, indexValue) VALUES %LQ',
$table,
$chunk);
}
}
$any_index->saveTransaction();
}
public function updateAbstractDocument(
PhabricatorSearchAbstractDocument $document) {
$role = PhabricatorCustomField::ROLE_GLOBALSEARCH;
foreach ($this->getFields() as $field) {
if (!$field->shouldEnableForRole($role)) {
continue;
}
$field->updateAbstractDocument($document);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/field/PhabricatorCustomFieldAttachment.php | src/infrastructure/customfield/field/PhabricatorCustomFieldAttachment.php | <?php
/**
* Convenience class which simplifies the implementation of
* @{interface:PhabricatorCustomFieldInterface} by obscuring the details of how
* custom fields are stored.
*
* Generally, you should not use this class directly. It is used by
* @{class:PhabricatorCustomField} to manage field storage on objects.
*/
final class PhabricatorCustomFieldAttachment extends Phobject {
private $lists = array();
public function addCustomFieldList($role, PhabricatorCustomFieldList $list) {
$this->lists[$role] = $list;
return $this;
}
public function getCustomFieldList($role) {
if (empty($this->lists[$role])) {
throw new PhabricatorCustomFieldNotAttachedException(
pht(
"Role list '%s' is not available!",
$role));
}
return $this->lists[$role];
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/field/PhabricatorCustomField.php | src/infrastructure/customfield/field/PhabricatorCustomField.php | <?php
/**
* @task apps Building Applications with Custom Fields
* @task core Core Properties and Field Identity
* @task proxy Field Proxies
* @task context Contextual Data
* @task render Rendering Utilities
* @task storage Field Storage
* @task edit Integration with Edit Views
* @task view Integration with Property Views
* @task list Integration with List views
* @task appsearch Integration with ApplicationSearch
* @task appxaction Integration with ApplicationTransactions
* @task xactionmail Integration with Transaction Mail
* @task globalsearch Integration with Global Search
* @task herald Integration with Herald
*/
abstract class PhabricatorCustomField extends Phobject {
private $viewer;
private $object;
private $proxy;
const ROLE_APPLICATIONTRANSACTIONS = 'ApplicationTransactions';
const ROLE_TRANSACTIONMAIL = 'ApplicationTransactions.mail';
const ROLE_APPLICATIONSEARCH = 'ApplicationSearch';
const ROLE_STORAGE = 'storage';
const ROLE_DEFAULT = 'default';
const ROLE_EDIT = 'edit';
const ROLE_VIEW = 'view';
const ROLE_LIST = 'list';
const ROLE_GLOBALSEARCH = 'GlobalSearch';
const ROLE_CONDUIT = 'conduit';
const ROLE_HERALD = 'herald';
const ROLE_EDITENGINE = 'EditEngine';
const ROLE_HERALDACTION = 'herald.action';
const ROLE_EXPORT = 'export';
/* -( Building Applications with Custom Fields )--------------------------- */
/**
* @task apps
*/
public static function getObjectFields(
PhabricatorCustomFieldInterface $object,
$role) {
try {
$attachment = $object->getCustomFields();
} catch (PhabricatorDataNotAttachedException $ex) {
$attachment = new PhabricatorCustomFieldAttachment();
$object->attachCustomFields($attachment);
}
try {
$field_list = $attachment->getCustomFieldList($role);
} catch (PhabricatorCustomFieldNotAttachedException $ex) {
$base_class = $object->getCustomFieldBaseClass();
$spec = $object->getCustomFieldSpecificationForRole($role);
if (!is_array($spec)) {
throw new Exception(
pht(
"Expected an array from %s for object of class '%s'.",
'getCustomFieldSpecificationForRole()',
get_class($object)));
}
$fields = self::buildFieldList(
$base_class,
$spec,
$object);
$fields = self::adjustCustomFieldsForObjectSubtype(
$object,
$role,
$fields);
foreach ($fields as $key => $field) {
// NOTE: We perform this filtering in "buildFieldList()", but may need
// to filter again after subtype adjustment.
if (!$field->isFieldEnabled()) {
unset($fields[$key]);
continue;
}
if (!$field->shouldEnableForRole($role)) {
unset($fields[$key]);
continue;
}
}
foreach ($fields as $field) {
$field->setObject($object);
}
$field_list = new PhabricatorCustomFieldList($fields);
$attachment->addCustomFieldList($role, $field_list);
}
return $field_list;
}
/**
* @task apps
*/
public static function getObjectField(
PhabricatorCustomFieldInterface $object,
$role,
$field_key) {
$fields = self::getObjectFields($object, $role)->getFields();
return idx($fields, $field_key);
}
/**
* @task apps
*/
public static function buildFieldList(
$base_class,
array $spec,
$object,
array $options = array()) {
$field_objects = id(new PhutilClassMapQuery())
->setAncestorClass($base_class)
->execute();
$fields = array();
foreach ($field_objects as $field_object) {
$field_object = clone $field_object;
foreach ($field_object->createFields($object) as $field) {
$key = $field->getFieldKey();
if (isset($fields[$key])) {
throw new Exception(
pht(
"Both '%s' and '%s' define a custom field with ".
"field key '%s'. Field keys must be unique.",
get_class($fields[$key]),
get_class($field),
$key));
}
$fields[$key] = $field;
}
}
foreach ($fields as $key => $field) {
if (!$field->isFieldEnabled()) {
unset($fields[$key]);
}
}
$fields = array_select_keys($fields, array_keys($spec)) + $fields;
if (empty($options['withDisabled'])) {
foreach ($fields as $key => $field) {
if (isset($spec[$key]['disabled'])) {
$is_disabled = $spec[$key]['disabled'];
} else {
$is_disabled = $field->shouldDisableByDefault();
}
if ($is_disabled) {
if ($field->canDisableField()) {
unset($fields[$key]);
}
}
}
}
return $fields;
}
/* -( Core Properties and Field Identity )--------------------------------- */
/**
* Return a key which uniquely identifies this field, like
* "mycompany:dinosaur:count". Normally you should provide some level of
* namespacing to prevent collisions.
*
* @return string String which uniquely identifies this field.
* @task core
*/
public function getFieldKey() {
if ($this->proxy) {
return $this->proxy->getFieldKey();
}
throw new PhabricatorCustomFieldImplementationIncompleteException(
$this,
$field_key_is_incomplete = true);
}
public function getModernFieldKey() {
if ($this->proxy) {
return $this->proxy->getModernFieldKey();
}
return $this->getFieldKey();
}
/**
* Return a human-readable field name.
*
* @return string Human readable field name.
* @task core
*/
public function getFieldName() {
if ($this->proxy) {
return $this->proxy->getFieldName();
}
return $this->getModernFieldKey();
}
/**
* Return a short, human-readable description of the field's behavior. This
* provides more context to administrators when they are customizing fields.
*
* @return string|null Optional human-readable description.
* @task core
*/
public function getFieldDescription() {
if ($this->proxy) {
return $this->proxy->getFieldDescription();
}
return null;
}
/**
* Most field implementations are unique, in that one class corresponds to
* one field. However, some field implementations are general and a single
* implementation may drive several fields.
*
* For general implementations, the general field implementation can return
* multiple field instances here.
*
* @param object The object to create fields for.
* @return list<PhabricatorCustomField> List of fields.
* @task core
*/
public function createFields($object) {
return array($this);
}
/**
* You can return `false` here if the field should not be enabled for any
* role. For example, it might depend on something (like an application or
* library) which isn't installed, or might have some global configuration
* which allows it to be disabled.
*
* @return bool False to completely disable this field for all roles.
* @task core
*/
public function isFieldEnabled() {
if ($this->proxy) {
return $this->proxy->isFieldEnabled();
}
return true;
}
/**
* Low level selector for field availability. Fields can appear in different
* roles (like an edit view, a list view, etc.), but not every field needs
* to appear everywhere. Fields that are disabled in a role won't appear in
* that context within applications.
*
* Normally, you do not need to override this method. Instead, override the
* methods specific to roles you want to enable. For example, implement
* @{method:shouldUseStorage()} to activate the `'storage'` role.
*
* @return bool True to enable the field for the given role.
* @task core
*/
public function shouldEnableForRole($role) {
// NOTE: All of these calls proxy individually, so we don't need to
// proxy this call as a whole.
switch ($role) {
case self::ROLE_APPLICATIONTRANSACTIONS:
return $this->shouldAppearInApplicationTransactions();
case self::ROLE_APPLICATIONSEARCH:
return $this->shouldAppearInApplicationSearch();
case self::ROLE_STORAGE:
return $this->shouldUseStorage();
case self::ROLE_EDIT:
return $this->shouldAppearInEditView();
case self::ROLE_VIEW:
return $this->shouldAppearInPropertyView();
case self::ROLE_LIST:
return $this->shouldAppearInListView();
case self::ROLE_GLOBALSEARCH:
return $this->shouldAppearInGlobalSearch();
case self::ROLE_CONDUIT:
return $this->shouldAppearInConduitDictionary();
case self::ROLE_TRANSACTIONMAIL:
return $this->shouldAppearInTransactionMail();
case self::ROLE_HERALD:
return $this->shouldAppearInHerald();
case self::ROLE_HERALDACTION:
return $this->shouldAppearInHeraldActions();
case self::ROLE_EDITENGINE:
return $this->shouldAppearInEditView() ||
$this->shouldAppearInEditEngine();
case self::ROLE_EXPORT:
return $this->shouldAppearInDataExport();
case self::ROLE_DEFAULT:
return true;
default:
throw new Exception(pht("Unknown field role '%s'!", $role));
}
}
/**
* Allow administrators to disable this field. Most fields should allow this,
* but some are fundamental to the behavior of the application and can be
* locked down to avoid chaos, disorder, and the decline of civilization.
*
* @return bool False to prevent this field from being disabled through
* configuration.
* @task core
*/
public function canDisableField() {
return true;
}
public function shouldDisableByDefault() {
return false;
}
/**
* Return an index string which uniquely identifies this field.
*
* @return string Index string which uniquely identifies this field.
* @task core
*/
final public function getFieldIndex() {
return PhabricatorHash::digestForIndex($this->getFieldKey());
}
/* -( Field Proxies )------------------------------------------------------ */
/**
* Proxies allow a field to use some other field's implementation for most
* of their behavior while still subclassing an application field. When a
* proxy is set for a field with @{method:setProxy}, all of its methods will
* call through to the proxy by default.
*
* This is most commonly used to implement configuration-driven custom fields
* using @{class:PhabricatorStandardCustomField}.
*
* This method must be overridden to return `true` before a field can accept
* proxies.
*
* @return bool True if you can @{method:setProxy} this field.
* @task proxy
*/
public function canSetProxy() {
if ($this instanceof PhabricatorStandardCustomFieldInterface) {
return true;
}
return false;
}
/**
* Set the proxy implementation for this field. See @{method:canSetProxy} for
* discussion of field proxies.
*
* @param PhabricatorCustomField Field implementation.
* @return this
*/
final public function setProxy(PhabricatorCustomField $proxy) {
if (!$this->canSetProxy()) {
throw new PhabricatorCustomFieldNotProxyException($this);
}
$this->proxy = $proxy;
return $this;
}
/**
* Get the field's proxy implementation, if any. For discussion, see
* @{method:canSetProxy}.
*
* @return PhabricatorCustomField|null Proxy field, if one is set.
*/
final public function getProxy() {
return $this->proxy;
}
/* -( Contextual Data )---------------------------------------------------- */
/**
* Sets the object this field belongs to.
*
* @param PhabricatorCustomFieldInterface The object this field belongs to.
* @return this
* @task context
*/
final public function setObject(PhabricatorCustomFieldInterface $object) {
if ($this->proxy) {
$this->proxy->setObject($object);
return $this;
}
$this->object = $object;
$this->didSetObject($object);
return $this;
}
/**
* Read object data into local field storage, if applicable.
*
* @param PhabricatorCustomFieldInterface The object this field belongs to.
* @return this
* @task context
*/
public function readValueFromObject(PhabricatorCustomFieldInterface $object) {
if ($this->proxy) {
$this->proxy->readValueFromObject($object);
}
return $this;
}
/**
* Get the object this field belongs to.
*
* @return PhabricatorCustomFieldInterface The object this field belongs to.
* @task context
*/
final public function getObject() {
if ($this->proxy) {
return $this->proxy->getObject();
}
return $this->object;
}
/**
* This is a hook, primarily for subclasses to load object data.
*
* @return PhabricatorCustomFieldInterface The object this field belongs to.
* @return void
*/
protected function didSetObject(PhabricatorCustomFieldInterface $object) {
return;
}
/**
* @task context
*/
final public function setViewer(PhabricatorUser $viewer) {
if ($this->proxy) {
$this->proxy->setViewer($viewer);
return $this;
}
$this->viewer = $viewer;
return $this;
}
/**
* @task context
*/
final public function getViewer() {
if ($this->proxy) {
return $this->proxy->getViewer();
}
return $this->viewer;
}
/**
* @task context
*/
final protected function requireViewer() {
if ($this->proxy) {
return $this->proxy->requireViewer();
}
if (!$this->viewer) {
throw new PhabricatorCustomFieldDataNotAvailableException($this);
}
return $this->viewer;
}
/* -( Rendering Utilities )------------------------------------------------ */
/**
* @task render
*/
protected function renderHandleList(array $handles) {
if (!$handles) {
return null;
}
$out = array();
foreach ($handles as $handle) {
$out[] = $handle->renderHovercardLink();
}
return phutil_implode_html(phutil_tag('br'), $out);
}
/* -( Storage )------------------------------------------------------------ */
/**
* Return true to use field storage.
*
* Fields which can be edited by the user will most commonly use storage,
* while some other types of fields (for instance, those which just display
* information in some stylized way) may not. Many builtin fields do not use
* storage because their data is available on the object itself.
*
* If you implement this, you must also implement @{method:getValueForStorage}
* and @{method:setValueFromStorage}.
*
* @return bool True to use storage.
* @task storage
*/
public function shouldUseStorage() {
if ($this->proxy) {
return $this->proxy->shouldUseStorage();
}
return false;
}
/**
* Return a new, empty storage object. This should be a subclass of
* @{class:PhabricatorCustomFieldStorage} which is bound to the application's
* database.
*
* @return PhabricatorCustomFieldStorage New empty storage object.
* @task storage
*/
public function newStorageObject() {
// NOTE: This intentionally isn't proxied, to avoid call cycles.
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
/**
* Return a serialized representation of the field value, appropriate for
* storing in auxiliary field storage. You must implement this method if
* you implement @{method:shouldUseStorage}.
*
* If the field value is a scalar, it can be returned unmodiifed. If not,
* it should be serialized (for example, using JSON).
*
* @return string Serialized field value.
* @task storage
*/
public function getValueForStorage() {
if ($this->proxy) {
return $this->proxy->getValueForStorage();
}
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
/**
* Set the field's value given a serialized storage value. This is called
* when the field is loaded; if no data is available, the value will be
* null. You must implement this method if you implement
* @{method:shouldUseStorage}.
*
* Usually, the value can be loaded directly. If it isn't a scalar, you'll
* need to undo whatever serialization you applied in
* @{method:getValueForStorage}.
*
* @param string|null Serialized field representation (from
* @{method:getValueForStorage}) or null if no value has
* ever been stored.
* @return this
* @task storage
*/
public function setValueFromStorage($value) {
if ($this->proxy) {
return $this->proxy->setValueFromStorage($value);
}
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
public function didSetValueFromStorage() {
if ($this->proxy) {
return $this->proxy->didSetValueFromStorage();
}
return $this;
}
/* -( ApplicationSearch )-------------------------------------------------- */
/**
* Appearing in ApplicationSearch allows a field to be indexed and searched
* for.
*
* @return bool True to appear in ApplicationSearch.
* @task appsearch
*/
public function shouldAppearInApplicationSearch() {
if ($this->proxy) {
return $this->proxy->shouldAppearInApplicationSearch();
}
return false;
}
/**
* Return one or more indexes which this field can meaningfully query against
* to implement ApplicationSearch.
*
* Normally, you should build these using @{method:newStringIndex} and
* @{method:newNumericIndex}. For example, if a field holds a numeric value
* it might return a single numeric index:
*
* return array($this->newNumericIndex($this->getValue()));
*
* If a field holds a more complex value (like a list of users), it might
* return several string indexes:
*
* $indexes = array();
* foreach ($this->getValue() as $phid) {
* $indexes[] = $this->newStringIndex($phid);
* }
* return $indexes;
*
* @return list<PhabricatorCustomFieldIndexStorage> List of indexes.
* @task appsearch
*/
public function buildFieldIndexes() {
if ($this->proxy) {
return $this->proxy->buildFieldIndexes();
}
return array();
}
/**
* Return an index against which this field can be meaningfully ordered
* against to implement ApplicationSearch.
*
* This should be a single index, normally built using
* @{method:newStringIndex} and @{method:newNumericIndex}.
*
* The value of the index is not used.
*
* Return null from this method if the field can not be ordered.
*
* @return PhabricatorCustomFieldIndexStorage A single index to order by.
* @task appsearch
*/
public function buildOrderIndex() {
if ($this->proxy) {
return $this->proxy->buildOrderIndex();
}
return null;
}
/**
* Build a new empty storage object for storing string indexes. Normally,
* this should be a concrete subclass of
* @{class:PhabricatorCustomFieldStringIndexStorage}.
*
* @return PhabricatorCustomFieldStringIndexStorage Storage object.
* @task appsearch
*/
protected function newStringIndexStorage() {
// NOTE: This intentionally isn't proxied, to avoid call cycles.
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
/**
* Build a new empty storage object for storing string indexes. Normally,
* this should be a concrete subclass of
* @{class:PhabricatorCustomFieldStringIndexStorage}.
*
* @return PhabricatorCustomFieldStringIndexStorage Storage object.
* @task appsearch
*/
protected function newNumericIndexStorage() {
// NOTE: This intentionally isn't proxied, to avoid call cycles.
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
/**
* Build and populate storage for a string index.
*
* @param string String to index.
* @return PhabricatorCustomFieldStringIndexStorage Populated storage.
* @task appsearch
*/
protected function newStringIndex($value) {
if ($this->proxy) {
return $this->proxy->newStringIndex();
}
$key = $this->getFieldIndex();
return $this->newStringIndexStorage()
->setIndexKey($key)
->setIndexValue($value);
}
/**
* Build and populate storage for a numeric index.
*
* @param string Numeric value to index.
* @return PhabricatorCustomFieldNumericIndexStorage Populated storage.
* @task appsearch
*/
protected function newNumericIndex($value) {
if ($this->proxy) {
return $this->proxy->newNumericIndex();
}
$key = $this->getFieldIndex();
return $this->newNumericIndexStorage()
->setIndexKey($key)
->setIndexValue($value);
}
/**
* Read a query value from a request, for storage in a saved query. Normally,
* this method should, e.g., read a string out of the request.
*
* @param PhabricatorApplicationSearchEngine Engine building the query.
* @param AphrontRequest Request to read from.
* @return wild
* @task appsearch
*/
public function readApplicationSearchValueFromRequest(
PhabricatorApplicationSearchEngine $engine,
AphrontRequest $request) {
if ($this->proxy) {
return $this->proxy->readApplicationSearchValueFromRequest(
$engine,
$request);
}
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
/**
* Constrain a query, given a field value. Generally, this method should
* use `with...()` methods to apply filters or other constraints to the
* query.
*
* @param PhabricatorApplicationSearchEngine Engine executing the query.
* @param PhabricatorCursorPagedPolicyAwareQuery Query to constrain.
* @param wild Constraint provided by the user.
* @return void
* @task appsearch
*/
public function applyApplicationSearchConstraintToQuery(
PhabricatorApplicationSearchEngine $engine,
PhabricatorCursorPagedPolicyAwareQuery $query,
$value) {
if ($this->proxy) {
return $this->proxy->applyApplicationSearchConstraintToQuery(
$engine,
$query,
$value);
}
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
/**
* Append search controls to the interface.
*
* @param PhabricatorApplicationSearchEngine Engine constructing the form.
* @param AphrontFormView The form to update.
* @param wild Value from the saved query.
* @return void
* @task appsearch
*/
public function appendToApplicationSearchForm(
PhabricatorApplicationSearchEngine $engine,
AphrontFormView $form,
$value) {
if ($this->proxy) {
return $this->proxy->appendToApplicationSearchForm(
$engine,
$form,
$value);
}
throw new PhabricatorCustomFieldImplementationIncompleteException($this);
}
/* -( ApplicationTransactions )-------------------------------------------- */
/**
* Appearing in ApplicationTrasactions allows a field to be edited using
* standard workflows.
*
* @return bool True to appear in ApplicationTransactions.
* @task appxaction
*/
public function shouldAppearInApplicationTransactions() {
if ($this->proxy) {
return $this->proxy->shouldAppearInApplicationTransactions();
}
return false;
}
/**
* @task appxaction
*/
public function getApplicationTransactionType() {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionType();
}
return PhabricatorTransactions::TYPE_CUSTOMFIELD;
}
/**
* @task appxaction
*/
public function getApplicationTransactionMetadata() {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionMetadata();
}
return array();
}
/**
* @task appxaction
*/
public function getOldValueForApplicationTransactions() {
if ($this->proxy) {
return $this->proxy->getOldValueForApplicationTransactions();
}
return $this->getValueForStorage();
}
/**
* @task appxaction
*/
public function getNewValueForApplicationTransactions() {
if ($this->proxy) {
return $this->proxy->getNewValueForApplicationTransactions();
}
return $this->getValueForStorage();
}
/**
* @task appxaction
*/
public function setValueFromApplicationTransactions($value) {
if ($this->proxy) {
return $this->proxy->setValueFromApplicationTransactions($value);
}
return $this->setValueFromStorage($value);
}
/**
* @task appxaction
*/
public function getNewValueFromApplicationTransactions(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->getNewValueFromApplicationTransactions($xaction);
}
return $xaction->getNewValue();
}
/**
* @task appxaction
*/
public function getApplicationTransactionHasEffect(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionHasEffect($xaction);
}
return ($xaction->getOldValue() !== $xaction->getNewValue());
}
/**
* @task appxaction
*/
public function applyApplicationTransactionInternalEffects(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->applyApplicationTransactionInternalEffects($xaction);
}
return;
}
/**
* @task appxaction
*/
public function getApplicationTransactionRemarkupBlocks(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionRemarkupBlocks($xaction);
}
return array();
}
/**
* @task appxaction
*/
public function applyApplicationTransactionExternalEffects(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->applyApplicationTransactionExternalEffects($xaction);
}
if (!$this->shouldEnableForRole(self::ROLE_STORAGE)) {
return;
}
$this->setValueFromApplicationTransactions($xaction->getNewValue());
$value = $this->getValueForStorage();
$table = $this->newStorageObject();
$conn_w = $table->establishConnection('w');
if ($value === null) {
queryfx(
$conn_w,
'DELETE FROM %T WHERE objectPHID = %s AND fieldIndex = %s',
$table->getTableName(),
$this->getObject()->getPHID(),
$this->getFieldIndex());
} else {
queryfx(
$conn_w,
'INSERT INTO %T (objectPHID, fieldIndex, fieldValue)
VALUES (%s, %s, %s)
ON DUPLICATE KEY UPDATE fieldValue = VALUES(fieldValue)',
$table->getTableName(),
$this->getObject()->getPHID(),
$this->getFieldIndex(),
$value);
}
return;
}
/**
* Validate transactions for an object. This allows you to raise an error
* when a transaction would set a field to an invalid value, or when a field
* is required but no transactions provide value.
*
* @param PhabricatorLiskDAO Editor applying the transactions.
* @param string Transaction type. This type is always
* `PhabricatorTransactions::TYPE_CUSTOMFIELD`, it is provided for
* convenience when constructing exceptions.
* @param list<PhabricatorApplicationTransaction> Transactions being applied,
* which may be empty if this field is not being edited.
* @return list<PhabricatorApplicationTransactionValidationError> Validation
* errors.
*
* @task appxaction
*/
public function validateApplicationTransactions(
PhabricatorApplicationTransactionEditor $editor,
$type,
array $xactions) {
if ($this->proxy) {
return $this->proxy->validateApplicationTransactions(
$editor,
$type,
$xactions);
}
return array();
}
public function getApplicationTransactionTitle(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionTitle(
$xaction);
}
$author_phid = $xaction->getAuthorPHID();
return pht(
'%s updated this object.',
$xaction->renderHandleLink($author_phid));
}
public function getApplicationTransactionTitleForFeed(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionTitleForFeed(
$xaction);
}
$author_phid = $xaction->getAuthorPHID();
$object_phid = $xaction->getObjectPHID();
return pht(
'%s updated %s.',
$xaction->renderHandleLink($author_phid),
$xaction->renderHandleLink($object_phid));
}
public function getApplicationTransactionHasChangeDetails(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionHasChangeDetails(
$xaction);
}
return false;
}
public function getApplicationTransactionChangeDetails(
PhabricatorApplicationTransaction $xaction,
PhabricatorUser $viewer) {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionChangeDetails(
$xaction,
$viewer);
}
return null;
}
public function getApplicationTransactionRequiredHandlePHIDs(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->getApplicationTransactionRequiredHandlePHIDs(
$xaction);
}
return array();
}
public function shouldHideInApplicationTransactions(
PhabricatorApplicationTransaction $xaction) {
if ($this->proxy) {
return $this->proxy->shouldHideInApplicationTransactions($xaction);
}
return false;
}
/* -( Transaction Mail )--------------------------------------------------- */
/**
* @task xactionmail
*/
public function shouldAppearInTransactionMail() {
if ($this->proxy) {
return $this->proxy->shouldAppearInTransactionMail();
}
return false;
}
/**
* @task xactionmail
*/
public function updateTransactionMailBody(
PhabricatorMetaMTAMailBody $body,
PhabricatorApplicationTransactionEditor $editor,
array $xactions) {
if ($this->proxy) {
return $this->proxy->updateTransactionMailBody($body, $editor, $xactions);
}
return;
}
/* -( Edit View )---------------------------------------------------------- */
public function getEditEngineFields(PhabricatorEditEngine $engine) {
$field = $this->newStandardEditField();
return array(
$field,
);
}
protected function newEditField() {
$field = id(new PhabricatorCustomFieldEditField())
->setCustomField($this);
$http_type = $this->getHTTPParameterType();
if ($http_type) {
$field->setCustomFieldHTTPParameterType($http_type);
}
$conduit_type = $this->getConduitEditParameterType();
if ($conduit_type) {
$field->setCustomFieldConduitParameterType($conduit_type);
}
$bulk_type = $this->getBulkParameterType();
if ($bulk_type) {
$field->setCustomFieldBulkParameterType($bulk_type);
}
$comment_action = $this->getCommentAction();
if ($comment_action) {
$field
->setCustomFieldCommentAction($comment_action)
->setCommentActionLabel(
pht(
'Change %s',
$this->getFieldName()));
}
return $field;
}
protected function newStandardEditField() {
if ($this->proxy) {
return $this->proxy->newStandardEditField();
}
if ($this->shouldAppearInEditView()) {
$form_field = true;
} else {
$form_field = false;
}
$bulk_label = $this->getBulkEditLabel();
return $this->newEditField()
->setKey($this->getFieldKey())
->setEditTypeKey($this->getModernFieldKey())
->setLabel($this->getFieldName())
->setBulkEditLabel($bulk_label)
->setDescription($this->getFieldDescription())
->setTransactionType($this->getApplicationTransactionType())
->setIsFormField($form_field)
->setValue($this->getNewValueForApplicationTransactions());
}
protected function getBulkEditLabel() {
if ($this->proxy) {
return $this->proxy->getBulkEditLabel();
}
return pht('Set "%s" to', $this->getFieldName());
}
public function getBulkParameterType() {
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/herald/PhabricatorCustomFieldHeraldFieldGroup.php | src/infrastructure/customfield/herald/PhabricatorCustomFieldHeraldFieldGroup.php | <?php
final class PhabricatorCustomFieldHeraldFieldGroup extends HeraldFieldGroup {
const FIELDGROUPKEY = 'customfield';
public function getGroupLabel() {
return pht('Custom Fields');
}
protected function getGroupOrder() {
return 2000;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/herald/PhabricatorCustomFieldHeraldField.php | src/infrastructure/customfield/herald/PhabricatorCustomFieldHeraldField.php | <?php
final class PhabricatorCustomFieldHeraldField extends HeraldField {
const FIELDCONST = 'herald.custom';
private $customField;
public function setCustomField(PhabricatorCustomField $custom_field) {
$this->customField = $custom_field;
return $this;
}
public function getCustomField() {
return $this->customField;
}
public function getFieldGroupKey() {
return PhabricatorCustomFieldHeraldFieldGroup::FIELDGROUPKEY;
}
public function supportsObject($object) {
return ($object instanceof PhabricatorCustomFieldInterface);
}
public function getFieldsForObject($object) {
$field_list = PhabricatorCustomField::getObjectFields(
$object,
PhabricatorCustomField::ROLE_HERALD);
$field_list->setViewer(PhabricatorUser::getOmnipotentUser());
$field_list->readFieldsFromStorage($object);
$prefix = 'herald.custom/';
$limit = self::getFieldConstantByteLimit();
$map = array();
foreach ($field_list->getFields() as $field) {
$key = $field->getFieldKey();
// NOTE: This use of digestToLength() isn't preferred (you should
// normally digest a key unconditionally, so that it isn't possible to
// arrange a collision) but preserves backward compatibility.
$full_key = $prefix.$key;
if (strlen($full_key) > $limit) {
$full_key = PhabricatorHash::digestToLength($full_key, $limit);
}
$map[$full_key] = id(new PhabricatorCustomFieldHeraldField())
->setCustomField($field);
}
return $map;
}
public function getHeraldFieldName() {
return $this->getCustomField()->getHeraldFieldName();
}
public function getHeraldFieldValue($object) {
return $this->getCustomField()->getHeraldFieldValue();
}
public function getHeraldFieldConditions() {
return $this->getCustomField()->getHeraldFieldConditions();
}
protected function getHeraldFieldStandardType() {
return $this->getCustomField()->getHeraldFieldStandardType();
}
public function getHeraldFieldValueType($condition) {
if ($this->getHeraldFieldStandardType()) {
return parent::getHeraldFieldValueType($condition);
}
return $this->getCustomField()->getHeraldFieldValueType($condition);
}
protected function getDatasource() {
return $this->getCustomField()->getHeraldDatasource();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/herald/PhabricatorCustomFieldHeraldActionGroup.php | src/infrastructure/customfield/herald/PhabricatorCustomFieldHeraldActionGroup.php | <?php
final class PhabricatorCustomFieldHeraldActionGroup
extends HeraldActionGroup {
const ACTIONGROUPKEY = 'customfield';
public function getGroupLabel() {
return pht('Custom Fields');
}
protected function getGroupOrder() {
return 2000;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/herald/PhabricatorCustomFieldHeraldAction.php | src/infrastructure/customfield/herald/PhabricatorCustomFieldHeraldAction.php | <?php
final class PhabricatorCustomFieldHeraldAction extends HeraldAction {
const ACTIONCONST = 'herald.action.custom';
const DO_SET_FIELD = 'do.set-custom-field';
private $customField;
public function setCustomField(PhabricatorCustomField $custom_field) {
$this->customField = $custom_field;
return $this;
}
public function getCustomField() {
return $this->customField;
}
public function getActionGroupKey() {
return PhabricatorCustomFieldHeraldActionGroup::ACTIONGROUPKEY;
}
public function supportsObject($object) {
return ($object instanceof PhabricatorCustomFieldInterface);
}
public function supportsRuleType($rule_type) {
return true;
}
public function getActionsForObject($object) {
$viewer = PhabricatorUser::getOmnipotentUser();
$role = PhabricatorCustomField::ROLE_HERALDACTION;
$field_list = PhabricatorCustomField::getObjectFields($object, $role)
->setViewer($viewer)
->readFieldsFromStorage($object);
$map = array();
foreach ($field_list->getFields() as $field) {
$key = $field->getFieldKey();
$map[$key] = id(new self())
->setCustomField($field);
}
return $map;
}
public function applyEffect($object, HeraldEffect $effect) {
$field = $this->getCustomField();
$value = $effect->getTarget();
$adapter = $this->getAdapter();
$old_value = $field->getOldValueForApplicationTransactions();
$new_value = id(clone $field)
->setValueFromApplicationTransactions($value)
->getValueForStorage();
$xaction = $adapter->newTransaction()
->setTransactionType(PhabricatorTransactions::TYPE_CUSTOMFIELD)
->setMetadataValue('customfield:key', $field->getFieldKey())
->setOldValue($old_value)
->setNewValue($new_value);
$adapter->queueTransaction($xaction);
$this->logEffect(self::DO_SET_FIELD, $value);
}
public function getHeraldActionName() {
return $this->getCustomField()->getHeraldActionName();
}
public function getHeraldActionStandardType() {
return $this->getCustomField()->getHeraldActionStandardType();
}
protected function getDatasource() {
return $this->getCustomField()->getHeraldActionDatasource();
}
public function renderActionDescription($value) {
return $this->getCustomField()->getHeraldActionDescription($value);
}
protected function getActionEffectMap() {
return array(
self::DO_SET_FIELD => array(
'icon' => 'fa-pencil',
'color' => 'green',
'name' => pht('Set Field Value'),
),
);
}
protected function renderActionEffectDescription($type, $data) {
switch ($type) {
case self::DO_SET_FIELD:
return $this->getCustomField()->getHeraldActionEffectDescription($data);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/config/PhabricatorCustomFieldConfigOptionType.php | src/infrastructure/customfield/config/PhabricatorCustomFieldConfigOptionType.php | <?php
final class PhabricatorCustomFieldConfigOptionType
extends PhabricatorConfigOptionType {
public function readRequest(
PhabricatorConfigOption $option,
AphrontRequest $request) {
$e_value = null;
$errors = array();
$storage_value = $request->getStr('value');
$in_value = phutil_json_decode($storage_value);
// When we submit from JS, we submit a list (since maps are not guaranteed
// to retain order). Convert it into a map for storage (since it's far more
// convenient for us elsewhere).
$storage_value = ipull($in_value, null, 'key');
$display_value = $storage_value;
return array($e_value, $errors, $storage_value, $display_value);
}
public function renderControl(
PhabricatorConfigOption $option,
$display_value,
$e_value) {
$field_base_class = $option->getCustomData();
$field_spec = $display_value;
if (!is_array($field_spec)) {
$field_spec = PhabricatorEnv::getEnvConfig($option->getKey());
}
// TODO: We might need to build a real object here eventually.
$faux_object = null;
$fields = PhabricatorCustomField::buildFieldList(
$field_base_class,
$field_spec,
$faux_object,
array(
'withDisabled' => true,
));
$list_id = celerity_generate_unique_node_id();
$input_id = celerity_generate_unique_node_id();
$list = id(new PHUIObjectItemListView())
->setFlush(true)
->setID($list_id);
foreach ($fields as $key => $field) {
$item = id(new PHUIObjectItemView())
->addSigil('field-spec')
->setMetadata(array('fieldKey' => $key))
->setGrippable(true)
->addAttribute($field->getFieldDescription())
->setHeader($field->getFieldName());
$spec = idx($field_spec, $key, array());
$is_disabled = idx($spec, 'disabled', $field->shouldDisableByDefault());
$disabled_item = clone $item;
$enabled_item = clone $item;
if ($is_disabled) {
$list->addItem($disabled_item);
} else {
$list->addItem($enabled_item);
}
$disabled_item->addIcon('none', pht('Disabled'));
$disabled_item->setDisabled(true);
$disabled_item->addAction(
id(new PHUIListItemView())
->setHref('#')
->addSigil('field-spec-toggle')
->setIcon('fa-plus'));
$enabled_item->setStatusIcon('fa-check green');
if (!$field->canDisableField()) {
$enabled_item->addAction(
id(new PHUIListItemView())
->setIcon('fa-lock grey'));
$enabled_item->addIcon('none', pht('Permanent Field'));
} else {
$enabled_item->addAction(
id(new PHUIListItemView())
->setHref('#')
->addSigil('field-spec-toggle')
->setIcon('fa-times'));
}
$fields[$key] = array(
'disabled' => $is_disabled,
'disabledMarkup' => $disabled_item->render(),
'enabledMarkup' => $enabled_item->render(),
);
}
$input = phutil_tag(
'input',
array(
'id' => $input_id,
'type' => 'hidden',
'name' => 'value',
'value' => '',
));
Javelin::initBehavior(
'config-reorder-fields',
array(
'listID' => $list_id,
'inputID' => $input_id,
'fields' => $fields,
));
return id(new AphrontFormMarkupControl())
->setLabel(pht('Value'))
->setError($e_value)
->setValue(
array(
$list,
$input,
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/customfield/parser/PhabricatorCustomFieldMonogramParser.php | src/infrastructure/customfield/parser/PhabricatorCustomFieldMonogramParser.php | <?php
abstract class PhabricatorCustomFieldMonogramParser
extends Phobject {
abstract protected function getPrefixes();
abstract protected function getSuffixes();
abstract protected function getInfixes();
abstract protected function getMonogramPattern();
public function parseCorpus($corpus) {
$prefixes = $this->getPrefixes();
$suffixes = $this->getSuffixes();
$infixes = $this->getInfixes();
$prefix_regex = $this->buildRegex($prefixes);
$infix_regex = $this->buildRegex($infixes, true);
$suffix_regex = $this->buildRegex($suffixes, true, true);
$monogram_pattern = $this->getMonogramPattern();
$pattern =
'/'.
'(?:^|\b)'.
$prefix_regex.
$infix_regex.
'((?:'.$monogram_pattern.'(?:\b|$)[,\s]*)+)'.
'(?:\band\s+('.$monogram_pattern.'(?:\b|$)))?'.
$suffix_regex.
'(?:$|\b)'.
'/';
$matches = null;
$ok = preg_match_all(
$pattern,
$corpus,
$matches,
PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
if ($ok === false) {
throw new Exception(pht('Regular expression "%s" is invalid!', $pattern));
}
$results = array();
foreach ($matches as $set) {
$monograms = array_filter(preg_split('/[,\s]+/', $set[3][0]));
if (isset($set[4]) && $set[4][0]) {
$monograms[] = $set[4][0];
}
$results[] = array(
'match' => $set[0][0],
'prefix' => $set[1][0],
'infix' => $set[2][0],
'monograms' => $monograms,
'suffix' => idx(idx($set, 5, array()), 0, ''),
'offset' => $set[0][1],
);
}
return $results;
}
private function buildRegex(array $list, $optional = false, $final = false) {
$parts = array();
foreach ($list as $string) {
$parts[] = preg_quote($string, '/');
}
$parts = implode('|', $parts);
$maybe_tail = $final ? '' : '\s+';
$maybe_optional = $optional ? '?' : '';
return '(?i:('.$parts.')'.$maybe_tail.')'.$maybe_optional;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/graph/DifferentialRevisionGraph.php | src/infrastructure/graph/DifferentialRevisionGraph.php | <?php
final class DifferentialRevisionGraph
extends PhabricatorObjectGraph {
protected function getEdgeTypes() {
return array(
DifferentialRevisionDependsOnRevisionEdgeType::EDGECONST,
DifferentialRevisionDependedOnByRevisionEdgeType::EDGECONST,
);
}
protected function getParentEdgeType() {
return DifferentialRevisionDependsOnRevisionEdgeType::EDGECONST;
}
protected function newQuery() {
return new DifferentialRevisionQuery();
}
protected function isClosed($object) {
return $object->isClosed();
}
protected function newTableRow($phid, $object, $trace) {
$viewer = $this->getViewer();
if ($object) {
$status_icon = $object->getStatusIcon();
$status_color = $object->getStatusIconColor();
$status_name = $object->getStatusDisplayName();
$status = array(
id(new PHUIIconView())
->setIcon($status_icon, $status_color),
' ',
$status_name,
);
$author = $viewer->renderHandle($object->getAuthorPHID());
$link = phutil_tag(
'a',
array(
'href' => $object->getURI(),
),
$object->getTitle());
$link = array(
$object->getMonogram(),
' ',
$link,
);
} else {
$status = null;
$author = null;
$link = $viewer->renderHandle($phid);
}
$link = AphrontTableView::renderSingleDisplayLine($link);
return array(
$trace,
$status,
$author,
$link,
);
}
protected function newTable(AphrontTableView $table) {
return $table
->setHeaders(
array(
null,
pht('Status'),
pht('Author'),
pht('Revision'),
))
->setColumnClasses(
array(
'threads',
'graph-status',
null,
'wide pri object-link',
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/graph/ManiphestTaskGraph.php | src/infrastructure/graph/ManiphestTaskGraph.php | <?php
final class ManiphestTaskGraph
extends PhabricatorObjectGraph {
private $seedMaps = array();
private $isStandalone;
protected function getEdgeTypes() {
return array(
ManiphestTaskDependedOnByTaskEdgeType::EDGECONST,
ManiphestTaskDependsOnTaskEdgeType::EDGECONST,
);
}
protected function getParentEdgeType() {
return ManiphestTaskDependsOnTaskEdgeType::EDGECONST;
}
protected function newQuery() {
return new ManiphestTaskQuery();
}
protected function isClosed($object) {
return $object->isClosed();
}
public function setIsStandalone($is_standalone) {
$this->isStandalone = $is_standalone;
return $this;
}
public function getIsStandalone() {
return $this->isStandalone;
}
protected function newTableRow($phid, $object, $trace) {
$viewer = $this->getViewer();
Javelin::initBehavior('phui-hovercards');
if ($object) {
$status = $object->getStatus();
$priority = $object->getPriority();
$status_icon = ManiphestTaskStatus::getStatusIcon($status);
$status_name = ManiphestTaskStatus::getTaskStatusName($status);
$priority_color = ManiphestTaskPriority::getTaskPriorityColor($priority);
if ($object->isClosed()) {
$priority_color = 'grey';
}
$status = array(
id(new PHUIIconView())->setIcon($status_icon, $priority_color),
' ',
$status_name,
);
$owner_phid = $object->getOwnerPHID();
if ($owner_phid) {
$assigned = $viewer->renderHandle($owner_phid);
} else {
$assigned = phutil_tag('em', array(), pht('None'));
}
$link = javelin_tag(
'a',
array(
'href' => $object->getURI(),
'sigil' => 'hovercard',
'meta' => array(
'hovercardSpec' => array(
'objectPHID' => $object->getPHID(),
),
),
),
$object->getTitle());
$link = array(
phutil_tag(
'span',
array(
'class' => 'object-name',
),
$object->getMonogram()),
' ',
$link,
);
$subtype_tag = null;
$subtype = $object->newSubtypeObject();
if ($subtype && $subtype->hasTagView()) {
$subtype_tag = $subtype->newTagView()
->setSlimShady(true);
}
} else {
$status = null;
$assigned = null;
$subtype_tag = null;
$link = $viewer->renderHandle($phid);
}
if ($this->isParentTask($phid)) {
$marker = 'fa-chevron-circle-up bluegrey';
$marker_tip = pht('Direct Parent');
} else if ($this->isChildTask($phid)) {
$marker = 'fa-chevron-circle-down bluegrey';
$marker_tip = pht('Direct Subtask');
} else {
$marker = null;
}
if ($marker) {
$marker = id(new PHUIIconView())
->setIcon($marker)
->addSigil('has-tooltip')
->setMetadata(
array(
'tip' => $marker_tip,
'align' => 'E',
));
}
return array(
$marker,
$trace,
$status,
$subtype_tag,
$assigned,
$link,
);
}
protected function newTable(AphrontTableView $table) {
$subtype_map = id(new ManiphestTask())->newEditEngineSubtypeMap();
$has_subtypes = ($subtype_map->getCount() > 1);
return $table
->setHeaders(
array(
null,
null,
pht('Status'),
pht('Subtype'),
pht('Assigned'),
pht('Task'),
))
->setColumnClasses(
array(
'nudgeright',
'threads',
'graph-status',
null,
null,
'wide pri object-link',
))
->setColumnVisibility(
array(
true,
!$this->getRenderOnlyAdjacentNodes(),
true,
$has_subtypes,
))
->setDeviceVisibility(
array(
true,
// On mobile, we only show the actual graph drawing if we're on the
// standalone page, since it can take over the screen otherwise.
$this->getIsStandalone(),
true,
// On mobile, don't show subtypes since they're relatively less
// important and we're more pressured for space.
false,
));
}
private function isParentTask($task_phid) {
$map = $this->getSeedMap(ManiphestTaskDependedOnByTaskEdgeType::EDGECONST);
return isset($map[$task_phid]);
}
private function isChildTask($task_phid) {
$map = $this->getSeedMap(ManiphestTaskDependsOnTaskEdgeType::EDGECONST);
return isset($map[$task_phid]);
}
private function getSeedMap($type) {
if (!isset($this->seedMaps[$type])) {
$maps = $this->getEdges($type);
$phids = idx($maps, $this->getSeedPHID(), array());
$phids = array_fuse($phids);
$this->seedMaps[$type] = $phids;
}
return $this->seedMaps[$type];
}
protected function newEllipsisRow() {
return array(
null,
null,
null,
null,
null,
pht("\xC2\xB7 \xC2\xB7 \xC2\xB7"),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/graph/PhabricatorObjectGraph.php | src/infrastructure/graph/PhabricatorObjectGraph.php | <?php
abstract class PhabricatorObjectGraph
extends AbstractDirectedGraph {
private $viewer;
private $edges = array();
private $edgeReach = array();
private $seedPHID;
private $objects;
private $loadEntireGraph = false;
private $limit;
private $adjacent;
private $height;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
if (!$this->viewer) {
throw new PhutilInvalidStateException('setViewer');
}
return $this->viewer;
}
public function setLimit($limit) {
$this->limit = $limit;
return $this;
}
public function getLimit() {
return $this->limit;
}
public function setHeight($height) {
$this->height = $height;
return $this;
}
public function getHeight() {
return $this->height;
}
final public function setRenderOnlyAdjacentNodes($adjacent) {
$this->adjacent = $adjacent;
return $this;
}
final public function getRenderOnlyAdjacentNodes() {
return $this->adjacent;
}
abstract protected function getEdgeTypes();
abstract protected function getParentEdgeType();
abstract protected function newQuery();
abstract protected function newTableRow($phid, $object, $trace);
abstract protected function newTable(AphrontTableView $table);
abstract protected function isClosed($object);
protected function newEllipsisRow() {
return array(
'...',
);
}
final public function setSeedPHID($phid) {
$this->seedPHID = $phid;
$this->edgeReach[$phid] = array_fill_keys($this->getEdgeTypes(), true);
return $this->addNodes(
array(
'<seed>' => array($phid),
));
}
final public function getSeedPHID() {
return $this->seedPHID;
}
final public function isEmpty() {
return (count($this->getNodes()) <= 2);
}
final public function isOverLimit() {
$limit = $this->getLimit();
if (!$limit) {
return false;
}
return (count($this->edgeReach) > $limit);
}
final public function getEdges($type) {
$edges = idx($this->edges, $type, array());
// Remove any nodes which we never reached. We can get these when loading
// only part of the graph: for example, they point at other subtasks of
// parents or other parents of subtasks.
$nodes = $this->getNodes();
foreach ($edges as $src => $dsts) {
foreach ($dsts as $key => $dst) {
if (!isset($nodes[$dst])) {
unset($edges[$src][$key]);
}
}
}
return $edges;
}
final public function setLoadEntireGraph($load_entire_graph) {
$this->loadEntireGraph = $load_entire_graph;
return $this;
}
final public function getLoadEntireGraph() {
return $this->loadEntireGraph;
}
final protected function loadEdges(array $nodes) {
if ($this->isOverLimit()) {
return array_fill_keys($nodes, array());
}
$edge_types = $this->getEdgeTypes();
$query = id(new PhabricatorEdgeQuery())
->withSourcePHIDs($nodes)
->withEdgeTypes($edge_types);
$query->execute();
$whole_graph = $this->getLoadEntireGraph();
$map = array();
foreach ($nodes as $node) {
$map[$node] = array();
foreach ($edge_types as $edge_type) {
$dst_phids = $query->getDestinationPHIDs(
array($node),
array($edge_type));
$this->edges[$edge_type][$node] = $dst_phids;
foreach ($dst_phids as $dst_phid) {
if ($whole_graph || isset($this->edgeReach[$node][$edge_type])) {
$map[$node][] = $dst_phid;
}
$this->edgeReach[$dst_phid][$edge_type] = true;
}
}
$map[$node] = array_values(array_fuse($map[$node]));
}
return $map;
}
final public function newGraphTable() {
$viewer = $this->getViewer();
$ancestry = $this->getEdges($this->getParentEdgeType());
$only_adjacent = $this->getRenderOnlyAdjacentNodes();
if ($only_adjacent) {
$adjacent = array(
$this->getSeedPHID() => $this->getSeedPHID(),
);
foreach ($this->getEdgeTypes() as $edge_type) {
$map = $this->getEdges($edge_type);
$direct = idx($map, $this->getSeedPHID(), array());
$adjacent += array_fuse($direct);
}
foreach ($ancestry as $key => $list) {
if (!isset($adjacent[$key])) {
unset($ancestry[$key]);
continue;
}
foreach ($list as $list_key => $item) {
if (!isset($adjacent[$item])) {
unset($ancestry[$key][$list_key]);
}
}
}
}
$objects = $this->newQuery()
->setViewer($viewer)
->withPHIDs(array_keys($ancestry))
->execute();
$objects = mpull($objects, null, 'getPHID');
$order = id(new PhutilDirectedScalarGraph())
->addNodes($ancestry)
->getNodesInTopologicalOrder();
$ancestry = array_select_keys($ancestry, $order);
$graph_view = id(new PHUIDiffGraphView());
$height = $this->getHeight();
if ($height !== null) {
$graph_view->setHeight($height);
}
$traces = $graph_view->renderGraph($ancestry);
$ii = 0;
$rows = array();
$rowc = array();
if ($only_adjacent) {
$rows[] = $this->newEllipsisRow();
$rowc[] = 'more';
}
foreach ($ancestry as $phid => $ignored) {
$object = idx($objects, $phid);
$rows[] = $this->newTableRow($phid, $object, $traces[$ii++]);
$classes = array();
if ($phid == $this->seedPHID) {
$classes[] = 'highlighted';
}
if ($object) {
if ($this->isClosed($object)) {
$classes[] = 'closed';
}
}
if ($classes) {
$classes = implode(' ', $classes);
} else {
$classes = null;
}
$rowc[] = $classes;
}
if ($only_adjacent) {
$rows[] = $this->newEllipsisRow();
$rowc[] = 'more';
}
$table = id(new AphrontTableView($rows))
->setClassName('object-graph-table')
->setRowClasses($rowc);
$this->objects = $objects;
return $this->newTable($table);
}
final public function getReachableObjects($edge_type) {
if ($this->objects === null) {
throw new PhutilInvalidStateException('newGraphTable');
}
$graph = $this->getEdges($edge_type);
$seen = array();
$look = array($this->seedPHID);
while ($look) {
$phid = array_pop($look);
$parents = idx($graph, $phid, array());
foreach ($parents as $parent) {
if (isset($seen[$parent])) {
continue;
}
$seen[$parent] = $parent;
$look[] = $parent;
}
}
$reachable = array();
foreach ($seen as $phid) {
if ($phid == $this->seedPHID) {
continue;
}
$object = idx($this->objects, $phid);
if (!$object) {
continue;
}
$reachable[] = $object;
}
return $reachable;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/engineextension/PhabricatorEdgesDestructionEngineExtension.php | src/infrastructure/edges/engineextension/PhabricatorEdgesDestructionEngineExtension.php | <?php
final class PhabricatorEdgesDestructionEngineExtension
extends PhabricatorDestructionEngineExtension {
const EXTENSIONKEY = 'edges';
public function getExtensionName() {
return pht('Edges');
}
public function destroyObject(
PhabricatorDestructionEngine $engine,
$object) {
$src_phid = $object->getPHID();
try {
$edges = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(array($src_phid))
->execute();
} catch (Exception $ex) {
// This is (presumably) a "no edges for this PHID type" exception.
return;
}
$editor = new PhabricatorEdgeEditor();
foreach ($edges as $type => $type_edges) {
foreach ($type_edges as $src => $src_edges) {
foreach ($src_edges as $dst => $edge) {
try {
$editor->removeEdge($edge['src'], $edge['type'], $edge['dst']);
} catch (Exception $ex) {
// We can run into an exception while removing the edge if the
// edge type no longer exists. This prevents us from figuring out
// if there's an inverse type. Just ignore any errors here and
// continue, since the best we can do is clean up all the edges
// we still have information about. See T11201.
phlog($ex);
}
}
}
}
$editor->save();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/util/PhabricatorEdgeChangeRecord.php | src/infrastructure/edges/util/PhabricatorEdgeChangeRecord.php | <?php
final class PhabricatorEdgeChangeRecord
extends Phobject {
private $xaction;
public static function newFromTransaction(
PhabricatorApplicationTransaction $xaction) {
$record = new self();
$record->xaction = $xaction;
return $record;
}
public function getChangedPHIDs() {
$add = $this->getAddedPHIDs();
$rem = $this->getRemovedPHIDs();
$add = array_fuse($add);
$rem = array_fuse($rem);
return array_keys($add + $rem);
}
public function getAddedPHIDs() {
$old = $this->getOldDestinationPHIDs();
$new = $this->getNewDestinationPHIDs();
$old = array_fuse($old);
$new = array_fuse($new);
$add = array_diff_key($new, $old);
return array_keys($add);
}
public function getRemovedPHIDs() {
$old = $this->getOldDestinationPHIDs();
$new = $this->getNewDestinationPHIDs();
$old = array_fuse($old);
$new = array_fuse($new);
$rem = array_diff_key($old, $new);
return array_keys($rem);
}
public function getModernOldEdgeTransactionData() {
return $this->getRemovedPHIDs();
}
public function getModernNewEdgeTransactionData() {
return $this->getAddedPHIDs();
}
private function getOldDestinationPHIDs() {
if ($this->xaction) {
$old = $this->xaction->getOldValue();
return $this->getPHIDsFromTransactionValue($old);
}
throw new Exception(
pht('Edge change record is not configured with any change data.'));
}
private function getNewDestinationPHIDs() {
if ($this->xaction) {
$new = $this->xaction->getNewValue();
return $this->getPHIDsFromTransactionValue($new);
}
throw new Exception(
pht('Edge change record is not configured with any change data.'));
}
private function getPHIDsFromTransactionValue($value) {
if (!$value) {
return array();
}
// If the list items are arrays, this is an older-style map of
// dictionaries.
$head = head($value);
if (is_array($head)) {
return ipull($value, 'dst');
}
// If the list items are not arrays, this is a newer-style list of PHIDs.
return $value;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/util/PhabricatorEdgeGraph.php | src/infrastructure/edges/util/PhabricatorEdgeGraph.php | <?php
final class PhabricatorEdgeGraph extends AbstractDirectedGraph {
private $edgeType;
public function setEdgeType($edge_type) {
$this->edgeType = $edge_type;
return $this;
}
protected function loadEdges(array $nodes) {
if (!$this->edgeType) {
throw new Exception(pht('Set edge type before loading graph!'));
}
$edges = id(new PhabricatorEdgeQuery())
->withSourcePHIDs($nodes)
->withEdgeTypes(array($this->edgeType))
->execute();
$results = array_fill_keys($nodes, array());
foreach ($edges as $src => $types) {
foreach ($types as $type => $dsts) {
foreach ($dsts as $dst => $edge) {
$results[$src][] = $dst;
}
}
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/type/PhabricatorEdgeType.php | src/infrastructure/edges/type/PhabricatorEdgeType.php | <?php
/**
* Defines an edge type.
*
* Edges are typed, directed connections between two objects. They are used to
* represent most simple relationships, like when a user is subscribed to an
* object or an object is a member of a project.
*
* @task load Loading Types
*/
abstract class PhabricatorEdgeType extends Phobject {
final public function getEdgeConstant() {
$const = $this->getPhobjectClassConstant('EDGECONST');
if (!is_int($const) || ($const <= 0)) {
throw new Exception(
pht(
'%s class "%s" has an invalid %s property. '.
'Edge constants must be positive integers.',
__CLASS__,
get_class($this),
'EDGECONST'));
}
return $const;
}
public function getConduitKey() {
return null;
}
public function getConduitName() {
return null;
}
public function getConduitDescription() {
return null;
}
public function getInverseEdgeConstant() {
return null;
}
public function shouldPreventCycles() {
return false;
}
public function shouldWriteInverseTransactions() {
return false;
}
public function getTransactionPreviewString($actor) {
return pht(
'%s edited edge metadata.',
$actor);
}
public function getTransactionAddString(
$actor,
$add_count,
$add_edges) {
return pht(
'%s added %s edge(s): %s.',
$actor,
$add_count,
$add_edges);
}
public function getTransactionRemoveString(
$actor,
$rem_count,
$rem_edges) {
return pht(
'%s removed %s edge(s): %s.',
$actor,
$rem_count,
$rem_edges);
}
public function getTransactionEditString(
$actor,
$total_count,
$add_count,
$add_edges,
$rem_count,
$rem_edges) {
return pht(
'%s edited %s edge(s), added %s: %s; removed %s: %s.',
$actor,
$total_count,
$add_count,
$add_edges,
$rem_count,
$rem_edges);
}
public function getFeedAddString(
$actor,
$object,
$add_count,
$add_edges) {
return pht(
'%s added %s edge(s) to %s: %s.',
$actor,
$add_count,
$object,
$add_edges);
}
public function getFeedRemoveString(
$actor,
$object,
$rem_count,
$rem_edges) {
return pht(
'%s removed %s edge(s) from %s: %s.',
$actor,
$rem_count,
$object,
$rem_edges);
}
public function getFeedEditString(
$actor,
$object,
$total_count,
$add_count,
$add_edges,
$rem_count,
$rem_edges) {
return pht(
'%s edited %s edge(s) for %s, added %s: %s; removed %s: %s.',
$actor,
$total_count,
$object,
$add_count,
$add_edges,
$rem_count,
$rem_edges);
}
/* -( Loading Types )------------------------------------------------------ */
/**
* @task load
*/
public static function getAllTypes() {
static $type_map;
if ($type_map === null) {
$types = id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getEdgeConstant')
->execute();
// Check that all the inverse edge definitions actually make sense. If
// edge type A says B is its inverse, B must exist and say that A is its
// inverse.
foreach ($types as $const => $type) {
$inverse = $type->getInverseEdgeConstant();
if ($inverse === null) {
continue;
}
if (empty($types[$inverse])) {
throw new Exception(
pht(
'Edge type "%s" ("%d") defines an inverse type ("%d") which '.
'does not exist.',
get_class($type),
$const,
$inverse));
}
$inverse_inverse = $types[$inverse]->getInverseEdgeConstant();
if ($inverse_inverse !== $const) {
throw new Exception(
pht(
'Edge type "%s" ("%d") defines an inverse type ("%d"), but that '.
'inverse type defines a different type ("%d") as its '.
'inverse.',
get_class($type),
$const,
$inverse,
$inverse_inverse));
}
}
$type_map = $types;
}
return $type_map;
}
/**
* @task load
*/
public static function getByConstant($const) {
$type = idx(self::getAllTypes(), $const);
if (!$type) {
throw new Exception(
pht('Unknown edge constant "%s"!', $const));
}
return $type;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/type/__tests__/PhabricatorEdgeTypeTestCase.php | src/infrastructure/edges/type/__tests__/PhabricatorEdgeTypeTestCase.php | <?php
final class PhabricatorEdgeTypeTestCase extends PhabricatorTestCase {
public function testGetAllTypes() {
PhabricatorEdgeType::getAllTypes();
$this->assertTrue(true);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/query/PhabricatorEdgeObjectQuery.php | src/infrastructure/edges/query/PhabricatorEdgeObjectQuery.php | <?php
/**
* This is a more formal version of @{class:PhabricatorEdgeQuery} that is used
* to expose edges to Conduit.
*/
final class PhabricatorEdgeObjectQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $sourcePHIDs;
private $sourcePHIDType;
private $edgeTypes;
private $destinationPHIDs;
public function withSourcePHIDs(array $source_phids) {
$this->sourcePHIDs = $source_phids;
return $this;
}
public function withEdgeTypes(array $types) {
$this->edgeTypes = $types;
return $this;
}
public function withDestinationPHIDs(array $destination_phids) {
$this->destinationPHIDs = $destination_phids;
return $this;
}
protected function willExecute() {
$source_phids = $this->sourcePHIDs;
if (!$source_phids) {
throw new Exception(
pht(
'Edge object query must be executed with a nonempty list of '.
'source PHIDs.'));
}
$phid_item = null;
$phid_type = null;
foreach ($source_phids as $phid) {
$this_type = phid_get_type($phid);
if ($this_type == PhabricatorPHIDConstants::PHID_TYPE_UNKNOWN) {
throw new Exception(
pht(
'Source PHID "%s" in edge object query has unknown PHID type.',
$phid));
}
if ($phid_type === null) {
$phid_type = $this_type;
$phid_item = $phid;
continue;
}
if ($phid_type !== $this_type) {
throw new Exception(
pht(
'Two source PHIDs ("%s" and "%s") have different PHID types '.
'("%s" and "%s"). All PHIDs must be of the same type to execute '.
'an edge object query.',
$phid_item,
$phid,
$phid_type,
$this_type));
}
}
$this->sourcePHIDType = $phid_type;
}
protected function loadPage() {
$type = $this->sourcePHIDType;
$conn = PhabricatorEdgeConfig::establishConnection($type, 'r');
$table = PhabricatorEdgeConfig::TABLE_NAME_EDGE;
$rows = $this->loadStandardPageRowsWithConnection($conn, $table);
$result = array();
foreach ($rows as $row) {
$result[] = PhabricatorEdgeObject::newFromRow($row);
}
return $result;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$parts = parent::buildWhereClauseParts($conn);
$parts[] = qsprintf(
$conn,
'src IN (%Ls)',
$this->sourcePHIDs);
$parts[] = qsprintf(
$conn,
'type IN (%Ls)',
$this->edgeTypes);
if ($this->destinationPHIDs !== null) {
$parts[] = qsprintf(
$conn,
'dst IN (%Ls)',
$this->destinationPHIDs);
}
return $parts;
}
public function getQueryApplicationClass() {
return null;
}
protected function getPrimaryTableAlias() {
return 'edge';
}
public function getOrderableColumns() {
return array(
'dateCreated' => array(
'table' => 'edge',
'column' => 'dateCreated',
'type' => 'int',
),
'sequence' => array(
'table' => 'edge',
'column' => 'seq',
'type' => 'int',
// TODO: This is not actually unique, but we're just doing our best
// here.
'unique' => true,
),
);
}
protected function getDefaultOrderVector() {
return array('dateCreated', 'sequence');
}
protected function newInternalCursorFromExternalCursor($cursor) {
list($epoch, $sequence) = $this->parseCursor($cursor);
// Instead of actually loading an edge, we're just making a fake edge
// with the properties the cursor describes.
$edge_object = PhabricatorEdgeObject::newFromRow(
array(
'dateCreated' => $epoch,
'seq' => $sequence,
));
return id(new PhabricatorQueryCursor())
->setObject($edge_object);
}
protected function newPagingMapFromPartialObject($object) {
return array(
'dateCreated' => $object->getDateCreated(),
'sequence' => $object->getSequence(),
);
}
protected function newExternalCursorStringForResult($object) {
return sprintf(
'%d_%d',
$object->getDateCreated(),
$object->getSequence());
}
private function parseCursor($cursor) {
if (!preg_match('/^\d+_\d+\z/', $cursor)) {
$this->throwCursorException(
pht(
'Expected edge cursor in the form "0123_6789", got "%s".',
$cursor));
}
return explode('_', $cursor);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/query/PhabricatorEdgeQuery.php | src/infrastructure/edges/query/PhabricatorEdgeQuery.php | <?php
/**
* Load object edges created by @{class:PhabricatorEdgeEditor}.
*
* name=Querying Edges
* $src = $earth_phid;
* $type = PhabricatorEdgeConfig::TYPE_BODY_HAS_SATELLITE;
*
* // Load the earth's satellites.
* $satellite_edges = id(new PhabricatorEdgeQuery())
* ->withSourcePHIDs(array($src))
* ->withEdgeTypes(array($type))
* ->execute();
*
* For more information on edges, see @{article:Using Edges}.
*
* @task config Configuring the Query
* @task exec Executing the Query
* @task internal Internal
*/
final class PhabricatorEdgeQuery extends PhabricatorQuery {
private $sourcePHIDs;
private $destPHIDs;
private $edgeTypes;
private $resultSet;
const ORDER_OLDEST_FIRST = 'order:oldest';
const ORDER_NEWEST_FIRST = 'order:newest';
private $order = self::ORDER_NEWEST_FIRST;
private $needEdgeData;
/* -( Configuring the Query )---------------------------------------------- */
/**
* Find edges originating at one or more source PHIDs. You MUST provide this
* to execute an edge query.
*
* @param list List of source PHIDs.
* @return this
*
* @task config
*/
public function withSourcePHIDs(array $source_phids) {
if (!$source_phids) {
throw new Exception(
pht(
'Edge list passed to "withSourcePHIDs(...)" is empty, but it must '.
'be nonempty.'));
}
$this->sourcePHIDs = $source_phids;
return $this;
}
/**
* Find edges terminating at one or more destination PHIDs.
*
* @param list List of destination PHIDs.
* @return this
*
*/
public function withDestinationPHIDs(array $dest_phids) {
$this->destPHIDs = $dest_phids;
return $this;
}
/**
* Find edges of specific types.
*
* @param list List of PhabricatorEdgeConfig type constants.
* @return this
*
* @task config
*/
public function withEdgeTypes(array $types) {
$this->edgeTypes = $types;
return $this;
}
/**
* Configure the order edge results are returned in.
*
* @param const Order constant.
* @return this
*
* @task config
*/
public function setOrder($order) {
$this->order = $order;
return $this;
}
/**
* When loading edges, also load edge data.
*
* @param bool True to load edge data.
* @return this
*
* @task config
*/
public function needEdgeData($need) {
$this->needEdgeData = $need;
return $this;
}
/* -( Executing the Query )------------------------------------------------ */
/**
* Convenience method for loading destination PHIDs with one source and one
* edge type. Equivalent to building a full query, but simplifies a common
* use case.
*
* @param phid Source PHID.
* @param const Edge type.
* @return list<phid> List of destination PHIDs.
*/
public static function loadDestinationPHIDs($src_phid, $edge_type) {
$edges = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(array($src_phid))
->withEdgeTypes(array($edge_type))
->execute();
return array_keys($edges[$src_phid][$edge_type]);
}
/**
* Convenience method for loading a single edge's metadata for
* a given source, destination, and edge type. Returns null
* if the edge does not exist or does not have metadata. Builds
* and immediately executes a full query.
*
* @param phid Source PHID.
* @param const Edge type.
* @param phid Destination PHID.
* @return wild Edge annotation (or null).
*/
public static function loadSingleEdgeData($src_phid, $edge_type, $dest_phid) {
$edges = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(array($src_phid))
->withEdgeTypes(array($edge_type))
->withDestinationPHIDs(array($dest_phid))
->needEdgeData(true)
->execute();
if (isset($edges[$src_phid][$edge_type][$dest_phid]['data'])) {
return $edges[$src_phid][$edge_type][$dest_phid]['data'];
}
return null;
}
/**
* Load specified edges.
*
* @task exec
*/
public function execute() {
if ($this->sourcePHIDs === null) {
throw new Exception(
pht(
'You must use "withSourcePHIDs()" to query edges.'));
}
$sources = phid_group_by_type($this->sourcePHIDs);
$result = array();
// When a query specifies types, make sure we return data for all queried
// types.
if ($this->edgeTypes) {
foreach ($this->sourcePHIDs as $phid) {
foreach ($this->edgeTypes as $type) {
$result[$phid][$type] = array();
}
}
}
foreach ($sources as $type => $phids) {
$conn_r = PhabricatorEdgeConfig::establishConnection($type, 'r');
$where = $this->buildWhereClause($conn_r);
$order = $this->buildOrderClause($conn_r);
$edges = queryfx_all(
$conn_r,
'SELECT edge.* FROM %T edge %Q %Q',
PhabricatorEdgeConfig::TABLE_NAME_EDGE,
$where,
$order);
if ($this->needEdgeData) {
$data_ids = array_filter(ipull($edges, 'dataID'));
$data_map = array();
if ($data_ids) {
$data_rows = queryfx_all(
$conn_r,
'SELECT edgedata.* FROM %T edgedata WHERE id IN (%Ld)',
PhabricatorEdgeConfig::TABLE_NAME_EDGEDATA,
$data_ids);
foreach ($data_rows as $row) {
$data_map[$row['id']] = idx(
phutil_json_decode($row['data']),
'data');
}
}
foreach ($edges as $key => $edge) {
$edges[$key]['data'] = idx($data_map, $edge['dataID'], array());
}
}
foreach ($edges as $edge) {
$result[$edge['src']][$edge['type']][$edge['dst']] = $edge;
}
}
$this->resultSet = $result;
return $result;
}
/**
* Convenience function for selecting edge destination PHIDs after calling
* execute().
*
* Returns a flat list of PHIDs matching the provided source PHID and type
* filters. By default, the filters are empty so all PHIDs will be returned.
* For example, if you're doing a batch query from several sources, you might
* write code like this:
*
* $query = new PhabricatorEdgeQuery();
* $query->setViewer($viewer);
* $query->withSourcePHIDs(mpull($objects, 'getPHID'));
* $query->withEdgeTypes(array($some_type));
* $query->execute();
*
* // Gets all of the destinations.
* $all_phids = $query->getDestinationPHIDs();
* $handles = id(new PhabricatorHandleQuery())
* ->setViewer($viewer)
* ->withPHIDs($all_phids)
* ->execute();
*
* foreach ($objects as $object) {
* // Get all of the destinations for the given object.
* $dst_phids = $query->getDestinationPHIDs(array($object->getPHID()));
* $object->attachHandles(array_select_keys($handles, $dst_phids));
* }
*
* @param list? List of PHIDs to select, or empty to select all.
* @param list? List of edge types to select, or empty to select all.
* @return list<phid> List of matching destination PHIDs.
*/
public function getDestinationPHIDs(
array $src_phids = array(),
array $types = array()) {
if ($this->resultSet === null) {
throw new PhutilInvalidStateException('execute');
}
$result_phids = array();
$set = $this->resultSet;
if ($src_phids) {
$set = array_select_keys($set, $src_phids);
}
foreach ($set as $src => $edges_by_type) {
if ($types) {
$edges_by_type = array_select_keys($edges_by_type, $types);
}
foreach ($edges_by_type as $edges) {
foreach ($edges as $edge_phid => $edge) {
$result_phids[$edge_phid] = true;
}
}
}
return array_keys($result_phids);
}
/* -( Internals )---------------------------------------------------------- */
/**
* @task internal
*/
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$where = array();
if ($this->sourcePHIDs) {
$where[] = qsprintf(
$conn,
'edge.src IN (%Ls)',
$this->sourcePHIDs);
}
if ($this->edgeTypes) {
$where[] = qsprintf(
$conn,
'edge.type IN (%Ls)',
$this->edgeTypes);
}
if ($this->destPHIDs) {
// potentially complain if $this->edgeType was not set
$where[] = qsprintf(
$conn,
'edge.dst IN (%Ls)',
$this->destPHIDs);
}
return $this->formatWhereClause($conn, $where);
}
/**
* @task internal
*/
private function buildOrderClause(AphrontDatabaseConnection $conn) {
if ($this->order == self::ORDER_NEWEST_FIRST) {
return qsprintf($conn, 'ORDER BY edge.dateCreated DESC, edge.seq DESC');
} else {
return qsprintf($conn, 'ORDER BY edge.dateCreated ASC, edge.seq ASC');
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/editor/PhabricatorEdgeEditor.php | src/infrastructure/edges/editor/PhabricatorEdgeEditor.php | <?php
/**
* Add and remove edges between objects. You can use
* @{class:PhabricatorEdgeQuery} to load object edges. For more information
* on edges, see @{article:Using Edges}.
*
* Edges are not directly policy aware, and this editor makes low-level changes
* below the policy layer.
*
* name=Adding Edges
* $src = $earth_phid;
* $type = PhabricatorEdgeConfig::TYPE_BODY_HAS_SATELLITE;
* $dst = $moon_phid;
*
* id(new PhabricatorEdgeEditor())
* ->addEdge($src, $type, $dst)
* ->save();
*
* @task edit Editing Edges
* @task cycles Cycle Prevention
* @task internal Internals
*/
final class PhabricatorEdgeEditor extends Phobject {
private $addEdges = array();
private $remEdges = array();
private $openTransactions = array();
/* -( Editing Edges )------------------------------------------------------ */
/**
* Add a new edge (possibly also adding its inverse). Changes take effect when
* you call @{method:save}. If the edge already exists, it will not be
* overwritten, but if data is attached to the edge it will be updated.
* Removals queued with @{method:removeEdge} are executed before
* adds, so the effect of removing and adding the same edge is to overwrite
* any existing edge.
*
* The `$options` parameter accepts these values:
*
* - `data` Optional, data to write onto the edge.
* - `inverse_data` Optional, data to write on the inverse edge. If not
* provided, `data` will be written.
*
* @param phid Source object PHID.
* @param const Edge type constant.
* @param phid Destination object PHID.
* @param map Options map (see documentation).
* @return this
*
* @task edit
*/
public function addEdge($src, $type, $dst, array $options = array()) {
foreach ($this->buildEdgeSpecs($src, $type, $dst, $options) as $spec) {
$this->addEdges[] = $spec;
}
return $this;
}
/**
* Remove an edge (possibly also removing its inverse). Changes take effect
* when you call @{method:save}. If an edge does not exist, the removal
* will be ignored. Edges are added after edges are removed, so the effect of
* a remove plus an add is to overwrite.
*
* @param phid Source object PHID.
* @param const Edge type constant.
* @param phid Destination object PHID.
* @return this
*
* @task edit
*/
public function removeEdge($src, $type, $dst) {
foreach ($this->buildEdgeSpecs($src, $type, $dst) as $spec) {
$this->remEdges[] = $spec;
}
return $this;
}
/**
* Apply edge additions and removals queued by @{method:addEdge} and
* @{method:removeEdge}. Note that transactions are opened, all additions and
* removals are executed, and then transactions are saved. Thus, in some cases
* it may be slightly more efficient to perform multiple edit operations
* (e.g., adds followed by removals) if their outcomes are not dependent,
* since transactions will not be held open as long.
*
* @return this
* @task edit
*/
public function save() {
$cycle_types = $this->getPreventCyclesEdgeTypes();
$locks = array();
$caught = null;
try {
// NOTE: We write edge data first, before doing any transactions, since
// it's OK if we just leave it hanging out in space unattached to
// anything.
$this->writeEdgeData();
// If we're going to perform cycle detection, lock the edge type before
// doing edits.
if ($cycle_types) {
$src_phids = ipull($this->addEdges, 'src');
foreach ($cycle_types as $cycle_type) {
$key = 'edge.cycle:'.$cycle_type;
$locks[] = PhabricatorGlobalLock::newLock($key)->lock(15);
}
}
static $id = 0;
$id++;
// NOTE: Removes first, then adds, so that "remove + add" is a useful
// operation meaning "overwrite".
$this->executeRemoves();
$this->executeAdds();
foreach ($cycle_types as $cycle_type) {
$this->detectCycles($src_phids, $cycle_type);
}
$this->saveTransactions();
} catch (Exception $ex) {
$caught = $ex;
}
if ($caught) {
$this->killTransactions();
}
foreach ($locks as $lock) {
$lock->unlock();
}
if ($caught) {
throw $caught;
}
}
/* -( Internals )---------------------------------------------------------- */
/**
* Build the specification for an edge operation, and possibly build its
* inverse as well.
*
* @task internal
*/
private function buildEdgeSpecs($src, $type, $dst, array $options = array()) {
$data = array();
if (!empty($options['data'])) {
$data['data'] = $options['data'];
}
$src_type = phid_get_type($src);
$dst_type = phid_get_type($dst);
$specs = array();
$specs[] = array(
'src' => $src,
'src_type' => $src_type,
'dst' => $dst,
'dst_type' => $dst_type,
'type' => $type,
'data' => $data,
);
$type_obj = PhabricatorEdgeType::getByConstant($type);
$inverse = $type_obj->getInverseEdgeConstant();
if ($inverse !== null) {
// If `inverse_data` is set, overwrite the edge data. Normally, just
// write the same data to the inverse edge.
if (array_key_exists('inverse_data', $options)) {
$data['data'] = $options['inverse_data'];
}
$specs[] = array(
'src' => $dst,
'src_type' => $dst_type,
'dst' => $src,
'dst_type' => $src_type,
'type' => $inverse,
'data' => $data,
);
}
return $specs;
}
/**
* Write edge data.
*
* @task internal
*/
private function writeEdgeData() {
$adds = $this->addEdges;
$writes = array();
foreach ($adds as $key => $edge) {
if ($edge['data']) {
$writes[] = array($key, $edge['src_type'], json_encode($edge['data']));
}
}
foreach ($writes as $write) {
list($key, $src_type, $data) = $write;
$conn_w = PhabricatorEdgeConfig::establishConnection($src_type, 'w');
queryfx(
$conn_w,
'INSERT INTO %T (data) VALUES (%s)',
PhabricatorEdgeConfig::TABLE_NAME_EDGEDATA,
$data);
$this->addEdges[$key]['data_id'] = $conn_w->getInsertID();
}
}
/**
* Add queued edges.
*
* @task internal
*/
private function executeAdds() {
$adds = $this->addEdges;
$adds = igroup($adds, 'src_type');
// Assign stable sequence numbers to each edge, so we have a consistent
// ordering across edges by source and type.
foreach ($adds as $src_type => $edges) {
$edges_by_src = igroup($edges, 'src');
foreach ($edges_by_src as $src => $src_edges) {
$seq = 0;
foreach ($src_edges as $key => $edge) {
$src_edges[$key]['seq'] = $seq++;
$src_edges[$key]['dateCreated'] = time();
}
$edges_by_src[$src] = $src_edges;
}
$adds[$src_type] = array_mergev($edges_by_src);
}
$inserts = array();
foreach ($adds as $src_type => $edges) {
$conn_w = PhabricatorEdgeConfig::establishConnection($src_type, 'w');
$sql = array();
foreach ($edges as $edge) {
$sql[] = qsprintf(
$conn_w,
'(%s, %d, %s, %d, %d, %nd)',
$edge['src'],
$edge['type'],
$edge['dst'],
$edge['dateCreated'],
$edge['seq'],
idx($edge, 'data_id'));
}
$inserts[] = array($conn_w, $sql);
}
foreach ($inserts as $insert) {
list($conn_w, $sql) = $insert;
$conn_w->openTransaction();
$this->openTransactions[] = $conn_w;
foreach (PhabricatorLiskDAO::chunkSQL($sql) as $chunk) {
queryfx(
$conn_w,
'INSERT INTO %T (src, type, dst, dateCreated, seq, dataID)
VALUES %LQ ON DUPLICATE KEY UPDATE dataID = VALUES(dataID)',
PhabricatorEdgeConfig::TABLE_NAME_EDGE,
$chunk);
}
}
}
/**
* Remove queued edges.
*
* @task internal
*/
private function executeRemoves() {
$rems = $this->remEdges;
$rems = igroup($rems, 'src_type');
$deletes = array();
foreach ($rems as $src_type => $edges) {
$conn_w = PhabricatorEdgeConfig::establishConnection($src_type, 'w');
$sql = array();
foreach ($edges as $edge) {
$sql[] = qsprintf(
$conn_w,
'(src = %s AND type = %d AND dst = %s)',
$edge['src'],
$edge['type'],
$edge['dst']);
}
$deletes[] = array($conn_w, $sql);
}
foreach ($deletes as $delete) {
list($conn_w, $sql) = $delete;
$conn_w->openTransaction();
$this->openTransactions[] = $conn_w;
foreach (array_chunk($sql, 256) as $chunk) {
queryfx(
$conn_w,
'DELETE FROM %T WHERE %LO',
PhabricatorEdgeConfig::TABLE_NAME_EDGE,
$chunk);
}
}
}
/**
* Save open transactions.
*
* @task internal
*/
private function saveTransactions() {
foreach ($this->openTransactions as $key => $conn_w) {
$conn_w->saveTransaction();
unset($this->openTransactions[$key]);
}
}
private function killTransactions() {
foreach ($this->openTransactions as $key => $conn_w) {
$conn_w->killTransaction();
unset($this->openTransactions[$key]);
}
}
/* -( Cycle Prevention )--------------------------------------------------- */
/**
* Get a list of all edge types which are being added, and which we should
* prevent cycles on.
*
* @return list<const> List of edge types which should have cycles prevented.
* @task cycle
*/
private function getPreventCyclesEdgeTypes() {
$edge_types = array();
foreach ($this->addEdges as $edge) {
$edge_types[$edge['type']] = true;
}
foreach ($edge_types as $type => $ignored) {
$type_obj = PhabricatorEdgeType::getByConstant($type);
if (!$type_obj->shouldPreventCycles()) {
unset($edge_types[$type]);
}
}
return array_keys($edge_types);
}
/**
* Detect graph cycles of a given edge type. If the edit introduces a cycle,
* a @{class:PhabricatorEdgeCycleException} is thrown with details.
*
* @return void
* @task cycle
*/
private function detectCycles(array $phids, $edge_type) {
// For simplicity, we just seed the graph with the affected nodes rather
// than seeding it with their edges. To do this, we just add synthetic
// edges from an imaginary '<seed>' node to the known edges.
$graph = id(new PhabricatorEdgeGraph())
->setEdgeType($edge_type)
->addNodes(
array(
'<seed>' => $phids,
))
->loadGraph();
foreach ($phids as $phid) {
$cycle = $graph->detectCycles($phid);
if ($cycle) {
throw new PhabricatorEdgeCycleException($edge_type, $cycle);
}
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/exception/PhabricatorEdgeCycleException.php | src/infrastructure/edges/exception/PhabricatorEdgeCycleException.php | <?php
final class PhabricatorEdgeCycleException extends Exception {
private $cycleEdgeType;
private $cycle;
public function __construct($cycle_edge_type, array $cycle) {
$this->cycleEdgeType = $cycle_edge_type;
$this->cycle = $cycle;
$cycle_list = implode(', ', $cycle);
parent::__construct(
pht(
'Graph cycle detected (type=%s, cycle=%s).',
$cycle_edge_type,
$cycle_list));
}
public function getCycle() {
return $this->cycle;
}
public function getCycleEdgeType() {
return $this->cycleEdgeType;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/__tests__/PhabricatorEdgeTestCase.php | src/infrastructure/edges/__tests__/PhabricatorEdgeTestCase.php | <?php
final class PhabricatorEdgeTestCase extends PhabricatorTestCase {
protected function getPhabricatorTestCaseConfiguration() {
return array(
self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true,
);
}
public function testCycleDetection() {
// The editor should detect that this introduces a cycle and prevent the
// edit.
$user = new PhabricatorUser();
$obj1 = id(new HarbormasterObject())->save();
$obj2 = id(new HarbormasterObject())->save();
$phid1 = $obj1->getPHID();
$phid2 = $obj2->getPHID();
$editor = id(new PhabricatorEdgeEditor())
->addEdge($phid1, PhabricatorTestNoCycleEdgeType::EDGECONST , $phid2)
->addEdge($phid2, PhabricatorTestNoCycleEdgeType::EDGECONST , $phid1);
$caught = null;
try {
$editor->save();
} catch (Exception $ex) {
$caught = $ex;
}
$this->assertTrue($caught instanceof Exception);
// The first edit should go through (no cycle), bu the second one should
// fail (it introduces a cycle).
$editor = id(new PhabricatorEdgeEditor())
->addEdge($phid1, PhabricatorTestNoCycleEdgeType::EDGECONST , $phid2)
->save();
$editor = id(new PhabricatorEdgeEditor())
->addEdge($phid2, PhabricatorTestNoCycleEdgeType::EDGECONST , $phid1);
$caught = null;
try {
$editor->save();
} catch (Exception $ex) {
$caught = $ex;
}
$this->assertTrue($caught instanceof Exception);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/__tests__/PhabricatorEdgeChangeRecordTestCase.php | src/infrastructure/edges/__tests__/PhabricatorEdgeChangeRecordTestCase.php | <?php
final class PhabricatorEdgeChangeRecordTestCase extends PhabricatorTestCase {
public function testEdgeStorageFormats() {
$old_bulky = phutil_json_decode(<<<EOJSON
{
"PHID-PROJ-5r2ed5v27xrgltvou5or" : {
"dataID" : null,
"dateCreated" : "1449170683",
"dst" : "PHID-PROJ-5r2ed5v27xrgltvou5or",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"type" : "41",
"data" : [],
"seq" : "0"
},
"PHID-PROJ-wh32nih7q5scvc5lvipv" : {
"dataID" : null,
"seq" : "0",
"type" : "41",
"data" : [],
"dst" : "PHID-PROJ-wh32nih7q5scvc5lvipv",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dateCreated" : "1449170691"
},
"PHID-PROJ-zfp44q7loir643b5i4v4" : {
"dataID" : null,
"type" : "41",
"data" : [],
"seq" : "0",
"dateCreated" : "1449170668",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dst" : "PHID-PROJ-zfp44q7loir643b5i4v4"
},
"PHID-PROJ-amvkc5zw2gsy7tyvocug" : {
"dataID" : null,
"dst" : "PHID-PROJ-amvkc5zw2gsy7tyvocug",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dateCreated" : "1448833330",
"seq" : "0",
"type" : "41",
"data" : []
},
"PHID-PROJ-3cuwfuuh4pwqyuof2hhr" : {
"dataID" : null,
"seq" : "0",
"type" : "41",
"data" : [],
"dst" : "PHID-PROJ-3cuwfuuh4pwqyuof2hhr",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dateCreated" : "1448899367"
},
"PHID-PROJ-okljqs7prifhajtvia3t" : {
"dataID" : null,
"seq" : "0",
"data" : [],
"type" : "41",
"dst" : "PHID-PROJ-okljqs7prifhajtvia3t",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dateCreated" : "1448902756"
}
}
EOJSON
);
$new_bulky = phutil_json_decode(<<<EOJSON
{
"PHID-PROJ-5r2ed5v27xrgltvou5or" : {
"dataID" : null,
"dateCreated" : "1449170683",
"dst" : "PHID-PROJ-5r2ed5v27xrgltvou5or",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"type" : "41",
"data" : [],
"seq" : "0"
},
"PHID-PROJ-wh32nih7q5scvc5lvipv" : {
"dataID" : null,
"seq" : "0",
"type" : "41",
"data" : [],
"dst" : "PHID-PROJ-wh32nih7q5scvc5lvipv",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dateCreated" : "1449170691"
},
"PHID-PROJ-zfp44q7loir643b5i4v4" : {
"dataID" : null,
"type" : "41",
"data" : [],
"seq" : "0",
"dateCreated" : "1449170668",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dst" : "PHID-PROJ-zfp44q7loir643b5i4v4"
},
"PHID-PROJ-amvkc5zw2gsy7tyvocug" : {
"dataID" : null,
"dst" : "PHID-PROJ-amvkc5zw2gsy7tyvocug",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dateCreated" : "1448833330",
"seq" : "0",
"type" : "41",
"data" : []
},
"PHID-PROJ-3cuwfuuh4pwqyuof2hhr" : {
"dataID" : null,
"seq" : "0",
"type" : "41",
"data" : [],
"dst" : "PHID-PROJ-3cuwfuuh4pwqyuof2hhr",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dateCreated" : "1448899367"
},
"PHID-PROJ-zzzzqs7prifhajtvia3t" : {
"dataID" : null,
"seq" : "0",
"data" : [],
"type" : "41",
"dst" : "PHID-PROJ-zzzzqs7prifhajtvia3t",
"src" : "PHID-PSTE-5uj6oqv4kmhtr6ctwcq7",
"dateCreated" : "1448902756"
}
}
EOJSON
);
$old_slim = array(
'PHID-PROJ-okljqs7prifhajtvia3t',
);
$new_slim = array(
'PHID-PROJ-zzzzqs7prifhajtvia3t',
);
$bulky_xaction = new ManiphestTransaction();
$bulky_xaction->setOldValue($old_bulky);
$bulky_xaction->setNewValue($new_bulky);
$slim_xaction = new ManiphestTransaction();
$slim_xaction->setOldValue($old_slim);
$slim_xaction->setNewValue($new_slim);
$bulky_record = PhabricatorEdgeChangeRecord::newFromTransaction(
$bulky_xaction);
$slim_record = PhabricatorEdgeChangeRecord::newFromTransaction(
$slim_xaction);
$this->assertEqual(
$bulky_record->getAddedPHIDs(),
$slim_record->getAddedPHIDs());
$this->assertEqual(
$bulky_record->getRemovedPHIDs(),
$slim_record->getRemovedPHIDs());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/conduit/PhabricatorEdgeObject.php | src/infrastructure/edges/conduit/PhabricatorEdgeObject.php | <?php
final class PhabricatorEdgeObject
extends Phobject
implements PhabricatorPolicyInterface {
private $id;
private $src;
private $dst;
private $type;
private $dateCreated;
private $sequence;
public static function newFromRow(array $row) {
$edge = new self();
$edge->id = idx($row, 'id');
$edge->src = idx($row, 'src');
$edge->dst = idx($row, 'dst');
$edge->type = idx($row, 'type');
$edge->dateCreated = idx($row, 'dateCreated');
$edge->sequence = idx($row, 'seq');
return $edge;
}
public function getID() {
return $this->id;
}
public function getSourcePHID() {
return $this->src;
}
public function getEdgeType() {
return $this->type;
}
public function getDestinationPHID() {
return $this->dst;
}
public function getPHID() {
return null;
}
public function getDateCreated() {
return $this->dateCreated;
}
public function getSequence() {
return $this->sequence;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return PhabricatorPolicies::getMostOpenPolicy();
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/conduit/EdgeSearchConduitAPIMethod.php | src/infrastructure/edges/conduit/EdgeSearchConduitAPIMethod.php | <?php
final class EdgeSearchConduitAPIMethod
extends ConduitAPIMethod {
public function getAPIMethodName() {
return 'edge.search';
}
public function getMethodDescription() {
return pht('Read edge relationships between objects.');
}
protected function newDocumentationPages(PhabricatorUser $viewer) {
$rows = array();
foreach ($this->getConduitEdgeTypeMap() as $key => $type) {
$inverse_constant = $type->getInverseEdgeConstant();
if ($inverse_constant) {
$inverse_type = PhabricatorEdgeType::getByConstant($inverse_constant);
$inverse = $inverse_type->getConduitKey();
} else {
$inverse = null;
}
$rows[] = array(
$key,
$type->getConduitName(),
$inverse,
new PHUIRemarkupView($viewer, $type->getConduitDescription()),
);
}
$types_table = id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Constant'),
pht('Name'),
pht('Inverse'),
pht('Description'),
))
->setColumnClasses(
array(
'mono',
'pri',
'mono',
'wide',
));
return array(
$this->newDocumentationBoxPage($viewer, pht('Edge Types'), $types_table)
->setAnchor('types'),
);
}
protected function defineParamTypes() {
return array(
'sourcePHIDs' => 'list<phid>',
'types' => 'list<const>',
'destinationPHIDs' => 'optional list<phid>',
) + $this->getPagerParamTypes();
}
protected function defineReturnType() {
return 'list<dict>';
}
protected function defineErrorTypes() {
return array();
}
protected function execute(ConduitAPIRequest $request) {
$viewer = $request->getUser();
$pager = $this->newPager($request);
$source_phids = $request->getValue('sourcePHIDs', array());
$edge_types = $request->getValue('types', array());
$destination_phids = $request->getValue('destinationPHIDs', array());
$object_query = id(new PhabricatorObjectQuery())
->setViewer($viewer)
->withNames($source_phids);
$object_query->execute();
$objects = $object_query->getNamedResults();
foreach ($source_phids as $phid) {
if (empty($objects[$phid])) {
throw new Exception(
pht(
'Source PHID "%s" does not identify a valid object, or you do '.
'not have permission to view it.',
$phid));
}
}
$source_phids = mpull($objects, 'getPHID');
if (!$edge_types) {
throw new Exception(
pht(
'Edge search must specify a nonempty list of edge types.'));
}
$edge_map = $this->getConduitEdgeTypeMap();
$constant_map = array();
$edge_constants = array();
foreach ($edge_types as $edge_type) {
if (!isset($edge_map[$edge_type])) {
throw new Exception(
pht(
'Edge type "%s" is not a recognized edge type.',
$edge_type));
}
$constant = $edge_map[$edge_type]->getEdgeConstant();
$edge_constants[] = $constant;
$constant_map[$constant] = $edge_type;
}
$edge_query = id(new PhabricatorEdgeObjectQuery())
->setViewer($viewer)
->withSourcePHIDs($source_phids)
->withEdgeTypes($edge_constants);
if ($destination_phids) {
$edge_query->withDestinationPHIDs($destination_phids);
}
$edge_objects = $edge_query->executeWithCursorPager($pager);
$edges = array();
foreach ($edge_objects as $edge_object) {
$edges[] = array(
'sourcePHID' => $edge_object->getSourcePHID(),
'edgeType' => $constant_map[$edge_object->getEdgeType()],
'destinationPHID' => $edge_object->getDestinationPHID(),
);
}
$results = array(
'data' => $edges,
);
return $this->addPagerResults($results, $pager);
}
private function getConduitEdgeTypeMap() {
$types = PhabricatorEdgeType::getAllTypes();
$map = array();
foreach ($types as $type) {
$key = $type->getConduitKey();
if ($key === null) {
continue;
}
$map[$key] = $type;
}
ksort($map);
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/constants/PhabricatorEdgeConfig.php | src/infrastructure/edges/constants/PhabricatorEdgeConfig.php | <?php
final class PhabricatorEdgeConfig extends PhabricatorEdgeConstants {
const TABLE_NAME_EDGE = 'edge';
const TABLE_NAME_EDGEDATA = 'edgedata';
public static function establishConnection($phid_type, $conn_type) {
$map = PhabricatorPHIDType::getAllTypes();
if (isset($map[$phid_type])) {
$type = $map[$phid_type];
$object = $type->newObject();
if ($object) {
return $object->establishConnection($conn_type);
}
}
static $class_map = array(
PhabricatorPHIDConstants::PHID_TYPE_TOBJ => 'HarbormasterObject',
);
$class = idx($class_map, $phid_type);
if (!$class) {
throw new Exception(
pht(
"Edges are not available for objects of type '%s'!",
$phid_type));
}
return newv($class, array())->establishConnection($conn_type);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/edges/constants/PhabricatorEdgeConstants.php | src/infrastructure/edges/constants/PhabricatorEdgeConstants.php | <?php
abstract class PhabricatorEdgeConstants extends Phobject {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/editor/PhabricatorEditorURIParserException.php | src/infrastructure/editor/PhabricatorEditorURIParserException.php | <?php
final class PhabricatorEditorURIParserException
extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/editor/PhabricatorEditorURIEngine.php | src/infrastructure/editor/PhabricatorEditorURIEngine.php | <?php
final class PhabricatorEditorURIEngine
extends Phobject {
private $viewer;
private $repository;
private $pattern;
private $rawTokens;
private $repositoryTokens;
public static function newForViewer(PhabricatorUser $viewer) {
if (!$viewer->isLoggedIn()) {
return null;
}
$pattern = $viewer->getUserSetting(PhabricatorEditorSetting::SETTINGKEY);
if ($pattern === null || !strlen(trim($pattern))) {
return null;
}
$engine = id(new self())
->setViewer($viewer)
->setPattern($pattern);
// If there's a problem with the pattern,
try {
$engine->validatePattern();
} catch (PhabricatorEditorURIParserException $ex) {
return null;
}
return $engine;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setRepository(PhabricatorRepository $repository) {
$this->repository = $repository;
return $this;
}
public function getRepository() {
return $this->repository;
}
public function setPattern($pattern) {
$this->pattern = $pattern;
return $this;
}
public function getPattern() {
return $this->pattern;
}
public function validatePattern() {
$this->getRawURITokens();
return true;
}
public function getURIForPath($path, $line) {
$tokens = $this->getURITokensForRepository($path);
$variables = array(
'f' => $this->escapeToken($path),
'l' => $this->escapeToken($line),
);
$tokens = $this->newTokensWithVariables($tokens, $variables);
return $this->newStringFromTokens($tokens);
}
public function getURITokensForPath($path) {
$tokens = $this->getURITokensForRepository($path);
$variables = array(
'f' => $this->escapeToken($path),
);
return $this->newTokensWithVariables($tokens, $variables);
}
public static function getVariableDefinitions() {
return array(
'f' => array(
'name' => pht('File Name'),
'example' => pht('path/to/source.c'),
),
'l' => array(
'name' => pht('Line Number'),
'example' => '777',
),
'n' => array(
'name' => pht('Repository Short Name'),
'example' => 'arcanist',
),
'd' => array(
'name' => pht('Repository ID'),
'example' => '42',
),
'p' => array(
'name' => pht('Repository PHID'),
'example' => 'PHID-REPO-abcdefghijklmnopqrst',
),
'r' => array(
'name' => pht('Repository Callsign'),
'example' => 'XYZ',
),
'%' => array(
'name' => pht('Literal Percent Symbol'),
'example' => '%',
),
);
}
private function getURITokensForRepository() {
if (!$this->repositoryTokens) {
$this->repositoryTokens = $this->newURITokensForRepository();
}
return $this->repositoryTokens;
}
private function newURITokensForRepository() {
$tokens = $this->getRawURITokens();
$repository = $this->getRepository();
if (!$repository) {
throw new PhutilInvalidStateException('setRepository');
}
$variables = array(
'r' => $this->escapeToken($repository->getCallsign()),
'n' => $this->escapeToken($repository->getRepositorySlug()),
'd' => $this->escapeToken($repository->getID()),
'p' => $this->escapeToken($repository->getPHID()),
);
return $this->newTokensWithVariables($tokens, $variables);
}
private function getRawURITokens() {
if (!$this->rawTokens) {
$this->rawTokens = $this->newRawURITokens();
}
return $this->rawTokens;
}
private function newRawURITokens() {
$raw_pattern = $this->getPattern();
$raw_tokens = self::newPatternTokens($raw_pattern);
$variable_definitions = self::getVariableDefinitions();
foreach ($raw_tokens as $token) {
if ($token['type'] !== 'variable') {
continue;
}
$value = $token['value'];
if (isset($variable_definitions[$value])) {
continue;
}
throw new PhabricatorEditorURIParserException(
pht(
'Editor pattern "%s" is invalid: the pattern contains an '.
'unrecognized variable ("%s"). Use "%%%%" to encode a literal '.
'percent symbol.',
$raw_pattern,
'%'.$value));
}
$variables = array(
'%' => '%',
);
$tokens = $this->newTokensWithVariables($raw_tokens, $variables);
$first_literal = null;
if ($tokens) {
foreach ($tokens as $token) {
if ($token['type'] === 'literal') {
$first_literal = $token['value'];
}
break;
}
if ($first_literal === null) {
throw new PhabricatorEditorURIParserException(
pht(
'Editor pattern "%s" is invalid: the pattern must begin with '.
'a valid editor protocol, but begins with a variable. This is '.
'very sneaky and also very forbidden.',
$raw_pattern));
}
}
$uri = new PhutilURI($first_literal);
$editor_protocol = $uri->getProtocol();
if (!$editor_protocol) {
throw new PhabricatorEditorURIParserException(
pht(
'Editor pattern "%s" is invalid: the pattern must begin with '.
'a valid editor protocol, but does not begin with a recognized '.
'protocol string.',
$raw_pattern));
}
$allowed_key = 'uri.allowed-editor-protocols';
$allowed_protocols = PhabricatorEnv::getEnvConfig($allowed_key);
if (empty($allowed_protocols[$editor_protocol])) {
throw new PhabricatorEditorURIParserException(
pht(
'Editor pattern "%s" is invalid: the pattern must begin with '.
'a valid editor protocol, but the protocol "%s://" is not allowed.',
$raw_pattern,
$editor_protocol));
}
return $tokens;
}
private function newTokensWithVariables(array $tokens, array $variables) {
// Replace all "variable" tokens that we have replacements for with
// the literal value.
foreach ($tokens as $key => $token) {
$type = $token['type'];
if ($type == 'variable') {
$variable = $token['value'];
if (isset($variables[$variable])) {
$tokens[$key] = array(
'type' => 'literal',
'value' => $variables[$variable],
);
}
}
}
// Now, merge sequences of adjacent "literal" tokens into a single token.
$last_literal = null;
foreach ($tokens as $key => $token) {
$is_literal = ($token['type'] === 'literal');
if (!$is_literal) {
$last_literal = null;
continue;
}
if ($last_literal !== null) {
$tokens[$key]['value'] =
$tokens[$last_literal]['value'].$token['value'];
unset($tokens[$last_literal]);
}
$last_literal = $key;
}
$tokens = array_values($tokens);
return $tokens;
}
private function escapeToken($token) {
// Paths are user controlled, so a clever user could potentially make
// editor links do surprising things with paths containing "/../".
// Find anything that looks like "/../" and mangle it.
$token = preg_replace('((^|/)\.\.(/|\z))', '\1dot-dot\2', $token);
return phutil_escape_uri($token);
}
private function newStringFromTokens(array $tokens) {
$result = array();
foreach ($tokens as $token) {
$token_type = $token['type'];
$token_value = $token['value'];
$is_literal = ($token_type === 'literal');
if (!$is_literal) {
throw new Exception(
pht(
'Editor pattern token list can not be converted into a string: '.
'it still contains a non-literal token ("%s", of type "%s").',
$token_value,
$token_type));
}
$result[] = $token_value;
}
$result = implode('', $result);
return $result;
}
public static function newPatternTokens($raw_pattern) {
$token_positions = array();
$len = strlen($raw_pattern);
for ($ii = 0; $ii < $len; $ii++) {
$c = $raw_pattern[$ii];
if ($c === '%') {
if (!isset($raw_pattern[$ii + 1])) {
throw new PhabricatorEditorURIParserException(
pht(
'Editor pattern "%s" is invalid: the final character in a '.
'pattern may not be an unencoded percent symbol ("%%"). '.
'Use "%%%%" to encode a literal percent symbol.',
$raw_pattern));
}
$token_positions[] = $ii;
$ii++;
}
}
// Add a final marker past the end of the string, so we'll collect any
// trailing literal bytes.
$token_positions[] = $len;
$tokens = array();
$cursor = 0;
foreach ($token_positions as $pos) {
$token_len = ($pos - $cursor);
if ($token_len > 0) {
$tokens[] = array(
'type' => 'literal',
'value' => substr($raw_pattern, $cursor, $token_len),
);
}
$cursor = $pos;
if ($cursor < $len) {
$tokens[] = array(
'type' => 'variable',
'value' => substr($raw_pattern, $cursor + 1, 1),
);
}
$cursor = $pos + 2;
}
return $tokens;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/editor/__tests__/PhabricatorEditorURIEngineTestCase.php | src/infrastructure/editor/__tests__/PhabricatorEditorURIEngineTestCase.php | <?php
final class PhabricatorEditorURIEngineTestCase
extends PhabricatorTestCase {
public function testPatternParsing() {
$map = array(
'' => array(),
'%' => false,
'aaa%' => false,
'quack' => array(
array(
'type' => 'literal',
'value' => 'quack',
),
),
'%a' => array(
array(
'type' => 'variable',
'value' => 'a',
),
),
'%%' => array(
array(
'type' => 'variable',
'value' => '%',
),
),
'x%y' => array(
array(
'type' => 'literal',
'value' => 'x',
),
array(
'type' => 'variable',
'value' => 'y',
),
),
'%xy' => array(
array(
'type' => 'variable',
'value' => 'x',
),
array(
'type' => 'literal',
'value' => 'y',
),
),
'x%yz' => array(
array(
'type' => 'literal',
'value' => 'x',
),
array(
'type' => 'variable',
'value' => 'y',
),
array(
'type' => 'literal',
'value' => 'z',
),
),
);
foreach ($map as $input => $expect) {
try {
$actual = PhabricatorEditorURIEngine::newPatternTokens($input);
} catch (Exception $ex) {
if ($expect !== false) {
throw $ex;
}
$actual = false;
}
$this->assertEqual(
$expect,
$actual,
pht('Parse of: %s', $input));
}
}
public function testPatternProtocols() {
$protocols = array(
'xyz',
);
$protocols = array_fuse($protocols);
$env = PhabricatorEnv::beginScopedEnv();
$env->overrideEnvConfig('uri.allowed-editor-protocols', $protocols);
$map = array(
'xyz:' => true,
'xyz:%%' => true,
'xyz://a' => true,
'xyz://open/?file=%f' => true,
'' => false,
'%%' => false,
'%r' => false,
'aaa' => false,
'xyz%%://' => false,
'http://' => false,
// These are fragments that "PhutilURI" can't figure out the protocol
// for. In theory, they would be safe to allow, they just probably are
// not very useful.
'xyz://' => false,
'xyz://%%' => false,
);
foreach ($map as $input => $expect) {
try {
id(new PhabricatorEditorURIEngine())
->setPattern($input)
->validatePattern();
$actual = true;
} catch (PhabricatorEditorURIParserException $ex) {
$actual = false;
}
$this->assertEqual(
$expect,
$actual,
pht(
'Allowed editor "xyz://" template: %s.',
$input));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/time/PhabricatorTime.php | src/infrastructure/time/PhabricatorTime.php | <?php
final class PhabricatorTime extends Phobject {
private static $stack = array();
private static $originalZone;
public static function pushTime($epoch, $timezone) {
if (empty(self::$stack)) {
self::$originalZone = date_default_timezone_get();
}
$ok = date_default_timezone_set($timezone);
if (!$ok) {
throw new Exception(pht("Invalid timezone '%s'!", $timezone));
}
self::$stack[] = array(
'epoch' => $epoch,
'timezone' => $timezone,
);
return new PhabricatorTimeGuard(last_key(self::$stack));
}
public static function popTime($key) {
if ($key !== last_key(self::$stack)) {
throw new Exception(
pht(
'%s with bad key.',
__METHOD__));
}
array_pop(self::$stack);
if (empty(self::$stack)) {
date_default_timezone_set(self::$originalZone);
} else {
$frame = end(self::$stack);
date_default_timezone_set($frame['timezone']);
}
}
public static function getNow() {
if (self::$stack) {
$frame = end(self::$stack);
return $frame['epoch'];
}
return time();
}
public static function parseLocalTime($time, PhabricatorUser $user) {
$old_zone = date_default_timezone_get();
date_default_timezone_set($user->getTimezoneIdentifier());
$timestamp = (int)strtotime($time, self::getNow());
if ($timestamp <= 0) {
$timestamp = null;
}
date_default_timezone_set($old_zone);
return $timestamp;
}
public static function getTodayMidnightDateTime($viewer) {
$timezone = new DateTimeZone($viewer->getTimezoneIdentifier());
$today = new DateTime('@'.time());
$today->setTimezone($timezone);
$year = $today->format('Y');
$month = $today->format('m');
$day = $today->format('d');
$today = new DateTime("{$year}-{$month}-{$day}", $timezone);
return $today;
}
public static function getDateTimeFromEpoch($epoch, PhabricatorUser $viewer) {
$datetime = new DateTime('@'.$epoch);
$datetime->setTimezone($viewer->getTimeZone());
return $datetime;
}
public static function getTimezoneDisplayName($raw_identifier) {
// Internal identifiers have names like "America/Los_Angeles", but this is
// just an implementation detail and we can render them in a more human
// readable format with spaces.
$name = str_replace('_', ' ', $raw_identifier);
return $name;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/time/PhabricatorTimeGuard.php | src/infrastructure/time/PhabricatorTimeGuard.php | <?php
final class PhabricatorTimeGuard extends Phobject {
private $frameKey;
public function __construct($frame_key) {
$this->frameKey = $frame_key;
}
public function __destruct() {
PhabricatorTime::popTime($this->frameKey);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/time/__tests__/PhabricatorTimeTestCase.php | src/infrastructure/time/__tests__/PhabricatorTimeTestCase.php | <?php
final class PhabricatorTimeTestCase extends PhabricatorTestCase {
public function testPhabricatorTimeStack() {
$t = 1370202281;
$time = PhabricatorTime::pushTime($t, 'UTC');
$this->assertTrue(PhabricatorTime::getNow() === $t);
unset($time);
$this->assertFalse(PhabricatorTime::getNow() === $t);
}
public function testParseLocalTime() {
$u = new PhabricatorUser();
$u->overrideTimezoneIdentifier('UTC');
$v = new PhabricatorUser();
$v->overrideTimezoneIdentifier('America/Los_Angeles');
$t = 1370202281; // 2013-06-02 12:44:41 -0700
$time = PhabricatorTime::pushTime($t, 'America/Los_Angeles');
$this->assertEqual(
$t,
PhabricatorTime::parseLocalTime('now', $u));
$this->assertEqual(
$t,
PhabricatorTime::parseLocalTime('now', $v));
$this->assertEqual(
$t,
PhabricatorTime::parseLocalTime('2013-06-02 12:44:41 -0700', $u));
$this->assertEqual(
$t,
PhabricatorTime::parseLocalTime('2013-06-02 12:44:41 -0700', $v));
$this->assertEqual(
$t,
PhabricatorTime::parseLocalTime('2013-06-02 12:44:41 PDT', $u));
$this->assertEqual(
$t,
PhabricatorTime::parseLocalTime('2013-06-02 12:44:41 PDT', $v));
$this->assertEqual(
$t,
PhabricatorTime::parseLocalTime('2013-06-02 19:44:41', $u));
$this->assertEqual(
$t,
PhabricatorTime::parseLocalTime('2013-06-02 12:44:41', $v));
$this->assertEqual(
$t + 3600,
PhabricatorTime::parseLocalTime('+1 hour', $u));
$this->assertEqual(
$t + 3600,
PhabricatorTime::parseLocalTime('+1 hour', $v));
unset($time);
$t = 1370239200; // 2013-06-02 23:00:00 -0700
$time = PhabricatorTime::pushTime($t, 'America/Los_Angeles');
// For the UTC user, midnight was 6 hours ago because it's early in the
// morning for htem. For the PDT user, midnight was 23 hours ago.
$this->assertEqual(
$t + (-6 * 3600) + 60,
PhabricatorTime::parseLocalTime('12:01:00 AM', $u));
$this->assertEqual(
$t + (-23 * 3600) + 60,
PhabricatorTime::parseLocalTime('12:01:00 AM', $v));
unset($time);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/ssh/PhabricatorSSHPassthruCommand.php | src/infrastructure/ssh/PhabricatorSSHPassthruCommand.php | <?php
/**
* Proxy an IO channel to an underlying command, with optional callbacks. This
* is a mostly a more general version of @{class:PhutilExecPassthru}. This
* class is used to proxy Git, SVN and Mercurial traffic to the commands which
* can actually serve it.
*
* Largely, this just reads an IO channel (like stdin from SSH) and writes
* the results into a command channel (like a command's stdin). Then it reads
* the command channel (like the command's stdout) and writes it into the IO
* channel (like stdout from SSH):
*
* IO Channel Command Channel
* stdin -> stdin
* stdout <- stdout
* stderr <- stderr
*
* You can provide **read and write callbacks** which are invoked as data
* is passed through this class. They allow you to inspect and modify traffic.
*
* IO Channel Passthru Command Channel
* stdout -> willWrite -> stdin
* stdin <- willRead <- stdout
* stderr <- (identity) <- stderr
*
* Primarily, this means:
*
* - the **IO Channel** can be a @{class:PhutilProtocolChannel} if the
* **write callback** can convert protocol messages into strings; and
* - the **write callback** can inspect and reject requests over the channel,
* e.g. to enforce policies.
*
* In practice, this is used when serving repositories to check each command
* issued over SSH and determine if it is a read command or a write command.
* Writes can then be checked for appropriate permissions.
*/
final class PhabricatorSSHPassthruCommand extends Phobject {
private $commandChannel;
private $ioChannel;
private $errorChannel;
private $execFuture;
private $willWriteCallback;
private $willReadCallback;
private $pauseIOReads;
public function setCommandChannelFromExecFuture(ExecFuture $exec_future) {
$exec_channel = new PhutilExecChannel($exec_future);
$exec_channel->setStderrHandler(array($this, 'writeErrorIOCallback'));
$this->execFuture = $exec_future;
$this->commandChannel = $exec_channel;
return $this;
}
public function setIOChannel(PhutilChannel $io_channel) {
$this->ioChannel = $io_channel;
return $this;
}
public function setErrorChannel(PhutilChannel $error_channel) {
$this->errorChannel = $error_channel;
return $this;
}
public function setWillReadCallback($will_read_callback) {
$this->willReadCallback = $will_read_callback;
return $this;
}
public function setWillWriteCallback($will_write_callback) {
$this->willWriteCallback = $will_write_callback;
return $this;
}
public function writeErrorIOCallback(PhutilChannel $channel, $data) {
$this->errorChannel->write($data);
}
public function setPauseIOReads($pause) {
$this->pauseIOReads = $pause;
return $this;
}
public function execute() {
$command_channel = $this->commandChannel;
$io_channel = $this->ioChannel;
$error_channel = $this->errorChannel;
if (!$command_channel) {
throw new Exception(
pht(
'Set a command channel before calling %s!',
__FUNCTION__.'()'));
}
if (!$io_channel) {
throw new Exception(
pht(
'Set an IO channel before calling %s!',
__FUNCTION__.'()'));
}
if (!$error_channel) {
throw new Exception(
pht(
'Set an error channel before calling %s!',
__FUNCTION__.'()'));
}
$channels = array($command_channel, $io_channel, $error_channel);
// We want to limit the amount of data we'll hold in memory for this
// process. See T4241 for a discussion of this issue in general.
$buffer_size = (1024 * 1024); // 1MB
$io_channel->setReadBufferSize($buffer_size);
$command_channel->setReadBufferSize($buffer_size);
// TODO: This just makes us throw away stderr after the first 1MB, but we
// don't currently have the support infrastructure to buffer it correctly.
// It's difficult to imagine this causing problems in practice, though.
$this->execFuture->getStderrSizeLimit($buffer_size);
while (true) {
PhutilChannel::waitForAny($channels);
$io_channel->update();
$command_channel->update();
$error_channel->update();
// If any channel is blocked on the other end, wait for it to flush before
// we continue reading. For example, if a user is running `git clone` on
// a 1GB repository, the underlying `git-upload-pack` may
// be able to produce data much more quickly than we can send it over
// the network. If we don't throttle the reads, we may only send a few
// MB over the I/O channel in the time it takes to read the entire 1GB off
// the command channel. That leaves us with 1GB of data in memory.
while ($command_channel->isOpen() &&
$io_channel->isOpenForWriting() &&
($command_channel->getWriteBufferSize() >= $buffer_size ||
$io_channel->getWriteBufferSize() >= $buffer_size ||
$error_channel->getWriteBufferSize() >= $buffer_size)) {
PhutilChannel::waitForActivity(array(), $channels);
$io_channel->update();
$command_channel->update();
$error_channel->update();
}
// If the subprocess has exited and we've read everything from it,
// we're all done.
$done = !$command_channel->isOpenForReading() &&
$command_channel->isReadBufferEmpty();
if (!$this->pauseIOReads) {
$in_message = $io_channel->read();
if ($in_message !== null) {
$this->writeIORead($in_message);
}
}
$out_message = $command_channel->read();
if (strlen($out_message)) {
$out_message = $this->willReadData($out_message);
if ($out_message !== null) {
$io_channel->write($out_message);
}
}
// If we have nothing left on stdin, close stdin on the subprocess.
if (!$io_channel->isOpenForReading()) {
$command_channel->closeWriteChannel();
}
if ($done) {
break;
}
// If the client has disconnected, kill the subprocess and bail.
if (!$io_channel->isOpenForWriting()) {
$this->execFuture
->setStdoutSizeLimit(0)
->setStderrSizeLimit(0)
->setReadBufferSize(null)
->resolveKill();
break;
}
}
list($err) = $this->execFuture
->setStdoutSizeLimit(0)
->setStderrSizeLimit(0)
->setReadBufferSize(null)
->resolve();
return $err;
}
public function writeIORead($in_message) {
$in_message = $this->willWriteData($in_message);
if (strlen($in_message)) {
$this->commandChannel->write($in_message);
}
}
public function willWriteData($message) {
if ($this->willWriteCallback) {
return call_user_func($this->willWriteCallback, $this, $message);
} else {
if (strlen($message)) {
return $message;
} else {
return null;
}
}
}
public function willReadData($message) {
if ($this->willReadCallback) {
return call_user_func($this->willReadCallback, $this, $message);
} else {
if (strlen($message)) {
return $message;
} else {
return null;
}
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/ssh/PhabricatorSSHWorkflow.php | src/infrastructure/ssh/PhabricatorSSHWorkflow.php | <?php
abstract class PhabricatorSSHWorkflow
extends PhutilArgumentWorkflow {
// NOTE: We are explicitly extending "PhutilArgumentWorkflow", not
// "PhabricatorManagementWorkflow". We want to avoid inheriting "getViewer()"
// and other methods which assume workflows are administrative commands
// like `bin/storage`.
private $sshUser;
private $iochannel;
private $errorChannel;
private $isClusterRequest;
private $originalArguments;
private $requestIdentifier;
public function isExecutable() {
return false;
}
public function setErrorChannel(PhutilChannel $error_channel) {
$this->errorChannel = $error_channel;
return $this;
}
public function getErrorChannel() {
return $this->errorChannel;
}
public function setSSHUser(PhabricatorUser $ssh_user) {
$this->sshUser = $ssh_user;
return $this;
}
public function getSSHUser() {
return $this->sshUser;
}
public function setIOChannel(PhutilChannel $channel) {
$this->iochannel = $channel;
return $this;
}
public function getIOChannel() {
return $this->iochannel;
}
public function readAllInput() {
$channel = $this->getIOChannel();
while ($channel->update()) {
PhutilChannel::waitForAny(array($channel));
if (!$channel->isOpenForReading()) {
break;
}
}
return $channel->read();
}
public function writeIO($data) {
$this->getIOChannel()->write($data);
return $this;
}
public function writeErrorIO($data) {
$this->getErrorChannel()->write($data);
return $this;
}
protected function newPassthruCommand() {
return id(new PhabricatorSSHPassthruCommand())
->setErrorChannel($this->getErrorChannel());
}
public function setIsClusterRequest($is_cluster_request) {
$this->isClusterRequest = $is_cluster_request;
return $this;
}
public function getIsClusterRequest() {
return $this->isClusterRequest;
}
public function setOriginalArguments(array $original_arguments) {
$this->originalArguments = $original_arguments;
return $this;
}
public function getOriginalArguments() {
return $this->originalArguments;
}
public function setRequestIdentifier($request_identifier) {
$this->requestIdentifier = $request_identifier;
return $this;
}
public function getRequestIdentifier() {
return $this->requestIdentifier;
}
public function getSSHRemoteAddress() {
$ssh_client = getenv('SSH_CLIENT');
if (!strlen($ssh_client)) {
return null;
}
// TODO: When commands are proxied, the original remote address should
// also be proxied.
// This has the format "<ip> <remote-port> <local-port>". Grab the IP.
$remote_address = head(explode(' ', $ssh_client));
try {
$address = PhutilIPAddress::newAddress($remote_address);
} catch (Exception $ex) {
return null;
}
return $address->getAddress();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/PhabricatorInlineCommentController.php | src/infrastructure/diff/PhabricatorInlineCommentController.php | <?php
abstract class PhabricatorInlineCommentController
extends PhabricatorController {
private $containerObject;
abstract protected function createComment();
abstract protected function newInlineCommentQuery();
abstract protected function loadCommentForDone($id);
abstract protected function loadObjectOwnerPHID(
PhabricatorInlineComment $inline);
abstract protected function newContainerObject();
final protected function getContainerObject() {
if ($this->containerObject === null) {
$object = $this->newContainerObject();
if (!$object) {
throw new Exception(
pht(
'Failed to load container object for inline comment.'));
}
$this->containerObject = $object;
}
return $this->containerObject;
}
protected function hideComments(array $ids) {
throw new PhutilMethodNotImplementedException();
}
protected function showComments(array $ids) {
throw new PhutilMethodNotImplementedException();
}
private $changesetID;
private $isNewFile;
private $isOnRight;
private $lineNumber;
private $lineLength;
private $operation;
private $commentID;
private $renderer;
private $replyToCommentPHID;
public function getCommentID() {
return $this->commentID;
}
public function getOperation() {
return $this->operation;
}
public function getLineLength() {
return $this->lineLength;
}
public function getLineNumber() {
return $this->lineNumber;
}
public function getIsOnRight() {
return $this->isOnRight;
}
public function getChangesetID() {
return $this->changesetID;
}
public function getIsNewFile() {
return $this->isNewFile;
}
public function setRenderer($renderer) {
$this->renderer = $renderer;
return $this;
}
public function getRenderer() {
return $this->renderer;
}
public function setReplyToCommentPHID($phid) {
$this->replyToCommentPHID = $phid;
return $this;
}
public function getReplyToCommentPHID() {
return $this->replyToCommentPHID;
}
public function processRequest() {
$request = $this->getRequest();
$viewer = $this->getViewer();
if (!$request->validateCSRF()) {
return new Aphront404Response();
}
$this->readRequestParameters();
$op = $this->getOperation();
switch ($op) {
case 'hide':
case 'show':
$ids = $request->getStrList('ids');
if ($ids) {
if ($op == 'hide') {
$this->hideComments($ids);
} else {
$this->showComments($ids);
}
}
return id(new AphrontAjaxResponse())->setContent(array());
case 'done':
$inline = $this->loadCommentForDone($this->getCommentID());
$is_draft_state = false;
$is_checked = false;
switch ($inline->getFixedState()) {
case PhabricatorInlineComment::STATE_DRAFT:
$next_state = PhabricatorInlineComment::STATE_UNDONE;
break;
case PhabricatorInlineComment::STATE_UNDRAFT:
$next_state = PhabricatorInlineComment::STATE_DONE;
$is_checked = true;
break;
case PhabricatorInlineComment::STATE_DONE:
$next_state = PhabricatorInlineComment::STATE_UNDRAFT;
$is_draft_state = true;
break;
default:
case PhabricatorInlineComment::STATE_UNDONE:
$next_state = PhabricatorInlineComment::STATE_DRAFT;
$is_draft_state = true;
$is_checked = true;
break;
}
$inline->setFixedState($next_state)->save();
return id(new AphrontAjaxResponse())
->setContent(
array(
'isChecked' => $is_checked,
'draftState' => $is_draft_state,
));
case 'delete':
case 'undelete':
case 'refdelete':
// NOTE: For normal deletes, we just process the delete immediately
// and show an "Undo" action. For deletes by reference from the
// preview ("refdelete"), we prompt first (because the "Undo" may
// not draw, or may not be easy to locate).
if ($op == 'refdelete') {
if (!$request->isFormPost()) {
return $this->newDialog()
->setTitle(pht('Really delete comment?'))
->addHiddenInput('id', $this->getCommentID())
->addHiddenInput('op', $op)
->appendParagraph(pht('Delete this inline comment?'))
->addCancelButton('#')
->addSubmitButton(pht('Delete'));
}
}
$is_delete = ($op == 'delete' || $op == 'refdelete');
$inline = $this->loadCommentByIDForEdit($this->getCommentID());
if ($is_delete) {
$inline
->setIsEditing(false)
->setIsDeleted(1);
} else {
$inline->setIsDeleted(0);
}
$this->saveComment($inline);
return $this->buildEmptyResponse();
case 'save':
$inline = $this->loadCommentByIDForEdit($this->getCommentID());
$this->updateCommentContentState($inline);
$inline
->setIsEditing(false)
->setIsDeleted(0);
// Since we're saving the comment, update the committed state.
$active_state = $inline->getContentState();
$inline->setCommittedContentState($active_state);
$this->saveComment($inline);
return $this->buildRenderedCommentResponse(
$inline,
$this->getIsOnRight());
case 'edit':
$inline = $this->loadCommentByIDForEdit($this->getCommentID());
// NOTE: At time of writing, the "editing" state of inlines is
// preserved by simulating a click on "Edit" when the inline loads.
// In this case, we don't want to "saveComment()", because it
// recalculates object drafts and purges versioned drafts.
// The recalculation is merely unnecessary (state doesn't change)
// but purging drafts means that loading a page and then closing it
// discards your drafts.
// To avoid the purge, only invoke "saveComment()" if we actually
// have changes to apply.
$is_dirty = false;
if (!$inline->getIsEditing()) {
$inline
->setIsDeleted(0)
->setIsEditing(true);
$is_dirty = true;
}
if ($this->hasContentState()) {
$this->updateCommentContentState($inline);
$is_dirty = true;
} else {
PhabricatorInlineComment::loadAndAttachVersionedDrafts(
$viewer,
array($inline));
}
if ($is_dirty) {
$this->saveComment($inline);
}
$edit_dialog = $this->buildEditDialog($inline)
->setTitle(pht('Edit Inline Comment'));
$view = $this->buildScaffoldForView($edit_dialog);
return $this->newInlineResponse($inline, $view, true);
case 'cancel':
$inline = $this->loadCommentByIDForEdit($this->getCommentID());
$inline->setIsEditing(false);
// If the user uses "Undo" to get into an edited state ("AB"), then
// clicks cancel to return to the previous state ("A"), we also want
// to set the stored state back to "A".
$this->updateCommentContentState($inline);
$this->saveComment($inline);
return $this->buildEmptyResponse();
case 'draft':
$inline = $this->loadCommentByIDForEdit($this->getCommentID());
$versioned_draft = PhabricatorVersionedDraft::loadOrCreateDraft(
$inline->getPHID(),
$viewer->getPHID(),
$inline->getID());
$map = $this->newRequestContentState($inline)->newStorageMap();
$versioned_draft->setProperty('inline.state', $map);
$versioned_draft->save();
// We have to synchronize the draft engine after saving a versioned
// draft, because taking an inline comment from "no text, no draft"
// to "no text, text in a draft" marks the container object as having
// a draft.
$draft_engine = $this->newDraftEngine();
if ($draft_engine) {
$draft_engine->synchronize();
}
return $this->buildEmptyResponse();
case 'new':
case 'reply':
default:
// NOTE: We read the values from the client (the display values), not
// the values from the database (the original values) when replying.
// In particular, when replying to a ghost comment which was moved
// across diffs and then moved backward to the most recent visible
// line, we want to reply on the display line (which exists), not on
// the comment's original line (which may not exist in this changeset).
$is_new = $this->getIsNewFile();
$number = $this->getLineNumber();
$length = $this->getLineLength();
$inline = $this->createComment()
->setChangesetID($this->getChangesetID())
->setAuthorPHID($viewer->getPHID())
->setIsNewFile($is_new)
->setLineNumber($number)
->setLineLength($length)
->setReplyToCommentPHID($this->getReplyToCommentPHID())
->setIsEditing(true)
->setStartOffset($request->getInt('startOffset'))
->setEndOffset($request->getInt('endOffset'))
->setContent('');
$document_engine_key = $request->getStr('documentEngineKey');
if ($document_engine_key !== null) {
$inline->setDocumentEngineKey($document_engine_key);
}
// If you own this object, mark your own inlines as "Done" by default.
$owner_phid = $this->loadObjectOwnerPHID($inline);
if ($owner_phid) {
if ($viewer->getPHID() == $owner_phid) {
$fixed_state = PhabricatorInlineComment::STATE_DRAFT;
$inline->setFixedState($fixed_state);
}
}
if ($this->hasContentState()) {
$this->updateCommentContentState($inline);
}
// NOTE: We're writing the comment as "deleted", then reloading to
// pick up context and undeleting it. This is silly -- we just want
// to load and attach context -- but just loading context is currently
// complicated (for example, context relies on cache keys that expect
// the inline to have an ID).
$inline->setIsDeleted(1);
$this->saveComment($inline);
// Reload the inline to attach context.
$inline = $this->loadCommentByIDForEdit($inline->getID());
// Now, we can read the source file and set the initial state.
$state = $inline->getContentState();
$default_suggestion = $inline->getDefaultSuggestionText();
$state->setContentSuggestionText($default_suggestion);
$inline->setInitialContentState($state);
$inline->setContentState($state);
$inline->setIsDeleted(0);
$this->saveComment($inline);
$edit_dialog = $this->buildEditDialog($inline);
if ($this->getOperation() == 'reply') {
$edit_dialog->setTitle(pht('Reply to Inline Comment'));
} else {
$edit_dialog->setTitle(pht('New Inline Comment'));
}
$view = $this->buildScaffoldForView($edit_dialog);
return $this->newInlineResponse($inline, $view, true);
}
}
private function readRequestParameters() {
$request = $this->getRequest();
// NOTE: This isn't necessarily a DifferentialChangeset ID, just an
// application identifier for the changeset. In Diffusion, it's a Path ID.
$this->changesetID = $request->getInt('changesetID');
$this->isNewFile = (int)$request->getBool('is_new');
$this->isOnRight = $request->getBool('on_right');
$this->lineNumber = $request->getInt('number');
$this->lineLength = $request->getInt('length');
$this->commentID = $request->getInt('id');
$this->operation = $request->getStr('op');
$this->renderer = $request->getStr('renderer');
$this->replyToCommentPHID = $request->getStr('replyToCommentPHID');
if ($this->getReplyToCommentPHID()) {
$reply_phid = $this->getReplyToCommentPHID();
$reply_comment = $this->loadCommentByPHID($reply_phid);
if (!$reply_comment) {
throw new Exception(
pht('Failed to load comment "%s".', $reply_phid));
}
// When replying, force the new comment into the same location as the
// old comment. If we don't do this, replying to a ghost comment from
// diff A while viewing diff B can end up placing the two comments in
// different places while viewing diff C, because the porting algorithm
// makes a different decision. Forcing the comments to bind to the same
// place makes sure they stick together no matter which diff is being
// viewed. See T10562 for discussion.
$this->changesetID = $reply_comment->getChangesetID();
$this->isNewFile = $reply_comment->getIsNewFile();
$this->lineNumber = $reply_comment->getLineNumber();
$this->lineLength = $reply_comment->getLineLength();
}
}
private function buildEditDialog(PhabricatorInlineComment $inline) {
$request = $this->getRequest();
$viewer = $this->getViewer();
$edit_dialog = id(new PHUIDiffInlineCommentEditView())
->setViewer($viewer)
->setInlineComment($inline)
->setIsOnRight($this->getIsOnRight())
->setRenderer($this->getRenderer());
return $edit_dialog;
}
private function buildEmptyResponse() {
return id(new AphrontAjaxResponse())
->setContent(
array(
'inline' => array(),
'view' => null,
));
}
private function buildRenderedCommentResponse(
PhabricatorInlineComment $inline,
$on_right) {
$request = $this->getRequest();
$viewer = $this->getViewer();
$engine = new PhabricatorMarkupEngine();
$engine->setViewer($viewer);
$engine->addObject(
$inline,
PhabricatorInlineComment::MARKUP_FIELD_BODY);
$engine->process();
$phids = array($viewer->getPHID());
$handles = $this->loadViewerHandles($phids);
$object_owner_phid = $this->loadObjectOwnerPHID($inline);
$view = id(new PHUIDiffInlineCommentDetailView())
->setUser($viewer)
->setInlineComment($inline)
->setIsOnRight($on_right)
->setMarkupEngine($engine)
->setHandles($handles)
->setEditable(true)
->setCanMarkDone(false)
->setObjectOwnerPHID($object_owner_phid);
$view = $this->buildScaffoldForView($view);
return $this->newInlineResponse($inline, $view, false);
}
private function buildScaffoldForView(PHUIDiffInlineCommentView $view) {
$renderer = DifferentialChangesetHTMLRenderer::getHTMLRendererByKey(
$this->getRenderer());
$view = $renderer->getRowScaffoldForInline($view);
return id(new PHUIDiffInlineCommentTableScaffold())
->addRowScaffold($view);
}
private function newInlineResponse(
PhabricatorInlineComment $inline,
$view,
$is_edit) {
$viewer = $this->getViewer();
if ($inline->getReplyToCommentPHID()) {
$can_suggest = false;
} else {
$can_suggest = (bool)$inline->getInlineContext();
}
if ($is_edit) {
$state = $inline->getContentStateMapForEdit($viewer);
} else {
$state = $inline->getContentStateMap();
}
$response = array(
'inline' => array(
'id' => $inline->getID(),
'state' => $state,
'canSuggestEdit' => $can_suggest,
),
'view' => hsprintf('%s', $view),
);
return id(new AphrontAjaxResponse())
->setContent($response);
}
final protected function loadCommentByID($id) {
$query = $this->newInlineCommentQuery()
->withIDs(array($id));
return $this->loadCommentByQuery($query);
}
final protected function loadCommentByPHID($phid) {
$query = $this->newInlineCommentQuery()
->withPHIDs(array($phid));
return $this->loadCommentByQuery($query);
}
final protected function loadCommentByIDForEdit($id) {
$viewer = $this->getViewer();
$query = $this->newInlineCommentQuery()
->withIDs(array($id))
->needInlineContext(true);
$inline = $this->loadCommentByQuery($query);
if (!$inline) {
throw new Exception(
pht(
'Unable to load inline "%s".',
$id));
}
if (!$this->canEditInlineComment($viewer, $inline)) {
throw new Exception(
pht(
'Inline comment "%s" is not editable.',
$id));
}
return $inline;
}
private function loadCommentByQuery(
PhabricatorDiffInlineCommentQuery $query) {
$viewer = $this->getViewer();
$inline = $query
->setViewer($viewer)
->executeOne();
if ($inline) {
$inline = $inline->newInlineCommentObject();
}
return $inline;
}
private function hasContentState() {
$request = $this->getRequest();
return (bool)$request->getBool('hasContentState');
}
private function newRequestContentState($inline) {
$request = $this->getRequest();
return $inline->newContentStateFromRequest($request);
}
private function updateCommentContentState(PhabricatorInlineComment $inline) {
if (!$this->hasContentState()) {
throw new Exception(
pht(
'Attempting to update comment content state, but request has no '.
'content state.'));
}
$state = $this->newRequestContentState($inline);
$inline->setContentState($state);
}
private function saveComment(PhabricatorInlineComment $inline) {
$viewer = $this->getViewer();
$draft_engine = $this->newDraftEngine();
$inline->openTransaction();
$inline->save();
PhabricatorVersionedDraft::purgeDrafts(
$inline->getPHID(),
$viewer->getPHID());
if ($draft_engine) {
$draft_engine->synchronize();
}
$inline->saveTransaction();
}
private function newDraftEngine() {
$viewer = $this->getViewer();
$object = $this->getContainerObject();
if (!($object instanceof PhabricatorDraftInterface)) {
return null;
}
return $object->newDraftEngine()
->setObject($object)
->setViewer($viewer);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/PhabricatorDifferenceEngine.php | src/infrastructure/diff/PhabricatorDifferenceEngine.php | <?php
/**
* Utility class which encapsulates some shared behavior between different
* applications which render diffs.
*
* @task config Configuring the Engine
* @task diff Generating Diffs
*/
final class PhabricatorDifferenceEngine extends Phobject {
private $oldName;
private $newName;
private $normalize;
/* -( Configuring the Engine )--------------------------------------------- */
/**
* Set the name to identify the old file with. Primarily cosmetic.
*
* @param string Old file name.
* @return this
* @task config
*/
public function setOldName($old_name) {
$this->oldName = $old_name;
return $this;
}
/**
* Set the name to identify the new file with. Primarily cosmetic.
*
* @param string New file name.
* @return this
* @task config
*/
public function setNewName($new_name) {
$this->newName = $new_name;
return $this;
}
public function setNormalize($normalize) {
$this->normalize = $normalize;
return $this;
}
public function getNormalize() {
return $this->normalize;
}
/* -( Generating Diffs )--------------------------------------------------- */
/**
* Generate a raw diff from two raw files. This is a lower-level API than
* @{method:generateChangesetFromFileContent}, but may be useful if you need
* to use a custom parser configuration, as with Diffusion.
*
* @param string Entire previous file content.
* @param string Entire current file content.
* @return string Raw diff between the two files.
* @task diff
*/
public function generateRawDiffFromFileContent($old, $new) {
$options = array();
// Generate diffs with full context.
$options[] = '-U65535';
$old_name = nonempty($this->oldName, '/dev/universe').' 9999-99-99';
$new_name = nonempty($this->newName, '/dev/universe').' 9999-99-99';
$options[] = '-L';
$options[] = $old_name;
$options[] = '-L';
$options[] = $new_name;
$normalize = $this->getNormalize();
if ($normalize) {
$old = $this->normalizeFile($old);
$new = $this->normalizeFile($new);
}
$old_tmp = new TempFile();
$new_tmp = new TempFile();
Filesystem::writeFile($old_tmp, $old);
Filesystem::writeFile($new_tmp, $new);
list($err, $diff) = exec_manual(
'diff %Ls %s %s',
$options,
$old_tmp,
$new_tmp);
if (!$err) {
// This indicates that the two files are the same. Build a synthetic,
// changeless diff so that we can still render the raw, unchanged file
// instead of being forced to just say "this file didn't change" since we
// don't have the content.
$entire_file = explode("\n", $old);
foreach ($entire_file as $k => $line) {
$entire_file[$k] = ' '.$line;
}
$len = count($entire_file);
$entire_file = implode("\n", $entire_file);
// TODO: If both files were identical but missing newlines, we probably
// get this wrong. Unclear if it ever matters.
// This is a bit hacky but the diff parser can handle it.
$diff = "--- {$old_name}\n".
"+++ {$new_name}\n".
"@@ -1,{$len} +1,{$len} @@\n".
$entire_file."\n";
}
return $diff;
}
/**
* Generate an @{class:DifferentialChangeset} from two raw files. This is
* principally useful because you can feed the output to
* @{class:DifferentialChangesetParser} in order to render it.
*
* @param string Entire previous file content.
* @param string Entire current file content.
* @return @{class:DifferentialChangeset} Synthetic changeset.
* @task diff
*/
public function generateChangesetFromFileContent($old, $new) {
$diff = $this->generateRawDiffFromFileContent($old, $new);
$changes = id(new ArcanistDiffParser())->parseDiff($diff);
$diff = DifferentialDiff::newEphemeralFromRawChanges(
$changes);
return head($diff->getChangesets());
}
private function normalizeFile($corpus) {
// We can freely apply any other transformations we want to here: we have
// no constraints on what we need to preserve. If we normalize every line
// to "cat", the diff will still work, the alignment of the "-" / "+"
// lines will just be very hard to read.
// In general, we'll make the diff better if we normalize two lines that
// humans think are the same.
// We'll make the diff worse if we normalize two lines that humans think
// are different.
// Strip all whitespace present anywhere in the diff, since humans never
// consider whitespace changes to alter the line into a "different line"
// even when they're semantic (e.g., in a string constant). This covers
// indentation changes, trailing whitepspace, and formatting changes
// like "+/-".
$corpus = preg_replace('/[ \t]/', '', $corpus);
return $corpus;
}
public static function applyIntralineDiff($str, $intra_stack) {
$buf = '';
$p = $s = $e = 0; // position, start, end
$highlight = $tag = $ent = false;
$highlight_o = '<span class="bright">';
$highlight_c = '</span>';
$depth_in = '<span class="depth-in">';
$depth_out = '<span class="depth-out">';
$is_html = false;
if ($str instanceof PhutilSafeHTML) {
$is_html = true;
$str = $str->getHTMLContent();
}
$n = strlen($str);
for ($i = 0; $i < $n; $i++) {
if ($p == $e) {
do {
if (empty($intra_stack)) {
$buf .= substr($str, $i);
break 2;
}
$stack = array_shift($intra_stack);
$s = $e;
$e += $stack[1];
} while ($stack[0] === 0);
switch ($stack[0]) {
case '>':
$open_tag = $depth_in;
break;
case '<':
$open_tag = $depth_out;
break;
default:
$open_tag = $highlight_o;
break;
}
}
if (!$highlight && !$tag && !$ent && $p == $s) {
$buf .= $open_tag;
$highlight = true;
}
if ($str[$i] == '<') {
$tag = true;
if ($highlight) {
$buf .= $highlight_c;
}
}
if (!$tag) {
if ($str[$i] == '&') {
$ent = true;
}
if ($ent && $str[$i] == ';') {
$ent = false;
}
if (!$ent) {
$p++;
}
}
$buf .= $str[$i];
if ($tag && $str[$i] == '>') {
$tag = false;
if ($highlight) {
$buf .= $open_tag;
}
}
if ($highlight && ($p == $e || $i == $n - 1)) {
$buf .= $highlight_c;
$highlight = false;
}
}
if ($is_html) {
return phutil_safe_html($buf);
}
return $buf;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/PhabricatorDiffScopeEngine.php | src/infrastructure/diff/PhabricatorDiffScopeEngine.php | <?php
final class PhabricatorDiffScopeEngine
extends Phobject {
private $lineTextMap;
private $lineDepthMap;
public function setLineTextMap(array $map) {
if (array_key_exists(0, $map)) {
throw new Exception(
pht('ScopeEngine text map must be a 1-based map of lines.'));
}
$expect = 1;
foreach ($map as $key => $value) {
if ($key === $expect) {
$expect++;
continue;
}
throw new Exception(
pht(
'ScopeEngine text map must be a contiguous map of '.
'lines, but is not: found key "%s" where key "%s" was expected.',
$key,
$expect));
}
$this->lineTextMap = $map;
return $this;
}
public function getLineTextMap() {
if ($this->lineTextMap === null) {
throw new PhutilInvalidStateException('setLineTextMap');
}
return $this->lineTextMap;
}
public function getScopeStart($line) {
$text_map = $this->getLineTextMap();
$depth_map = $this->getLineDepthMap();
$length = count($text_map);
// Figure out the effective depth of the line we're getting scope for.
// If the line is just whitespace, it may have no depth on its own. In
// this case, we look for the next line.
$line_depth = null;
for ($ii = $line; $ii <= $length; $ii++) {
if ($depth_map[$ii] !== null) {
$line_depth = $depth_map[$ii];
break;
}
}
// If we can't find a line depth for the target line, just bail.
if ($line_depth === null) {
return null;
}
// Limit the maximum number of lines we'll examine. If a user has a
// million-line diff of nonsense, scanning the whole thing is a waste
// of time.
$search_range = 1000;
$search_until = max(0, $ii - $search_range);
for ($ii = $line - 1; $ii > $search_until; $ii--) {
$line_text = $text_map[$ii];
// This line is in missing context: the diff was diffed with partial
// context, and we ran out of context before finding a good scope line.
// Bail out, we don't want to jump across missing context blocks.
if ($line_text === null) {
return null;
}
$depth = $depth_map[$ii];
// This line is all whitespace. This isn't a possible match.
if ($depth === null) {
continue;
}
// Don't match context lines which are too deeply indented, since they
// are very unlikely to be symbol definitions.
if ($depth > 2) {
continue;
}
// The depth is the same as (or greater than) the depth we started with,
// so this isn't a possible match.
if ($depth >= $line_depth) {
continue;
}
// Reject lines which begin with "}" or "{". These lines are probably
// never good matches.
if (preg_match('/^\s*[{}]/i', $line_text)) {
continue;
}
return $ii;
}
return null;
}
private function getLineDepthMap() {
if (!$this->lineDepthMap) {
$this->lineDepthMap = $this->newLineDepthMap();
}
return $this->lineDepthMap;
}
private function getTabWidth() {
// TODO: This should be configurable once we handle tab widths better.
return 2;
}
private function newLineDepthMap() {
$text_map = $this->getLineTextMap();
$tab_width = $this->getTabWidth();
$depth_map = array();
foreach ($text_map as $line_number => $line_text) {
if ($line_text === null) {
$depth_map[$line_number] = null;
continue;
}
$len = strlen($line_text);
// If the line has no actual text, don't assign it a depth.
if (!$len || !strlen(trim($line_text))) {
$depth_map[$line_number] = null;
continue;
}
$count = 0;
for ($ii = 0; $ii < $len; $ii++) {
$c = $line_text[$ii];
if ($c == ' ') {
$count++;
} else if ($c == "\t") {
$count += $tab_width;
} else {
break;
}
}
// Round down to cheat our way through the " *" parts of docblock
// comments.
$depth = (int)floor($count / $tab_width);
$depth_map[$line_number] = $depth;
}
return $depth_map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/PhabricatorChangesetResponse.php | src/infrastructure/diff/PhabricatorChangesetResponse.php | <?php
final class PhabricatorChangesetResponse extends AphrontProxyResponse {
private $renderedChangeset;
private $coverage;
private $changesetState;
public function setRenderedChangeset($rendered_changeset) {
$this->renderedChangeset = $rendered_changeset;
return $this;
}
public function getRenderedChangeset() {
return $this->renderedChangeset;
}
public function setCoverage($coverage) {
$this->coverage = $coverage;
return $this;
}
protected function buildProxy() {
return new AphrontAjaxResponse();
}
public function reduceProxyResponse() {
$content = array(
'changeset' => $this->getRenderedChangeset(),
) + $this->getChangesetState();
if ($this->coverage) {
$content['coverage'] = $this->coverage;
}
return $this->getProxy()->setContent($content);
}
public function setChangesetState(array $state) {
$this->changesetState = $state;
return $this;
}
public function getChangesetState() {
return $this->changesetState;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/query/PhabricatorDiffInlineCommentQuery.php | src/infrastructure/diff/query/PhabricatorDiffInlineCommentQuery.php | <?php
abstract class PhabricatorDiffInlineCommentQuery
extends PhabricatorApplicationTransactionCommentQuery {
const INLINE_CONTEXT_CACHE_VERSION = 1;
private $fixedStates;
private $needReplyToComments;
private $publishedComments;
private $publishableComments;
private $needHidden;
private $needAppliedDrafts;
private $needInlineContext;
abstract protected function buildInlineCommentWhereClauseParts(
AphrontDatabaseConnection $conn);
abstract public function withObjectPHIDs(array $phids);
abstract protected function loadHiddenCommentIDs(
$viewer_phid,
array $comments);
abstract protected function newInlineContextMap(array $inlines);
abstract protected function newInlineContextFromCacheData(array $map);
final public function withFixedStates(array $states) {
$this->fixedStates = $states;
return $this;
}
final public function needReplyToComments($need_reply_to) {
$this->needReplyToComments = $need_reply_to;
return $this;
}
final public function withPublishableComments($with_publishable) {
$this->publishableComments = $with_publishable;
return $this;
}
final public function withPublishedComments($with_published) {
$this->publishedComments = $with_published;
return $this;
}
final public function needHidden($need_hidden) {
$this->needHidden = $need_hidden;
return $this;
}
final public function needInlineContext($need_context) {
$this->needInlineContext = $need_context;
return $this;
}
final public function needAppliedDrafts($need_applied) {
$this->needAppliedDrafts = $need_applied;
return $this;
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
$alias = $this->getPrimaryTableAlias();
foreach ($this->buildInlineCommentWhereClauseParts($conn) as $part) {
$where[] = $part;
}
if ($this->fixedStates !== null) {
$where[] = qsprintf(
$conn,
'%T.fixedState IN (%Ls)',
$alias,
$this->fixedStates);
}
$show_published = false;
$show_publishable = false;
if ($this->publishableComments !== null) {
if (!$this->publishableComments) {
throw new Exception(
pht(
'Querying for comments that are "not publishable" is '.
'not supported.'));
}
$show_publishable = true;
}
if ($this->publishedComments !== null) {
if (!$this->publishedComments) {
throw new Exception(
pht(
'Querying for comments that are "not published" is '.
'not supported.'));
}
$show_published = true;
}
if ($show_publishable || $show_published) {
$clauses = array();
if ($show_published) {
$clauses[] = qsprintf(
$conn,
'%T.transactionPHID IS NOT NULL',
$alias);
}
if ($show_publishable) {
$viewer = $this->getViewer();
$viewer_phid = $viewer->getPHID();
// If the viewer has a PHID, unpublished comments they authored and
// have not deleted are visible.
if ($viewer_phid) {
$clauses[] = qsprintf(
$conn,
'%T.authorPHID = %s
AND %T.isDeleted = 0
AND %T.transactionPHID IS NULL ',
$alias,
$viewer_phid,
$alias,
$alias);
}
}
// We can end up with a known-empty query if we (for example) query for
// publishable comments and the viewer is logged-out.
if (!$clauses) {
throw new PhabricatorEmptyQueryException();
}
$where[] = qsprintf(
$conn,
'%LO',
$clauses);
}
return $where;
}
protected function willFilterPage(array $inlines) {
$viewer = $this->getViewer();
if ($this->needReplyToComments) {
$reply_phids = array();
foreach ($inlines as $inline) {
$reply_phid = $inline->getReplyToCommentPHID();
if ($reply_phid) {
$reply_phids[] = $reply_phid;
}
}
if ($reply_phids) {
$reply_inlines = newv(get_class($this), array())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($reply_phids)
->execute();
$reply_inlines = mpull($reply_inlines, null, 'getPHID');
} else {
$reply_inlines = array();
}
foreach ($inlines as $key => $inline) {
$reply_phid = $inline->getReplyToCommentPHID();
if (!$reply_phid) {
$inline->attachReplyToComment(null);
continue;
}
$reply = idx($reply_inlines, $reply_phid);
if (!$reply) {
$this->didRejectResult($inline);
unset($inlines[$key]);
continue;
}
$inline->attachReplyToComment($reply);
}
}
if (!$inlines) {
return $inlines;
}
$need_drafts = $this->needAppliedDrafts;
$drop_void = $this->publishableComments;
$convert_objects = ($need_drafts || $drop_void);
if ($convert_objects) {
$inlines = mpull($inlines, 'newInlineCommentObject');
PhabricatorInlineComment::loadAndAttachVersionedDrafts(
$viewer,
$inlines);
if ($need_drafts) {
// Don't count void inlines when considering draft state.
foreach ($inlines as $key => $inline) {
if ($inline->isVoidComment($viewer)) {
$this->didRejectResult($inline->getStorageObject());
unset($inlines[$key]);
continue;
}
// For other inlines: if they have a nonempty draft state, set their
// content to the draft state content. We want to submit the comment
// as it is currently shown to the user, not as it was stored the last
// time they clicked "Save".
$draft_state = $inline->getContentStateForEdit($viewer);
if (!$draft_state->isEmptyContentState()) {
$inline->setContentState($draft_state);
}
}
}
// If we're loading publishable comments, discard any comments that are
// empty.
if ($drop_void) {
foreach ($inlines as $key => $inline) {
if ($inline->getTransactionPHID()) {
continue;
}
if ($inline->isVoidComment($viewer)) {
$this->didRejectResult($inline->getStorageObject());
unset($inlines[$key]);
continue;
}
}
}
$inlines = mpull($inlines, 'getStorageObject');
}
return $inlines;
}
protected function didFilterPage(array $inlines) {
$viewer = $this->getViewer();
if ($this->needHidden) {
$viewer_phid = $viewer->getPHID();
if ($viewer_phid) {
$hidden = $this->loadHiddenCommentIDs(
$viewer_phid,
$inlines);
} else {
$hidden = array();
}
foreach ($inlines as $inline) {
$inline->attachIsHidden(isset($hidden[$inline->getID()]));
}
}
if ($this->needInlineContext) {
$need_context = array();
foreach ($inlines as $inline) {
$object = $inline->newInlineCommentObject();
if ($object->getDocumentEngineKey() !== null) {
$inline->attachInlineContext(null);
continue;
}
$need_context[] = $inline;
}
if ($need_context) {
$this->loadInlineCommentContext($need_context);
}
}
return $inlines;
}
private function loadInlineCommentContext(array $inlines) {
$cache_keys = array();
foreach ($inlines as $key => $inline) {
$object = $inline->newInlineCommentObject();
$fragment = $object->getInlineCommentCacheFragment();
if ($fragment === null) {
continue;
}
$cache_keys[$key] = sprintf(
'%s.context(v%d)',
$fragment,
self::INLINE_CONTEXT_CACHE_VERSION);
}
$cache = PhabricatorCaches::getMutableStructureCache();
$cache_map = $cache->getKeys($cache_keys);
$context_map = array();
$need_construct = array();
foreach ($inlines as $key => $inline) {
$cache_key = idx($cache_keys, $key);
if ($cache_key !== null) {
if (array_key_exists($cache_key, $cache_map)) {
$cache_data = $cache_map[$cache_key];
$context_map[$key] = $this->newInlineContextFromCacheData(
$cache_data);
continue;
}
}
$need_construct[$key] = $inline;
}
if ($need_construct) {
$construct_map = $this->newInlineContextMap($need_construct);
$write_map = array();
foreach ($construct_map as $key => $context) {
if ($context === null) {
$cache_data = $context;
} else {
$cache_data = $this->newCacheDataFromInlineContext($context);
}
$cache_key = idx($cache_keys, $key);
if ($cache_key !== null) {
$write_map[$cache_key] = $cache_data;
}
}
if ($write_map) {
$cache->setKeys($write_map);
}
$context_map += $construct_map;
}
foreach ($inlines as $key => $inline) {
$inline->attachInlineContext(idx($context_map, $key));
}
}
protected function newCacheDataFromInlineContext(
PhabricatorInlineCommentContext $context) {
return $context->newCacheDataMap();
}
final protected function simplifyContext(array $lines, $is_head) {
// We want to provide the smallest amount of context we can while still
// being useful, since the actual code is visible nearby and showing a
// ton of context is silly.
// Examine each line until we find one that looks "useful" (not just
// whitespace or a single bracket). Once we find a useful piece of context
// to anchor the text, discard the rest of the lines beyond it.
if ($is_head) {
$lines = array_reverse($lines, true);
}
$saw_context = false;
foreach ($lines as $key => $line) {
if ($saw_context) {
unset($lines[$key]);
continue;
}
$saw_context = (strlen(trim($line)) > 3);
}
if ($is_head) {
$lines = array_reverse($lines, true);
}
return $lines;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/interface/PhabricatorInlineComment.php | src/infrastructure/diff/interface/PhabricatorInlineComment.php | <?php
abstract class PhabricatorInlineComment
extends Phobject
implements
PhabricatorMarkupInterface {
const MARKUP_FIELD_BODY = 'markup:body';
const STATE_UNDONE = 'undone';
const STATE_DRAFT = 'draft';
const STATE_UNDRAFT = 'undraft';
const STATE_DONE = 'done';
private $storageObject;
private $syntheticAuthor;
private $isGhost;
private $versionedDrafts = array();
public function __clone() {
$this->storageObject = clone $this->storageObject;
}
final public static function loadAndAttachVersionedDrafts(
PhabricatorUser $viewer,
array $inlines) {
$viewer_phid = $viewer->getPHID();
if (!$viewer_phid) {
return;
}
$inlines = mpull($inlines, null, 'getPHID');
$load = array();
foreach ($inlines as $key => $inline) {
if (!$inline->getIsEditing()) {
continue;
}
if ($inline->getAuthorPHID() !== $viewer_phid) {
continue;
}
$load[$key] = $inline;
}
if (!$load) {
return;
}
$drafts = PhabricatorVersionedDraft::loadDrafts(
array_keys($load),
$viewer_phid);
$drafts = mpull($drafts, null, 'getObjectPHID');
foreach ($inlines as $inline) {
$draft = idx($drafts, $inline->getPHID());
$inline->attachVersionedDraftForViewer($viewer, $draft);
}
}
public function setSyntheticAuthor($synthetic_author) {
$this->syntheticAuthor = $synthetic_author;
return $this;
}
public function getSyntheticAuthor() {
return $this->syntheticAuthor;
}
public function setStorageObject($storage_object) {
$this->storageObject = $storage_object;
return $this;
}
public function getStorageObject() {
if (!$this->storageObject) {
$this->storageObject = $this->newStorageObject();
}
return $this->storageObject;
}
public function getInlineCommentCacheFragment() {
$phid = $this->getPHID();
if ($phid === null) {
return null;
}
return sprintf('inline(%s)', $phid);
}
abstract protected function newStorageObject();
abstract public function getControllerURI();
abstract public function setChangesetID($id);
abstract public function getChangesetID();
abstract public function supportsHiding();
abstract public function isHidden();
public function isDraft() {
return !$this->getTransactionPHID();
}
public function getTransactionPHID() {
return $this->getStorageObject()->getTransactionPHID();
}
public function isCompatible(PhabricatorInlineComment $comment) {
return
($this->getAuthorPHID() === $comment->getAuthorPHID()) &&
($this->getSyntheticAuthor() === $comment->getSyntheticAuthor()) &&
($this->getContent() === $comment->getContent());
}
public function setIsGhost($is_ghost) {
$this->isGhost = $is_ghost;
return $this;
}
public function getIsGhost() {
return $this->isGhost;
}
public function setContent($content) {
$this->getStorageObject()->setContent($content);
return $this;
}
public function getContent() {
return $this->getStorageObject()->getContent();
}
public function getID() {
return $this->getStorageObject()->getID();
}
public function getPHID() {
return $this->getStorageObject()->getPHID();
}
public function setIsNewFile($is_new) {
$this->getStorageObject()->setIsNewFile($is_new);
return $this;
}
public function getIsNewFile() {
return $this->getStorageObject()->getIsNewFile();
}
public function setFixedState($state) {
$this->getStorageObject()->setFixedState($state);
return $this;
}
public function setHasReplies($has_replies) {
$this->getStorageObject()->setHasReplies($has_replies);
return $this;
}
public function getHasReplies() {
return $this->getStorageObject()->getHasReplies();
}
public function getFixedState() {
return $this->getStorageObject()->getFixedState();
}
public function setLineNumber($number) {
$this->getStorageObject()->setLineNumber($number);
return $this;
}
public function getLineNumber() {
return $this->getStorageObject()->getLineNumber();
}
public function setLineLength($length) {
$this->getStorageObject()->setLineLength($length);
return $this;
}
public function getLineLength() {
return $this->getStorageObject()->getLineLength();
}
public function setAuthorPHID($phid) {
$this->getStorageObject()->setAuthorPHID($phid);
return $this;
}
public function getAuthorPHID() {
return $this->getStorageObject()->getAuthorPHID();
}
public function setReplyToCommentPHID($phid) {
$this->getStorageObject()->setReplyToCommentPHID($phid);
return $this;
}
public function getReplyToCommentPHID() {
return $this->getStorageObject()->getReplyToCommentPHID();
}
public function setIsDeleted($is_deleted) {
$this->getStorageObject()->setIsDeleted($is_deleted);
return $this;
}
public function getIsDeleted() {
return $this->getStorageObject()->getIsDeleted();
}
public function setIsEditing($is_editing) {
$this->getStorageObject()->setAttribute('editing', (bool)$is_editing);
return $this;
}
public function getIsEditing() {
return (bool)$this->getStorageObject()->getAttribute('editing', false);
}
public function setDocumentEngineKey($engine_key) {
$this->getStorageObject()->setAttribute('documentEngineKey', $engine_key);
return $this;
}
public function getDocumentEngineKey() {
return $this->getStorageObject()->getAttribute('documentEngineKey');
}
public function setStartOffset($offset) {
$this->getStorageObject()->setAttribute('startOffset', $offset);
return $this;
}
public function getStartOffset() {
return $this->getStorageObject()->getAttribute('startOffset');
}
public function setEndOffset($offset) {
$this->getStorageObject()->setAttribute('endOffset', $offset);
return $this;
}
public function getEndOffset() {
return $this->getStorageObject()->getAttribute('endOffset');
}
public function getDateModified() {
return $this->getStorageObject()->getDateModified();
}
public function getDateCreated() {
return $this->getStorageObject()->getDateCreated();
}
public function openTransaction() {
$this->getStorageObject()->openTransaction();
}
public function saveTransaction() {
$this->getStorageObject()->saveTransaction();
}
public function save() {
$this->getTransactionCommentForSave()->save();
return $this;
}
public function delete() {
$this->getStorageObject()->delete();
return $this;
}
public function makeEphemeral() {
$this->getStorageObject()->makeEphemeral();
return $this;
}
public function attachVersionedDraftForViewer(
PhabricatorUser $viewer,
PhabricatorVersionedDraft $draft = null) {
$key = $viewer->getCacheFragment();
$this->versionedDrafts[$key] = $draft;
return $this;
}
public function hasVersionedDraftForViewer(PhabricatorUser $viewer) {
$key = $viewer->getCacheFragment();
return array_key_exists($key, $this->versionedDrafts);
}
public function getVersionedDraftForViewer(PhabricatorUser $viewer) {
$key = $viewer->getCacheFragment();
if (!array_key_exists($key, $this->versionedDrafts)) {
throw new Exception(
pht(
'Versioned draft is not attached for user with fragment "%s".',
$key));
}
return $this->versionedDrafts[$key];
}
public function isVoidComment(PhabricatorUser $viewer) {
return $this->getContentStateForEdit($viewer)->isEmptyContentState();
}
public function getContentStateForEdit(PhabricatorUser $viewer) {
$state = $this->getContentState();
if ($this->hasVersionedDraftForViewer($viewer)) {
$versioned_draft = $this->getVersionedDraftForViewer($viewer);
if ($versioned_draft) {
$storage_map = $versioned_draft->getProperty('inline.state');
if (is_array($storage_map)) {
$state->readStorageMap($storage_map);
}
}
}
return $state;
}
protected function newContentState() {
return new PhabricatorDiffInlineCommentContentState();
}
public function newContentStateFromRequest(AphrontRequest $request) {
return $this->newContentState()->readFromRequest($request);
}
public function getInitialContentState() {
return $this->getNamedContentState('inline.state.initial');
}
public function setInitialContentState(
PhabricatorInlineCommentContentState $state) {
return $this->setNamedContentState('inline.state.initial', $state);
}
public function getCommittedContentState() {
return $this->getNamedContentState('inline.state.committed');
}
public function setCommittedContentState(
PhabricatorInlineCommentContentState $state) {
return $this->setNamedContentState('inline.state.committed', $state);
}
public function getContentState() {
$state = $this->getNamedContentState('inline.state');
if (!$state) {
$state = $this->newContentState();
}
$state->setContentText($this->getContent());
return $state;
}
public function setContentState(PhabricatorInlineCommentContentState $state) {
$this->setContent($state->getContentText());
return $this->setNamedContentState('inline.state', $state);
}
private function getNamedContentState($key) {
$storage = $this->getStorageObject();
$storage_map = $storage->getAttribute($key);
if (!is_array($storage_map)) {
return null;
}
$state = $this->newContentState();
$state->readStorageMap($storage_map);
return $state;
}
private function setNamedContentState(
$key,
PhabricatorInlineCommentContentState $state) {
$storage = $this->getStorageObject();
$storage_map = $state->newStorageMap();
$storage->setAttribute($key, $storage_map);
return $this;
}
public function getInlineContext() {
return $this->getStorageObject()->getInlineContext();
}
public function getContentStateMapForEdit(PhabricatorUser $viewer) {
return $this->getWireContentStateMap(true, $viewer);
}
public function getContentStateMap() {
return $this->getWireContentStateMap(false, null);
}
private function getWireContentStateMap(
$is_edit,
PhabricatorUser $viewer = null) {
$initial_state = $this->getInitialContentState();
$committed_state = $this->getCommittedContentState();
if ($is_edit) {
$active_state = $this->getContentStateForEdit($viewer);
} else {
$active_state = $this->getContentState();
}
return array(
'initial' => $this->getWireContentState($initial_state),
'committed' => $this->getWireContentState($committed_state),
'active' => $this->getWireContentState($active_state),
);
}
private function getWireContentState($content_state) {
if ($content_state === null) {
return null;
}
return $content_state->newStorageMap();
}
public function getDefaultSuggestionText() {
$context = $this->getInlineContext();
if (!$context) {
return null;
}
$default = $context->getBodyLines();
$default = implode('', $default);
return $default;
}
/* -( PhabricatorMarkupInterface Implementation )-------------------------- */
public function getMarkupFieldKey($field) {
$content = $this->getMarkupText($field);
return PhabricatorMarkupEngine::digestRemarkupContent($this, $content);
}
public function newMarkupEngine($field) {
return PhabricatorMarkupEngine::newDifferentialMarkupEngine();
}
public function getMarkupText($field) {
return $this->getContent();
}
public function didMarkupText($field, $output, PhutilMarkupEngine $engine) {
return $output;
}
public function shouldUseMarkupCache($field) {
return !$this->isDraft();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/inline/PhabricatorDiffInlineCommentContentState.php | src/infrastructure/diff/inline/PhabricatorDiffInlineCommentContentState.php | <?php
final class PhabricatorDiffInlineCommentContentState
extends PhabricatorInlineCommentContentState {
private $hasSuggestion = false;
private $suggestionText = '';
public function isEmptyContentState() {
if (!parent::isEmptyContentState()) {
return false;
}
if ($this->getContentHasSuggestion()) {
if (strlen($this->getContentSuggestionText())) {
return false;
}
}
return true;
}
public function setContentSuggestionText($suggestion_text) {
$this->suggestionText = $suggestion_text;
return $this;
}
public function getContentSuggestionText() {
return $this->suggestionText;
}
public function setContentHasSuggestion($has_suggestion) {
$this->hasSuggestion = $has_suggestion;
return $this;
}
public function getContentHasSuggestion() {
return $this->hasSuggestion;
}
public function newStorageMap() {
return parent::writeStorageMap() + array(
'hasSuggestion' => $this->getContentHasSuggestion(),
'suggestionText' => $this->getContentSuggestionText(),
);
}
public function readStorageMap(array $map) {
$result = parent::readStorageMap($map);
$has_suggestion = (bool)idx($map, 'hasSuggestion');
$this->setContentHasSuggestion($has_suggestion);
$suggestion_text = (string)idx($map, 'suggestionText');
$this->setContentSuggestionText($suggestion_text);
return $result;
}
protected function newStorageMapFromRequest(AphrontRequest $request) {
$map = parent::newStorageMapFromRequest($request);
$map['hasSuggestion'] = (bool)$request->getBool('hasSuggestion');
$map['suggestionText'] = (string)$request->getStr('suggestionText');
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/inline/PhabricatorInlineCommentContentState.php | src/infrastructure/diff/inline/PhabricatorInlineCommentContentState.php | <?php
abstract class PhabricatorInlineCommentContentState
extends Phobject {
private $contentText = '';
public function setContentText($content_text) {
$this->contentText = $content_text;
return $this;
}
public function getContentText() {
return $this->contentText;
}
public function isEmptyContentState() {
return !strlen($this->getContentText());
}
public function writeStorageMap() {
return array(
'text' => $this->getContentText(),
);
}
public function readStorageMap(array $map) {
$text = (string)idx($map, 'text');
$this->setContentText($text);
return $this;
}
final public function readFromRequest(AphrontRequest $request) {
$map = $this->newStorageMapFromRequest($request);
return $this->readStorageMap($map);
}
protected function newStorageMapFromRequest(AphrontRequest $request) {
$map = array();
$map['text'] = (string)$request->getStr('text');
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/inline/PhabricatorInlineCommentContext.php | src/infrastructure/diff/inline/PhabricatorInlineCommentContext.php | <?php
abstract class PhabricatorInlineCommentContext
extends Phobject {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/inline/PhabricatorDiffInlineCommentContext.php | src/infrastructure/diff/inline/PhabricatorDiffInlineCommentContext.php | <?php
final class PhabricatorDiffInlineCommentContext
extends PhabricatorInlineCommentContext {
private $filename;
private $headLines;
private $bodyLines;
private $tailLines;
public static function newFromCacheData(array $map) {
$context = new self();
$context->setFilename(idx($map, 'filename'));
$context->setHeadLines(idx($map, 'headLines'));
$context->setBodyLines(idx($map, 'bodyLines'));
$context->setTailLines(idx($map, 'tailLines'));
return $context;
}
public function newCacheDataMap() {
return array(
'filename' => $this->getFilename(),
'headLines' => $this->getHeadLines(),
'bodyLines' => $this->getBodyLines(),
'tailLines' => $this->getTailLines(),
);
}
public function setFilename($filename) {
$this->filename = $filename;
return $this;
}
public function getFilename() {
return $this->filename;
}
public function setHeadLines(array $head_lines) {
$this->headLines = $head_lines;
return $this;
}
public function getHeadLines() {
return $this->headLines;
}
public function setBodyLines(array $body_lines) {
$this->bodyLines = $body_lines;
return $this;
}
public function getBodyLines() {
return $this->bodyLines;
}
public function setTailLines(array $tail_lines) {
$this->tailLines = $tail_lines;
return $this;
}
public function getTailLines() {
return $this->tailLines;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/__tests__/PhabricatorDiffScopeEngineTestCase.php | src/infrastructure/diff/__tests__/PhabricatorDiffScopeEngineTestCase.php | <?php
final class PhabricatorDiffScopeEngineTestCase
extends PhabricatorTestCase {
private $engines = array();
public function testScopeEngine() {
$this->assertScopeStart('zebra.c', 4, 2);
}
private function assertScopeStart($file, $line, $expect) {
$engine = $this->getScopeTestEngine($file);
$actual = $engine->getScopeStart($line);
$this->assertEqual(
$expect,
$actual,
pht(
'Expect scope for line %s to start on line %s (actual: %s) in "%s".',
$line,
$expect,
$actual,
$file));
}
private function getScopeTestEngine($file) {
if (!isset($this->engines[$file])) {
$this->engines[$file] = $this->newScopeTestEngine($file);
}
return $this->engines[$file];
}
private function newScopeTestEngine($file) {
$path = dirname(__FILE__).'/data/'.$file;
$data = Filesystem::readFile($path);
$lines = phutil_split_lines($data);
$map = array();
foreach ($lines as $key => $line) {
$map[$key + 1] = $line;
}
$engine = id(new PhabricatorDiffScopeEngine())
->setLineTextMap($map);
return $engine;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffTableOfContentsItemView.php | src/infrastructure/diff/view/PHUIDiffTableOfContentsItemView.php | <?php
final class PHUIDiffTableOfContentsItemView extends AphrontView {
private $changeset;
private $isVisible = true;
private $anchor;
private $coverage;
private $coverageID;
private $context;
private $packages;
public function setChangeset(DifferentialChangeset $changeset) {
$this->changeset = $changeset;
return $this;
}
public function getChangeset() {
return $this->changeset;
}
public function setIsVisible($is_visible) {
$this->isVisible = $is_visible;
return $this;
}
public function getIsVisible() {
return $this->isVisible;
}
public function setAnchor($anchor) {
$this->anchor = $anchor;
return $this;
}
public function getAnchor() {
return $this->anchor;
}
public function setCoverage($coverage) {
$this->coverage = $coverage;
return $this;
}
public function getCoverage() {
return $this->coverage;
}
public function setCoverageID($coverage_id) {
$this->coverageID = $coverage_id;
return $this;
}
public function getCoverageID() {
return $this->coverageID;
}
public function setContext($context) {
$this->context = $context;
return $this;
}
public function getContext() {
return $this->context;
}
public function setPackages(array $packages) {
assert_instances_of($packages, 'PhabricatorOwnersPackage');
$this->packages = mpull($packages, null, 'getPHID');
return $this;
}
public function getPackages() {
return $this->packages;
}
public function render() {
$changeset = $this->getChangeset();
$cells = array();
$cells[] = $this->getContext();
$cells[] = $changeset->newFileTreeIcon();
$link = $this->renderChangesetLink();
$lines = $this->renderChangesetLines();
$meta = $this->renderChangesetMetadata();
$cells[] = array(
$link,
$lines,
$meta,
);
$cells[] = $this->renderCoverage();
$cells[] = $this->renderModifiedCoverage();
$cells[] = $this->renderPackages();
return $cells;
}
public function newLink() {
$anchor = $this->getAnchor();
$changeset = $this->getChangeset();
$name = $changeset->getDisplayFilename();
$name = basename($name);
return javelin_tag(
'a',
array(
'href' => '#'.$anchor,
'sigil' => 'differential-load',
'meta' => array(
'id' => 'diff-'.$anchor,
),
),
$name);
}
public function renderChangesetLines() {
$changeset = $this->getChangeset();
if ($changeset->getIsLowImportanceChangeset()) {
return null;
}
$line_count = $changeset->getAffectedLineCount();
if (!$line_count) {
return null;
}
return pht('%d line(s)', $line_count);
}
public function renderCoverage() {
$not_applicable = '-';
$coverage = $this->getCoverage();
if ($coverage === null || !strlen($coverage)) {
return $not_applicable;
}
$covered = substr_count($coverage, 'C');
$not_covered = substr_count($coverage, 'U');
if (!$not_covered && !$covered) {
return $not_applicable;
}
return sprintf('%d%%', 100 * ($covered / ($covered + $not_covered)));
}
public function renderModifiedCoverage() {
$not_applicable = '-';
$coverage = $this->getCoverage();
if ($coverage === null || !strlen($coverage)) {
return $not_applicable;
}
if ($this->getIsVisible()) {
$label = pht('Loading...');
} else {
$label = pht('?');
}
return phutil_tag(
'div',
array(
'id' => $this->getCoverageID(),
'class' => 'differential-mcoverage-loading',
),
$label);
}
private function renderChangesetMetadata() {
$changeset = $this->getChangeset();
$type = $changeset->getChangeType();
$meta = array();
if (DifferentialChangeType::isOldLocationChangeType($type)) {
$away = $changeset->getAwayPaths();
if (count($away) > 1) {
if ($type == DifferentialChangeType::TYPE_MULTICOPY) {
$meta[] = pht('Deleted after being copied to multiple locations:');
} else {
$meta[] = pht('Copied to multiple locations:');
}
foreach ($away as $path) {
$meta[] = $path;
}
} else {
if ($type == DifferentialChangeType::TYPE_MOVE_AWAY) {
// This case is handled when we render the path.
} else {
$meta[] = pht('Copied to %s', head($away));
}
}
} else if ($type == DifferentialChangeType::TYPE_COPY_HERE) {
$meta[] = pht('Copied from %s', $changeset->getOldFile());
}
if (!$meta) {
return null;
}
$meta = phutil_implode_html(phutil_tag('br'), $meta);
return phutil_tag(
'div',
array(
'class' => 'differential-toc-meta',
),
$meta);
}
public function renderPackages() {
$packages = $this->getPackages();
if (!$packages) {
return null;
}
$viewer = $this->getViewer();
$package_phids = mpull($packages, 'getPHID');
return $viewer->renderHandleList($package_phids)
->setGlyphLimit(48);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffInlineCommentDetailView.php | src/infrastructure/diff/view/PHUIDiffInlineCommentDetailView.php | <?php
final class PHUIDiffInlineCommentDetailView
extends PHUIDiffInlineCommentView {
private $handles;
private $markupEngine;
private $editable;
private $preview;
private $allowReply;
private $canMarkDone;
private $objectOwnerPHID;
public function isHidden() {
return $this->getInlineComment()->isHidden();
}
public function setHandles(array $handles) {
assert_instances_of($handles, 'PhabricatorObjectHandle');
$this->handles = $handles;
return $this;
}
public function setMarkupEngine(PhabricatorMarkupEngine $engine) {
$this->markupEngine = $engine;
return $this;
}
public function setEditable($editable) {
$this->editable = $editable;
return $this;
}
public function setPreview($preview) {
$this->preview = $preview;
return $this;
}
public function setAllowReply($allow_reply) {
$this->allowReply = $allow_reply;
return $this;
}
public function setCanMarkDone($can_mark_done) {
$this->canMarkDone = $can_mark_done;
return $this;
}
public function getCanMarkDone() {
return $this->canMarkDone;
}
public function setObjectOwnerPHID($phid) {
$this->objectOwnerPHID = $phid;
return $this;
}
public function getObjectOwnerPHID() {
return $this->objectOwnerPHID;
}
public function getAnchorName() {
$inline = $this->getInlineComment();
if ($inline->getID()) {
return 'inline-'.$inline->getID();
}
return null;
}
public function getScaffoldCellID() {
$anchor = $this->getAnchorName();
if ($anchor) {
return 'anchor-'.$anchor;
}
return null;
}
public function render() {
require_celerity_resource('phui-inline-comment-view-css');
$inline = $this->getInlineComment();
$is_synthetic = false;
if ($inline->getSyntheticAuthor()) {
$is_synthetic = true;
}
$is_preview = $this->preview;
$metadata = $this->getInlineCommentMetadata();
$classes = array(
'differential-inline-comment',
);
$sigil = 'differential-inline-comment';
if ($is_preview) {
$sigil = $sigil.' differential-inline-comment-preview';
$classes[] = 'inline-comment-preview';
} else {
$classes[] = 'inline-comment-element';
}
$handles = $this->handles;
$links = array();
$draft_text = null;
if (!$is_synthetic) {
// This display is controlled by CSS
$draft_text = id(new PHUITagView())
->setType(PHUITagView::TYPE_SHADE)
->setName(pht('Unsubmitted'))
->setSlimShady(true)
->setColor(PHUITagView::COLOR_RED)
->addClass('mml inline-draft-text');
}
$ghost_tag = null;
$ghost = $inline->getIsGhost();
$ghost_id = null;
if ($ghost) {
if ($ghost['new']) {
$ghosticon = 'fa-fast-forward';
$reason = pht('View on forward revision');
} else {
$ghosticon = 'fa-fast-backward';
$reason = pht('View on previous revision');
}
$ghost_icon = id(new PHUIIconView())
->setIcon($ghosticon)
->addSigil('has-tooltip')
->setMetadata(
array(
'tip' => $reason,
'size' => 300,
));
$ghost_tag = phutil_tag(
'a',
array(
'class' => 'ghost-icon',
'href' => $ghost['href'],
'target' => '_blank',
),
$ghost_icon);
$classes[] = 'inline-comment-ghost';
}
if ($inline->getReplyToCommentPHID()) {
$classes[] = 'inline-comment-is-reply';
}
$viewer_phid = $this->getUser()->getPHID();
$owner_phid = $this->getObjectOwnerPHID();
if ($viewer_phid) {
if ($viewer_phid == $owner_phid) {
$classes[] = 'viewer-is-object-owner';
}
}
$anchor_name = $this->getAnchorName();
$action_buttons = array();
$menu_items = array();
if ($this->editable && !$is_preview) {
$menu_items[] = array(
'label' => pht('Edit Comment'),
'icon' => 'fa-pencil',
'action' => 'edit',
'key' => 'e',
);
} else if ($is_preview) {
$links[] = javelin_tag(
'a',
array(
'class' => 'inline-button-divider pml msl',
'meta' => array(
'inlineCommentID' => $inline->getID(),
),
'sigil' => 'differential-inline-preview-jump',
),
pht('View'));
$action_buttons[] = id(new PHUIButtonView())
->setTag('a')
->setTooltip(pht('Delete'))
->setIcon('fa-trash-o')
->addSigil('differential-inline-delete')
->setMustCapture(true)
->setAuralLabel(pht('Delete'));
}
if (!$is_preview && $this->canHide()) {
$menu_items[] = array(
'label' => pht('Collapse'),
'icon' => 'fa-times',
'action' => 'collapse',
'key' => 'q',
);
}
$can_reply =
(!$this->editable) &&
(!$is_preview) &&
($this->allowReply) &&
// NOTE: No product reason why you can't reply to synthetic comments,
// but the reply mechanism currently sends the inline comment ID to the
// server, not file/line information, and synthetic comments don't have
// an inline comment ID.
(!$is_synthetic);
if ($can_reply) {
$menu_items[] = array(
'label' => pht('Reply to Comment'),
'icon' => 'fa-reply',
'action' => 'reply',
'key' => 'r',
);
$menu_items[] = array(
'label' => pht('Quote Comment'),
'icon' => 'fa-quote-left',
'action' => 'quote',
'key' => 'R',
);
}
if (!$is_preview) {
$xaction_phid = $inline->getTransactionPHID();
$storage = $inline->getStorageObject();
if ($xaction_phid) {
$menu_items[] = array(
'label' => pht('View Raw Remarkup'),
'icon' => 'fa-code',
'action' => 'raw',
'uri' => $storage->getRawRemarkupURI(),
);
}
}
if ($this->editable && !$is_preview) {
$menu_items[] = array(
'label' => pht('Delete Comment'),
'icon' => 'fa-trash-o',
'action' => 'delete',
);
}
$done_button = null;
$mark_done = $this->getCanMarkDone();
// Allow users to mark their own draft inlines as "Done".
if ($viewer_phid == $inline->getAuthorPHID()) {
if ($inline->isDraft()) {
$mark_done = true;
}
}
if (!$is_synthetic) {
$draft_state = false;
switch ($inline->getFixedState()) {
case PhabricatorInlineComment::STATE_DRAFT:
$is_done = $mark_done;
$draft_state = true;
break;
case PhabricatorInlineComment::STATE_UNDRAFT:
$is_done = !$mark_done;
$draft_state = true;
break;
case PhabricatorInlineComment::STATE_DONE:
$is_done = true;
break;
default:
case PhabricatorInlineComment::STATE_UNDONE:
$is_done = false;
break;
}
// If you don't have permission to mark the comment as "Done", you also
// can not see the draft state.
if (!$mark_done) {
$draft_state = false;
}
if ($is_done) {
$classes[] = 'inline-is-done';
}
if ($draft_state) {
$classes[] = 'inline-state-is-draft';
}
if ($mark_done && !$is_preview) {
$done_input = javelin_tag(
'input',
array(
'type' => 'checkbox',
'checked' => ($is_done ? 'checked' : null),
'class' => 'differential-inline-done',
'sigil' => 'differential-inline-done',
));
$done_button = phutil_tag(
'label',
array(
'class' => 'differential-inline-done-label ',
),
array(
$done_input,
pht('Done'),
));
} else {
if ($is_done) {
$icon = id(new PHUIIconView())->setIcon('fa-check sky msr');
$label = pht('Done');
$class = 'button-done';
} else {
$icon = null;
$label = pht('Not Done');
$class = 'button-not-done';
}
$done_button = phutil_tag(
'div',
array(
'class' => 'done-label '.$class,
),
array(
$icon,
$label,
));
}
}
$content = $this->markupEngine->getOutput(
$inline,
PhabricatorInlineComment::MARKUP_FIELD_BODY);
if ($is_preview) {
$anchor = null;
} else {
$anchor = phutil_tag(
'a',
array(
'name' => $anchor_name,
'id' => $anchor_name,
'class' => 'differential-inline-comment-anchor',
),
'');
}
if ($inline->isDraft() && !$is_synthetic) {
$classes[] = 'inline-state-is-draft';
}
if ($is_synthetic) {
$classes[] = 'differential-inline-comment-synthetic';
}
$classes = implode(' ', $classes);
$author_owner = null;
if ($is_synthetic) {
$author = $inline->getSyntheticAuthor();
} else {
$author = $handles[$inline->getAuthorPHID()]->getName();
if ($inline->getAuthorPHID() == $this->objectOwnerPHID) {
$author_owner = id(new PHUITagView())
->setType(PHUITagView::TYPE_SHADE)
->setName(pht('Author'))
->setSlimShady(true)
->setColor(PHUITagView::COLOR_YELLOW)
->addClass('mml');
}
}
$actions = null;
if ($action_buttons || $menu_items) {
$actions = new PHUIButtonBarView();
$actions->setBorderless(true);
$actions->addClass('inline-button-divider');
foreach ($action_buttons as $button) {
$actions->addButton($button);
}
if (!$is_preview) {
$menu_button = id(new PHUIButtonView())
->setTag('a')
->setColor(PHUIButtonView::GREY)
->setDropdown(true)
->setAuralLabel(pht('Inline Actions'))
->addSigil('inline-action-dropdown');
$actions->addButton($menu_button);
}
}
$group_left = phutil_tag(
'div',
array(
'class' => 'inline-head-left',
),
array(
$author,
$author_owner,
$draft_text,
$ghost_tag,
));
$group_right = phutil_tag(
'div',
array(
'class' => 'inline-head-right',
),
array(
$done_button,
$links,
$actions,
));
$snippet = id(new PhutilUTF8StringTruncator())
->setMaximumGlyphs(96)
->truncateString($inline->getContent());
$metadata['snippet'] = pht('%s: %s', $author, $snippet);
$metadata['menuItems'] = $menu_items;
$suggestion_content = $this->newSuggestionView($inline);
$inline_content = phutil_tag(
'div',
array(
'class' => 'phabricator-remarkup',
),
$content);
$markup = javelin_tag(
'div',
array(
'class' => $classes,
'sigil' => $sigil,
'meta' => $metadata,
),
array(
javelin_tag(
'div',
array(
'class' => 'differential-inline-comment-head grouped',
'sigil' => 'differential-inline-header',
),
array(
$group_left,
$group_right,
)),
phutil_tag(
'div',
array(
'class' => 'differential-inline-comment-content',
),
array(
$suggestion_content,
$inline_content,
)),
));
$summary = phutil_tag(
'div',
array(
'class' => 'differential-inline-summary',
),
array(
phutil_tag('strong', array(), pht('%s:', $author)),
' ',
$snippet,
));
return array(
$anchor,
$markup,
$summary,
);
}
private function canHide() {
$inline = $this->getInlineComment();
if ($inline->isDraft()) {
return false;
}
if (!$inline->getID()) {
return false;
}
$viewer = $this->getUser();
if (!$viewer->isLoggedIn()) {
return false;
}
if (!$inline->supportsHiding()) {
return false;
}
return true;
}
private function newSuggestionView(PhabricatorInlineComment $inline) {
$content_state = $inline->getContentState();
if (!$content_state->getContentHasSuggestion()) {
return null;
}
$context = $inline->getInlineContext();
if (!$context) {
return null;
}
$head_lines = $context->getHeadLines();
$head_lines = implode('', $head_lines);
$tail_lines = $context->getTailLines();
$tail_lines = implode('', $tail_lines);
$old_lines = $context->getBodyLines();
$old_lines = implode('', $old_lines);
$old_lines = $head_lines.$old_lines.$tail_lines;
if (strlen($old_lines) && !preg_match('/\n\z/', $old_lines)) {
$old_lines .= "\n";
}
$new_lines = $content_state->getContentSuggestionText();
$new_lines = $head_lines.$new_lines.$tail_lines;
if (strlen($new_lines) && !preg_match('/\n\z/', $new_lines)) {
$new_lines .= "\n";
}
if ($old_lines === $new_lines) {
return null;
}
$viewer = $this->getViewer();
$changeset = id(new PhabricatorDifferenceEngine())
->generateChangesetFromFileContent($old_lines, $new_lines);
$changeset->setFilename($context->getFilename());
$viewstate = new PhabricatorChangesetViewState();
$parser = id(new DifferentialChangesetParser())
->setViewer($viewer)
->setViewstate($viewstate)
->setChangeset($changeset);
$fragment = $inline->getInlineCommentCacheFragment();
if ($fragment !== null) {
$cache_key = sprintf(
'%s.suggestion-view(v1, %s)',
$fragment,
PhabricatorHash::digestForIndex($new_lines));
$parser->setRenderCacheKey($cache_key);
}
$renderer = new DifferentialChangesetOneUpRenderer();
$renderer->setSimpleMode(true);
$parser->setRenderer($renderer);
// See PHI1896. If a user leaves an inline on a very long range with
// suggestions at the beginning and end, we'll hide context in the middle
// by default. We don't want to do this in the context of an inline
// suggestion, so build a mask to force display of all lines.
// (We don't know exactly how many lines the diff has, we just know that
// it can't have more lines than the old file plus the new file, so we're
// using that as an upper bound.)
$min = 0;
$old_len = count(phutil_split_lines($old_lines));
$new_len = count(phutil_split_lines($new_lines));
$max = ($old_len + $new_len);
$mask = array_fill($min, ($max - $min), true);
$diff_view = $parser->render($min, ($max - $min), $mask);
$view = phutil_tag(
'div',
array(
'class' => 'inline-suggestion-view PhabricatorMonospaced',
),
$diff_view);
return $view;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffInlineThreader.php | src/infrastructure/diff/view/PHUIDiffInlineThreader.php | <?php
final class PHUIDiffInlineThreader extends Phobject {
public function reorderAndThreadCommments(array $comments) {
$comments = msort($comments, 'getID');
// Build an empty map of all the comments we actually have. If a comment
// is a reply but the parent has gone missing, we don't want it to vanish
// completely.
$comment_phids = mpull($comments, 'getPHID');
$replies = array_fill_keys($comment_phids, array());
// Now, remove all comments which are replies, leaving only the top-level
// comments.
foreach ($comments as $key => $comment) {
$reply_phid = $comment->getReplyToCommentPHID();
if (isset($replies[$reply_phid])) {
$replies[$reply_phid][] = $comment;
unset($comments[$key]);
}
}
// For each top level comment, add the comment, then add any replies
// to it. Do this recursively so threads are shown in threaded order.
$results = array();
foreach ($comments as $comment) {
$results[] = $comment;
$phid = $comment->getPHID();
$descendants = $this->getInlineReplies($replies, $phid, 1);
foreach ($descendants as $descendant) {
$results[] = $descendant;
}
}
// If we have anything left, they were cyclic references. Just dump
// them in a the end. This should be impossible, but users are very
// creative.
foreach ($replies as $phid => $comments) {
foreach ($comments as $comment) {
$results[] = $comment;
}
}
return $results;
}
private function getInlineReplies(array &$replies, $phid, $depth) {
$comments = idx($replies, $phid, array());
unset($replies[$phid]);
$results = array();
foreach ($comments as $comment) {
$results[] = $comment;
$descendants = $this->getInlineReplies(
$replies,
$comment->getPHID(),
$depth + 1);
foreach ($descendants as $descendant) {
$results[] = $descendant;
}
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffTableOfContentsListView.php | src/infrastructure/diff/view/PHUIDiffTableOfContentsListView.php | <?php
final class PHUIDiffTableOfContentsListView extends AphrontView {
private $items = array();
private $authorityPackages;
private $header;
private $infoView;
private $background;
private $bare;
private $components = array();
public function addItem(PHUIDiffTableOfContentsItemView $item) {
$this->items[] = $item;
return $this;
}
public function setAuthorityPackages(array $authority_packages) {
assert_instances_of($authority_packages, 'PhabricatorOwnersPackage');
$this->authorityPackages = $authority_packages;
return $this;
}
public function getAuthorityPackages() {
return $this->authorityPackages;
}
public function setBackground($background) {
$this->background = $background;
return $this;
}
public function setHeader(PHUIHeaderView $header) {
$this->header = $header;
return $this;
}
public function setInfoView(PHUIInfoView $infoview) {
$this->infoView = $infoview;
return $this;
}
public function setBare($bare) {
$this->bare = $bare;
return $this;
}
public function getBare() {
return $this->bare;
}
public function render() {
$this->requireResource('differential-core-view-css');
$this->requireResource('differential-table-of-contents-css');
Javelin::initBehavior('phabricator-tooltips');
if ($this->getAuthorityPackages()) {
$authority = mpull($this->getAuthorityPackages(), null, 'getPHID');
} else {
$authority = array();
}
$items = $this->items;
$viewer = $this->getViewer();
$item_map = array();
$vector_tree = new ArcanistDiffVectorTree();
foreach ($items as $item) {
$item->setViewer($viewer);
$changeset = $item->getChangeset();
$old_vector = $changeset->getOldStatePathVector();
$new_vector = $changeset->getNewStatePathVector();
$tree_vector = $this->newTreeVector($old_vector, $new_vector);
$item_map[implode("\n", $tree_vector)] = $item;
$vector_tree->addVector($tree_vector);
}
$node_list = $vector_tree->newDisplayList();
$node_map = array();
foreach ($node_list as $node) {
$path_vector = $node->getVector();
$path_vector = implode("\n", $path_vector);
$node_map[$path_vector] = $node;
}
// Mark all nodes which contain at least one path which exists in the new
// state. Nodes we don't mark contain only deleted or moved files, so they
// can be rendered with a less-prominent style.
foreach ($node_map as $node_key => $node) {
$item = idx($item_map, $node_key);
if (!$item) {
continue;
}
$changeset = $item->getChangeset();
if (!$changeset->getIsLowImportanceChangeset()) {
$node->setAncestralAttribute('important', true);
}
}
$any_packages = false;
$any_coverage = false;
$any_context = false;
$rows = array();
$rowc = array();
foreach ($node_map as $node_key => $node) {
$display_vector = $node->getDisplayVector();
$item = idx($item_map, $node_key);
if ($item) {
$changeset = $item->getChangeset();
$icon = $changeset->newFileTreeIcon();
} else {
$changeset = null;
$icon = id(new PHUIIconView())
->setIcon('fa-folder-open-o grey');
}
if ($node->getChildren()) {
$old_dir = true;
$new_dir = true;
} else {
// TODO: When properties are set on a directory in SVN directly, this
// might be incorrect.
$old_dir = false;
$new_dir = false;
}
$display_view = $this->newComponentView(
$icon,
$display_vector,
$old_dir,
$new_dir,
$item);
$depth = $node->getDisplayDepth();
$style = sprintf('padding-left: %dpx;', $depth * 16);
if ($item) {
$packages = $item->renderPackages();
} else {
$packages = null;
}
if ($packages) {
$any_packages = true;
}
if ($item) {
if ($item->getCoverage()) {
$any_coverage = true;
}
$coverage = $item->renderCoverage();
$modified_coverage = $item->renderModifiedCoverage();
} else {
$coverage = null;
$modified_coverage = null;
}
if ($item) {
$context = $item->getContext();
if ($context) {
$any_context = true;
}
} else {
$context = null;
}
if ($item) {
$lines = $item->renderChangesetLines();
} else {
$lines = null;
}
$rows[] = array(
$context,
phutil_tag(
'div',
array(
'style' => $style,
),
$display_view),
$lines,
$coverage,
$modified_coverage,
$packages,
);
$classes = array();
$have_authority = false;
if ($item) {
$packages = $item->getPackages();
if ($packages) {
if (array_intersect_key($packages, $authority)) {
$have_authority = true;
}
}
}
if ($have_authority) {
$classes[] = 'highlighted';
}
if (!$node->getAttribute('important')) {
$classes[] = 'diff-toc-low-importance-row';
}
if ($changeset) {
$classes[] = 'diff-toc-changeset-row';
} else {
$classes[] = 'diff-toc-no-changeset-row';
}
$rowc[] = implode(' ', $classes);
}
$table = id(new AphrontTableView($rows))
->setRowClasses($rowc)
->setClassName('aphront-table-view-compact')
->setHeaders(
array(
null,
pht('Path'),
pht('Size'),
pht('Coverage (All)'),
pht('Coverage (Touched)'),
pht('Packages'),
))
->setColumnClasses(
array(
null,
'diff-toc-path wide',
'right',
'differential-toc-cov',
'differential-toc-cov',
null,
))
->setColumnVisibility(
array(
$any_context,
true,
true,
$any_coverage,
$any_coverage,
$any_packages,
))
->setDeviceVisibility(
array(
true,
true,
false,
false,
false,
true,
));
$anchor = id(new PhabricatorAnchorView())
->setAnchorName('toc')
->setNavigationMarker(true);
if ($this->bare) {
return $table;
}
$header = id(new PHUIHeaderView())
->setHeader(pht('Table of Contents'));
if ($this->header) {
$header = $this->header;
}
$box = id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground($this->background)
->setTable($table)
->appendChild($anchor);
if ($this->infoView) {
$box->setInfoView($this->infoView);
}
return $box;
}
private function newTreeVector($old, $new) {
if ($old === null && $new === null) {
throw new Exception(pht('Changeset has no path vectors!'));
}
$vector = null;
if ($old === null) {
$vector = $new;
} else if ($new === null) {
$vector = $old;
} else if ($old === $new) {
$vector = $new;
}
if ($vector) {
foreach ($vector as $k => $v) {
$vector[$k] = $this->newScalarComponent($v);
}
return $vector;
}
$matrix = id(new PhutilEditDistanceMatrix())
->setSequences($old, $new)
->setComputeString(true);
$edits = $matrix->getEditString();
// If the edit sequence contains deletions followed by edits, move
// the deletions to the end to left-align the new path.
$edits = preg_replace('/(d+)(x+)/', '\2\1', $edits);
$vector = array();
$length = strlen($edits);
$old_cursor = 0;
$new_cursor = 0;
for ($ii = 0; $ii < strlen($edits); $ii++) {
$c = $edits[$ii];
switch ($c) {
case 'i':
$vector[] = $this->newPairComponent(null, $new[$new_cursor]);
$new_cursor++;
break;
case 'd':
$vector[] = $this->newPairComponent($old[$old_cursor], null);
$old_cursor++;
break;
case 's':
case 'x':
case 't':
$vector[] = $this->newPairComponent(
$old[$old_cursor],
$new[$new_cursor]);
$old_cursor++;
$new_cursor++;
break;
default:
throw new Exception(pht('Unknown edit string "%s"!', $c));
}
}
return $vector;
}
private function newScalarComponent($v) {
$key = sprintf('path(%s)', $v);
if (!isset($this->components[$key])) {
$this->components[$key] = $v;
}
return $key;
}
private function newPairComponent($u, $v) {
if ($u === $v) {
return $this->newScalarComponent($u);
}
$key = sprintf('pair(%s > %s)', $u, $v);
if (!isset($this->components[$key])) {
$this->components[$key] = array($u, $v);
}
return $key;
}
private function newComponentView(
$icon,
array $keys,
$old_dir,
$new_dir,
$item) {
$is_simple = true;
$items = array();
foreach ($keys as $key) {
$component = $this->components[$key];
if (is_array($component)) {
$is_simple = false;
} else {
$component = array(
$component,
$component,
);
}
$items[] = $component;
}
$move_icon = id(new PHUIIconView())
->setIcon('fa-angle-double-right pink');
$old_row = array(
phutil_tag('td', array(), $move_icon),
);
$new_row = array(
phutil_tag('td', array(), $icon),
);
$last_old_key = null;
$last_new_key = null;
foreach ($items as $key => $component) {
if (!is_array($component)) {
$last_old_key = $key;
$last_new_key = $key;
} else {
if ($component[0] !== null) {
$last_old_key = $key;
}
if ($component[1] !== null) {
$last_new_key = $key;
}
}
}
foreach ($items as $key => $component) {
if (!is_array($component)) {
$old = $component;
$new = $component;
} else {
$old = $component[0];
$new = $component[1];
}
$old_classes = array();
$new_classes = array();
if ($old === $new) {
// Do nothing.
} else if ($old === null) {
$new_classes[] = 'diff-path-component-new';
} else if ($new === null) {
$old_classes[] = 'diff-path-component-old';
} else {
$old_classes[] = 'diff-path-component-old';
$new_classes[] = 'diff-path-component-new';
}
if ($old !== null) {
if (($key === $last_old_key) && !$old_dir) {
// Do nothing.
} else {
$old = $old.'/';
}
}
if ($new !== null) {
if (($key === $last_new_key) && $item) {
$new = $item->newLink();
} else if (($key === $last_new_key) && !$new_dir) {
// Do nothing.
} else {
$new = $new.'/';
}
}
$old_row[] = phutil_tag(
'td',
array(),
phutil_tag(
'div',
array(
'class' => implode(' ', $old_classes),
),
$old));
$new_row[] = phutil_tag(
'td',
array(),
phutil_tag(
'div',
array(
'class' => implode(' ', $new_classes),
),
$new));
}
$old_row = phutil_tag(
'tr',
array(
'class' => 'diff-path-old',
),
$old_row);
$new_row = phutil_tag(
'tr',
array(
'class' => 'diff-path-new',
),
$new_row);
$rows = array();
$rows[] = $new_row;
if (!$is_simple) {
$rows[] = $old_row;
}
$body = phutil_tag('tbody', array(), $rows);
$table = phutil_tag(
'table',
array(
),
$body);
return $table;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffInlineCommentTableScaffold.php | src/infrastructure/diff/view/PHUIDiffInlineCommentTableScaffold.php | <?php
/**
* Wraps an inline comment row scaffold in a table.
*
* This scaffold is used to ship inlines over the wire to the client, so they
* arrive in a form that's easy to manipulate (a valid table node).
*/
final class PHUIDiffInlineCommentTableScaffold extends AphrontView {
private $rows = array();
public function addRowScaffold(PHUIDiffInlineCommentRowScaffold $row) {
$this->rows[] = $row;
return $this;
}
public function render() {
return phutil_tag('table', array(), $this->rows);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffInlineCommentRowScaffold.php | src/infrastructure/diff/view/PHUIDiffInlineCommentRowScaffold.php | <?php
/**
* Wraps an inline comment in a table row.
*
* Inline comments need different wrapping cells when shown in unified vs
* side-by-side diffs, as the two tables have different layouts. This wraps
* an inline comment element in an appropriate table row.
*/
abstract class PHUIDiffInlineCommentRowScaffold extends AphrontView {
private $views = array();
private $isUndoTemplate;
final public function setIsUndoTemplate($is_undo_template) {
$this->isUndoTemplate = $is_undo_template;
return $this;
}
final public function getIsUndoTemplate() {
return $this->isUndoTemplate;
}
public function getInlineViews() {
return $this->views;
}
public function addInlineView(PHUIDiffInlineCommentView $view) {
$this->views[] = $view;
return $this;
}
protected function getRowAttributes() {
$is_undo_template = $this->getIsUndoTemplate();
$is_hidden = false;
if ($is_undo_template) {
// NOTE: When this scaffold is turned into an "undo" template, it is
// important it not have any metadata: the metadata reference will be
// copied to each instance of the row. This is a complicated mess; for
// now, just sneak by without generating metadata when rendering undo
// templates.
$metadata = null;
} else {
foreach ($this->getInlineViews() as $view) {
if ($view->isHidden()) {
$is_hidden = true;
}
}
$metadata = array(
'hidden' => $is_hidden,
);
}
$classes = array();
$classes[] = 'inline';
if ($is_hidden) {
$classes[] = 'inline-hidden';
}
$result = array(
'class' => implode(' ', $classes),
'sigil' => 'inline-row',
'meta' => $metadata,
);
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffInlineCommentView.php | src/infrastructure/diff/view/PHUIDiffInlineCommentView.php | <?php
abstract class PHUIDiffInlineCommentView extends AphrontView {
private $isOnRight;
private $renderer;
private $inlineComment;
public function setInlineComment(PhabricatorInlineComment $comment) {
$this->inlineComment = $comment;
return $this;
}
public function getInlineComment() {
return $this->inlineComment;
}
public function getIsOnRight() {
return $this->isOnRight;
}
public function setIsOnRight($on_right) {
$this->isOnRight = $on_right;
return $this;
}
public function setRenderer($renderer) {
$this->renderer = $renderer;
return $this;
}
public function getRenderer() {
return $this->renderer;
}
public function getScaffoldCellID() {
return null;
}
public function isHidden() {
return false;
}
public function isHideable() {
return true;
}
public function newHiddenIcon() {
if ($this->isHideable()) {
return new PHUIDiffRevealIconView();
} else {
return null;
}
}
protected function getInlineCommentMetadata() {
$viewer = $this->getViewer();
$inline = $this->getInlineComment();
$is_synthetic = (bool)$inline->getSyntheticAuthor();
$is_fixed = false;
switch ($inline->getFixedState()) {
case PhabricatorInlineComment::STATE_DONE:
case PhabricatorInlineComment::STATE_DRAFT:
$is_fixed = true;
break;
}
$is_draft_done = false;
switch ($inline->getFixedState()) {
case PhabricatorInlineComment::STATE_DRAFT:
case PhabricatorInlineComment::STATE_UNDRAFT:
$is_draft_done = true;
break;
}
return array(
'id' => $inline->getID(),
'phid' => $inline->getPHID(),
'changesetID' => $inline->getChangesetID(),
'number' => $inline->getLineNumber(),
'length' => $inline->getLineLength(),
'isNewFile' => (bool)$inline->getIsNewFile(),
'replyToCommentPHID' => $inline->getReplyToCommentPHID(),
'isDraft' => $inline->isDraft(),
'isFixed' => $is_fixed,
'isGhost' => $inline->getIsGhost(),
'isSynthetic' => $is_synthetic,
'isDraftDone' => $is_draft_done,
'isEditing' => $inline->getIsEditing(),
'documentEngineKey' => $inline->getDocumentEngineKey(),
'startOffset' => $inline->getStartOffset(),
'endOffset' => $inline->getEndOffset(),
'on_right' => $this->getIsOnRight(),
'state' => $inline->getContentStateMap(),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffTwoUpInlineCommentRowScaffold.php | src/infrastructure/diff/view/PHUIDiffTwoUpInlineCommentRowScaffold.php | <?php
/**
* Row scaffold for 2up (side-by-side) changeset views.
*
* Although this scaffold is normally straightforward, it may also accept
* two inline comments and display them adjacently.
*/
final class PHUIDiffTwoUpInlineCommentRowScaffold
extends PHUIDiffInlineCommentRowScaffold {
public function render() {
$inlines = $this->getInlineViews();
if (!$inlines) {
throw new Exception(
pht('Two-up inline row scaffold must have at least one inline view.'));
}
if (count($inlines) > 2) {
throw new Exception(
pht('Two-up inline row scaffold must have at most two inline views.'));
}
if (count($inlines) == 1) {
$inline = head($inlines);
if ($inline->getIsOnRight()) {
$left_side = null;
$right_side = $inline;
$left_hidden = null;
$right_hidden = $inline->newHiddenIcon();
} else {
$left_side = $inline;
$right_side = null;
$left_hidden = $inline->newHiddenIcon();
$right_hidden = null;
}
} else {
list($u, $v) = $inlines;
if ($u->getIsOnRight() == $v->getIsOnRight()) {
throw new Exception(
pht(
'Two-up inline row scaffold must have one comment on the left and '.
'one comment on the right when showing two comments.'));
}
if ($v->getIsOnRight()) {
$left_side = $u;
$right_side = $v;
} else {
$left_side = $v;
$right_side = $u;
}
$left_hidden = null;
$right_hidden = null;
}
$left_attrs = array(
'class' => 'left',
'id' => ($left_side ? $left_side->getScaffoldCellID() : null),
);
$right_attrs = array(
'colspan' => 2,
'id' => ($right_side ? $right_side->getScaffoldCellID() : null),
);
$cells = array(
phutil_tag('td', array('class' => 'n'), $left_hidden),
phutil_tag('td', $left_attrs, $left_side),
phutil_tag('td', array('class' => 'n'), $right_hidden),
phutil_tag('td', array('class' => 'copy')),
phutil_tag('td', $right_attrs, $right_side),
);
return javelin_tag('tr', $this->getRowAttributes(), $cells);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffInlineCommentUndoView.php | src/infrastructure/diff/view/PHUIDiffInlineCommentUndoView.php | <?php
/**
* Render the "Undo" action to recover discarded inline comments.
*
* This extends @{class:PHUIDiffInlineCommentView} so it can use the same
* scaffolding code as other kinds of inline comments.
*/
final class PHUIDiffInlineCommentUndoView
extends PHUIDiffInlineCommentView {
public function isHideable() {
return false;
}
public function render() {
$link = javelin_tag(
'a',
array(
'href' => '#',
'sigil' => 'differential-inline-comment-undo',
),
pht('Undo'));
return phutil_tag(
'div',
array(
'class' => 'differential-inline-undo',
),
array(pht('Changes discarded.'), ' ', $link));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffOneUpInlineCommentRowScaffold.php | src/infrastructure/diff/view/PHUIDiffOneUpInlineCommentRowScaffold.php | <?php
/**
* Row scaffold for `1up` (unified) changeset views.
*
* This scaffold is straightforward.
*/
final class PHUIDiffOneUpInlineCommentRowScaffold
extends PHUIDiffInlineCommentRowScaffold {
public function render() {
$inlines = $this->getInlineViews();
if (count($inlines) != 1) {
throw new Exception(
pht('One-up inline row scaffold must have exactly one inline view!'));
}
$inline = head($inlines);
$attrs = array(
'colspan' => 2,
'id' => $inline->getScaffoldCellID(),
);
if ($inline->getIsOnRight()) {
$left_hidden = null;
$right_hidden = $inline->newHiddenIcon();
} else {
$left_hidden = $inline->newHiddenIcon();
$right_hidden = null;
}
$cells = array(
phutil_tag('td', array('class' => 'n'), $left_hidden),
phutil_tag('td', array('class' => 'n'), $right_hidden),
phutil_tag('td', array('class' => 'copy')),
phutil_tag('td', $attrs, $inline),
);
return javelin_tag('tr', $this->getRowAttributes(), $cells);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffInlineCommentPreviewListView.php | src/infrastructure/diff/view/PHUIDiffInlineCommentPreviewListView.php | <?php
final class PHUIDiffInlineCommentPreviewListView
extends AphrontView {
private $inlineComments = array();
private $ownerPHID;
public function setInlineComments(array $comments) {
assert_instances_of($comments, 'PhabricatorApplicationTransactionComment');
$this->inlineComments = $comments;
return $this;
}
public function getInlineComments() {
return $this->inlineComments;
}
public function setOwnerPHID($owner_phid) {
$this->ownerPHID = $owner_phid;
return $this;
}
public function getOwnerPHID() {
return $this->ownerPHID;
}
public function render() {
$viewer = $this->getViewer();
$inlines = $this->getInlineComments();
foreach ($inlines as $key => $inline) {
$inlines[$key] = $inline->newInlineCommentObject();
}
$engine = new PhabricatorMarkupEngine();
$engine->setViewer($viewer);
foreach ($inlines as $inline) {
$engine->addObject(
$inline,
PhabricatorInlineComment::MARKUP_FIELD_BODY);
}
$engine->process();
$owner_phid = $this->getOwnerPHID();
$handles = $viewer->loadHandles(array($viewer->getPHID()));
$handles = iterator_to_array($handles);
$views = array();
foreach ($inlines as $inline) {
$views[] = id(new PHUIDiffInlineCommentDetailView())
->setUser($viewer)
->setInlineComment($inline)
->setMarkupEngine($engine)
->setHandles($handles)
->setEditable(false)
->setPreview(true)
->setCanMarkDone(false)
->setObjectOwnerPHID($owner_phid);
}
return $views;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffRevealIconView.php | src/infrastructure/diff/view/PHUIDiffRevealIconView.php | <?php
final class PHUIDiffRevealIconView extends AphrontView {
public function render() {
$icon = id(new PHUIIconView())
->setIcon('fa-comment')
->addSigil('has-tooltip')
->setMetadata(
array(
'tip' => pht('Expand'),
'align' => 'E',
'size' => 275,
));
return javelin_tag(
'a',
array(
'href' => '#',
'class' => 'reveal-inline',
'sigil' => 'reveal-inline',
'mustcapture' => true,
),
$icon);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PhabricatorInlineSummaryView.php | src/infrastructure/diff/view/PhabricatorInlineSummaryView.php | <?php
final class PhabricatorInlineSummaryView extends AphrontView {
private $groups = array();
public function addCommentGroup($name, array $items) {
if (!isset($this->groups[$name])) {
$this->groups[$name] = $items;
} else {
$this->groups[$name] = array_merge($this->groups[$name], $items);
}
return $this;
}
public function render() {
require_celerity_resource('inline-comment-summary-css');
return hsprintf('%s', $this->renderTable());
}
private function renderTable() {
$rows = array();
foreach ($this->groups as $group => $items) {
$has_where = false;
foreach ($items as $item) {
if (!empty($item['where'])) {
$has_where = true;
break;
}
}
$icon = id(new PHUIIconView())
->setIcon('fa-file-code-o darkbluetext mmr');
$header = phutil_tag(
'th',
array(
'colspan' => 3,
'class' => 'inline-comment-summary-table-header',
),
array(
$icon,
$group,
));
$rows[] = phutil_tag('tr', array(), $header);
foreach ($items as $item) {
$line = $item['line'];
$length = $item['length'];
if ($length) {
$lines = $line."\xE2\x80\x93".($line + $length);
} else {
$lines = $line;
}
if (isset($item['href'])) {
$href = $item['href'];
$target = '_blank';
$tail = " \xE2\x86\x97";
} else {
$href = '#inline-'.$item['id'];
$target = null;
$tail = null;
}
if ($href) {
$icon = id(new PHUIIconView())
->setIcon('fa-share darkbluetext mmr');
$lines = phutil_tag(
'a',
array(
'href' => $href,
'target' => $target,
'class' => 'num',
),
array(
$icon,
$lines,
$tail,
));
}
$where = idx($item, 'where');
$colspan = ($has_where ? null : 2);
$rows[] = phutil_tag(
'tr',
array(),
array(
phutil_tag('td',
array('class' => 'inline-line-number inline-table-dolumn'),
$lines),
($has_where
? phutil_tag('td',
array('class' => 'inline-which-diff inline-table-dolumn'),
$where)
: null),
phutil_tag(
'td',
array(
'class' => 'inline-summary-content inline-table-dolumn',
'colspan' => $colspan,
),
phutil_tag_div('phabricator-remarkup', $item['content'])),
));
}
}
return phutil_tag(
'table',
array(
'class' => 'phabricator-inline-summary-table',
),
phutil_implode_html("\n", $rows));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffGraphView.php | src/infrastructure/diff/view/PHUIDiffGraphView.php | <?php
final class PHUIDiffGraphView extends Phobject {
private $isHead = true;
private $isTail = true;
private $height;
public function setIsHead($is_head) {
$this->isHead = $is_head;
return $this;
}
public function getIsHead() {
return $this->isHead;
}
public function setIsTail($is_tail) {
$this->isTail = $is_tail;
return $this;
}
public function getIsTail() {
return $this->isTail;
}
public function setHeight($height) {
$this->height = $height;
return $this;
}
public function getHeight() {
return $this->height;
}
public function renderRawGraph(array $parents) {
// This keeps our accumulated information about each line of the
// merge/branch graph.
$graph = array();
// This holds the next commit we're looking for in each column of the
// graph.
$threads = array();
// This is the largest number of columns any row has, i.e. the width of
// the graph.
$count = 0;
foreach ($parents as $cursor => $parent_list) {
$joins = array();
$splits = array();
// Look for some thread which has this commit as the next commit. If
// we find one, this commit goes on that thread. Otherwise, this commit
// goes on a new thread.
$line = '';
$found = false;
$pos = count($threads);
$thread_count = $pos;
for ($n = 0; $n < $thread_count; $n++) {
if (empty($threads[$n])) {
$line .= ' ';
continue;
}
if ($threads[$n] == $cursor) {
if ($found) {
$line .= ' ';
$joins[] = $n;
$threads[$n] = false;
} else {
$line .= 'o';
$found = true;
$pos = $n;
}
} else {
// We render a "|" for any threads which have a commit that we haven't
// seen yet, this is later drawn as a vertical line.
$line .= '|';
}
}
// If we didn't find the thread this commit goes on, start a new thread.
// We use "o" to mark the commit for the rendering engine, or "^" to
// indicate that there's nothing after it so the line from the commit
// upward should not be drawn.
if (!$found) {
if ($this->getIsHead()) {
$line .= '^';
} else {
$line .= 'o';
foreach ($graph as $k => $meta) {
// Go back across all the lines we've already drawn and add a
// "|" to the end, since this is connected to some future commit
// we don't know about.
for ($jj = strlen($meta['line']); $jj <= $count; $jj++) {
$graph[$k]['line'] .= '|';
}
}
}
}
// Update the next commit on this thread to the commit's first parent.
// This might have the effect of making a new thread.
$threads[$pos] = head($parent_list);
// If we made a new thread, increase the thread count.
$count = max($pos + 1, $count);
// Now, deal with splits (merges). I picked this terms opposite to the
// underlying repository term to confuse you.
foreach (array_slice($parent_list, 1) as $parent) {
$found = false;
// Try to find the other parent(s) in our existing threads. If we find
// them, split to that thread.
foreach ($threads as $idx => $thread_commit) {
if ($thread_commit == $parent) {
$found = true;
$splits[] = $idx;
break;
}
}
// If we didn't find the parent, we don't know about it yet. Find the
// first free thread and add it as the "next" commit in that thread.
// This might create a new thread.
if (!$found) {
for ($n = 0; $n < $count; $n++) {
if (empty($threads[$n])) {
break;
}
}
$threads[$n] = $parent;
$splits[] = $n;
$count = max($n + 1, $count);
}
}
$graph[] = array(
'line' => $line,
'split' => $splits,
'join' => $joins,
);
}
// If this is the last page in history, replace any "o" characters at the
// bottom of columns with "x" characters so we do not draw a connecting
// line downward, and replace "^" with an "X" for repositories with
// exactly one commit.
if ($this->getIsTail() && $graph) {
$terminated = array();
foreach (array_reverse(array_keys($graph)) as $key) {
$line = $graph[$key]['line'];
$len = strlen($line);
for ($ii = 0; $ii < $len; $ii++) {
$c = $line[$ii];
if ($c == 'o') {
// If we've already terminated this thread, we don't need to add
// a terminator.
if (isset($terminated[$ii])) {
continue;
}
$terminated[$ii] = true;
// If this thread is joining some other node here, we don't want
// to terminate it.
if (isset($graph[$key + 1])) {
$joins = $graph[$key + 1]['join'];
if (in_array($ii, $joins)) {
continue;
}
}
$graph[$key]['line'][$ii] = 'x';
} else if ($c != ' ') {
$terminated[$ii] = true;
} else {
unset($terminated[$ii]);
}
}
}
$last = array_pop($graph);
$last['line'] = str_replace('^', 'X', $last['line']);
$graph[] = $last;
}
return array($graph, $count);
}
public function renderGraph(array $parents) {
list($graph, $count) = $this->renderRawGraph($parents);
// Render into tags for the behavior.
foreach ($graph as $k => $meta) {
$graph[$k] = javelin_tag(
'div',
array(
'sigil' => 'commit-graph',
'meta' => $meta,
),
'');
}
Javelin::initBehavior(
'diffusion-commit-graph',
array(
'count' => $count,
'height' => $this->getHeight(),
));
return $graph;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/PHUIDiffInlineCommentEditView.php | src/infrastructure/diff/view/PHUIDiffInlineCommentEditView.php | <?php
final class PHUIDiffInlineCommentEditView
extends PHUIDiffInlineCommentView {
private $title;
public function setTitle($title) {
$this->title = $title;
return $this;
}
public function render() {
$viewer = $this->getViewer();
$inline = $this->getInlineComment();
$content = phabricator_form(
$viewer,
array(
'action' => $inline->getControllerURI(),
'method' => 'POST',
'sigil' => 'inline-edit-form',
),
array(
$this->renderBody(),
));
return $content;
}
private function renderBody() {
$buttons = array();
$buttons[] = id(new PHUIButtonView())
->setText(pht('Save Draft'));
$buttons[] = id(new PHUIButtonView())
->setText(pht('Cancel'))
->setColor(PHUIButtonView::GREY)
->addSigil('inline-edit-cancel');
$title = phutil_tag(
'div',
array(
'class' => 'differential-inline-comment-edit-title',
),
$this->title);
$corpus_view = $this->newCorpusView();
$body = phutil_tag(
'div',
array(
'class' => 'differential-inline-comment-edit-body',
),
array(
$corpus_view,
$this->newTextarea(),
));
$edit = javelin_tag(
'div',
array(
'class' => 'differential-inline-comment-edit-buttons grouped',
'sigil' => 'inline-edit-buttons',
),
array(
$buttons,
));
$inline = $this->getInlineComment();
return javelin_tag(
'div',
array(
'class' => 'differential-inline-comment-edit',
'sigil' => 'differential-inline-comment',
'meta' => $this->getInlineCommentMetadata(),
),
array(
$title,
$body,
$edit,
));
}
private function newTextarea() {
$viewer = $this->getViewer();
$inline = $this->getInlineComment();
$state = $inline->getContentStateForEdit($viewer);
return id(new PhabricatorRemarkupControl())
->setViewer($viewer)
->setSigil('inline-content-text')
->setValue($state->getContentText())
->setDisableFullScreen(true);
}
private function newCorpusView() {
$viewer = $this->getViewer();
$inline = $this->getInlineComment();
$context = $inline->getInlineContext();
if ($context === null) {
return null;
}
$head = $context->getHeadLines();
$head = $this->newContextView($head);
$state = $inline->getContentStateForEdit($viewer);
$main = $state->getContentSuggestionText();
$main_count = count(phutil_split_lines($main));
// Browsers ignore one leading newline in text areas. Add one so that
// any actual leading newlines in the content are preserved.
$main = "\n".$main;
$textarea = javelin_tag(
'textarea',
array(
'class' => 'inline-suggestion-input PhabricatorMonospaced',
'rows' => max(3, $main_count + 1),
'sigil' => 'inline-content-suggestion',
),
$main);
$main = phutil_tag(
'tr',
array(
'class' => 'inline-suggestion-input-row',
),
array(
phutil_tag(
'td',
array(
'class' => 'inline-suggestion-line-cell',
),
null),
phutil_tag(
'td',
array(
'class' => 'inline-suggestion-input-cell',
),
$textarea),
));
$tail = $context->getTailLines();
$tail = $this->newContextView($tail);
$body = phutil_tag(
'tbody',
array(),
array(
$head,
$main,
$tail,
));
$table = phutil_tag(
'table',
array(
'class' => 'inline-suggestion-table',
),
$body);
$container = phutil_tag(
'div',
array(
'class' => 'inline-suggestion',
),
$table);
return $container;
}
private function newContextView(array $lines) {
if (!$lines) {
return array();
}
$rows = array();
foreach ($lines as $index => $line) {
$line_cell = phutil_tag(
'td',
array(
'class' => 'inline-suggestion-line-cell PhabricatorMonospaced',
),
$index + 1);
$text_cell = phutil_tag(
'td',
array(
'class' => 'inline-suggestion-text-cell PhabricatorMonospaced',
),
$line);
$cells = array(
$line_cell,
$text_cell,
);
$rows[] = phutil_tag('tr', array(), $cells);
}
return $rows;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/view/__tests__/PHUIDiffGraphViewTestCase.php | src/infrastructure/diff/view/__tests__/PHUIDiffGraphViewTestCase.php | <?php
final class PHUIDiffGraphViewTestCase extends PhabricatorTestCase {
public function testTailTermination() {
$nodes = array(
'A' => array('B'),
'B' => array('C', 'D', 'E'),
'E' => array(),
'D' => array(),
'C' => array('F', 'G'),
'G' => array(),
'F' => array(),
);
$graph = $this->newGraph($nodes);
$picture = array(
'^',
'o',
'||x',
'|x ',
'o ',
'|x ',
'x ',
);
$this->assertGraph($picture, $graph, pht('Terminating Tree'));
}
public function testReverseTree() {
$nodes = array(
'A' => array('B'),
'C' => array('B'),
'B' => array('D'),
'E' => array('D'),
'F' => array('D'),
'D' => array('G'),
'G' => array(),
);
$graph = $this->newGraph($nodes);
$picture = array(
'^',
'|^',
'o ',
'| ^',
'| |^',
'o ',
'x ',
);
$this->assertGraph($picture, $graph, pht('Reverse Tree'));
}
public function testJoinTerminateTree() {
$nodes = array(
'A' => array('D'),
'B' => array('C'),
'C' => array('D'),
'D' => array(),
);
$graph = $this->newGraph($nodes);
$picture = array(
'^',
'|^',
'|o',
'x ',
);
$this->assertGraph($picture, $graph, pht('Terminated Tree'));
}
public function testThreeWayGraphJoin() {
$nodes = array(
'A' => array('D', 'C', 'B'),
'B' => array('D'),
'C' => array('B', 'E', 'F'),
'D' => array(),
'E' => array(),
'F' => array(),
);
$graph = $this->newGraph($nodes);
$picture = array(
'^',
'||o',
'|o|',
'x| ||',
' | x|',
' | x',
);
$this->assertGraph($picture, $graph, pht('Three-Way Tree'));
}
private function newGraph(array $nodes) {
return id(new PHUIDiffGraphView())
->setIsHead(true)
->setIsTail(true)
->renderRawGraph($nodes);
}
private function assertGraph($picture, $graph, $label) {
list($data, $count) = $graph;
$lines = ipull($data, 'line');
$picture = implode("\n", $picture);
$lines = implode("\n", $lines);
$this->assertEqual($picture, $lines, $label);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/viewstate/PhabricatorChangesetViewState.php | src/infrastructure/diff/viewstate/PhabricatorChangesetViewState.php | <?php
final class PhabricatorChangesetViewState
extends Phobject {
private $highlightLanguage;
private $characterEncoding;
private $documentEngineKey;
private $rendererKey;
private $defaultDeviceRendererKey;
private $hidden;
private $modifiedSinceHide;
private $discardResponse;
public function setHighlightLanguage($highlight_language) {
$this->highlightLanguage = $highlight_language;
return $this;
}
public function getHighlightLanguage() {
return $this->highlightLanguage;
}
public function setCharacterEncoding($character_encoding) {
$this->characterEncoding = $character_encoding;
return $this;
}
public function getCharacterEncoding() {
return $this->characterEncoding;
}
public function setDocumentEngineKey($document_engine_key) {
$this->documentEngineKey = $document_engine_key;
return $this;
}
public function getDocumentEngineKey() {
return $this->documentEngineKey;
}
public function setRendererKey($renderer_key) {
$this->rendererKey = $renderer_key;
return $this;
}
public function getRendererKey() {
return $this->rendererKey;
}
public function setDefaultDeviceRendererKey($renderer_key) {
$this->defaultDeviceRendererKey = $renderer_key;
return $this;
}
public function getDefaultDeviceRendererKey() {
return $this->defaultDeviceRendererKey;
}
public function setHidden($hidden) {
$this->hidden = $hidden;
return $this;
}
public function getHidden() {
return $this->hidden;
}
public function setModifiedSinceHide($modified_since_hide) {
$this->modifiedSinceHide = $modified_since_hide;
return $this;
}
public function getModifiedSinceHide() {
return $this->modifiedSinceHide;
}
public function setDiscardResponse($discard_response) {
$this->discardResponse = $discard_response;
return $this;
}
public function getDiscardResponse() {
return $this->discardResponse;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/viewstate/PhabricatorChangesetViewStateEngine.php | src/infrastructure/diff/viewstate/PhabricatorChangesetViewStateEngine.php | <?php
final class PhabricatorChangesetViewStateEngine
extends Phobject {
private $viewer;
private $objectPHID;
private $changeset;
private $storage;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setObjectPHID($object_phid) {
$this->objectPHID = $object_phid;
return $this;
}
public function getObjectPHID() {
return $this->objectPHID;
}
public function setChangeset(DifferentialChangeset $changeset) {
$this->changeset = $changeset;
return $this;
}
public function getChangeset() {
return $this->changeset;
}
public function newViewStateFromRequest(AphrontRequest $request) {
$storage = $this->loadViewStateStorage();
$this->setStorage($storage);
$highlight = $request->getStr('highlight');
if ($highlight !== null) {
$this->setChangesetProperty('highlight', $highlight);
}
$encoding = $request->getStr('encoding');
if ($encoding !== null) {
$this->setChangesetProperty('encoding', $encoding);
}
$engine = $request->getStr('engine');
if ($engine !== null) {
$this->setChangesetProperty('engine', $engine);
}
$renderer = $request->getStr('renderer');
if ($renderer !== null) {
$this->setChangesetProperty('renderer', $renderer);
}
$hidden = $request->getStr('hidden');
if ($hidden !== null) {
$this->setChangesetProperty('hidden', (int)$hidden);
}
$this->saveViewStateStorage();
$state = new PhabricatorChangesetViewState();
$highlight_language = $this->getChangesetProperty('highlight');
$state->setHighlightLanguage($highlight_language);
$encoding = $this->getChangesetProperty('encoding');
$state->setCharacterEncoding($encoding);
$document_engine = $this->getChangesetProperty('engine');
$state->setDocumentEngineKey($document_engine);
$renderer = $this->getChangesetProperty('renderer');
$state->setRendererKey($renderer);
$this->updateHiddenState($state);
// This is the client-selected default renderer based on viewport
// dimensions.
$device_key = $request->getStr('device');
if ($device_key !== null) {
$state->setDefaultDeviceRendererKey($device_key);
}
$discard_response = $request->getStr('discard');
if ($discard_response !== null) {
$state->setDiscardResponse(true);
}
return $state;
}
private function setStorage(DifferentialViewState $storage) {
$this->storage = $storage;
return $this;
}
private function getStorage() {
return $this->storage;
}
private function setChangesetProperty(
$key,
$value) {
$storage = $this->getStorage();
$changeset = $this->getChangeset();
$storage->setChangesetProperty($changeset, $key, $value);
}
private function getChangesetProperty(
$key,
$default = null) {
$storage = $this->getStorage();
$changeset = $this->getChangeset();
return $storage->getChangesetProperty($changeset, $key, $default);
}
private function loadViewStateStorage() {
$viewer = $this->getViewer();
$object_phid = $this->getObjectPHID();
$viewer_phid = $viewer->getPHID();
$storage = null;
if ($viewer_phid !== null) {
$storage = id(new DifferentialViewStateQuery())
->setViewer($viewer)
->withViewerPHIDs(array($viewer_phid))
->withObjectPHIDs(array($object_phid))
->executeOne();
}
if ($storage === null) {
$storage = id(new DifferentialViewState())
->setObjectPHID($object_phid);
if ($viewer_phid !== null) {
$storage->setViewerPHID($viewer_phid);
} else {
$storage->makeEphemeral();
}
}
return $storage;
}
private function saveViewStateStorage() {
if (PhabricatorEnv::isReadOnly()) {
return;
}
$storage = $this->getStorage();
$viewer_phid = $storage->getViewerPHID();
if ($viewer_phid === null) {
return;
}
if (!$storage->getHasModifications()) {
return;
}
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
try {
$storage->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// We may race another process to save view state. For now, just discard
// our state if we do.
}
unset($unguarded);
}
private function updateHiddenState(PhabricatorChangesetViewState $state) {
$is_hidden = false;
$was_modified = false;
$storage = $this->getStorage();
$changeset = $this->getChangeset();
$entries = $storage->getChangesetPropertyEntries($changeset, 'hidden');
$entries = isort($entries, 'epoch');
if ($entries) {
$other_spec = last($entries);
$this_version = (int)$changeset->getDiffID();
$other_version = (int)idx($other_spec, 'diffID');
$other_value = (bool)idx($other_spec, 'value', false);
$other_id = (int)idx($other_spec, 'changesetID');
if ($other_value === false) {
$is_hidden = false;
} else if ($other_version >= $this_version) {
$is_hidden = $other_value;
} else {
$viewer = $this->getViewer();
if ($other_id) {
$other_changeset = id(new DifferentialChangesetQuery())
->setViewer($viewer)
->withIDs(array($other_id))
->executeOne();
} else {
$other_changeset = null;
}
$is_modified = false;
if ($other_changeset) {
if (!$changeset->hasSameEffectAs($other_changeset)) {
$is_modified = true;
}
}
$is_hidden = false;
$was_modified = true;
}
}
$state->setHidden($is_hidden);
$state->setModifiedSinceHide($was_modified);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/prose/PhutilProseDiff.php | src/infrastructure/diff/prose/PhutilProseDiff.php | <?php
final class PhutilProseDiff extends Phobject {
private $parts = array();
public function addPart($type, $text) {
$this->parts[] = array(
'type' => $type,
'text' => $text,
);
return $this;
}
public function getParts() {
return $this->parts;
}
/**
* Get diff parts, but replace large blocks of unchanged text with "."
* parts representing missing context.
*/
public function getSummaryParts() {
$parts = $this->getParts();
$head_key = head_key($parts);
$last_key = last_key($parts);
$results = array();
foreach ($parts as $key => $part) {
$is_head = ($key == $head_key);
$is_last = ($key == $last_key);
switch ($part['type']) {
case '=':
$pieces = $this->splitTextForSummary($part['text']);
if ($is_head || $is_last) {
$need = 2;
} else {
$need = 3;
}
// We don't have enough pieces to omit anything, so just continue.
if (count($pieces) < $need) {
$results[] = $part;
break;
}
if (!$is_head) {
$results[] = array(
'type' => '=',
'text' => head($pieces),
);
}
$results[] = array(
'type' => '.',
'text' => null,
);
if (!$is_last) {
$results[] = array(
'type' => '=',
'text' => last($pieces),
);
}
break;
default:
$results[] = $part;
break;
}
}
return $results;
}
public function reorderParts() {
// Reorder sequences of removed and added sections to put all the "-"
// parts together first, then all the "+" parts together. This produces
// a more human-readable result than intermingling them.
$o_run = array();
$n_run = array();
$result = array();
foreach ($this->parts as $part) {
$type = $part['type'];
switch ($type) {
case '-':
$o_run[] = $part;
break;
case '+':
$n_run[] = $part;
break;
default:
if ($o_run || $n_run) {
foreach ($this->combineRuns($o_run, $n_run) as $merged_part) {
$result[] = $merged_part;
}
$o_run = array();
$n_run = array();
}
$result[] = $part;
break;
}
}
if ($o_run || $n_run) {
foreach ($this->combineRuns($o_run, $n_run) as $part) {
$result[] = $part;
}
}
// Now, combine consecuitive runs of the same type of change (like a
// series of "-" parts) into a single run.
$combined = array();
$last = null;
$last_text = null;
foreach ($result as $part) {
$type = $part['type'];
if ($last !== $type) {
if ($last !== null) {
$combined[] = array(
'type' => $last,
'text' => $last_text,
);
}
$last_text = null;
$last = $type;
}
$last_text .= $part['text'];
}
if ($last_text !== null) {
$combined[] = array(
'type' => $last,
'text' => $last_text,
);
}
$this->parts = $combined;
return $this;
}
private function combineRuns($o_run, $n_run) {
$o_merge = $this->mergeParts($o_run);
$n_merge = $this->mergeParts($n_run);
// When removed and added blocks share a prefix or suffix, we sometimes
// want to count it as unchanged (for example, if it is whitespace) but
// sometimes want to count it as changed (for example, if it is a word
// suffix like "ing"). Find common prefixes and suffixes of these layout
// characters and emit them as "=" (unchanged) blocks.
$layout_characters = array(
' ' => true,
"\n" => true,
'.' => true,
'!' => true,
',' => true,
'?' => true,
']' => true,
'[' => true,
'(' => true,
')' => true,
'<' => true,
'>' => true,
);
$o_text = $o_merge['text'];
$n_text = $n_merge['text'];
$o_len = strlen($o_text);
$n_len = strlen($n_text);
$min_len = min($o_len, $n_len);
$prefix_len = 0;
for ($pos = 0; $pos < $min_len; $pos++) {
$o = $o_text[$pos];
$n = $n_text[$pos];
if ($o !== $n) {
break;
}
if (empty($layout_characters[$o])) {
break;
}
$prefix_len++;
}
$suffix_len = 0;
for ($pos = 0; $pos < ($min_len - $prefix_len); $pos++) {
$o = $o_text[$o_len - ($pos + 1)];
$n = $n_text[$n_len - ($pos + 1)];
if ($o !== $n) {
break;
}
if (empty($layout_characters[$o])) {
break;
}
$suffix_len++;
}
$results = array();
if ($prefix_len) {
$results[] = array(
'type' => '=',
'text' => substr($o_text, 0, $prefix_len),
);
}
if ($prefix_len < $o_len) {
$results[] = array(
'type' => '-',
'text' => substr(
$o_text,
$prefix_len,
$o_len - $prefix_len - $suffix_len),
);
}
if ($prefix_len < $n_len) {
$results[] = array(
'type' => '+',
'text' => substr(
$n_text,
$prefix_len,
$n_len - $prefix_len - $suffix_len),
);
}
if ($suffix_len) {
$results[] = array(
'type' => '=',
'text' => substr($o_text, -$suffix_len),
);
}
return $results;
}
private function mergeParts(array $parts) {
$text = '';
$type = null;
foreach ($parts as $part) {
$part_type = $part['type'];
if ($type === null) {
$type = $part_type;
}
if ($type !== $part_type) {
throw new Exception(pht('Can not merge parts of dissimilar types!'));
}
$text .= $part['text'];
}
return array(
'type' => $type,
'text' => $text,
);
}
private function splitTextForSummary($text) {
$matches = null;
$ok = preg_match('/^(\n*[^\n]+)\n/', $text, $matches);
if (!$ok) {
return array($text);
}
$head = $matches[1];
$text = substr($text, strlen($head));
$ok = preg_match('/\n([^\n]+\n*)\z/', $text, $matches);
if (!$ok) {
return array($text);
}
$last = $matches[1];
$text = substr($text, 0, -strlen($last));
if (!strlen(trim($text))) {
return array($head, $last);
} else {
return array($head, $text, $last);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/prose/PhutilProseDifferenceEngine.php | src/infrastructure/diff/prose/PhutilProseDifferenceEngine.php | <?php
final class PhutilProseDifferenceEngine extends Phobject {
public function getDiff($u, $v) {
return $this->buildDiff($u, $v, 0);
}
private function buildDiff($u, $v, $level) {
$u_parts = $this->splitCorpus($u, $level);
$v_parts = $this->splitCorpus($v, $level);
if ($level === 0) {
$diff = $this->newHashDiff($u_parts, $v_parts);
$too_large = false;
} else {
list($diff, $too_large) = $this->newEditDistanceMatrixDiff(
$u_parts,
$v_parts,
$level);
}
$diff->reorderParts();
// If we just built a character-level diff, we're all done and do not
// need to go any deeper.
if ($level == 3) {
return $diff;
}
$blocks = array();
$block = null;
foreach ($diff->getParts() as $part) {
$type = $part['type'];
$text = $part['text'];
switch ($type) {
case '=':
if ($block) {
$blocks[] = $block;
$block = null;
}
$blocks[] = array(
'type' => $type,
'text' => $text,
);
break;
case '-':
if (!$block) {
$block = array(
'type' => '!',
'old' => '',
'new' => '',
);
}
$block['old'] .= $text;
break;
case '+':
if (!$block) {
$block = array(
'type' => '!',
'old' => '',
'new' => '',
);
}
$block['new'] .= $text;
break;
}
}
if ($block) {
$blocks[] = $block;
}
$result = new PhutilProseDiff();
foreach ($blocks as $block) {
$type = $block['type'];
if ($type == '=') {
$result->addPart('=', $block['text']);
} else {
$old = $block['old'];
$new = $block['new'];
if (!strlen($old) && !strlen($new)) {
// Nothing to do.
} else if (!strlen($old)) {
$result->addPart('+', $new);
} else if (!strlen($new)) {
$result->addPart('-', $old);
} else {
if ($too_large) {
// If this text was too big to diff, don't try to subdivide it.
$result->addPart('-', $old);
$result->addPart('+', $new);
} else {
$subdiff = $this->buildDiff(
$old,
$new,
$level + 1);
foreach ($subdiff->getParts() as $part) {
$result->addPart($part['type'], $part['text']);
}
}
}
}
}
$result->reorderParts();
return $result;
}
private function splitCorpus($corpus, $level) {
switch ($level) {
case 0:
// Level 0: Split into paragraphs.
$expr = '/([\n]+)/';
break;
case 1:
// Level 1: Split into sentences.
$expr = '/([\n,!;?\.]+)/';
break;
case 2:
// Level 2: Split into words.
$expr = '/(\s+)/';
break;
case 3:
// Level 3: Split into characters.
return phutil_utf8v_combined($corpus);
}
$pieces = preg_split($expr, $corpus, -1, PREG_SPLIT_DELIM_CAPTURE);
return $this->stitchPieces($pieces, $level);
}
private function stitchPieces(array $pieces, $level) {
$results = array();
$count = count($pieces);
for ($ii = 0; $ii < $count; $ii += 2) {
$result = $pieces[$ii];
if ($ii + 1 < $count) {
$result .= $pieces[$ii + 1];
}
if ($level < 2) {
$trimmed_pieces = $this->trimApart($result);
foreach ($trimmed_pieces as $trimmed_piece) {
$results[] = $trimmed_piece;
}
} else {
$results[] = $result;
}
}
// If the input ended with a delimiter, we can get an empty final piece.
// Just discard it.
if (last($results) == '') {
array_pop($results);
}
return $results;
}
private function newEditDistanceMatrixDiff(
array $u_parts,
array $v_parts,
$level) {
$matrix = id(new PhutilEditDistanceMatrix())
->setMaximumLength(128)
->setSequences($u_parts, $v_parts)
->setComputeString(true);
// For word-level and character-level changes, smooth the output string
// to reduce the choppiness of the diff.
if ($level > 1) {
$matrix->setApplySmoothing(PhutilEditDistanceMatrix::SMOOTHING_FULL);
}
$u_pos = 0;
$v_pos = 0;
$edits = $matrix->getEditString();
$edits_length = strlen($edits);
$diff = new PhutilProseDiff();
for ($ii = 0; $ii < $edits_length; $ii++) {
$c = $edits[$ii];
if ($c == 's') {
$diff->addPart('=', $u_parts[$u_pos]);
$u_pos++;
$v_pos++;
} else if ($c == 'd') {
$diff->addPart('-', $u_parts[$u_pos]);
$u_pos++;
} else if ($c == 'i') {
$diff->addPart('+', $v_parts[$v_pos]);
$v_pos++;
} else if ($c == 'x') {
$diff->addPart('-', $u_parts[$u_pos]);
$diff->addPart('+', $v_parts[$v_pos]);
$u_pos++;
$v_pos++;
} else {
throw new Exception(
pht(
'Unexpected character ("%s") in edit string.',
$c));
}
}
return array($diff, $matrix->didReachMaximumLength());
}
private function newHashDiff(array $u_parts, array $v_parts) {
$u_ref = new PhabricatorDocumentRef();
$v_ref = new PhabricatorDocumentRef();
$u_blocks = $this->newDocumentEngineBlocks($u_parts);
$v_blocks = $this->newDocumentEngineBlocks($v_parts);
$rows = id(new PhabricatorDocumentEngineBlocks())
->addBlockList($u_ref, $u_blocks)
->addBlockList($v_ref, $v_blocks)
->newTwoUpLayout();
$diff = new PhutilProseDiff();
foreach ($rows as $row) {
list($u_block, $v_block) = $row;
if ($u_block && $v_block) {
if ($u_block->getDifferenceType() === '-') {
$diff->addPart('-', $u_block->getContent());
$diff->addPart('+', $v_block->getContent());
} else {
$diff->addPart('=', $u_block->getContent());
}
} else if ($u_block) {
$diff->addPart('-', $u_block->getContent());
} else {
$diff->addPart('+', $v_block->getContent());
}
}
return $diff;
}
private function newDocumentEngineBlocks(array $parts) {
$blocks = array();
foreach ($parts as $part) {
$hash = PhabricatorHash::digestForIndex($part);
$blocks[] = id(new PhabricatorDocumentEngineBlock())
->setContent($part)
->setDifferenceHash($hash);
}
return $blocks;
}
public static function trimApart($input) {
// Split pieces into separate text and whitespace sections: make one
// piece out of all the whitespace at the beginning, one piece out of
// all the actual text in the middle, and one piece out of all the
// whitespace at the end.
$parts = array();
$length = strlen($input);
$corpus = ltrim($input);
$l_length = strlen($corpus);
if ($l_length !== $length) {
$parts[] = substr($input, 0, $length - $l_length);
}
$corpus = rtrim($corpus);
$lr_length = strlen($corpus);
if ($lr_length) {
$parts[] = $corpus;
}
if ($lr_length !== $l_length) {
// NOTE: This will be a negative value; we're slicing from the end of
// the input string.
$parts[] = substr($input, $lr_length - $l_length);
}
return $parts;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/prose/__tests__/PhutilProseDiffTestCase.php | src/infrastructure/diff/prose/__tests__/PhutilProseDiffTestCase.php | <?php
final class PhutilProseDiffTestCase
extends PhabricatorTestCase {
public function testTrimApart() {
$map = array(
'' => array(),
'a' => array('a'),
' a ' => array(
' ',
'a',
' ',
),
' a' => array(
' ',
'a',
),
'a ' => array(
'a',
' ',
),
' a b ' => array(
' ',
'a b',
' ',
),
);
foreach ($map as $input => $expect) {
$actual = PhutilProseDifferenceEngine::trimApart($input);
$this->assertEqual(
$expect,
$actual,
pht('Trim Apart: %s', $input));
}
}
public function testProseDiffsDistance() {
$this->assertProseParts(
'',
'',
array(),
pht('Empty'));
$this->assertProseParts(
"xxx\nyyy",
"xxx\nzzz\nyyy",
array(
"= xxx\n",
"+ zzz\n",
'= yyy',
),
pht('Add Paragraph'));
$this->assertProseParts(
"xxx\nzzz\nyyy",
"xxx\nyyy",
array(
"= xxx\n",
"- zzz\n",
'= yyy',
),
pht('Remove Paragraph'));
$this->assertProseParts(
'xxx',
"xxxyyy\n.zzz",
array(
'= xxx',
"+ yyy\n.zzz",
),
pht('Amend paragraph, and add paragraph starting with punctuation'));
// Without smoothing, the alogorithm identifies that "shark" and "cat"
// both contain the letter "a" and tries to express this as a very
// fine-grained edit which replaces "sh" with "c" and then "rk" with "t".
// This is technically correct, but it is much easier for human viewers to
// parse if we smooth this into a single removal and a single addition.
$this->assertProseParts(
'They say the shark has nine lives.',
'They say the cat has nine lives.',
array(
'= They say the ',
'- shark',
'+ cat',
'= has nine lives.',
),
pht('"Shark/cat" word edit smoothenss.'));
$this->assertProseParts(
'Rising quickly, she says',
'Rising quickly, she remarks:',
array(
'= Rising quickly, she ',
'- says',
'+ remarks:',
),
pht('"Says/remarks" word edit smoothenss.'));
$this->assertProseParts(
'See screenshots',
'Viewed video files',
array(
'- See screenshots',
'+ Viewed video files',
),
pht('Complete paragraph rewrite.'));
$this->assertProseParts(
'xaaax',
'xbbbx',
array(
'- xaaax',
'+ xbbbx',
),
pht('Whole word rewrite with common prefix and suffix.'));
$this->assertProseParts(
' aaa ',
' bbb ',
array(
'= ',
'- aaa',
'+ bbb',
'= ',
),
pht('Whole word rewrite with whitespace prefix and suffix.'));
$this->assertSummaryProseParts(
"a\nb\nc\nd\ne\nf\ng\nh\n",
"a\nb\nc\nd\nX\nf\ng\nh\n",
array(
'.',
"= d\n",
'- e',
'+ X',
"= \nf",
'.',
),
pht('Summary diff with middle change.'));
$this->assertSummaryProseParts(
"a\nb\nc\nd\ne\nf\ng\nh\n",
"X\nb\nc\nd\ne\nf\ng\nh\n",
array(
'- a',
'+ X',
"= \nb",
'.',
),
pht('Summary diff with head change.'));
$this->assertSummaryProseParts(
"a\nb\nc\nd\ne\nf\ng\nh\n",
"a\nb\nc\nd\ne\nf\ng\nX\n",
array(
'.',
"= g\n",
'- h',
'+ X',
"= \n",
),
pht('Summary diff with last change.'));
$this->assertProseParts(
'aaa aaa aaa aaa, bbb bbb bbb bbb.',
"aaa aaa aaa aaa, bbb bbb bbb bbb.\n\n- ccc ccc ccc",
array(
'= aaa aaa aaa aaa, bbb bbb bbb bbb.',
"+ \n\n- ccc ccc ccc",
),
pht('Diff with new trailing content.'));
$this->assertProseParts(
'aaa aaa aaa aaa, bbb bbb bbb bbb.',
'aaa aaa aaa aaa bbb bbb bbb bbb.',
array(
'= aaa aaa aaa aaa',
'- ,',
'= bbb bbb bbb bbb.',
),
pht('Diff with a removed comma.'));
$this->assertProseParts(
'aaa aaa aaa aaa, bbb bbb bbb bbb.',
"aaa aaa aaa aaa bbb bbb bbb bbb.\n\n- ccc ccc ccc!",
array(
'= aaa aaa aaa aaa',
'- ,',
'= bbb bbb bbb bbb.',
"+ \n\n- ccc ccc ccc!",
),
pht('Diff with a removed comma and new trailing content.'));
$this->assertProseParts(
'[ ] Walnuts',
'[X] Walnuts',
array(
'= [',
'- ',
'+ X',
'= ] Walnuts',
),
pht('Diff adding a tickmark to a checkbox list.'));
$this->assertProseParts(
'[[ ./week49 ]]',
'[[ ./week50 ]]',
array(
'= [[ ./week',
'- 49',
'+ 50',
'= ]]',
),
pht('Diff changing a remarkup wiki link target.'));
// Create a large corpus with many sentences and paragraphs.
$large_paragraph = 'xyz. ';
$large_paragraph = str_repeat($large_paragraph, 50);
$large_paragraph = rtrim($large_paragraph);
$large_corpus = $large_paragraph."\n\n";
$large_corpus = str_repeat($large_corpus, 50);
$large_corpus = rtrim($large_corpus);
$this->assertProseParts(
$large_corpus,
"aaa\n\n".$large_corpus."\n\nzzz",
array(
"+ aaa\n\n",
'= '.$large_corpus,
"+ \n\nzzz",
),
pht('Adding initial and final lines to a large corpus.'));
}
private function assertProseParts($old, $new, array $expect_parts, $label) {
$engine = new PhutilProseDifferenceEngine();
$diff = $engine->getDiff($old, $new);
$parts = $diff->getParts();
$this->assertParts($expect_parts, $parts, $label);
}
private function assertSummaryProseParts(
$old,
$new,
array $expect_parts,
$label) {
$engine = new PhutilProseDifferenceEngine();
$diff = $engine->getDiff($old, $new);
$parts = $diff->getSummaryParts();
$this->assertParts($expect_parts, $parts, $label);
}
private function assertParts(
array $expect,
array $actual_parts,
$label) {
$actual = array();
foreach ($actual_parts as $actual_part) {
$type = $actual_part['type'];
$text = $actual_part['text'];
switch ($type) {
case '.':
$actual[] = $type;
break;
default:
$actual[] = "{$type} {$text}";
break;
}
}
$this->assertEqual($expect, $actual, $label);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/diff/engine/PhabricatorInlineCommentAdjustmentEngine.php | src/infrastructure/diff/engine/PhabricatorInlineCommentAdjustmentEngine.php | <?php
final class PhabricatorInlineCommentAdjustmentEngine
extends Phobject {
private $viewer;
private $inlines;
private $revision;
private $oldChangesets;
private $newChangesets;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setInlines(array $inlines) {
assert_instances_of($inlines, 'DifferentialInlineComment');
$this->inlines = $inlines;
return $this;
}
public function getInlines() {
return $this->inlines;
}
public function setOldChangesets(array $old_changesets) {
assert_instances_of($old_changesets, 'DifferentialChangeset');
$this->oldChangesets = $old_changesets;
return $this;
}
public function getOldChangesets() {
return $this->oldChangesets;
}
public function setNewChangesets(array $new_changesets) {
assert_instances_of($new_changesets, 'DifferentialChangeset');
$this->newChangesets = $new_changesets;
return $this;
}
public function getNewChangesets() {
return $this->newChangesets;
}
public function setRevision(DifferentialRevision $revision) {
$this->revision = $revision;
return $this;
}
public function getRevision() {
return $this->revision;
}
public function execute() {
$viewer = $this->getViewer();
$inlines = $this->getInlines();
$revision = $this->getRevision();
$old = $this->getOldChangesets();
$new = $this->getNewChangesets();
$no_ghosts = $viewer->compareUserSetting(
PhabricatorOlderInlinesSetting::SETTINGKEY,
PhabricatorOlderInlinesSetting::VALUE_GHOST_INLINES_DISABLED);
if ($no_ghosts) {
return $inlines;
}
$all = array_merge($old, $new);
$changeset_ids = mpull($inlines, 'getChangesetID');
$changeset_ids = array_unique($changeset_ids);
$all_map = mpull($all, null, 'getID');
// We already have at least some changesets, and we might not need to do
// any more data fetching. Remove everything we already have so we can
// tell if we need new stuff.
foreach ($changeset_ids as $key => $id) {
if (isset($all_map[$id])) {
unset($changeset_ids[$key]);
}
}
if ($changeset_ids) {
$changesets = id(new DifferentialChangesetQuery())
->setViewer($viewer)
->withIDs($changeset_ids)
->execute();
$changesets = mpull($changesets, null, 'getID');
} else {
$changesets = array();
}
$changesets += $all_map;
$id_map = array();
foreach ($all as $changeset) {
$id_map[$changeset->getID()] = $changeset->getID();
}
// Generate filename maps for older and newer comments. If we're bringing
// an older comment forward in a diff-of-diffs, we want to put it on the
// left side of the screen, not the right side. Both sides are "new" files
// with the same name, so they're both appropriate targets, but the left
// is a better target conceptually for users because it's more consistent
// with the rest of the UI, which shows old information on the left and
// new information on the right.
$move_here = DifferentialChangeType::TYPE_MOVE_HERE;
$name_map_old = array();
$name_map_new = array();
$move_map = array();
foreach ($all as $changeset) {
$changeset_id = $changeset->getID();
$filenames = array();
$filenames[] = $changeset->getFilename();
// If this is the target of a move, also map comments on the old filename
// to this changeset.
if ($changeset->getChangeType() == $move_here) {
$old_file = $changeset->getOldFile();
$filenames[] = $old_file;
$move_map[$changeset_id][$old_file] = true;
}
foreach ($filenames as $filename) {
// We update the old map only if we don't already have an entry (oldest
// changeset persists).
if (empty($name_map_old[$filename])) {
$name_map_old[$filename] = $changeset_id;
}
// We always update the new map (newest changeset overwrites).
$name_map_new[$changeset->getFilename()] = $changeset_id;
}
}
$new_id_map = mpull($new, null, 'getID');
$results = array();
foreach ($inlines as $inline) {
$changeset_id = $inline->getChangesetID();
if (isset($id_map[$changeset_id])) {
// This inline is legitimately on one of the current changesets, so
// we can include it in the result set unmodified.
$results[] = $inline;
continue;
}
$changeset = idx($changesets, $changeset_id);
if (!$changeset) {
// Just discard this inline, as it has bogus data.
continue;
}
$target_id = null;
if (isset($new_id_map[$changeset_id])) {
$name_map = $name_map_new;
$is_new = true;
} else {
$name_map = $name_map_old;
$is_new = false;
}
$filename = $changeset->getFilename();
if (isset($name_map[$filename])) {
// This changeset is on a file with the same name as the current
// changeset, so we're going to port it forward or backward.
$target_id = $name_map[$filename];
$is_move = isset($move_map[$target_id][$filename]);
if ($is_new) {
if ($is_move) {
$reason = pht(
'This comment was made on a file with the same name as the '.
'file this file was moved from, but in a newer diff.');
} else {
$reason = pht(
'This comment was made on a file with the same name, but '.
'in a newer diff.');
}
} else {
if ($is_move) {
$reason = pht(
'This comment was made on a file with the same name as the '.
'file this file was moved from, but in an older diff.');
} else {
$reason = pht(
'This comment was made on a file with the same name, but '.
'in an older diff.');
}
}
}
// If we didn't find a target and this change is the target of a move,
// look for a match against the old filename.
if (!$target_id) {
if ($changeset->getChangeType() == $move_here) {
$filename = $changeset->getOldFile();
if (isset($name_map[$filename])) {
$target_id = $name_map[$filename];
if ($is_new) {
$reason = pht(
'This comment was made on a file which this file was moved '.
'to, but in a newer diff.');
} else {
$reason = pht(
'This comment was made on a file which this file was moved '.
'to, but in an older diff.');
}
}
}
}
// If we found a changeset to port this comment to, bring it forward
// or backward and mark it.
if ($target_id) {
$diff_id = $changeset->getDiffID();
$inline_id = $inline->getID();
$revision_id = $revision->getID();
$href = "/D{$revision_id}?id={$diff_id}#inline-{$inline_id}";
$inline
->makeEphemeral(true)
->setChangesetID($target_id)
->setIsGhost(
array(
'new' => $is_new,
'reason' => $reason,
'href' => $href,
'originalID' => $changeset->getID(),
));
$results[] = $inline;
}
}
// Filter out the inlines we ported forward which won't be visible because
// they appear on the wrong side of a file.
$keep_map = array();
foreach ($old as $changeset) {
$keep_map[$changeset->getID()][0] = true;
}
foreach ($new as $changeset) {
$keep_map[$changeset->getID()][1] = true;
}
foreach ($results as $key => $inline) {
$is_new = (int)$inline->getIsNewFile();
$changeset_id = $inline->getChangesetID();
if (!isset($keep_map[$changeset_id][$is_new])) {
unset($results[$key]);
continue;
}
}
// Adjust inline line numbers to account for content changes across
// updates and rebases.
$plan = array();
$need = array();
foreach ($results as $inline) {
$ghost = $inline->getIsGhost();
if (!$ghost) {
// If this isn't a "ghost" inline, ignore it.
continue;
}
$src_id = $ghost['originalID'];
$dst_id = $inline->getChangesetID();
$xforms = array();
// If the comment is on the right, transform it through the inverse map
// back to the left.
if ($inline->getIsNewFile()) {
$xforms[] = array($src_id, $src_id, true);
}
// Transform it across rebases.
$xforms[] = array($src_id, $dst_id, false);
// If the comment is on the right, transform it back onto the right.
if ($inline->getIsNewFile()) {
$xforms[] = array($dst_id, $dst_id, false);
}
$key = array();
foreach ($xforms as $xform) {
list($u, $v, $inverse) = $xform;
$short = $u.'/'.$v;
$need[$short] = array($u, $v);
$part = $u.($inverse ? '<' : '>').$v;
$key[] = $part;
}
$key = implode(',', $key);
if (empty($plan[$key])) {
$plan[$key] = array(
'xforms' => $xforms,
'inlines' => array(),
);
}
$plan[$key]['inlines'][] = $inline;
}
if ($need) {
$maps = DifferentialLineAdjustmentMap::loadMaps($need);
} else {
$maps = array();
}
foreach ($plan as $step) {
$xforms = $step['xforms'];
$chain = null;
foreach ($xforms as $xform) {
list($u, $v, $inverse) = $xform;
$map = idx(idx($maps, $u, array()), $v);
if (!$map) {
continue 2;
}
if ($inverse) {
$map = DifferentialLineAdjustmentMap::newInverseMap($map);
} else {
$map = clone $map;
}
if ($chain) {
$chain->addMapToChain($map);
} else {
$chain = $map;
}
}
foreach ($step['inlines'] as $inline) {
$head_line = $inline->getLineNumber();
$tail_line = ($head_line + $inline->getLineLength());
$head_info = $chain->mapLine($head_line, false);
$tail_info = $chain->mapLine($tail_line, true);
list($head_deleted, $head_offset, $head_line) = $head_info;
list($tail_deleted, $tail_offset, $tail_line) = $tail_info;
if ($head_offset !== false) {
$inline->setLineNumber($head_line + $head_offset);
} else {
$inline->setLineNumber($head_line);
$inline->setLineLength($tail_line - $head_line);
}
}
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/events/PhabricatorEventEngine.php | src/infrastructure/events/PhabricatorEventEngine.php | <?php
final class PhabricatorEventEngine extends Phobject {
public static function initialize() {
// NOTE: If any of this fails, we just log it and move on. It's important
// to try to make it through here because users may have difficulty fixing
// fix the errors if we don't: for example, if we fatal here a user may not
// be able to run `bin/config` in order to remove an invalid listener.
// Load automatic listeners.
$listeners = id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorAutoEventListener')
->execute();
// Load configured listeners.
$config_listeners = PhabricatorEnv::getEnvConfig('events.listeners');
foreach ($config_listeners as $listener_class) {
try {
$listeners[] = newv($listener_class, array());
} catch (Exception $ex) {
phlog($ex);
}
}
// Add built-in listeners.
$listeners[] = new DarkConsoleEventPluginAPI();
// Add application listeners.
$applications = PhabricatorApplication::getAllInstalledApplications();
foreach ($applications as $application) {
$app_listeners = $application->getEventListeners();
foreach ($app_listeners as $listener) {
$listener->setApplication($application);
$listeners[] = $listener;
}
}
// Now, register all of the listeners.
foreach ($listeners as $listener) {
try {
$listener->register();
} catch (Exception $ex) {
phlog($ex);
}
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/events/PhabricatorEventListener.php | src/infrastructure/events/PhabricatorEventListener.php | <?php
abstract class PhabricatorEventListener extends PhutilEventListener {
private $application;
public function setApplication(PhabricatorApplication $application) {
$this->application = $application;
return $this;
}
public function getApplication() {
return $this->application;
}
public function hasApplicationCapability(
PhabricatorUser $viewer,
$capability) {
return PhabricatorPolicyFilter::hasCapability(
$viewer,
$this->getApplication(),
$capability);
}
public function canUseApplication(PhabricatorUser $viewer) {
return $this->hasApplicationCapability(
$viewer,
PhabricatorPolicyCapability::CAN_VIEW);
}
protected function addActionMenuItems(PhutilEvent $event, $items) {
if ($event->getType() !== PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS) {
throw new Exception(pht('Not an action menu event!'));
}
if (!$items) {
return;
}
if (!is_array($items)) {
$items = array($items);
}
$event_actions = $event->getValue('actions');
foreach ($items as $item) {
$event_actions[] = $item;
}
$event->setValue('actions', $event_actions);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/events/PhabricatorAutoEventListener.php | src/infrastructure/events/PhabricatorAutoEventListener.php | <?php
/**
* Event listener which is registered automatically, without requiring
* configuration.
*
* Normally, event listeners must be registered via applications. This is
* appropriate for structured listeners in libraries, but it adds a lot of
* overhead and is cumbersome for one-off listeners.
*
* All concrete subclasses of this class are automatically registered at
* startup. This allows it to be used with custom one-offs that can be dropped
* into `phabricator/src/extensions/`.
*/
abstract class PhabricatorAutoEventListener extends PhabricatorEventListener {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/events/PhabricatorEvent.php | src/infrastructure/events/PhabricatorEvent.php | <?php
final class PhabricatorEvent extends PhutilEvent {
private $user;
private $aphrontRequest;
private $conduitRequest;
public function setUser(PhabricatorUser $user) {
$this->user = $user;
return $this;
}
public function getUser() {
return $this->user;
}
public function setAphrontRequest(AphrontRequest $aphront_request) {
$this->aphrontRequest = $aphront_request;
return $this;
}
public function getAphrontRequest() {
return $this->aphrontRequest;
}
public function setConduitRequest(ConduitAPIRequest $conduit_request) {
$this->conduitRequest = $conduit_request;
return $this;
}
public function getConduitRequest() {
return $this->conduitRequest;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/events/PhabricatorExampleEventListener.php | src/infrastructure/events/PhabricatorExampleEventListener.php | <?php
/**
* Example event listener. For details about installing Phabricator event hooks,
* refer to @{article:Events User Guide: Installing Event Listeners}.
*/
final class PhabricatorExampleEventListener extends PhabricatorEventListener {
public function register() {
// When your listener is installed, its register() method will be called.
// You should listen() to any events you are interested in here.
$this->listen(PhabricatorEventType::TYPE_TEST_DIDRUNTEST);
}
public function handleEvent(PhutilEvent $event) {
// When an event you have called listen() for in your register() method
// occurs, this method will be invoked. You should respond to the event.
// In this case, we just echo a message out so the event test script will
// do something visible.
$console = PhutilConsole::getConsole();
$console->writeOut(
"%s\n",
pht(
'%s got test event at %d',
__CLASS__,
$event->getValue('time')));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/events/constant/PhabricatorEventType.php | src/infrastructure/events/constant/PhabricatorEventType.php | <?php
/**
* For detailed explanations of these events, see
* @{article:Events User Guide: Installing Event Listeners}.
*/
final class PhabricatorEventType extends PhutilEventType {
const TYPE_DIFFERENTIAL_WILLMARKGENERATED = 'differential.willMarkGenerated';
const TYPE_DIFFUSION_DIDDISCOVERCOMMIT = 'diffusion.didDiscoverCommit';
const TYPE_TEST_DIDRUNTEST = 'test.didRunTest';
const TYPE_UI_DIDRENDERACTIONS = 'ui.didRenderActions';
const TYPE_UI_WILLRENDEROBJECTS = 'ui.willRenderObjects';
const TYPE_UI_DDIDRENDEROBJECT = 'ui.didRenderObject';
const TYPE_UI_DIDRENDEROBJECTS = 'ui.didRenderObjects';
const TYPE_UI_WILLRENDERPROPERTIES = 'ui.willRenderProperties';
const TYPE_PEOPLE_DIDRENDERMENU = 'people.didRenderMenu';
const TYPE_AUTH_WILLREGISTERUSER = 'auth.willRegisterUser';
const TYPE_AUTH_DIDVERIFYEMAIL = 'auth.didVerifyEmail';
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/lipsum/PhutilRealNameContextFreeGrammar.php | src/infrastructure/lipsum/PhutilRealNameContextFreeGrammar.php | <?php
final class PhutilRealNameContextFreeGrammar
extends PhutilContextFreeGrammar {
protected function getRules() {
return array(
'start' => array(
'[first] [last]',
'[first] [last]',
'[first] [last]',
'[first] [last]',
'[first] [last]',
'[first] [last]',
'[first] [last]',
'[first] [last]',
'[first] [last]-[last]',
'[first] [middle] [last]',
'[first] "[nick]" [last]',
'[first] [particle] [particle] [particle]',
),
'first' => array(
'Mohamed',
'Youssef',
'Ahmed',
'Mahmoud',
'Mustafa',
'Fatma',
'Aya',
'Noam',
'Adam',
'Lucas',
'Noah',
'Jakub',
'Victor',
'Harry',
'Rasmus',
'Nathan',
'Emil',
'Charlie',
'Leon',
'Dylan',
'Alexander',
'Emma',
'Marie',
'Lea',
'Amelia',
'Hanna',
'Emily',
'Sofia',
'Julia',
'Santiago',
'Sebastian',
'Olivia',
'Madison',
'Isabella',
'Esther',
'Anya',
'Camila',
'Jack',
'Oliver',
),
'nick' => array(
'Buzz',
'Juggernaut',
'Haze',
'Hawk',
'Iceman',
'Killer',
'Apex',
'Ocelot',
),
'middle' => array(
'Rose',
'Grace',
'Jane',
'Louise',
'Jade',
'James',
'John',
'William',
'Thomas',
'Alexander',
),
'last' => array(
'[termlast]',
'[termlast]',
'[termlast]',
'[termlast]',
'[termlast]',
'[termlast]',
'[termlast]',
'[termlast]',
'O\'[termlast]',
'Mc[termlast]',
),
'termlast' => array(
'Smith',
'Johnson',
'Williams',
'Jones',
'Brown',
'Davis',
'Miller',
'Wilson',
'Moore',
'Taylor',
'Anderson',
'Thomas',
'Jackson',
'White',
'Harris',
'Martin',
'Thompson',
'Garcia',
'Marinez',
'Robinson',
'Clark',
'Rodrigues',
'Lewis',
'Lee',
'Walker',
'Hall',
'Allen',
'Young',
'Hernandex',
'King',
'Wang',
'Li',
'Zhang',
'Liu',
'Chen',
'Yang',
'Huang',
'Zhao',
'Wu',
'Zhou',
'Xu',
'Sun',
'Ma',
),
'particle' => array(
'Wu',
'Xu',
'Ma',
'Li',
'Liu',
'Shao',
'Lin',
'Khan',
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/lipsum/PhutilLipsumContextFreeGrammar.php | src/infrastructure/lipsum/PhutilLipsumContextFreeGrammar.php | <?php
final class PhutilLipsumContextFreeGrammar
extends PhutilContextFreeGrammar {
protected function getRules() {
return array(
'start' => array(
'[words].',
'[words].',
'[words].',
'[words]: [word], [word], [word] [word].',
'[words]; [lowerwords].',
'[words]!',
'[words], "[words]."',
'[words] ("[upperword] [upperword] [upperword]") [lowerwords].',
'[words]?',
),
'words' => array(
'[upperword] [lowerwords]',
),
'upperword' => array(
'Lorem',
'Ipsum',
'Dolor',
'Sit',
'Amet',
),
'lowerwords' => array(
'[word]',
'[word] [word]',
'[word] [word] [word]',
'[word] [word] [word] [word]',
'[word] [word] [word] [word] [word]',
'[word] [word] [word] [word] [word]',
'[word] [word] [word] [word] [word] [word]',
'[word] [word] [word] [word] [word] [word]',
),
'word' => array(
'ad',
'adipisicing',
'aliqua',
'aliquip',
'amet',
'anim',
'aute',
'cillum',
'commodo',
'consectetur',
'consequat',
'culpa',
'cupidatat',
'deserunt',
'do',
'dolor',
'dolore',
'duis',
'ea',
'eiusmod',
'elit',
'enim',
'esse',
'est',
'et',
'eu',
'ex',
'excepteur',
'exercitation',
'fugiat',
'id',
'in',
'incididunt',
'ipsum',
'irure',
'labore',
'laboris',
'laborum',
'lorem',
'magna',
'minim',
'mollit',
'nisi',
'non',
'nostrud',
'nulla',
'occaecat',
'officia',
'pariatur',
'proident',
'qui',
'quis',
'reprehenderit',
'sed',
'sint',
'sit',
'sunt',
'tempor',
'ullamco',
'ut',
'velit',
'veniam',
'voluptate',
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/lipsum/PhutilContextFreeGrammar.php | src/infrastructure/lipsum/PhutilContextFreeGrammar.php | <?php
/**
* Generate nonsense test data according to a context-free grammar definition.
*/
abstract class PhutilContextFreeGrammar extends Phobject {
private $limit = 65535;
abstract protected function getRules();
public function generateSeveral($count, $implode = ' ') {
$paragraph = array();
for ($ii = 0; $ii < $count; $ii++) {
$paragraph[$ii] = $this->generate();
}
return implode($implode, $paragraph);
}
public function generate() {
$count = 0;
$rules = $this->getRules();
return $this->applyRules('[start]', $count, $rules);
}
final protected function applyRules($input, &$count, array $rules) {
if (++$count > $this->limit) {
throw new Exception(pht('Token replacement count exceeded limit!'));
}
$matches = null;
preg_match_all('/(\\[[^\\]]+\\])/', $input, $matches, PREG_OFFSET_CAPTURE);
foreach (array_reverse($matches[1]) as $token_spec) {
list($token, $offset) = $token_spec;
$token_name = substr($token, 1, -1);
$options = array();
if (($name_end = strpos($token_name, ','))) {
$options_parser = new PhutilSimpleOptions();
$options = $options_parser->parse($token_name);
$token_name = substr($token_name, 0, $name_end);
}
if (empty($rules[$token_name])) {
throw new Exception(pht("Invalid token '%s' in grammar.", $token_name));
}
$key = array_rand($rules[$token_name]);
$replacement = $this->applyRules($rules[$token_name][$key],
$count, $rules);
if (isset($options['indent'])) {
if (is_numeric($options['indent'])) {
$replacement = self::strPadLines($replacement, $options['indent']);
} else {
$replacement = self::strPadLines($replacement);
}
}
if (isset($options['trim'])) {
switch ($options['trim']) {
case 'left':
$replacement = ltrim($replacement);
break;
case 'right':
$replacement = rtrim($replacement);
break;
default:
case 'both':
$replacement = trim($replacement);
break;
}
}
if (isset($options['block'])) {
$replacement = "\n".$replacement."\n";
}
$input = substr_replace($input, $replacement, $offset, strlen($token));
}
return $input;
}
private static function strPadLines($text, $num_spaces = 2) {
$text_lines = phutil_split_lines($text);
foreach ($text_lines as $linenr => $line) {
$text_lines[$linenr] = str_repeat(' ', $num_spaces).$line;
}
return implode('', $text_lines);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/lipsum/code/PhutilJavaCodeSnippetContextFreeGrammar.php | src/infrastructure/lipsum/code/PhutilJavaCodeSnippetContextFreeGrammar.php | <?php
final class PhutilJavaCodeSnippetContextFreeGrammar
extends PhutilCLikeCodeSnippetContextFreeGrammar {
protected function buildRuleSet() {
$parent_ruleset = parent::buildRuleSet();
$rulesset = array_merge($parent_ruleset, $this->getClassRuleSets());
$rulesset[] = $this->getTypeNameGrammarSet();
$rulesset[] = $this->getNamespaceDeclGrammarSet();
$rulesset[] = $this->getNamespaceNameGrammarSet();
$rulesset[] = $this->getImportGrammarSet();
$rulesset[] = $this->getMethodReturnTypeGrammarSet();
$rulesset[] = $this->getMethodNameGrammarSet();
$rulesset[] = $this->getVarDeclGrammarSet();
$rulesset[] = $this->getClassDerivGrammarSet();
return $rulesset;
}
protected function getStartGrammarSet() {
return $this->buildGrammarSet('start',
array(
'[import, block][nmspdecl, block][classdecl, block]',
));
}
protected function getClassDeclGrammarSet() {
return $this->buildGrammarSet('classdecl',
array(
'[classinheritancemod] [visibility] class [classname][classderiv] '.
'{[classbody, indent, block]}',
'[visibility] class [classname][classderiv] '.
'{[classbody, indent, block]}',
));
}
protected function getClassDerivGrammarSet() {
return $this->buildGrammarSet('classderiv',
array(
' extends [classname]',
'',
'',
));
}
protected function getTypeNameGrammarSet() {
return $this->buildGrammarSet('type',
array(
'int',
'boolean',
'char',
'short',
'long',
'float',
'double',
'[classname]',
'[type][]',
));
}
protected function getMethodReturnTypeGrammarSet() {
return $this->buildGrammarSet('methodreturn',
array(
'[type]',
'void',
));
}
protected function getNamespaceDeclGrammarSet() {
return $this->buildGrammarSet('nmspdecl',
array(
'package [nmspname][term]',
));
}
protected function getNamespaceNameGrammarSet() {
return $this->buildGrammarSet('nmspname',
array(
'java.lang',
'java.io',
'com.example.proj.std',
'derp.example.www',
));
}
protected function getImportGrammarSet() {
return $this->buildGrammarSet('import',
array(
'import [nmspname][term]',
'import [nmspname].*[term]',
'import [nmspname].[classname][term]',
));
}
protected function getExprGrammarSet() {
$expr = parent::getExprGrammarSet();
$expr['expr'][] = 'new [classname]([funccallparam])';
$expr['expr'][] = '[methodcall]';
$expr['expr'][] = '[methodcall]';
$expr['expr'][] = '[methodcall]';
$expr['expr'][] = '[methodcall]';
// Add some 'char's
for ($ii = 0; $ii < 2; $ii++) {
$expr['expr'][] = "'".Filesystem::readRandomCharacters(1)."'";
}
return $expr;
}
protected function getStmtGrammarSet() {
$stmt = parent::getStmtGrammarSet();
$stmt['stmt'][] = '[vardecl]';
$stmt['stmt'][] = '[vardecl]';
// `try` to `throw` a `Ball`!
$stmt['stmt'][] = 'throw [classname][term]';
return $stmt;
}
protected function getPropDeclGrammarSet() {
return $this->buildGrammarSet('propdecl',
array(
'[visibility] [type] [varname][term]',
));
}
protected function getVarDeclGrammarSet() {
return $this->buildGrammarSet('vardecl',
array(
'[type] [varname][term]',
'[type] [assignment][term]',
));
}
protected function getFuncNameGrammarSet() {
return $this->buildGrammarSet('funcname',
array(
'[methodname]',
'[classname].[methodname]',
// This is just silly (too much recursion)
// '[classname].[funcname]',
// Don't do this for now, it just clutters up output (thanks to rec.)
// '[nmspname].[classname].[methodname]',
));
}
// Renamed from `funcname`
protected function getMethodNameGrammarSet() {
$funcnames = head(parent::getFuncNameGrammarSet());
return $this->buildGrammarSet('methodname', $funcnames);
}
protected function getMethodFuncDeclGrammarSet() {
return $this->buildGrammarSet('methodfuncdecl',
array(
'[methodreturn] [methodname]([funcparam]) '.
'{[methodbody, indent, block, trim=right]}',
));
}
protected function getFuncParamGrammarSet() {
return $this->buildGrammarSet('funcparam',
array(
'',
'[type] [varname]',
'[type] [varname], [type] [varname]',
'[type] [varname], [type] [varname], [type] [varname]',
));
}
protected function getAbstractMethodDeclGrammarSet() {
return $this->buildGrammarSet('abstractmethoddecl',
array(
'abstract [methodreturn] [methodname]([funcparam])[term]',
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/lipsum/code/PhutilCLikeCodeSnippetContextFreeGrammar.php | src/infrastructure/lipsum/code/PhutilCLikeCodeSnippetContextFreeGrammar.php | <?php
/**
* Generates valid context-free code for most programming languages that could
* pass as C. Except for PHP. But includes Java (mostly).
*/
abstract class PhutilCLikeCodeSnippetContextFreeGrammar
extends PhutilCodeSnippetContextFreeGrammar {
protected function buildRuleSet() {
return array(
$this->getStmtTerminationGrammarSet(),
$this->getVarNameGrammarSet(),
$this->getNullExprGrammarSet(),
$this->getNumberGrammarSet(),
$this->getExprGrammarSet(),
$this->getCondGrammarSet(),
$this->getLoopGrammarSet(),
$this->getStmtGrammarSet(),
$this->getAssignmentGrammarSet(),
$this->getArithExprGrammarSet(),
$this->getBoolExprGrammarSet(),
$this->getBoolValGrammarSet(),
$this->getTernaryExprGrammarSet(),
$this->getFuncNameGrammarSet(),
$this->getFuncCallGrammarSet(),
$this->getFuncCallParamGrammarSet(),
$this->getFuncDeclGrammarSet(),
$this->getFuncParamGrammarSet(),
$this->getFuncBodyGrammarSet(),
$this->getFuncReturnGrammarSet(),
);
}
protected function getStartGrammarSet() {
$start_grammar = parent::getStartGrammarSet();
$start_grammar['start'][] = '[funcdecl]';
return $start_grammar;
}
protected function getStmtTerminationGrammarSet() {
return $this->buildGrammarSet('term', array(';'));
}
protected function getFuncCallGrammarSet() {
return $this->buildGrammarSet('funccall',
array(
'[funcname]([funccallparam])',
));
}
protected function getFuncCallParamGrammarSet() {
return $this->buildGrammarSet('funccallparam',
array(
'',
'[expr]',
'[expr], [expr]',
));
}
protected function getFuncDeclGrammarSet() {
return $this->buildGrammarSet('funcdecl',
array(
'function [funcname]([funcparam]) '.
'{[funcbody, indent, block, trim=right]}',
));
}
protected function getFuncParamGrammarSet() {
return $this->buildGrammarSet('funcparam',
array(
'',
'[varname]',
'[varname], [varname]',
'[varname], [varname], [varname]',
));
}
protected function getFuncBodyGrammarSet() {
return $this->buildGrammarSet('funcbody',
array(
"[stmt]\n[stmt]\n[funcreturn]",
"[stmt]\n[stmt]\n[stmt]\n[funcreturn]",
"[stmt]\n[stmt]\n[stmt]\n[stmt]\n[funcreturn]",
));
}
protected function getFuncReturnGrammarSet() {
return $this->buildGrammarSet('funcreturn',
array(
'return [expr][term]',
'',
));
}
// Not really C, but put it here because of the curly braces and mostly shared
// among Java and PHP
protected function getClassDeclGrammarSet() {
return $this->buildGrammarSet('classdecl',
array(
'[classinheritancemod] class [classname] {[classbody, indent, block]}',
'class [classname] {[classbody, indent, block]}',
));
}
protected function getClassNameGrammarSet() {
return $this->buildGrammarSet('classname',
array(
'MuffinHouse',
'MuffinReader',
'MuffinAwesomizer',
'SuperException',
'Librarian',
'Book',
'Ball',
'BallOfCode',
'AliceAndBobsSharedSecret',
'FileInputStream',
'FileOutputStream',
'BufferedReader',
'BufferedWriter',
'Cardigan',
'HouseOfCards',
'UmbrellaClass',
'GenericThing',
));
}
protected function getClassBodyGrammarSet() {
return $this->buildGrammarSet('classbody',
array(
'[methoddecl]',
"[methoddecl]\n\n[methoddecl]",
"[propdecl]\n[propdecl]\n\n[methoddecl]\n\n[methoddecl]",
"[propdecl]\n[propdecl]\n[propdecl]\n\n[methoddecl]\n\n[methoddecl]".
"\n\n[methoddecl]",
));
}
protected function getVisibilityGrammarSet() {
return $this->buildGrammarSet('visibility',
array(
'private',
'protected',
'public',
));
}
protected function getClassInheritanceModGrammarSet() {
return $this->buildGrammarSet('classinheritancemod',
array(
'final',
'abstract',
));
}
// Keeping this separate so we won't give abstract methods a function body
protected function getMethodInheritanceModGrammarSet() {
return $this->buildGrammarSet('methodinheritancemod',
array(
'final',
));
}
protected function getMethodDeclGrammarSet() {
return $this->buildGrammarSet('methoddecl',
array(
'[visibility] [methodfuncdecl]',
'[visibility] [methodfuncdecl]',
'[methodinheritancemod] [visibility] [methodfuncdecl]',
'[abstractmethoddecl]',
));
}
protected function getMethodFuncDeclGrammarSet() {
return $this->buildGrammarSet('methodfuncdecl',
array(
'function [funcname]([funcparam]) '.
'{[methodbody, indent, block, trim=right]}',
));
}
protected function getMethodBodyGrammarSet() {
return $this->buildGrammarSet('methodbody',
array(
"[methodstmt]\n[methodbody]",
"[methodstmt]\n[funcreturn]",
));
}
protected function getMethodStmtGrammarSet() {
$stmts = $this->getStmtGrammarSet();
return $this->buildGrammarSet('methodstmt',
array_merge(
$stmts['stmt'],
array(
'[methodcall][term]',
)));
}
protected function getMethodCallGrammarSet() {
// Java/JavaScript
return $this->buildGrammarSet('methodcall',
array(
'this.[funccall]',
'[varname].[funccall]',
'[classname].[funccall]',
));
}
protected function getAbstractMethodDeclGrammarSet() {
return $this->buildGrammarSet('abstractmethoddecl',
array(
'abstract function [funcname]([funcparam])[term]',
));
}
protected function getPropDeclGrammarSet() {
return $this->buildGrammarSet('propdecl',
array(
'[visibility] [varname][term]',
));
}
protected function getClassRuleSets() {
return array(
$this->getClassInheritanceModGrammarSet(),
$this->getMethodInheritanceModGrammarSet(),
$this->getClassDeclGrammarSet(),
$this->getClassNameGrammarSet(),
$this->getClassBodyGrammarSet(),
$this->getMethodDeclGrammarSet(),
$this->getMethodFuncDeclGrammarSet(),
$this->getMethodBodyGrammarSet(),
$this->getMethodStmtGrammarSet(),
$this->getMethodCallGrammarSet(),
$this->getAbstractMethodDeclGrammarSet(),
$this->getPropDeclGrammarSet(),
$this->getVisibilityGrammarSet(),
);
}
public function generateClass() {
$rules = array_merge($this->getRules(), $this->getClassRuleSets());
$rules['start'] = array('[classdecl]');
$count = 0;
return $this->applyRules('[start]', $count, $rules);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/lipsum/code/PhutilCodeSnippetContextFreeGrammar.php | src/infrastructure/lipsum/code/PhutilCodeSnippetContextFreeGrammar.php | <?php
/**
* Generates non-sense code snippets according to context-free rules, respecting
* indentation etc.
*
* Also provides a common ruleset shared among many mainstream programming
* languages (that is, not Lisp).
*/
abstract class PhutilCodeSnippetContextFreeGrammar
extends PhutilContextFreeGrammar {
public function generate() {
// A trailing newline is favorable for source code
return trim(parent::generate())."\n";
}
final protected function getRules() {
return array_merge(
$this->getStartGrammarSet(),
$this->getStmtGrammarSet(),
array_mergev($this->buildRuleSet()));
}
abstract protected function buildRuleSet();
protected function buildGrammarSet($name, array $set) {
return array(
$name => $set,
);
}
protected function getStartGrammarSet() {
return $this->buildGrammarSet('start',
array(
"[stmt]\n[stmt]",
"[stmt]\n[stmt]\n[stmt]",
"[stmt]\n[stmt]\n[stmt]\n[stmt]",
));
}
protected function getStmtGrammarSet() {
return $this->buildGrammarSet('stmt',
array(
'[assignment][term]',
'[assignment][term]',
'[assignment][term]',
'[assignment][term]',
'[funccall][term]',
'[funccall][term]',
'[funccall][term]',
'[funccall][term]',
'[cond]',
'[loop]',
));
}
protected function getFuncNameGrammarSet() {
return $this->buildGrammarSet('funcname',
array(
'do_something',
'nonempty',
'noOp',
'call_user_func',
'getenv',
'render',
'super',
'derpify',
'awesomize',
'equals',
'run',
'flee',
'fight',
'notify',
'listen',
'calculate',
'aim',
'open',
));
}
protected function getVarNameGrammarSet() {
return $this->buildGrammarSet('varname',
array(
'is_something',
'object',
'name',
'token',
'label',
'piece_of_the_pie',
'type',
'state',
'param',
'action',
'key',
'timeout',
'result',
));
}
protected function getNullExprGrammarSet() {
return $this->buildGrammarSet('null', array('null'));
}
protected function getNumberGrammarSet() {
return $this->buildGrammarSet('number',
array(
mt_rand(-1, 100),
mt_rand(-100, 1000),
mt_rand(-1000, 5000),
mt_rand(0, 1).'.'.mt_rand(1, 1000),
mt_rand(0, 50).'.'.mt_rand(1, 1000),
));
}
protected function getExprGrammarSet() {
return $this->buildGrammarSet('expr',
array(
'[null]',
'[number]',
'[number]',
'[varname]',
'[varname]',
'[boolval]',
'[boolval]',
'[boolexpr]',
'[boolexpr]',
'[funccall]',
'[arithexpr]',
'[arithexpr]',
// Some random strings
'"'.Filesystem::readRandomCharacters(4).'"',
'"'.Filesystem::readRandomCharacters(5).'"',
));
}
protected function getBoolExprGrammarSet() {
return $this->buildGrammarSet('boolexpr',
array(
'[varname]',
'![varname]',
'[varname] == [boolval]',
'[varname] != [boolval]',
'[ternary]',
));
}
protected function getBoolValGrammarSet() {
return $this->buildGrammarSet('boolval',
array(
'true',
'false',
));
}
protected function getArithExprGrammarSet() {
return $this->buildGrammarSet('arithexpr',
array(
'[varname]++',
'++[varname]',
'[varname] + [number]',
'[varname]--',
'--[varname]',
'[varname] - [number]',
));
}
protected function getAssignmentGrammarSet() {
return $this->buildGrammarSet('assignment',
array(
'[varname] = [expr]',
'[varname] = [arithexpr]',
'[varname] += [expr]',
));
}
protected function getCondGrammarSet() {
return $this->buildGrammarSet('cond',
array(
'if ([boolexpr]) {[stmt, indent, block]}',
'if ([boolexpr]) {[stmt, indent, block]} else {[stmt, indent, block]}',
));
}
protected function getLoopGrammarSet() {
return $this->buildGrammarSet('loop',
array(
'while ([boolexpr]) {[stmt, indent, block]}',
'do {[stmt, indent, block]} while ([boolexpr])[term]',
'for ([assignment]; [boolexpr]; [expr]) {[stmt, indent, block]}',
));
}
protected function getTernaryExprGrammarSet() {
return $this->buildGrammarSet('ternary',
array(
'[boolexpr] ? [expr] : [expr]',
));
}
protected function getStmtTerminationGrammarSet() {
return $this->buildGrammarSet('term', array(''));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/lipsum/code/PhutilPHPCodeSnippetContextFreeGrammar.php | src/infrastructure/lipsum/code/PhutilPHPCodeSnippetContextFreeGrammar.php | <?php
final class PhutilPHPCodeSnippetContextFreeGrammar
extends PhutilCLikeCodeSnippetContextFreeGrammar {
protected function buildRuleSet() {
return array_merge(parent::buildRuleSet(), $this->getClassRuleSets());
}
protected function getStartGrammarSet() {
$start_grammar = parent::getStartGrammarSet();
$start_grammar['start'][] = '[classdecl]';
$start_grammar['start'][] = '[classdecl]';
return $start_grammar;
}
protected function getExprGrammarSet() {
$expr = parent::getExprGrammarSet();
$expr['expr'][] = 'new [classname]([funccallparam])';
$expr['expr'][] = '[classname]::[funccall]';
return $expr;
}
protected function getVarNameGrammarSet() {
$varnames = parent::getVarNameGrammarSet();
foreach ($varnames as $vn_key => $vn_val) {
foreach ($vn_val as $vv_key => $vv_value) {
$varnames[$vn_key][$vv_key] = '$'.$vv_value;
}
}
return $varnames;
}
protected function getFuncNameGrammarSet() {
return $this->buildGrammarSet('funcname',
array_mergev(get_defined_functions()));
}
protected function getMethodCallGrammarSet() {
return $this->buildGrammarSet('methodcall',
array(
'$this->[funccall]',
'self::[funccall]',
'static::[funccall]',
'[varname]->[funccall]',
'[classname]::[funccall]',
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/scope/PhabricatorLocaleScopeGuard.php | src/infrastructure/internationalization/scope/PhabricatorLocaleScopeGuard.php | <?php
/**
* Change the effective locale for the lifetime of this guard.
*
* Use @{method:PhabricatorEnv::beginScopedLocale} to acquire a guard.
* Guards are released when they exit scope.
*/
final class PhabricatorLocaleScopeGuard
extends Phobject {
private static $stack = array();
private $key;
private $destroyed;
public function __construct($code) {
// If this is the first time we're building a guard, push the default
// locale onto the bottom of the stack. We'll never remove it.
if (empty(self::$stack)) {
self::$stack[] = PhabricatorEnv::getLocaleCode();
}
// If there's no locale, use the server default locale.
if (!$code) {
$code = self::$stack[0];
}
// Push this new locale onto the stack and set it as the active locale.
// We keep track of which key this guard owns, in case guards are destroyed
// out-of-order.
self::$stack[] = $code;
$this->key = last_key(self::$stack);
PhabricatorEnv::setLocaleCode($code);
}
public function __destruct() {
if ($this->destroyed) {
return;
}
$this->destroyed = true;
// Remove this locale from the stack and set the new active locale. Usually,
// we're the last item on the stack, so this shortens the stack by one item
// and sets the locale underneath. However, it's possible that guards are
// being destroyed out of order, so we might just be removing an item
// somewhere in the middle of the stack. In this case, we won't actually
// change the locale, just set it to its current value again.
unset(self::$stack[$this->key]);
PhabricatorEnv::setLocaleCode(end(self::$stack));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/scope/__tests__/PhabricatorLocaleScopeGuardTestCase.php | src/infrastructure/internationalization/scope/__tests__/PhabricatorLocaleScopeGuardTestCase.php | <?php
final class PhabricatorLocaleScopeGuardTestCase
extends PhabricatorTestCase {
public function testLocaleScopeGuard() {
$original = PhabricatorEnv::getLocaleCode();
// Set a guard; it should change the locale, then revert it when destroyed.
$guard = PhabricatorEnv::beginScopedLocale('en_GB');
$this->assertEqual('en_GB', PhabricatorEnv::getLocaleCode());
unset($guard);
$this->assertEqual($original, PhabricatorEnv::getLocaleCode());
// Nest guards, then destroy them out of order.
$guard1 = PhabricatorEnv::beginScopedLocale('en_GB');
$this->assertEqual('en_GB', PhabricatorEnv::getLocaleCode());
$guard2 = PhabricatorEnv::beginScopedLocale('en_A*');
$this->assertEqual('en_A*', PhabricatorEnv::getLocaleCode());
unset($guard1);
$this->assertEqual('en_A*', PhabricatorEnv::getLocaleCode());
unset($guard2);
$this->assertEqual($original, PhabricatorEnv::getLocaleCode());
// If you push `null`, that should mean "the default locale", not
// "the current locale".
$guard3 = PhabricatorEnv::beginScopedLocale('en_GB');
$this->assertEqual('en_GB', PhabricatorEnv::getLocaleCode());
$guard4 = PhabricatorEnv::beginScopedLocale(null);
$this->assertEqual($original, PhabricatorEnv::getLocaleCode());
unset($guard4);
$this->assertEqual('en_GB', PhabricatorEnv::getLocaleCode());
unset($guard3);
$this->assertEqual($original, PhabricatorEnv::getLocaleCode());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/management/PhabricatorInternationalizationManagementExtractWorkflow.php | src/infrastructure/internationalization/management/PhabricatorInternationalizationManagementExtractWorkflow.php | <?php
final class PhabricatorInternationalizationManagementExtractWorkflow
extends PhabricatorInternationalizationManagementWorkflow {
const CACHE_VERSION = 1;
protected function didConstruct() {
$this
->setName('extract')
->setExamples(
'**extract** [__options__] __library__')
->setSynopsis(pht('Extract translatable strings.'))
->setArguments(
array(
array(
'name' => 'paths',
'wildcard' => true,
),
array(
'name' => 'clean',
'help' => pht('Drop caches before extracting strings. Slow!'),
),
));
}
public function execute(PhutilArgumentParser $args) {
$console = PhutilConsole::getConsole();
$paths = $args->getArg('paths');
if (!$paths) {
$paths = array(getcwd());
}
$targets = array();
foreach ($paths as $path) {
$root = Filesystem::resolvePath($path);
if (!Filesystem::pathExists($root) || !is_dir($root)) {
throw new PhutilArgumentUsageException(
pht(
'Path "%s" does not exist, or is not a directory.',
$path));
}
$libraries = id(new FileFinder($path))
->withPath('*/__phutil_library_init__.php')
->find();
if (!$libraries) {
throw new PhutilArgumentUsageException(
pht(
'Path "%s" contains no libphutil libraries.',
$path));
}
foreach ($libraries as $library) {
$targets[] = Filesystem::resolvePath(dirname($path.'/'.$library)).'/';
}
}
$targets = array_unique($targets);
foreach ($targets as $library) {
echo tsprintf(
"**<bg:blue> %s </bg>** %s\n",
pht('EXTRACT'),
pht(
'Extracting "%s"...',
Filesystem::readablePath($library)));
$this->extractLibrary($library);
}
return 0;
}
private function extractLibrary($root) {
$files = $this->loadLibraryFiles($root);
$cache = $this->readCache($root);
$modified = $this->getModifiedFiles($files, $cache);
$cache['files'] = $files;
if ($modified) {
echo tsprintf(
"**<bg:blue> %s </bg>** %s\n",
pht('MODIFIED'),
pht(
'Found %s modified file(s) (of %s total).',
phutil_count($modified),
phutil_count($files)));
$old_strings = idx($cache, 'strings');
$old_strings = array_select_keys($old_strings, $files);
$new_strings = $this->extractFiles($root, $modified);
$all_strings = $new_strings + $old_strings;
$cache['strings'] = $all_strings;
$this->writeStrings($root, $all_strings);
} else {
echo tsprintf(
"**<bg:blue> %s </bg>** %s\n",
pht('NOT MODIFIED'),
pht('Strings for this library are already up to date.'));
}
$cache = id(new PhutilJSON())->encodeFormatted($cache);
$this->writeCache($root, 'i18n_files.json', $cache);
}
private function getModifiedFiles(array $files, array $cache) {
$known = idx($cache, 'files', array());
$known = array_fuse($known);
$modified = array();
foreach ($files as $file => $hash) {
if (isset($known[$hash])) {
continue;
}
$modified[$file] = $hash;
}
return $modified;
}
private function extractFiles($root_path, array $files) {
$hashes = array();
$futures = array();
foreach ($files as $file => $hash) {
$full_path = $root_path.DIRECTORY_SEPARATOR.$file;
$data = Filesystem::readFile($full_path);
$futures[$full_path] = PhutilXHPASTBinary::getParserFuture($data);
$hashes[$full_path] = $hash;
}
$bar = id(new PhutilConsoleProgressBar())
->setTotal(count($futures));
$messages = array();
$results = array();
$futures = id(new FutureIterator($futures))
->limit(8);
foreach ($futures as $full_path => $future) {
$bar->update(1);
$hash = $hashes[$full_path];
try {
$tree = XHPASTTree::newFromDataAndResolvedExecFuture(
Filesystem::readFile($full_path),
$future->resolve());
} catch (Exception $ex) {
$messages[] = pht(
'WARNING: Failed to extract strings from file "%s": %s',
$full_path,
$ex->getMessage());
continue;
}
$root = $tree->getRootNode();
$calls = $root->selectDescendantsOfType('n_FUNCTION_CALL');
foreach ($calls as $call) {
$name = $call->getChildByIndex(0)->getConcreteString();
if ($name != 'pht') {
continue;
}
$params = $call->getChildByIndex(1, 'n_CALL_PARAMETER_LIST');
$string_node = $params->getChildByIndex(0);
$string_line = $string_node->getLineNumber();
try {
$string_value = $string_node->evalStatic();
$args = $params->getChildren();
$args = array_slice($args, 1);
$types = array();
foreach ($args as $child) {
$type = null;
switch ($child->getTypeName()) {
case 'n_FUNCTION_CALL':
$call = $child->getChildByIndex(0);
if ($call->getTypeName() == 'n_SYMBOL_NAME') {
switch ($call->getConcreteString()) {
case 'phutil_count':
$type = 'number';
break;
case 'phutil_person':
$type = 'person';
break;
}
}
break;
case 'n_NEW':
$class = $child->getChildByIndex(0);
if ($class->getTypeName() == 'n_CLASS_NAME') {
switch ($class->getConcreteString()) {
case 'PhutilNumber':
$type = 'number';
break;
}
}
break;
default:
break;
}
$types[] = $type;
}
$results[$hash][] = array(
'string' => $string_value,
'file' => Filesystem::readablePath($full_path, $root_path),
'line' => $string_line,
'types' => $types,
);
} catch (Exception $ex) {
$messages[] = pht(
'WARNING: Failed to evaluate pht() call on line %d in "%s": %s',
$call->getLineNumber(),
$full_path,
$ex->getMessage());
}
}
$tree->dispose();
}
$bar->done();
foreach ($messages as $message) {
echo tsprintf(
"**<bg:yellow> %s </bg>** %s\n",
pht('WARNING'),
$message);
}
return $results;
}
private function writeStrings($root, array $strings) {
$map = array();
foreach ($strings as $hash => $string_list) {
foreach ($string_list as $string_info) {
$string = $string_info['string'];
$map[$string]['uses'][] = array(
'file' => $string_info['file'],
'line' => $string_info['line'],
);
if (!isset($map[$string]['types'])) {
$map[$string]['types'] = $string_info['types'];
} else if ($map[$string]['types'] !== $string_info['types']) {
echo tsprintf(
"**<bg:yellow> %s </bg>** %s\n",
pht('WARNING'),
pht(
'Inferred types for string "%s" vary across callsites.',
$string_info['string']));
}
}
}
ksort($map);
$json = id(new PhutilJSON())->encodeFormatted($map);
$this->writeCache($root, 'i18n_strings.json', $json);
}
private function loadLibraryFiles($root) {
$files = id(new FileFinder($root))
->withType('f')
->withSuffix('php')
->excludePath('*/.*')
->setGenerateChecksums(true)
->find();
$map = array();
foreach ($files as $file => $hash) {
$file = Filesystem::readablePath($file, $root);
$file = ltrim($file, '/');
if (dirname($file) == '.') {
continue;
}
if (dirname($file) == 'extensions') {
continue;
}
$map[$file] = md5($hash.$file);
}
return $map;
}
private function readCache($root) {
$path = $this->getCachePath($root, 'i18n_files.json');
$default = array(
'version' => self::CACHE_VERSION,
'files' => array(),
'strings' => array(),
);
if ($this->getArgv()->getArg('clean')) {
return $default;
}
if (!Filesystem::pathExists($path)) {
return $default;
}
try {
$data = Filesystem::readFile($path);
} catch (Exception $ex) {
return $default;
}
try {
$cache = phutil_json_decode($data);
} catch (PhutilJSONParserException $e) {
return $default;
}
$version = idx($cache, 'version');
if ($version !== self::CACHE_VERSION) {
return $default;
}
return $cache;
}
private function writeCache($root, $file, $data) {
$path = $this->getCachePath($root, $file);
$cache_dir = dirname($path);
if (!Filesystem::pathExists($cache_dir)) {
Filesystem::createDirectory($cache_dir, 0755, true);
}
Filesystem::writeFile($path, $data);
}
private function getCachePath($root, $to_file) {
return $root.'/.cache/'.$to_file;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/management/PhabricatorInternationalizationManagementWorkflow.php | src/infrastructure/internationalization/management/PhabricatorInternationalizationManagementWorkflow.php | <?php
abstract class PhabricatorInternationalizationManagementWorkflow
extends PhabricatorManagementWorkflow {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/translation/PhabricatorVeryWowEnglishTranslation.php | src/infrastructure/internationalization/translation/PhabricatorVeryWowEnglishTranslation.php | <?php
final class PhabricatorVeryWowEnglishTranslation
extends PhutilTranslation {
public function getLocaleCode() {
return 'en_W*';
}
protected function getTranslations() {
return array(
'Search' => 'Search! Wow!',
'Review Code' => 'Wow! Code Review! Wow!',
'Tasks and Bugs' => 'Much Bug! Very Bad!',
'Cancel' => 'Nope!',
'Advanced Search' => 'Much Search!',
'No search results.' => 'No results! Wow!',
'Send' => 'Bark Bark!',
'Partial' => 'Pawtial',
'Partial Upload' => 'Pawtial Upload',
'Submit' => 'Such Send!',
'Create Task' => 'Very Create Task',
'Create' => 'Very Create',
'Host and Browse Repositories' => 'Many Repositories',
'Okay' => 'Wow!',
'Save Preferences' => 'Make Such Saves',
'Edit Query' => 'Play With Query',
'Hide Query' => 'Bury Query',
'Execute Query' => 'Throw the Query',
'Wiki' => 'Wow-ki',
'Get Organized' => 'Such Organized',
'Explore More Applications' => 'Browse For More Wow',
'Prototype' => 'Chew Toy',
'Continue' => 'Bark And Run',
'Countdown to Events' => 'To the Moon!',
'English (Very Wow)' => 'Such English',
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/translation/PhabricatorBritishEnglishTranslation.php | src/infrastructure/internationalization/translation/PhabricatorBritishEnglishTranslation.php | <?php
final class PhabricatorBritishEnglishTranslation
extends PhutilTranslation {
public function getLocaleCode() {
return 'en_GB';
}
protected function getTranslations() {
return array(
"%s set this project's color to %s." =>
"%s set this project's colour to %s.",
'Basic Colors' =>
'Basic Colours',
'Choose Icon and Color...' =>
'Choose Icon and Colour...',
'Choose Background Color' =>
'Choose Background Colour',
'Color' => 'Colour',
'Colors' => 'Colours',
'Colors and Transforms' => 'Colours and Transforms',
'Configure the Phabricator UI, including colors.' =>
'Configure the Phabricator UI, including colours.',
'Flag Color' => 'Flag Colour',
'Sets the color of the main header.' =>
'Sets the colour of the main header.',
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/translation/PhabricatorUSEnglishTranslation.php | src/infrastructure/internationalization/translation/PhabricatorUSEnglishTranslation.php | <?php
final class PhabricatorUSEnglishTranslation
extends PhutilTranslation {
public function getLocaleCode() {
return 'en_US';
}
protected function getTranslations() {
return array(
'These %d configuration value(s) are related:' => array(
'This configuration value is related:',
'These configuration values are related:',
),
'%s Task(s)' => array('Task', 'Tasks'),
'%s ERROR(S)' => array('ERROR', 'ERRORS'),
'%d Error(s)' => array('%d Error', '%d Errors'),
'%d Warning(s)' => array('%d Warning', '%d Warnings'),
'%d Auto-Fix(es)' => array('%d Auto-Fix', '%d Auto-Fixes'),
'%d Advice(s)' => array('%d Advice', '%d Pieces of Advice'),
'%d Detail(s)' => array('%d Detail', '%d Details'),
'(%d line(s))' => array('(%d line)', '(%d lines)'),
'%d line(s)' => array('%d line', '%d lines'),
'%d path(s)' => array('%d path', '%d paths'),
'%d diff(s)' => array('%d diff', '%d diffs'),
'%s Answer(s)' => array('%s Answer', '%s Answers'),
'Show %d Comment(s)' => array('Show %d Comment', 'Show %d Comments'),
'%s DIFF LINK(S)' => array('DIFF LINK', 'DIFF LINKS'),
'You successfully created %d diff(s).' => array(
'You successfully created %d diff.',
'You successfully created %d diffs.',
),
'Diff creation failed; see body for %s error(s).' => array(
'Diff creation failed; see body for error.',
'Diff creation failed; see body for errors.',
),
'There are %d raw fact(s) in storage.' => array(
'There is %d raw fact in storage.',
'There are %d raw facts in storage.',
),
'There are %d aggregate fact(s) in storage.' => array(
'There is %d aggregate fact in storage.',
'There are %d aggregate facts in storage.',
),
'%s Commit(s) Awaiting Audit' => array(
'%s Commit Awaiting Audit',
'%s Commits Awaiting Audit',
),
'%s Problem Commit(s)' => array(
'%s Problem Commit',
'%s Problem Commits',
),
'%s Review(s) Blocking Others' => array(
'%s Review Blocking Others',
'%s Reviews Blocking Others',
),
'%s Review(s) Need Attention' => array(
'%s Review Needs Attention',
'%s Reviews Need Attention',
),
'%s Review(s) Waiting on Others' => array(
'%s Review Waiting on Others',
'%s Reviews Waiting on Others',
),
'%s Active Review(s)' => array(
'%s Active Review',
'%s Active Reviews',
),
'%s Flagged Object(s)' => array(
'%s Flagged Object',
'%s Flagged Objects',
),
'%s Object(s) Tracked' => array(
'%s Object Tracked',
'%s Objects Tracked',
),
'%s Assigned Task(s)' => array(
'%s Assigned Task',
'%s Assigned Tasks',
),
'Show %d Lint Message(s)' => array(
'Show %d Lint Message',
'Show %d Lint Messages',
),
'Hide %d Lint Message(s)' => array(
'Hide %d Lint Message',
'Hide %d Lint Messages',
),
'This is a binary file. It is %s byte(s) in length.' => array(
'This is a binary file. It is %s byte in length.',
'This is a binary file. It is %s bytes in length.',
),
'%s Action(s) Have No Effect' => array(
'Action Has No Effect',
'Actions Have No Effect',
),
'%s Action(s) With No Effect' => array(
'Action With No Effect',
'Actions With No Effect',
),
'Some of your %s action(s) have no effect:' => array(
'One of your actions has no effect:',
'Some of your actions have no effect:',
),
'Apply remaining %d action(s)?' => array(
'Apply remaining action?',
'Apply remaining actions?',
),
'Apply %d Other Action(s)' => array(
'Apply Remaining Action',
'Apply Remaining Actions',
),
'The %s action(s) you are taking have no effect:' => array(
'The action you are taking has no effect:',
'The actions you are taking have no effect:',
),
'%s edited member(s), added %d: %s; removed %d: %s.' =>
'%s edited members, added: %3$s; removed: %5$s.',
'%s added %s member(s): %s.' => array(
array(
'%s added a member: %3$s.',
'%s added members: %3$s.',
),
),
'%s removed %s member(s): %s.' => array(
array(
'%s removed a member: %3$s.',
'%s removed members: %3$s.',
),
),
'%s edited project(s), added %s: %s; removed %s: %s.' =>
'%s edited projects, added: %3$s; removed: %5$s.',
'%s added %s project(s): %s.' => array(
array(
'%s added a project: %3$s.',
'%s added projects: %3$s.',
),
),
'%s removed %s project(s): %s.' => array(
array(
'%s removed a project: %3$s.',
'%s removed projects: %3$s.',
),
),
'%s merged %s task(s): %s.' => array(
array(
'%s merged a task: %3$s.',
'%s merged tasks: %3$s.',
),
),
'%s merged %s task(s) %s into %s.' => array(
array(
'%s merged %3$s into %4$s.',
'%s merged tasks %3$s into %4$s.',
),
),
'%s added %s voting user(s): %s.' => array(
array(
'%s added a voting user: %3$s.',
'%s added voting users: %3$s.',
),
),
'%s removed %s voting user(s): %s.' => array(
array(
'%s removed a voting user: %3$s.',
'%s removed voting users: %3$s.',
),
),
'%s added %s subtask(s): %s.' => array(
array(
'%s added a subtask: %3$s.',
'%s added subtasks: %3$s.',
),
),
'%s added %s parent task(s): %s.' => array(
array(
'%s added a parent task: %3$s.',
'%s added parent tasks: %3$s.',
),
),
'%s removed %s subtask(s): %s.' => array(
array(
'%s removed a subtask: %3$s.',
'%s removed subtasks: %3$s.',
),
),
'%s removed %s parent task(s): %s.' => array(
array(
'%s removed a parent task: %3$s.',
'%s removed parent tasks: %3$s.',
),
),
'%s added %s subtask(s) for %s: %s.' => array(
array(
'%s added a subtask for %3$s: %4$s.',
'%s added subtasks for %3$s: %4$s.',
),
),
'%s added %s parent task(s) for %s: %s.' => array(
array(
'%s added a parent task for %3$s: %4$s.',
'%s added parent tasks for %3$s: %4$s.',
),
),
'%s removed %s subtask(s) for %s: %s.' => array(
array(
'%s removed a subtask for %3$s: %4$s.',
'%s removed subtasks for %3$s: %4$s.',
),
),
'%s removed %s parent task(s) for %s: %s.' => array(
array(
'%s removed a parent task for %3$s: %4$s.',
'%s removed parent tasks for %3$s: %4$s.',
),
),
'%s edited subtask(s), added %s: %s; removed %s: %s.' =>
'%s edited subtasks, added: %3$s; removed: %5$s.',
'%s edited subtask(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited subtasks for %s, added: %4$s; removed: %6$s.',
'%s edited parent task(s), added %s: %s; removed %s: %s.' =>
'%s edited parent tasks, added: %3$s; removed: %5$s.',
'%s edited parent task(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited parent tasks for %s, added: %4$s; removed: %6$s.',
'%s edited answer(s), added %s: %s; removed %d: %s.' =>
'%s edited answers, added: %3$s; removed: %5$s.',
'%s added %s answer(s): %s.' => array(
array(
'%s added an answer: %3$s.',
'%s added answers: %3$s.',
),
),
'%s removed %s answer(s): %s.' => array(
array(
'%s removed a answer: %3$s.',
'%s removed answers: %3$s.',
),
),
'%s edited question(s), added %s: %s; removed %s: %s.' =>
'%s edited questions, added: %3$s; removed: %5$s.',
'%s added %s question(s): %s.' => array(
array(
'%s added a question: %3$s.',
'%s added questions: %3$s.',
),
),
'%s removed %s question(s): %s.' => array(
array(
'%s removed a question: %3$s.',
'%s removed questions: %3$s.',
),
),
'%s edited mock(s), added %s: %s; removed %s: %s.' =>
'%s edited mocks, added: %3$s; removed: %5$s.',
'%s added %s mock(s): %s.' => array(
array(
'%s added a mock: %3$s.',
'%s added mocks: %3$s.',
),
),
'%s removed %s mock(s): %s.' => array(
array(
'%s removed a mock: %3$s.',
'%s removed mocks: %3$s.',
),
),
'%s added %s task(s): %s.' => array(
array(
'%s added a task: %3$s.',
'%s added tasks: %3$s.',
),
),
'%s removed %s task(s): %s.' => array(
array(
'%s removed a task: %3$s.',
'%s removed tasks: %3$s.',
),
),
'%s edited file(s), added %s: %s; removed %s: %s.' =>
'%s edited files, added: %3$s; removed: %5$s.',
'%s added %s file(s): %s.' => array(
array(
'%s added a file: %3$s.',
'%s added files: %3$s.',
),
),
'%s removed %s file(s): %s.' => array(
array(
'%s removed a file: %3$s.',
'%s removed files: %3$s.',
),
),
'%s edited contributor(s), added %s: %s; removed %s: %s.' =>
'%s edited contributors, added: %3$s; removed: %5$s.',
'%s added %s contributor(s): %s.' => array(
array(
'%s added a contributor: %3$s.',
'%s added contributors: %3$s.',
),
),
'%s removed %s contributor(s): %s.' => array(
array(
'%s removed a contributor: %3$s.',
'%s removed contributors: %3$s.',
),
),
'%s edited %s reviewer(s), added %s: %s; removed %s: %s.' =>
'%s edited reviewers, added: %4$s; removed: %6$s.',
'%s edited %s reviewer(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited reviewers for %3$s, added: %5$s; removed: %7$s.',
'%s added %s reviewer(s): %s.' => array(
array(
'%s added a reviewer: %3$s.',
'%s added reviewers: %3$s.',
),
),
'%s added %s reviewer(s) for %s: %s.' => array(
array(
'%s added a reviewer for %3$s: %4$s.',
'%s added reviewers for %3$s: %4$s.',
),
),
'%s removed %s reviewer(s): %s.' => array(
array(
'%s removed a reviewer: %3$s.',
'%s removed reviewers: %3$s.',
),
),
'%s removed %s reviewer(s) for %s: %s.' => array(
array(
'%s removed a reviewer for %3$s: %4$s.',
'%s removed reviewers for %3$s: %4$s.',
),
),
'%d other(s)' => array(
'1 other',
'%d others',
),
'%s edited subscriber(s), added %d: %s; removed %d: %s.' =>
'%s edited subscribers, added: %3$s; removed: %5$s.',
'%s added %d subscriber(s): %s.' => array(
array(
'%s added a subscriber: %3$s.',
'%s added subscribers: %3$s.',
),
),
'%s removed %d subscriber(s): %s.' => array(
array(
'%s removed a subscriber: %3$s.',
'%s removed subscribers: %3$s.',
),
),
'%s edited watcher(s), added %s: %s; removed %d: %s.' =>
'%s edited watchers, added: %3$s; removed: %5$s.',
'%s added %s watcher(s): %s.' => array(
array(
'%s added a watcher: %3$s.',
'%s added watchers: %3$s.',
),
),
'%s removed %s watcher(s): %s.' => array(
array(
'%s removed a watcher: %3$s.',
'%s removed watchers: %3$s.',
),
),
'%s edited participant(s), added %d: %s; removed %d: %s.' =>
'%s edited participants, added: %3$s; removed: %5$s.',
'%s added %d participant(s): %s.' => array(
array(
'%s added a participant: %3$s.',
'%s added participants: %3$s.',
),
),
'%s removed %d participant(s): %s.' => array(
array(
'%s removed a participant: %3$s.',
'%s removed participants: %3$s.',
),
),
'%s edited image(s), added %d: %s; removed %d: %s.' =>
'%s edited images, added: %3$s; removed: %5$s',
'%s added %d image(s): %s.' => array(
array(
'%s added an image: %3$s.',
'%s added images: %3$s.',
),
),
'%s removed %d image(s): %s.' => array(
array(
'%s removed an image: %3$s.',
'%s removed images: %3$s.',
),
),
'%s Line(s)' => array(
'%s Line',
'%s Lines',
),
'Indexing %d object(s) of type %s.' => array(
'Indexing %d object of type %s.',
'Indexing %d object of type %s.',
),
'Run these %d command(s):' => array(
'Run this command:',
'Run these commands:',
),
'Install these %d PHP extension(s):' => array(
'Install this PHP extension:',
'Install these PHP extensions:',
),
'The current Phabricator configuration has these %d value(s):' => array(
'The current Phabricator configuration has this value:',
'The current Phabricator configuration has these values:',
),
'The current MySQL configuration has these %d value(s):' => array(
'The current MySQL configuration has this value:',
'The current MySQL configuration has these values:',
),
'You can update these %d value(s) here:' => array(
'You can update this value here:',
'You can update these values here:',
),
'The current PHP configuration has these %d value(s):' => array(
'The current PHP configuration has this value:',
'The current PHP configuration has these values:',
),
'To update these %d value(s), edit your PHP configuration file.' => array(
'To update this %d value, edit your PHP configuration file.',
'To update these %d values, edit your PHP configuration file.',
),
'To update these %d value(s), edit your PHP configuration file, located '.
'here:' => array(
'To update this value, edit your PHP configuration file, located '.
'here:',
'To update these values, edit your PHP configuration file, located '.
'here:',
),
'PHP also loaded these %s configuration file(s):' => array(
'PHP also loaded this configuration file:',
'PHP also loaded these configuration files:',
),
'%s added %d inline comment(s).' => array(
array(
'%s added an inline comment.',
'%s added inline comments.',
),
),
'%s comment(s)' => array('%s comment', '%s comments'),
'%s rejection(s)' => array('%s rejection', '%s rejections'),
'%s update(s)' => array('%s update', '%s updates'),
'This configuration value is defined in these %d '.
'configuration source(s): %s.' => array(
'This configuration value is defined in this '.
'configuration source: %2$s.',
'This configuration value is defined in these %d '.
'configuration sources: %s.',
),
'%s Open Pull Request(s)' => array(
'%s Open Pull Request',
'%s Open Pull Requests',
),
'Stale (%s day(s))' => array(
'Stale (%s day)',
'Stale (%s days)',
),
'Old (%s day(s))' => array(
'Old (%s day)',
'Old (%s days)',
),
'%s Commit(s)' => array(
'%s Commit',
'%s Commits',
),
'%s attached %d file(s): %s.' => array(
array(
'%s attached a file: %3$s.',
'%s attached files: %3$s.',
),
),
'%s detached %d file(s): %s.' => array(
array(
'%s detached a file: %3$s.',
'%s detached files: %3$s.',
),
),
'%s changed file(s), attached %d: %s; detached %d: %s.' =>
'%s changed files, attached: %3$s; detached: %5$s.',
'%s added %s parent revision(s): %s.' => array(
array(
'%s added a parent revision: %3$s.',
'%s added parent revisions: %3$s.',
),
),
'%s added %s parent revision(s) for %s: %s.' => array(
array(
'%s added a parent revision for %3$s: %4$s.',
'%s added parent revisions for %3$s: %4$s.',
),
),
'%s removed %s parent revision(s): %s.' => array(
array(
'%s removed a parent revision: %3$s.',
'%s removed parent revisions: %3$s.',
),
),
'%s removed %s parent revision(s) for %s: %s.' => array(
array(
'%s removed a parent revision for %3$s: %4$s.',
'%s removed parent revisions for %3$s: %4$s.',
),
),
'%s edited parent revision(s), added %s: %s; removed %s: %s.' => array(
'%s edited parent revisions, added: %3$s; removed: %5$s.',
),
'%s edited parent revision(s) for %s, '.
'added %s: %s; removed %s: %s.' => array(
'%s edited parent revisions for %s, added: %3$s; removed: %5$s.',
),
'%s added %s child revision(s): %s.' => array(
array(
'%s added a child revision: %3$s.',
'%s added child revisions: %3$s.',
),
),
'%s added %s child revision(s) for %s: %s.' => array(
array(
'%s added a child revision for %3$s: %4$s.',
'%s added child revisions for %3$s: %4$s.',
),
),
'%s removed %s child revision(s): %s.' => array(
array(
'%s removed a child revision: %3$s.',
'%s removed child revisions: %3$s.',
),
),
'%s removed %s child revision(s) for %s: %s.' => array(
array(
'%s removed a child revision for %3$s: %4$s.',
'%s removed child revisions for %3$s: %4$s.',
),
),
'%s edited child revision(s), added %s: %s; removed %s: %s.' => array(
'%s edited child revisions, added: %3$s; removed: %5$s.',
),
'%s edited child revision(s) for %s, '.
'added %s: %s; removed %s: %s.' => array(
'%s edited child revisions for %s, added: %3$s; removed: %5$s.',
),
'%s added %s commit(s): %s.' => array(
array(
'%s added a commit: %3$s.',
'%s added commits: %3$s.',
),
),
'%s removed %s commit(s): %s.' => array(
array(
'%s removed a commit: %3$s.',
'%s removed commits: %3$s.',
),
),
'%s edited commit(s), added %s: %s; removed %s: %s.' =>
'%s edited commits, added %3$s; removed %5$s.',
'%s added %s reverted change(s): %s.' => array(
array(
'%s added a reverted change: %3$s.',
'%s added reverted changes: %3$s.',
),
),
'%s removed %s reverted change(s): %s.' => array(
array(
'%s removed a reverted change: %3$s.',
'%s removed reverted changes: %3$s.',
),
),
'%s edited reverted change(s), added %s: %s; removed %s: %s.' =>
'%s edited reverted changes, added %3$s; removed %5$s.',
'%s added %s reverted change(s) for %s: %s.' => array(
array(
'%s added a reverted change for %3$s: %4$s.',
'%s added reverted changes for %3$s: %4$s.',
),
),
'%s removed %s reverted change(s) for %s: %s.' => array(
array(
'%s removed a reverted change for %3$s: %4$s.',
'%s removed reverted changes for %3$s: %4$s.',
),
),
'%s edited reverted change(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited reverted changes for %2$s, added %4$s; removed %6$s.',
'%s added %s reverting change(s): %s.' => array(
array(
'%s added a reverting change: %3$s.',
'%s added reverting changes: %3$s.',
),
),
'%s removed %s reverting change(s): %s.' => array(
array(
'%s removed a reverting change: %3$s.',
'%s removed reverting changes: %3$s.',
),
),
'%s edited reverting change(s), added %s: %s; removed %s: %s.' =>
'%s edited reverting changes, added %3$s; removed %5$s.',
'%s added %s reverting change(s) for %s: %s.' => array(
array(
'%s added a reverting change for %3$s: %4$s.',
'%s added reverting changes for %3$s: %4$s.',
),
),
'%s removed %s reverting change(s) for %s: %s.' => array(
array(
'%s removed a reverting change for %3$s: %4$s.',
'%s removed reverting changes for %3$s: %4$s.',
),
),
'%s edited reverting change(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited reverting changes for %s, added %4$s; removed %6$s.',
'%s changed project member(s), added %d: %s; removed %d: %s.' =>
'%s changed project members, added %3$s; removed %5$s.',
'%s added %d project member(s): %s.' => array(
array(
'%s added a member: %3$s.',
'%s added members: %3$s.',
),
),
'%s removed %d project member(s): %s.' => array(
array(
'%s removed a member: %3$s.',
'%s removed members: %3$s.',
),
),
'%s project hashtag(s) are already used by other projects: %s.' => array(
'Project hashtag "%2$s" is already used by another project.',
'Some project hashtags are already used by other projects: %2$s.',
),
'%s changed project hashtag(s), added %d: %s; removed %d: %s.' =>
'%s changed project hashtags, added %3$s; removed %5$s.',
'Hashtags must contain at least one letter or number. %s '.
'project hashtag(s) are invalid: %s.' => array(
'Hashtags must contain at least one letter or number. The '.
'hashtag "%2$s" is not valid.',
'Hashtags must contain at least one letter or number. These '.
'hashtags are invalid: %2$s.',
),
'%s added %d project hashtag(s): %s.' => array(
array(
'%s added a hashtag: %3$s.',
'%s added hashtags: %3$s.',
),
),
'%s removed %d project hashtag(s): %s.' => array(
array(
'%s removed a hashtag: %3$s.',
'%s removed hashtags: %3$s.',
),
),
'%s changed %s hashtag(s), added %d: %s; removed %d: %s.' =>
'%s changed hashtags for %s, added %4$s; removed %6$s.',
'%s added %d %s hashtag(s): %s.' => array(
array(
'%s added a hashtag to %3$s: %4$s.',
'%s added hashtags to %3$s: %4$s.',
),
),
'%s removed %d %s hashtag(s): %s.' => array(
array(
'%s removed a hashtag from %3$s: %4$s.',
'%s removed hashtags from %3$s: %4$s.',
),
),
'%d User(s) Need Approval' => array(
'%d User Needs Approval',
'%d Users Need Approval',
),
'%s, %s line(s)' => array(
array(
'%s, %s line',
'%s, %s lines',
),
),
'%s pushed %d commit(s) to %s.' => array(
array(
'%s pushed a commit to %3$s.',
'%s pushed %d commits to %s.',
),
),
'%s commit(s)' => array(
'1 commit',
'%s commits',
),
'%s removed %s JIRA issue(s): %s.' => array(
array(
'%s removed a JIRA issue: %3$s.',
'%s removed JIRA issues: %3$s.',
),
),
'%s added %s JIRA issue(s): %s.' => array(
array(
'%s added a JIRA issue: %3$s.',
'%s added JIRA issues: %3$s.',
),
),
'%s added %s required legal document(s): %s.' => array(
array(
'%s added a required legal document: %3$s.',
'%s added required legal documents: %3$s.',
),
),
'%s updated JIRA issue(s): added %s %s; removed %d %s.' =>
'%s updated JIRA issues: added %3$s; removed %5$s.',
'%s edited %s task(s), added %s: %s; removed %s: %s.' =>
'%s edited tasks, added %4$s; removed %6$s.',
'%s added %s task(s) to %s: %s.' => array(
array(
'%s added a task to %3$s: %4$s.',
'%s added tasks to %3$s: %4$s.',
),
),
'%s removed %s task(s) from %s: %s.' => array(
array(
'%s removed a task from %3$s: %4$s.',
'%s removed tasks from %3$s: %4$s.',
),
),
'%s edited %s task(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited tasks for %3$s, added: %5$s; removed %7$s.',
'%s edited %s commit(s), added %s: %s; removed %s: %s.' =>
'%s edited commits, added %4$s; removed %6$s.',
'%s added %s commit(s) to %s: %s.' => array(
array(
'%s added a commit to %3$s: %4$s.',
'%s added commits to %3$s: %4$s.',
),
),
'%s removed %s commit(s) from %s: %s.' => array(
array(
'%s removed a commit from %3$s: %4$s.',
'%s removed commits from %3$s: %4$s.',
),
),
'%s edited %s commit(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited commits for %3$s, added: %5$s; removed %7$s.',
'%s added %s revision(s): %s.' => array(
array(
'%s added a revision: %3$s.',
'%s added revisions: %3$s.',
),
),
'%s removed %s revision(s): %s.' => array(
array(
'%s removed a revision: %3$s.',
'%s removed revisions: %3$s.',
),
),
'%s edited %s revision(s), added %s: %s; removed %s: %s.' =>
'%s edited revisions, added %4$s; removed %6$s.',
'%s added %s revision(s) to %s: %s.' => array(
array(
'%s added a revision to %3$s: %4$s.',
'%s added revisions to %3$s: %4$s.',
),
),
'%s removed %s revision(s) from %s: %s.' => array(
array(
'%s removed a revision from %3$s: %4$s.',
'%s removed revisions from %3$s: %4$s.',
),
),
'%s edited %s revision(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited revisions for %3$s, added: %5$s; removed %7$s.',
'%s edited %s project(s), added %s: %s; removed %s: %s.' =>
'%s edited projects, added %4$s; removed %6$s.',
'%s added %s project(s) to %s: %s.' => array(
array(
'%s added a project to %3$s: %4$s.',
'%s added projects to %3$s: %4$s.',
),
),
'%s removed %s project(s) from %s: %s.' => array(
array(
'%s removed a project from %3$s: %4$s.',
'%s removed projects from %3$s: %4$s.',
),
),
'%s edited %s project(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited projects for %3$s, added: %5$s; removed %7$s.',
'%s added %s panel(s): %s.' => array(
array(
'%s added a panel: %3$s.',
'%s added panels: %3$s.',
),
),
'%s removed %s panel(s): %s.' => array(
array(
'%s removed a panel: %3$s.',
'%s removed panels: %3$s.',
),
),
'%s edited %s panel(s), added %s: %s; removed %s: %s.' =>
'%s edited panels, added %4$s; removed %6$s.',
'%s added %s dashboard(s): %s.' => array(
array(
'%s added a dashboard: %3$s.',
'%s added dashboards: %3$s.',
),
),
'%s removed %s dashboard(s): %s.' => array(
array(
'%s removed a dashboard: %3$s.',
'%s removed dashboards: %3$s.',
),
),
'%s edited %s dashboard(s), added %s: %s; removed %s: %s.' =>
'%s edited dashboards, added %4$s; removed %6$s.',
'%s added %s edge(s): %s.' => array(
array(
'%s added an edge: %3$s.',
'%s added edges: %3$s.',
),
),
'%s added %s edge(s) to %s: %s.' => array(
array(
'%s added an edge to %3$s: %4$s.',
'%s added edges to %3$s: %4$s.',
),
),
'%s removed %s edge(s): %s.' => array(
array(
'%s removed an edge: %3$s.',
'%s removed edges: %3$s.',
),
),
'%s removed %s edge(s) from %s: %s.' => array(
array(
'%s removed an edge from %3$s: %4$s.',
'%s removed edges from %3$s: %4$s.',
),
),
'%s edited edge(s), added %s: %s; removed %s: %s.' =>
'%s edited edges, added: %3$s; removed: %5$s.',
'%s edited %s edge(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited edges for %3$s, added: %5$s; removed %7$s.',
'%s added %s member(s) for %s: %s.' => array(
array(
'%s added a member for %3$s: %4$s.',
'%s added members for %3$s: %4$s.',
),
),
'%s removed %s member(s) for %s: %s.' => array(
array(
'%s removed a member for %3$s: %4$s.',
'%s removed members for %3$s: %4$s.',
),
),
'%s edited %s member(s) for %s, added %s: %s; removed %s: %s.' =>
'%s edited members for %3$s, added: %5$s; removed %7$s.',
'%d related link(s):' => array(
'Related link:',
'Related links:',
),
'You have %d unpaid invoice(s).' => array(
'You have an unpaid invoice.',
'You have unpaid invoices.',
),
'The configurations differ in the following %s way(s):' => array(
'The configurations differ:',
'The configurations differ in these ways:',
),
'Phabricator is configured with an email domain whitelist (in %s), so '.
'only users with a verified email address at one of these %s '.
'allowed domain(s) will be able to register an account: %s' => array(
array(
'Phabricator is configured with an email domain whitelist (in %s), '.
'so only users with a verified email address at %3$s will be '.
'allowed to register an account.',
'Phabricator is configured with an email domain whitelist (in %s), '.
'so only users with a verified email address at one of these '.
'allowed domains will be able to register an account: %3$s',
),
),
'Show First %s Line(s)' => array(
'Show First Line',
'Show First %s Lines',
),
'Show First %s Block(s)' => array(
'Show First Block',
'Show First %s Blocks',
),
"\xE2\x96\xB2 Show %s Line(s)" => array(
"\xE2\x96\xB2 Show Line",
"\xE2\x96\xB2 Show %s Lines",
),
"\xE2\x96\xB2 Show %s Block(s)" => array(
"\xE2\x96\xB2 Show Block",
"\xE2\x96\xB2 Show %s Blocks",
),
'Show All %s Line(s)' => array(
'Show Line',
'Show All %s Lines',
),
'Show All %s Block(s)' => array(
'Show Block',
'Show All %s Blocks',
),
"\xE2\x96\xBC Show %s Line(s)" => array(
"\xE2\x96\xBC Show Line",
"\xE2\x96\xBC Show %s Lines",
),
"\xE2\x96\xBC Show %s Block(s)" => array(
"\xE2\x96\xBC Show Block",
"\xE2\x96\xBC Show %s Blocks",
),
'Show Last %s Line(s)' => array(
'Show Last Line',
'Show Last %s Lines',
),
'Show Last %s Block(s)' => array(
'Show Last Block',
'Show Last %s Blocks',
),
'%s marked %s inline comment(s) as done and %s inline comment(s) as '.
'not done.' => array(
array(
array(
'%s marked an inline comment as done and an inline comment '.
'as not done.',
'%s marked an inline comment as done and %3$s inline comments '.
'as not done.',
),
array(
'%s marked %s inline comments as done and an inline comment '.
'as not done.',
'%s marked %s inline comments as done and %s inline comments '.
'as done.',
),
),
),
'%s marked %s inline comment(s) as done.' => array(
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | true |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/translation/PhabricatorEmojiTranslation.php | src/infrastructure/internationalization/translation/PhabricatorEmojiTranslation.php | <?php
final class PhabricatorEmojiTranslation
extends PhutilTranslation {
public function getLocaleCode() {
return 'en_X*';
}
protected function getTranslations() {
return array(
'Emoji (Internet)' => "\xF0\x9F\x92\xAC (\xF0\x9F\x8C\x8D)",
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/internationalization/translation/PhabricatorPirateEnglishTranslation.php | src/infrastructure/internationalization/translation/PhabricatorPirateEnglishTranslation.php | <?php
final class PhabricatorPirateEnglishTranslation
extends PhutilTranslation {
public function getLocaleCode() {
return 'en_P*';
}
protected function getTranslations() {
return array(
'Search' => 'Scour',
'Review Code' => 'Inspect Riggins',
'Tasks and Bugs' => 'Bilge rats',
'Cancel' => 'Belay',
'Advanced Search' => 'Scour Hard',
'No search results.' => 'We be finding nothin.',
'Send' => 'Aye!',
'Partial' => 'Parrtial',
'Upload' => 'Hoist',
'Partial Upload' => 'Parrtial Hoist',
'Submit' => 'Aye!',
'Create' => 'Make Sail',
'Okay' => 'Ahoy!',
'Edit Query' => 'Overhaul Query',
'Hide Query' => 'Furl Query',
'Execute Query' => 'Quarter Query',
'Wiki' => 'Sea Log',
'Blog' => 'Capn\'s Tales',
'Add Action...' => 'Be Addin\' an Action...',
'Change Subscribers' => 'Change Spies',
'Change Projects' => 'Change Prrojects',
'Change Priority' => 'Change Priarrrity',
'Change Status' => 'Change Ye Status',
'Assign / Claim' => 'Arrsign / Stake Claim',
'Prototype' => 'Ramshackle',
'Continue' => 'Set Sail',
'Recent Activity' => 'Recent Plunderin\'s',
'Browse and Audit Commits' => 'Inspect ye Work of Yore',
'Upcoming Events' => 'Upcoming Pillages',
'Get Organized' => 'Straighten yer gig',
'Host and Browse Repositories' => 'Hide ye Treasures',
'Chat with Others' => 'Parley with yer Mates',
'Review Recent Activity' => 'Spy ye Freshest Bottles',
'Comment' => 'Scrawl',
'Actions' => 'Actions! Arrr!',
'Title' => 'Ye Olde Title',
'Assigned To' => 'Matey Assigned',
'Status' => 'Ye Status',
'Priority' => 'Priarrrity',
'Description' => 'Splainin\'',
'Visible To' => 'Bein\' Spied By',
'Editable By' => 'Plunderable By',
'Subscribers' => 'Spies',
'Projects' => 'Prrojects',
'%s added a comment.' => '%s scrawled.',
'%s edited the task description.' =>
'Cap\'n %s be updatin\' ye task\'s splainin\'.',
'%s claimed this task.' =>
'Cap\'n %s be stakin\' a claim on this here task.',
'%s created this task.' =>
'Cap\'n %s be the one creatin\' this here task.',
);
}
}
| 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.