repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/controller/PhabricatorPhurlURLViewController.php
src/applications/phurl/controller/PhabricatorPhurlURLViewController.php
<?php final class PhabricatorPhurlURLViewController extends PhabricatorPhurlController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $timeline = null; $url = id(new PhabricatorPhurlURLQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); if (!$url) { return new Aphront404Response(); } $title = $url->getMonogram(); $page_title = $title.' '.$url->getName(); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($title); $crumbs->setBorder(true); $timeline = $this->buildTransactionTimeline( $url, new PhabricatorPhurlURLTransactionQuery()); $timeline->setQuoteRef($url->getMonogram()); $header = $this->buildHeaderView($url); $curtain = $this->buildCurtain($url); $details = $this->buildPropertySectionView($url); $url_error = id(new PHUIInfoView()) ->setErrors(array(pht('This URL is invalid due to a bad protocol.'))) ->setIsHidden($url->isValid()); $add_comment_form = $this->buildCommentForm($url, $timeline); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setCurtain($curtain) ->setMainColumn(array( $url_error, $details, $timeline, $add_comment_form, )); return $this->newPage() ->setTitle($page_title) ->setCrumbs($crumbs) ->setPageObjectPHIDs(array($url->getPHID())) ->appendChild( array( $view, )); } private function buildCommentForm(PhabricatorPhurlURL $url, $timeline) { $viewer = $this->getViewer(); $box = id(new PhabricatorPhurlURLEditEngine()) ->setViewer($viewer) ->buildEditEngineCommentView($url) ->setTransactionTimeline($timeline); return $box; } private function buildHeaderView(PhabricatorPhurlURL $url) { $viewer = $this->getViewer(); $icon = 'fa-check'; $color = 'bluegrey'; $status = pht('Active'); $id = $url->getID(); $visit = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Visit URL')) ->setIcon('fa-external-link') ->setHref($url->getRedirectURI()) ->setDisabled(!$url->isValid()); $header = id(new PHUIHeaderView()) ->setUser($viewer) ->setHeader($url->getDisplayName()) ->setStatus($icon, $color, $status) ->setPolicyObject($url) ->setHeaderIcon('fa-compress') ->addActionLink($visit); return $header; } private function buildCurtain(PhabricatorPhurlURL $url) { $viewer = $this->getViewer(); $id = $url->getID(); $curtain = $this->newCurtainView($url); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $url, PhabricatorPolicyCapability::CAN_EDIT); $curtain ->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Phurl')) ->setIcon('fa-pencil') ->setHref($this->getApplicationURI("url/edit/{$id}/")) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); return $curtain; } private function buildPropertySectionView(PhabricatorPhurlURL $url) { $viewer = $this->getViewer(); $properties = id(new PHUIPropertyListView()) ->setUser($viewer); $properties->addProperty( pht('Short URL'), $url->getRedirectURI()); $properties->addProperty( pht('Original URL'), $url->getLongURL()); $properties->addProperty( pht('Alias'), $url->getAlias()); $description = $url->getDescription(); if (strlen($description)) { $description = new PHUIRemarkupView($viewer, $description); $properties->addSectionHeader(pht('Description')); $properties->addTextContent($description); } return id(new PHUIObjectBoxView()) ->setHeaderText(pht('Details')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild($properties); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/storage/PhabricatorPhurlDAO.php
src/applications/phurl/storage/PhabricatorPhurlDAO.php
<?php abstract class PhabricatorPhurlDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'phurl'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/storage/PhabricatorPhurlURL.php
src/applications/phurl/storage/PhabricatorPhurlURL.php
<?php final class PhabricatorPhurlURL extends PhabricatorPhurlDAO implements PhabricatorPolicyInterface, PhabricatorProjectInterface, PhabricatorApplicationTransactionInterface, PhabricatorSubscribableInterface, PhabricatorTokenReceiverInterface, PhabricatorDestructibleInterface, PhabricatorMentionableInterface, PhabricatorFlaggableInterface, PhabricatorSpacesInterface, PhabricatorConduitResultInterface, PhabricatorNgramsInterface { protected $name; protected $alias; protected $longURL; protected $description; protected $viewPolicy; protected $editPolicy; protected $authorPHID; protected $spacePHID; protected $mailKey; const DEFAULT_ICON = 'fa-compress'; public static function initializeNewPhurlURL(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery()) ->setViewer($actor) ->withClasses(array('PhabricatorPhurlApplication')) ->executeOne(); return id(new PhabricatorPhurlURL()) ->setAuthorPHID($actor->getPHID()) ->setViewPolicy(PhabricatorPolicies::getMostOpenPolicy()) ->setEditPolicy($actor->getPHID()) ->setSpacePHID($actor->getDefaultSpacePHID()); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_COLUMN_SCHEMA => array( 'name' => 'text', 'alias' => 'sort64?', 'longURL' => 'text', 'description' => 'text', 'mailKey' => 'bytes20', ), self::CONFIG_KEY_SCHEMA => array( 'key_instance' => array( 'columns' => array('alias'), 'unique' => true, ), 'key_author' => array( 'columns' => array('authorPHID'), ), ), ) + parent::getConfiguration(); } public function save() { if (!$this->getMailKey()) { $this->setMailKey(Filesystem::readRandomCharacters(20)); } return parent::save(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorPhurlURLPHIDType::TYPECONST); } public function getMonogram() { return 'U'.$this->getID(); } public function getURI() { $uri = '/'.$this->getMonogram(); return $uri; } public function isValid() { $allowed_protocols = PhabricatorEnv::getEnvConfig('uri.allowed-protocols'); $uri = new PhutilURI($this->getLongURL()); return isset($allowed_protocols[$uri->getProtocol()]); } public function getDisplayName() { if ($this->getName()) { return $this->getName(); } else { return $this->getLongURL(); } } public function getRedirectURI() { if (strlen($this->getAlias())) { $path = '/u/'.$this->getAlias(); } else { $path = '/u/'.$this->getID(); } $domain = PhabricatorEnv::getEnvConfig('phurl.short-uri'); if (!$domain) { $domain = PhabricatorEnv::getEnvConfig('phabricator.base-uri'); } $uri = new PhutilURI($domain); $uri->setPath($path); return (string)$uri; } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->getViewPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return $this->getEditPolicy(); } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { $user_phid = $this->getAuthorPHID(); if ($user_phid) { $viewer_phid = $viewer->getPHID(); if ($viewer_phid == $user_phid) { return true; } } return false; } public function describeAutomaticCapability($capability) { return pht('The owner of a URL can always view and edit it.'); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhabricatorPhurlURLEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorPhurlURLTransaction(); } /* -( PhabricatorSubscribableInterface )----------------------------------- */ public function isAutomaticallySubscribed($phid) { return ($phid == $this->getAuthorPHID()); } /* -( PhabricatorTokenReceiverInterface )---------------------------------- */ public function getUsersToNotifyOfTokenGiven() { return array($this->getAuthorPHID()); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); $this->delete(); $this->saveTransaction(); } /* -( PhabricatorSpacesInterface )----------------------------------------- */ public function getSpacePHID() { return $this->spacePHID; } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('name') ->setType('string') ->setDescription(pht('URL name.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('alias') ->setType('string') ->setDescription(pht('The alias for the URL.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('longurl') ->setType('string') ->setDescription(pht('The pre-shortened URL.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('description') ->setType('string') ->setDescription(pht('A description of the URL.')), ); } public function getFieldValuesForConduit() { return array( 'name' => $this->getName(), 'alias' => $this->getAlias(), 'description' => $this->getDescription(), 'urls' => array( 'long' => $this->getLongURL(), 'short' => $this->getRedirectURI(), ), ); } public function getConduitSearchAttachments() { return array(); } /* -( PhabricatorNgramInterface )------------------------------------------ */ public function newNgrams() { return array( id(new PhabricatorPhurlURLNameNgrams()) ->setValue($this->getName()), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/storage/PhabricatorPhurlURLTransaction.php
src/applications/phurl/storage/PhabricatorPhurlURLTransaction.php
<?php final class PhabricatorPhurlURLTransaction extends PhabricatorModularTransaction { const MAILTAG_DETAILS = 'phurl-details'; public function getApplicationName() { return 'phurl'; } public function getApplicationTransactionType() { return PhabricatorPhurlURLPHIDType::TYPECONST; } public function getApplicationTransactionCommentObject() { return new PhabricatorPhurlURLTransactionComment(); } public function getBaseTransactionClass() { return 'PhabricatorPhurlURLTransactionType'; } public function getRequiredHandlePHIDs() { $phids = parent::getRequiredHandlePHIDs(); switch ($this->getTransactionType()) { case PhabricatorPhurlURLNameTransaction::TRANSACTIONTYPE: case PhabricatorPhurlURLLongURLTransaction::TRANSACTIONTYPE: case PhabricatorPhurlURLAliasTransaction::TRANSACTIONTYPE: case PhabricatorPhurlURLDescriptionTransaction::TRANSACTIONTYPE: $phids[] = $this->getObjectPHID(); break; } return $phids; } public function getMailTags() { $tags = array(); switch ($this->getTransactionType()) { case PhabricatorPhurlURLNameTransaction::TRANSACTIONTYPE: case PhabricatorPhurlURLLongURLTransaction::TRANSACTIONTYPE: case PhabricatorPhurlURLAliasTransaction::TRANSACTIONTYPE: case PhabricatorPhurlURLDescriptionTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_DETAILS; break; } return $tags; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/storage/PhabricatorPhurlURLNameNgrams.php
src/applications/phurl/storage/PhabricatorPhurlURLNameNgrams.php
<?php final class PhabricatorPhurlURLNameNgrams extends PhabricatorSearchNgrams { public function getNgramKey() { return 'phurlname'; } public function getColumnName() { return 'name'; } public function getApplicationName() { return 'phurl'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/storage/PhabricatorPhurlURLTransactionComment.php
src/applications/phurl/storage/PhabricatorPhurlURLTransactionComment.php
<?php final class PhabricatorPhurlURLTransactionComment extends PhabricatorApplicationTransactionComment { public function getApplicationTransactionObject() { return new PhabricatorPhurlURLTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/storage/PhabricatorPhurlSchemaSpec.php
src/applications/phurl/storage/PhabricatorPhurlSchemaSpec.php
<?php final class PhabricatorPhurlSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new PhabricatorPhurlURL()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/query/PhabricatorPhurlURLSearchEngine.php
src/applications/phurl/query/PhabricatorPhurlURLSearchEngine.php
<?php final class PhabricatorPhurlURLSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Phurl URLs'); } public function getApplicationClassName() { return 'PhabricatorPhurlApplication'; } public function newQuery() { return new PhabricatorPhurlURLQuery(); } protected function shouldShowOrderField() { return true; } protected function buildCustomSearchFields() { return array( id(new PhabricatorSearchDatasourceField()) ->setLabel(pht('Created By')) ->setKey('authorPHIDs') ->setDatasource(new PhabricatorPeopleUserFunctionDatasource()), id(new PhabricatorSearchTextField()) ->setLabel(pht('Name Contains')) ->setKey('name') ->setDescription(pht('Search for Phurl URLs by name substring.')), id(new PhabricatorSearchStringListField()) ->setLabel(pht('Aliases')) ->setKey('aliases') ->setDescription(pht('Search for Phurl URLs by alias.')), id(new PhabricatorSearchStringListField()) ->setLabel(pht('Long URLs')) ->setKey('longurls') ->setDescription( pht('Search for Phurl URLs by the non-shortened URL.')), ); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['authorPHIDs']) { $query->withAuthorPHIDs($map['authorPHIDs']); } if ($map['name'] !== null) { $query->withNameNgrams($map['name']); } if ($map['aliases']) { $query->withAliases($map['aliases']); } if ($map['longurls']) { $query->withLongURLs($map['longurls']); } return $query; } protected function getURI($path) { return '/phurl/'.$path; } protected function getBuiltinQueryNames() { $names = array( 'all' => pht('All URLs'), 'authored' => pht('Authored'), ); return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); $viewer = $this->requireViewer(); switch ($query_key) { case 'authored': return $query->setParameter('authorPHIDs', array($viewer->getPHID())); case 'all': return $query; } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $urls, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($urls, 'PhabricatorPhurlURL'); $viewer = $this->requireViewer(); $list = new PHUIObjectItemListView(); $handles = $viewer->loadHandles(mpull($urls, 'getAuthorPHID')); foreach ($urls as $url) { $name = $url->getName(); $item = id(new PHUIObjectItemView()) ->setUser($viewer) ->setObject($url) ->setObjectName('U'.$url->getID()) ->setHeader($name) ->setHref('/U'.$url->getID()) ->addAttribute($url->getAlias()) ->addAttribute($url->getLongURL()); $list->addItem($item); } $result = new PhabricatorApplicationSearchResultView(); $result->setObjectList($list); $result->setNoDataString(pht('No URLs found.')); return $result; } protected function getNewUserBody() { $create_uri = id(new PhabricatorPhurlURLEditEngine()) ->getEditURI(); $create_button = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Shorten a URL')) ->setHref($create_uri) ->setColor(PHUIButtonView::GREEN); $icon = $this->getApplication()->getIcon(); $app_name = $this->getApplication()->getName(); $view = id(new PHUIBigInfoView()) ->setIcon($icon) ->setTitle(pht('Welcome to %s', $app_name)) ->setDescription( pht('Create reusable, memorable, shorter URLs for easy accessibility.')) ->addAction($create_button); return $view; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/query/PhabricatorPhurlURLQuery.php
src/applications/phurl/query/PhabricatorPhurlURLQuery.php
<?php final class PhabricatorPhurlURLQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $names; private $longURLs; private $aliases; private $authorPHIDs; public function newResultObject() { return new PhabricatorPhurlURL(); } public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withNames(array $names) { $this->names = $names; return $this; } public function withNameNgrams($ngrams) { return $this->withNgramsConstraint( id(new PhabricatorPhurlURLNameNgrams()), $ngrams); } public function withLongURLs(array $long_urls) { $this->longURLs = $long_urls; return $this; } public function withAliases(array $aliases) { $this->aliases = $aliases; return $this; } public function withAuthorPHIDs(array $author_phids) { $this->authorPHIDs = $author_phids; return $this; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'url.id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'url.phid IN (%Ls)', $this->phids); } if ($this->authorPHIDs !== null) { $where[] = qsprintf( $conn, 'url.authorPHID IN (%Ls)', $this->authorPHIDs); } if ($this->names !== null) { $where[] = qsprintf( $conn, 'url.name IN (%Ls)', $this->names); } if ($this->longURLs !== null) { $where[] = qsprintf( $conn, 'url.longURL IN (%Ls)', $this->longURLs); } if ($this->aliases !== null) { $where[] = qsprintf( $conn, 'url.alias IN (%Ls)', $this->aliases); } return $where; } protected function getPrimaryTableAlias() { return 'url'; } public function getQueryApplicationClass() { return 'PhabricatorPhurlApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/query/PhabricatorPhurlURLTransactionQuery.php
src/applications/phurl/query/PhabricatorPhurlURLTransactionQuery.php
<?php final class PhabricatorPhurlURLTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhabricatorPhurlURLTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/mail/PhabricatorPhurlURLMailReceiver.php
src/applications/phurl/mail/PhabricatorPhurlURLMailReceiver.php
<?php final class PhabricatorPhurlURLMailReceiver extends PhabricatorObjectMailReceiver { public function isEnabled() { return PhabricatorApplication::isClassInstalled( 'PhabricatorPhurlApplication'); } protected function getObjectPattern() { return 'U[1-9]\d*'; } protected function loadObject($pattern, PhabricatorUser $viewer) { $id = (int)substr($pattern, 1); return id(new PhabricatorPhurlURLQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); } protected function getTransactionReplyHandler() { return new PhabricatorPhurlURLReplyHandler(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/mail/PhabricatorPhurlURLReplyHandler.php
src/applications/phurl/mail/PhabricatorPhurlURLReplyHandler.php
<?php final class PhabricatorPhurlURLReplyHandler extends PhabricatorApplicationTransactionReplyHandler { public function validateMailReceiver($mail_receiver) { if (!($mail_receiver instanceof PhabricatorPhurlURL)) { throw new Exception( pht( 'Mail receiver is not a %s!', 'PhabricatorPhurlURL')); } } public function getObjectPrefix() { return 'U'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/editor/PhabricatorPhurlURLEditor.php
src/applications/phurl/editor/PhabricatorPhurlURLEditor.php
<?php final class PhabricatorPhurlURLEditor extends PhabricatorApplicationTransactionEditor { public function getEditorApplicationClass() { return 'PhabricatorPhurlApplication'; } public function getEditorObjectsDescription() { return pht('Phurl'); } public function getCreateObjectTitle($author, $object) { return pht('%s created this URL.', $author); } public function getCreateObjectTitleForFeed($author, $object) { return pht('%s created %s.', $author, $object); } protected function supportsSearch() { return true; } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorTransactions::TYPE_COMMENT; $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY; $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY; return $types; } protected function shouldSendMail( PhabricatorLiskDAO $object, array $xactions) { return true; } public function getMailTagsMap() { return array( PhabricatorPhurlURLTransaction::MAILTAG_DETAILS => pht( "A URL's details change."), ); } protected function shouldPublishFeedStory( PhabricatorLiskDAO $object, array $xactions) { return true; } protected function getMailSubjectPrefix() { return pht('[Phurl]'); } protected function getMailTo(PhabricatorLiskDAO $object) { $phids = array(); $phids[] = $this->getActingAsPHID(); return $phids; } protected function buildMailTemplate(PhabricatorLiskDAO $object) { $id = $object->getID(); $name = $object->getName(); return id(new PhabricatorMetaMTAMail()) ->setSubject("U{$id}: {$name}"); } protected function buildMailBody( PhabricatorLiskDAO $object, array $xactions) { $description = $object->getDescription(); $body = parent::buildMailBody($object, $xactions); if (strlen($description)) { $body->addRemarkupSection( pht('URL DESCRIPTION'), $object->getDescription()); } $body->addLinkSection( pht('URL DETAIL'), PhabricatorEnv::getProductionURI('/U'.$object->getID())); return $body; } protected function didCatchDuplicateKeyException( PhabricatorLiskDAO $object, array $xactions, Exception $ex) { $errors = array(); $errors[] = new PhabricatorApplicationTransactionValidationError( PhabricatorPhurlURLAliasTransaction::TRANSACTIONTYPE, pht('Duplicate'), pht('This alias is already in use.'), null); throw new PhabricatorApplicationTransactionValidationException($errors); } protected function buildReplyHandler(PhabricatorLiskDAO $object) { return id(new PhabricatorPhurlURLReplyHandler()) ->setMailReceiver($object); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/editor/PhabricatorPhurlURLEditEngine.php
src/applications/phurl/editor/PhabricatorPhurlURLEditEngine.php
<?php final class PhabricatorPhurlURLEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'phurl.url'; public function getEngineName() { return pht('Phurl'); } public function getEngineApplicationClass() { return 'PhabricatorPhurlApplication'; } public function getSummaryHeader() { return pht('Configure Phurl Forms'); } public function getSummaryText() { return pht('Configure creation and editing forms in Phurl.'); } public function isEngineConfigurable() { return false; } protected function newEditableObject() { return PhabricatorPhurlURL::initializeNewPhurlURL($this->getViewer()); } protected function newObjectQuery() { return new PhabricatorPhurlURLQuery(); } protected function getObjectCreateTitleText($object) { return pht('Create New URL'); } protected function getObjectEditTitleText($object) { return pht('Edit URL: %s', $object->getName()); } protected function getObjectEditShortText($object) { return $object->getName(); } protected function getObjectCreateShortText() { return pht('Create URL'); } protected function getObjectName() { return pht('URL'); } protected function getObjectCreateCancelURI($object) { return $this->getApplication()->getApplicationURI('/'); } protected function getEditorURI() { return $this->getApplication()->getApplicationURI('url/edit/'); } protected function getObjectViewURI($object) { return $object->getURI(); } protected function getCreateNewObjectPolicy() { return $this->getApplication()->getPolicy( PhabricatorPhurlURLCreateCapability::CAPABILITY); } protected function buildCustomEditFields($object) { return array( id(new PhabricatorTextEditField()) ->setKey('name') ->setLabel(pht('Name')) ->setDescription(pht('URL name.')) ->setIsRequired(true) ->setConduitTypeDescription(pht('New URL name.')) ->setTransactionType( PhabricatorPhurlURLNameTransaction::TRANSACTIONTYPE) ->setValue($object->getName()), id(new PhabricatorTextEditField()) ->setKey('url') ->setLabel(pht('URL')) ->setDescription(pht('The URL to shorten.')) ->setConduitTypeDescription(pht('New URL.')) ->setValue($object->getLongURL()) ->setIsRequired(true) ->setTransactionType( PhabricatorPhurlURLLongURLTransaction::TRANSACTIONTYPE), id(new PhabricatorTextEditField()) ->setKey('alias') ->setLabel(pht('Alias')) ->setIsRequired(true) ->setTransactionType( PhabricatorPhurlURLAliasTransaction::TRANSACTIONTYPE) ->setDescription(pht('The alias to give the URL.')) ->setConduitTypeDescription(pht('New alias.')) ->setValue($object->getAlias()), id(new PhabricatorRemarkupEditField()) ->setKey('description') ->setLabel(pht('Description')) ->setDescription(pht('URL long description.')) ->setConduitTypeDescription(pht('New URL description.')) ->setTransactionType( PhabricatorPhurlURLDescriptionTransaction::TRANSACTIONTYPE) ->setValue($object->getDescription()), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/xaction/PhabricatorPhurlURLTransactionType.php
src/applications/phurl/xaction/PhabricatorPhurlURLTransactionType.php
<?php abstract class PhabricatorPhurlURLTransactionType extends PhabricatorModularTransactionType {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/xaction/PhabricatorPhurlURLNameTransaction.php
src/applications/phurl/xaction/PhabricatorPhurlURLNameTransaction.php
<?php final class PhabricatorPhurlURLNameTransaction extends PhabricatorPhurlURLTransactionType { const TRANSACTIONTYPE = 'phurl.name'; public function generateOldValue($object) { return $object->getName(); } public function applyInternalEffects($object, $value) { $object->setName($value); } public function getTitle() { return pht( '%s changed the name of the URL from %s to %s.', $this->renderAuthor(), $this->renderOldValue(), $this->renderNewValue()); } public function getTitleForFeed() { return pht( '%s changed the name of %s from %s to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderOldValue(), $this->renderNewValue()); } public function validateTransactions($object, array $xactions) { $errors = array(); if ($this->isEmptyTextTransaction($object->getName(), $xactions)) { $errors[] = $this->newRequiredError( pht('Phurls must have a name.')); } return $errors; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/xaction/PhabricatorPhurlURLDescriptionTransaction.php
src/applications/phurl/xaction/PhabricatorPhurlURLDescriptionTransaction.php
<?php final class PhabricatorPhurlURLDescriptionTransaction extends PhabricatorPhurlURLTransactionType { const TRANSACTIONTYPE = 'phurl.description'; public function generateOldValue($object) { return $object->getDescription(); } public function applyInternalEffects($object, $value) { $object->setDescription($value); } public function getTitle() { return pht( '%s updated the description.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s updated the description for %s.', $this->renderAuthor(), $this->renderObject()); } public function hasChangeDetailView() { return true; } public function getMailDiffSectionHeader() { return pht('CHANGES TO PHURL DESCRIPTION'); } public function newChangeDetailView() { $viewer = $this->getViewer(); return id(new PhabricatorApplicationTransactionTextDiffDetailView()) ->setViewer($viewer) ->setOldText($this->getOldValue()) ->setNewText($this->getNewValue()); } public function newRemarkupChanges() { $changes = array(); $changes[] = $this->newRemarkupChange() ->setOldValue($this->getOldValue()) ->setNewValue($this->getNewValue()); return $changes; } public function getIcon() { return 'fa-file-text-o'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/xaction/PhabricatorPhurlURLAliasTransaction.php
src/applications/phurl/xaction/PhabricatorPhurlURLAliasTransaction.php
<?php final class PhabricatorPhurlURLAliasTransaction extends PhabricatorPhurlURLTransactionType { const TRANSACTIONTYPE = 'phurl.alias'; public function generateOldValue($object) { return $object->getAlias(); } public function applyInternalEffects($object, $value) { $object->setAlias($value); } public function getTitle() { return pht( '%s changed the alias from %s to %s.', $this->renderAuthor(), $this->renderOldValue(), $this->renderNewValue()); } public function getTitleForFeed() { return pht( '%s changed the alias of %s from %s to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderOldValue(), $this->renderNewValue()); } public function validateTransactions($object, array $xactions) { $errors = array(); if ($this->isEmptyTextTransaction($object->getAlias(), $xactions)) { $errors[] = $this->newRequiredError( pht('Phurls must have an alias.')); } $max_length = $object->getColumnMaximumByteLength('alias'); foreach ($xactions as $xaction) { $new_alias = $xaction->getNewValue(); // Check length $new_length = strlen($new_alias); if ($new_length > $max_length) { $errors[] = $this->newRequiredError( pht('The alias can be no longer than %d characters.', $max_length)); } // Check characters if ($xaction->getOldValue() != $xaction->getNewValue()) { $debug_alias = new PHUIInvisibleCharacterView($new_alias); if (!preg_match('/[a-zA-Z]/', $new_alias)) { $errors[] = $this->newRequiredError( pht('The alias you provided (%s) must contain at least one '. 'letter.', $debug_alias)); } if (preg_match('/[^a-z0-9]/i', $new_alias)) { $errors[] = $this->newRequiredError( pht('The alias you provided (%s) may only contain letters and '. 'numbers.', $debug_alias)); } } } return $errors; } public function getIcon() { return 'fa-compress'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/xaction/PhabricatorPhurlURLLongURLTransaction.php
src/applications/phurl/xaction/PhabricatorPhurlURLLongURLTransaction.php
<?php final class PhabricatorPhurlURLLongURLTransaction extends PhabricatorPhurlURLTransactionType { const TRANSACTIONTYPE = 'phurl.longurl'; public function generateOldValue($object) { return $object->getLongURL(); } public function applyInternalEffects($object, $value) { $object->setLongURL($value); } public function getTitle() { return pht( '%s changed the destination URL from %s to %s.', $this->renderAuthor(), $this->renderOldValue(), $this->renderNewValue()); } public function getTitleForFeed() { return pht( '%s changed the destination URL %s from %s to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderOldValue(), $this->renderNewValue()); } public function validateTransactions($object, array $xactions) { $errors = array(); if ($this->isEmptyTextTransaction($object->getLongURL(), $xactions)) { $errors[] = $this->newRequiredError( pht('URL path is required')); } foreach ($xactions as $xaction) { if ($xaction->getOldValue() != $xaction->getNewValue()) { $protocols = PhabricatorEnv::getEnvConfig('uri.allowed-protocols'); $uri = new PhutilURI($xaction->getNewValue()); if (!isset($protocols[$uri->getProtocol()])) { $errors[] = $this->newRequiredError( pht('The protocol of the URL is invalid.')); } } } return $errors; } public function getIcon() { return 'fa-external-link-square'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/application/PhabricatorPhurlApplication.php
src/applications/phurl/application/PhabricatorPhurlApplication.php
<?php final class PhabricatorPhurlApplication extends PhabricatorApplication { public function getName() { return pht('Phurl'); } public function getShortDescription() { return pht('URL Shortener'); } public function getFlavorText() { return pht('Shorten your favorite URL.'); } public function getBaseURI() { return '/phurl/'; } public function getIcon() { return 'fa-compress'; } public function isPrototype() { return true; } public function getApplicationGroup() { return self::GROUP_UTILITIES; } public function getRemarkupRules() { return array( new PhabricatorPhurlRemarkupRule(), new PhabricatorPhurlLinkRemarkupRule(), ); } public function getRoutes() { return array( '/U(?P<id>[1-9]\d*)/?' => 'PhabricatorPhurlURLViewController', '/u/(?P<id>[1-9]\d*)/?' => 'PhabricatorPhurlURLAccessController', '/u/(?P<alias>[^/]+)/?' => 'PhabricatorPhurlURLAccessController', '/phurl/' => array( '(?:query/(?P<queryKey>[^/]+)/)?' => 'PhabricatorPhurlURLListController', 'url/' => array( $this->getEditRoutePattern('edit/') => 'PhabricatorPhurlURLEditController', ), ), ); } public function getShortRoutes() { return array( '/status/' => 'PhabricatorStatusController', '/favicon.ico' => 'PhabricatorFaviconController', '/robots.txt' => 'PhabricatorRobotsShortController', '/u/(?P<append>[^/]+)' => 'PhabricatorPhurlShortURLController', '.*' => 'PhabricatorPhurlShortURLDefaultController', ); } protected function getCustomCapabilities() { return array( PhabricatorPhurlURLCreateCapability::CAPABILITY => array( 'default' => PhabricatorPolicies::POLICY_USER, ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/phid/PhabricatorPhurlURLPHIDType.php
src/applications/phurl/phid/PhabricatorPhurlURLPHIDType.php
<?php final class PhabricatorPhurlURLPHIDType extends PhabricatorPHIDType { const TYPECONST = 'PHRL'; public function getTypeName() { return pht('URL'); } public function newObject() { return new PhabricatorPhurlURL(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorPhurlApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorPhurlURLQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $url = $objects[$phid]; $id = $url->getID(); $name = $url->getName(); $full_name = $url->getMonogram().' '.$name; $handle ->setName($name) ->setFullName($full_name) ->setURI($url->getURI()); } } public function canLoadNamedObject($name) { return preg_match('/^U[1-9]\d*$/i', $name); } public function loadNamedObjects( PhabricatorObjectQuery $query, array $names) { $id_map = array(); foreach ($names as $name) { $id = (int)substr($name, 1); $id_map[$id][] = $name; } $objects = id(new PhabricatorPhurlURLQuery()) ->setViewer($query->getViewer()) ->withIDs(array_keys($id_map)) ->execute(); $results = array(); foreach ($objects as $id => $object) { foreach (idx($id_map, $id, array()) as $name) { $results[$name] = $object; } } return $results; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/conduit/PhabricatorPhurlURLEditConduitAPIMethod.php
src/applications/phurl/conduit/PhabricatorPhurlURLEditConduitAPIMethod.php
<?php final class PhabricatorPhurlURLEditConduitAPIMethod extends PhabricatorEditEngineAPIMethod { public function getAPIMethodName() { return 'phurls.edit'; } public function newEditEngine() { return new PhabricatorPhurlURLEditEngine(); } public function getMethodSummary() { return pht( 'Apply transactions to create a new Phurl URL or edit an existing one.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/conduit/PhabricatorPhurlURLSearchConduitAPIMethod.php
src/applications/phurl/conduit/PhabricatorPhurlURLSearchConduitAPIMethod.php
<?php final class PhabricatorPhurlURLSearchConduitAPIMethod extends PhabricatorSearchEngineAPIMethod { public function getAPIMethodName() { return 'phurls.search'; } public function newSearchEngine() { return new PhabricatorPhurlURLSearchEngine(); } public function getMethodSummary() { return pht('Read information about Phurl URLS.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/typeahead/PhabricatorPhurlURLDatasource.php
src/applications/phurl/typeahead/PhabricatorPhurlURLDatasource.php
<?php final class PhabricatorPhurlURLDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Phurl URLs'); } public function getPlaceholderText() { return pht('Select a phurl...'); } public function getDatasourceApplicationClass() { return 'PhabricatorPhurlApplication'; } public function loadResults() { $query = id(new PhabricatorPhurlURLQuery()); $urls = $this->executeQuery($query); $results = array(); foreach ($urls as $url) { $result = id(new PhabricatorTypeaheadResult()) ->setDisplayName($url->getName()) ->setName($url->getName()." ".$url->getAlias()) ->setPHID($url->getPHID()) ->setAutocomplete('(('.$url->getAlias().'))') ->addAttribute($url->getLongURL()); $results[] = $result; } return $this->filterResultsAgainstTokens($results); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/capability/PhabricatorPhurlURLCreateCapability.php
src/applications/phurl/capability/PhabricatorPhurlURLCreateCapability.php
<?php final class PhabricatorPhurlURLCreateCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'phurl.url.create'; public function getCapabilityName() { return pht('Can Create Phurl URLs'); } public function describeCapabilityRejection() { return pht('You do not have permission to create a Phurl URL.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/remarkup/PhabricatorPhurlLinkRemarkupRule.php
src/applications/phurl/remarkup/PhabricatorPhurlLinkRemarkupRule.php
<?php final class PhabricatorPhurlLinkRemarkupRule extends PhutilRemarkupRule { public function getPriority() { return 200.0; } public function apply($text) { // `((123))` remarkup link to `/u/123` // `((alias))` remarkup link to `/u/alias` return preg_replace_callback( '/\(\(([^ )]+)\)\)/', array($this, 'markupLink'), $text); } public function markupLink(array $matches) { $engine = $this->getEngine(); $viewer = $engine->getConfig('viewer'); $text_mode = $engine->isTextMode(); $html_mode = $engine->isHTMLMailMode(); if (!$this->isFlatText($matches[0])) { return $matches[0]; } $ref = $matches[1]; $monogram = null; $is_monogram = '/^U(?P<id>[1-9]\d*)/'; $query = id(new PhabricatorPhurlURLQuery()) ->setViewer($viewer); if (preg_match($is_monogram, $ref, $monogram)) { $query->withIDs(array($monogram[1])); } else if (ctype_digit($ref)) { $query->withIDs(array($ref)); } else { $query->withAliases(array($ref)); } $phurl = $query->executeOne(); if (!$phurl) { return $matches[0]; } $uri = $phurl->getRedirectURI(); $name = $phurl->getDisplayName(); if ($text_mode || $html_mode) { $uri = PhabricatorEnv::getProductionURI($uri); } if ($text_mode) { return pht( '%s <%s>', $name, $uri); } else { $link = phutil_tag( 'a', array( 'href' => $uri, 'target' => '_blank', 'rel' => 'noreferrer', ), $name); } return $this->getEngine()->storeText($link); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phurl/remarkup/PhabricatorPhurlRemarkupRule.php
src/applications/phurl/remarkup/PhabricatorPhurlRemarkupRule.php
<?php final class PhabricatorPhurlRemarkupRule extends PhabricatorObjectRemarkupRule { protected function getObjectNamePrefix() { return 'U'; } protected function loadObjects(array $ids) { $viewer = $this->getEngine()->getConfig('viewer'); return id(new PhabricatorPhurlURLQuery()) ->setViewer($viewer) ->withIDs($ids) ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/controller/PhabricatorCountdownViewController.php
src/applications/countdown/controller/PhabricatorCountdownViewController.php
<?php final class PhabricatorCountdownViewController extends PhabricatorCountdownController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $countdown = id(new PhabricatorCountdownQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); if (!$countdown) { return new Aphront404Response(); } $countdown_view = id(new PhabricatorCountdownView()) ->setUser($viewer) ->setCountdown($countdown); $id = $countdown->getID(); $title = $countdown->getTitle(); $crumbs = $this ->buildApplicationCrumbs() ->addTextCrumb($countdown->getMonogram()) ->setBorder(true); $epoch = $countdown->getEpoch(); if ($epoch >= PhabricatorTime::getNow()) { $icon = 'fa-clock-o'; $color = ''; $status = pht('Running'); } else { $icon = 'fa-check-square-o'; $color = 'dark'; $status = pht('Launched'); } $header = id(new PHUIHeaderView()) ->setHeader($title) ->setUser($viewer) ->setPolicyObject($countdown) ->setStatus($icon, $color, $status) ->setHeaderIcon('fa-rocket'); $curtain = $this->buildCurtain($countdown); $subheader = $this->buildSubheaderView($countdown); $timeline = $this->buildTransactionTimeline( $countdown, new PhabricatorCountdownTransactionQuery()); $comment_view = id(new PhabricatorCountdownEditEngine()) ->setViewer($viewer) ->buildEditEngineCommentView($countdown); $content = array( $countdown_view, $timeline, $comment_view, ); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setSubheader($subheader) ->setCurtain($curtain) ->setMainColumn($content); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->setPageObjectPHIDs( array( $countdown->getPHID(), )) ->appendChild($view); } private function buildCurtain(PhabricatorCountdown $countdown) { $viewer = $this->getViewer(); $id = $countdown->getID(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $countdown, PhabricatorPolicyCapability::CAN_EDIT); $curtain = $this->newCurtainView($countdown); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Countdown')) ->setHref($this->getApplicationURI("edit/{$id}/")) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); return $curtain; } private function buildSubheaderView( PhabricatorCountdown $countdown) { $viewer = $this->getViewer(); $author = $viewer->renderHandle($countdown->getAuthorPHID())->render(); $date = phabricator_datetime($countdown->getDateCreated(), $viewer); $author = phutil_tag('strong', array(), $author); $person = id(new PhabricatorPeopleQuery()) ->setViewer($viewer) ->withPHIDs(array($countdown->getAuthorPHID())) ->needProfileImage(true) ->executeOne(); $image_uri = $person->getProfileImageURI(); $image_href = '/p/'.$person->getUsername(); $content = pht('Authored by %s on %s.', $author, $date); return id(new PHUIHeadThingView()) ->setImage($image_uri) ->setImageHref($image_href) ->setContent($content); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/controller/PhabricatorCountdownListController.php
src/applications/countdown/controller/PhabricatorCountdownListController.php
<?php final class PhabricatorCountdownListController extends PhabricatorCountdownController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { return id(new PhabricatorCountdownSearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); id(new PhabricatorCountdownEditEngine()) ->setViewer($this->getViewer()) ->addActionToCrumbs($crumbs); return $crumbs; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/controller/PhabricatorCountdownEditController.php
src/applications/countdown/controller/PhabricatorCountdownEditController.php
<?php final class PhabricatorCountdownEditController extends PhabricatorCountdownController { public function handleRequest(AphrontRequest $request) { return id(new PhabricatorCountdownEditEngine()) ->setController($this) ->buildResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/controller/PhabricatorCountdownController.php
src/applications/countdown/controller/PhabricatorCountdownController.php
<?php abstract class PhabricatorCountdownController extends PhabricatorController { public function buildApplicationMenu() { return $this->newApplicationMenu() ->setSearchEngine(new PhabricatorCountdownSearchEngine()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/storage/PhabricatorCountdownDAO.php
src/applications/countdown/storage/PhabricatorCountdownDAO.php
<?php abstract class PhabricatorCountdownDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'countdown'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/storage/PhabricatorCountdownSchemaSpec.php
src/applications/countdown/storage/PhabricatorCountdownSchemaSpec.php
<?php final class PhabricatorCountdownSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new PhabricatorCountdown()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/storage/PhabricatorCountdownTransactionComment.php
src/applications/countdown/storage/PhabricatorCountdownTransactionComment.php
<?php final class PhabricatorCountdownTransactionComment extends PhabricatorApplicationTransactionComment { public function getApplicationTransactionObject() { return new PhabricatorCountdownTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/storage/PhabricatorCountdown.php
src/applications/countdown/storage/PhabricatorCountdown.php
<?php final class PhabricatorCountdown extends PhabricatorCountdownDAO implements PhabricatorPolicyInterface, PhabricatorFlaggableInterface, PhabricatorSubscribableInterface, PhabricatorApplicationTransactionInterface, PhabricatorTokenReceiverInterface, PhabricatorSpacesInterface, PhabricatorProjectInterface, PhabricatorDestructibleInterface, PhabricatorConduitResultInterface { protected $title; protected $authorPHID; protected $epoch; protected $description; protected $viewPolicy; protected $editPolicy; protected $mailKey; protected $spacePHID; public static function initializeNewCountdown(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery()) ->setViewer($actor) ->withClasses(array('PhabricatorCountdownApplication')) ->executeOne(); $view_policy = $app->getPolicy( PhabricatorCountdownDefaultViewCapability::CAPABILITY); $edit_policy = $app->getPolicy( PhabricatorCountdownDefaultEditCapability::CAPABILITY); return id(new PhabricatorCountdown()) ->setAuthorPHID($actor->getPHID()) ->setViewPolicy($view_policy) ->setEditPolicy($edit_policy) ->setSpacePHID($actor->getDefaultSpacePHID()); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_COLUMN_SCHEMA => array( 'title' => 'text255', 'description' => 'text', 'mailKey' => 'bytes20', ), self::CONFIG_KEY_SCHEMA => array( 'key_epoch' => array( 'columns' => array('epoch'), ), 'key_author' => array( 'columns' => array('authorPHID', 'epoch'), ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorCountdownCountdownPHIDType::TYPECONST); } public function getMonogram() { return 'C'.$this->getID(); } public function getURI() { return '/'.$this->getMonogram(); } public function save() { if (!$this->getMailKey()) { $this->setMailKey(Filesystem::readRandomCharacters(20)); } return parent::save(); } /* -( PhabricatorSubscribableInterface )----------------------------------- */ public function isAutomaticallySubscribed($phid) { return ($phid == $this->getAuthorPHID()); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhabricatorCountdownEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorCountdownTransaction(); } /* -( PhabricatorTokenReceiverInterface )---------------------------------- */ public function getUsersToNotifyOfTokenGiven() { return array($this->getAuthorPHID()); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->getViewPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return $this->getEditPolicy(); } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return false; } /* -( PhabricatorSpacesInterface )------------------------------------------- */ public function getSpacePHID() { return $this->spacePHID; } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); $this->delete(); $this->saveTransaction(); } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('title') ->setType('string') ->setDescription(pht('The title of the countdown.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('description') ->setType('remarkup') ->setDescription(pht('The description of the countdown.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('epoch') ->setType('epoch') ->setDescription(pht('The end date of the countdown.')), ); } public function getFieldValuesForConduit() { return array( 'title' => $this->getTitle(), 'description' => array( 'raw' => $this->getDescription(), ), 'epoch' => (int)$this->getEpoch(), ); } public function getConduitSearchAttachments() { return array(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/storage/PhabricatorCountdownTransaction.php
src/applications/countdown/storage/PhabricatorCountdownTransaction.php
<?php final class PhabricatorCountdownTransaction extends PhabricatorModularTransaction { const MAILTAG_DETAILS = 'countdown:details'; const MAILTAG_COMMENT = 'countdown:comment'; const MAILTAG_OTHER = 'countdown:other'; public function getApplicationName() { return 'countdown'; } public function getApplicationTransactionType() { return PhabricatorCountdownCountdownPHIDType::TYPECONST; } public function getApplicationTransactionCommentObject() { return new PhabricatorCountdownTransactionComment(); } public function getBaseTransactionClass() { return 'PhabricatorCountdownTransactionType'; } public function getMailTags() { $tags = parent::getMailTags(); switch ($this->getTransactionType()) { case PhabricatorTransactions::TYPE_COMMENT: $tags[] = self::MAILTAG_COMMENT; break; case PhabricatorCountdownTitleTransaction::TRANSACTIONTYPE: case PhabricatorCountdownEpochTransaction::TRANSACTIONTYPE: case PhabricatorCountdownDescriptionTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_DETAILS; break; default: $tags[] = self::MAILTAG_OTHER; break; } return $tags; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/query/PhabricatorCountdownQuery.php
src/applications/countdown/query/PhabricatorCountdownQuery.php
<?php final class PhabricatorCountdownQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $authorPHIDs; private $upcoming; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withAuthorPHIDs(array $author_phids) { $this->authorPHIDs = $author_phids; return $this; } public function withUpcoming() { $this->upcoming = true; return $this; } public function newResultObject() { return new PhabricatorCountdown(); } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'phid IN (%Ls)', $this->phids); } if ($this->authorPHIDs !== null) { $where[] = qsprintf( $conn, 'authorPHID in (%Ls)', $this->authorPHIDs); } if ($this->upcoming !== null) { $where[] = qsprintf( $conn, 'epoch >= %d', PhabricatorTime::getNow()); } return $where; } public function getQueryApplicationClass() { return 'PhabricatorCountdownApplication'; } public function getBuiltinOrders() { return array( 'ending' => array( 'vector' => array('-epoch', '-id'), 'name' => pht('End Date (Past to Future)'), ), 'unending' => array( 'vector' => array('epoch', 'id'), 'name' => pht('End Date (Future to Past)'), ), ) + parent::getBuiltinOrders(); } public function getOrderableColumns() { return array( 'epoch' => array( 'table' => $this->getPrimaryTableAlias(), 'column' => 'epoch', 'type' => 'int', ), ) + parent::getOrderableColumns(); } protected function newPagingMapFromPartialObject($object) { return array( 'id' => (int)$object->getID(), 'epoch' => (int)$object->getEpoch(), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/query/PhabricatorCountdownSearchEngine.php
src/applications/countdown/query/PhabricatorCountdownSearchEngine.php
<?php final class PhabricatorCountdownSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Countdowns'); } public function getApplicationClassName() { return 'PhabricatorCountdownApplication'; } public function newQuery() { return new PhabricatorCountdownQuery(); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['authorPHIDs']) { $query->withAuthorPHIDs($map['authorPHIDs']); } if ($map['upcoming'] && $map['upcoming'][0] == 'upcoming') { $query->withUpcoming(); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorUsersSearchField()) ->setLabel(pht('Authors')) ->setKey('authorPHIDs') ->setAliases(array('author', 'authors')), id(new PhabricatorSearchCheckboxesField()) ->setKey('upcoming') ->setOptions( array( 'upcoming' => pht('Show only upcoming countdowns.'), )), ); } protected function getURI($path) { return '/countdown/'.$path; } protected function getBuiltinQueryNames() { $names = array( 'upcoming' => pht('Upcoming'), 'all' => pht('All'), ); if ($this->requireViewer()->getPHID()) { $names['authored'] = pht('Authored'); } return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; case 'authored': return $query->setParameter( 'authorPHIDs', array($this->requireViewer()->getPHID())); case 'upcoming': return $query->setParameter('upcoming', array('upcoming')); } return parent::buildSavedQueryFromBuiltin($query_key); } protected function getRequiredHandlePHIDsForResultList( array $countdowns, PhabricatorSavedQuery $query) { return mpull($countdowns, 'getAuthorPHID'); } protected function renderResultList( array $countdowns, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($countdowns, 'PhabricatorCountdown'); $viewer = $this->requireViewer(); $list = new PHUIObjectItemListView(); $list->setUser($viewer); foreach ($countdowns as $countdown) { $id = $countdown->getID(); $ended = false; $epoch = $countdown->getEpoch(); if ($epoch <= PhabricatorTime::getNow()) { $ended = true; } $item = id(new PHUIObjectItemView()) ->setUser($viewer) ->setObject($countdown) ->setObjectName($countdown->getMonogram()) ->setHeader($countdown->getTitle()) ->setHref($countdown->getURI()) ->addByline( pht( 'Created by %s', $handles[$countdown->getAuthorPHID()]->renderLink())); if ($ended) { $item->addAttribute( pht('Launched on %s', phabricator_datetime($epoch, $viewer))); $item->setDisabled(true); } else { $time_left = ($epoch - PhabricatorTime::getNow()); $num = round($time_left / (60 * 60 * 24)); $noun = pht('Days'); if ($num < 1) { $num = round($time_left / (60 * 60), 1); $noun = pht('Hours'); } $item->setCountdown($num, $noun); $item->addAttribute( phabricator_datetime($epoch, $viewer)); } $list->addItem($item); } $result = new PhabricatorApplicationSearchResultView(); $result->setObjectList($list); $result->setNoDataString(pht('No countdowns found.')); return $result; } protected function getNewUserBody() { $create_button = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Create a Countdown')) ->setHref('/countdown/edit/') ->setColor(PHUIButtonView::GREEN); $icon = $this->getApplication()->getIcon(); $app_name = $this->getApplication()->getName(); $view = id(new PHUIBigInfoView()) ->setIcon($icon) ->setTitle(pht('Welcome to %s', $app_name)) ->setDescription( pht('Keep track of upcoming launch dates with '. 'embeddable counters.')) ->addAction($create_button); return $view; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/query/PhabricatorCountdownTransactionQuery.php
src/applications/countdown/query/PhabricatorCountdownTransactionQuery.php
<?php final class PhabricatorCountdownTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhabricatorCountdownTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/mail/PhabricatorCountdownMailReceiver.php
src/applications/countdown/mail/PhabricatorCountdownMailReceiver.php
<?php final class PhabricatorCountdownMailReceiver extends PhabricatorObjectMailReceiver { public function isEnabled() { return PhabricatorApplication::isClassInstalled( 'PhabricatorCountdownApplication'); } protected function getObjectPattern() { return 'C[1-9]\d*'; } protected function loadObject($pattern, PhabricatorUser $viewer) { $id = (int)substr($pattern, 1); return id(new PhabricatorCountdownQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); } protected function getTransactionReplyHandler() { return new PhabricatorCountdownReplyHandler(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/mail/PhabricatorCountdownReplyHandler.php
src/applications/countdown/mail/PhabricatorCountdownReplyHandler.php
<?php final class PhabricatorCountdownReplyHandler extends PhabricatorApplicationTransactionReplyHandler { public function validateMailReceiver($mail_receiver) { if (!($mail_receiver instanceof PhabricatorCountdown)) { throw new Exception(pht('Mail receiver is not a %s!', 'Countdown')); } } public function getObjectPrefix() { return 'C'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/editor/PhabricatorCountdownEditor.php
src/applications/countdown/editor/PhabricatorCountdownEditor.php
<?php final class PhabricatorCountdownEditor extends PhabricatorApplicationTransactionEditor { public function getEditorApplicationClass() { return 'PhabricatorCountdownApplication'; } public function getEditorObjectsDescription() { return pht('Countdown'); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorTransactions::TYPE_EDGE; $types[] = PhabricatorTransactions::TYPE_SPACE; $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY; $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY; $types[] = PhabricatorTransactions::TYPE_COMMENT; return $types; } protected function shouldSendMail( PhabricatorLiskDAO $object, array $xactions) { return true; } public function getMailTagsMap() { return array( PhabricatorCountdownTransaction::MAILTAG_DETAILS => pht('Someone changes the countdown details.'), PhabricatorCountdownTransaction::MAILTAG_COMMENT => pht('Someone comments on a countdown.'), PhabricatorCountdownTransaction::MAILTAG_OTHER => pht('Other countdown activity not listed above occurs.'), ); } protected function buildMailTemplate(PhabricatorLiskDAO $object) { $monogram = $object->getMonogram(); $name = $object->getTitle(); return id(new PhabricatorMetaMTAMail()) ->setSubject("{$monogram}: {$name}"); } protected function buildMailBody( PhabricatorLiskDAO $object, array $xactions) { $body = parent::buildMailBody($object, $xactions); $description = $object->getDescription(); if (strlen($description)) { $body->addRemarkupSection( pht('COUNTDOWN DESCRIPTION'), $object->getDescription()); } $body->addLinkSection( pht('COUNTDOWN DETAIL'), PhabricatorEnv::getProductionURI('/'.$object->getMonogram())); return $body; } protected function getMailTo(PhabricatorLiskDAO $object) { return array( $object->getAuthorPHID(), $this->requireActor()->getPHID(), ); } protected function getMailSubjectPrefix() { return '[Countdown]'; } protected function buildReplyHandler(PhabricatorLiskDAO $object) { return id(new PhabricatorCountdownReplyHandler()) ->setMailReceiver($object); } protected function shouldPublishFeedStory( PhabricatorLiskDAO $object, array $xactions) { return true; } protected function supportsSearch() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/editor/PhabricatorCountdownEditEngine.php
src/applications/countdown/editor/PhabricatorCountdownEditEngine.php
<?php final class PhabricatorCountdownEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'countdown.countdown'; public function isEngineConfigurable() { return false; } public function getEngineName() { return pht('Countdowns'); } public function getSummaryHeader() { return pht('Edit Countdowns'); } public function getSummaryText() { return pht('Creates and edits countdowns.'); } public function getEngineApplicationClass() { return 'PhabricatorCountdownApplication'; } protected function newEditableObject() { return PhabricatorCountdown::initializeNewCountdown( $this->getViewer()); } protected function newObjectQuery() { return id(new PhabricatorCountdownQuery()); } protected function getObjectCreateTitleText($object) { return pht('Create Countdown'); } protected function getObjectCreateButtonText($object) { return pht('Create Countdown'); } protected function getObjectEditTitleText($object) { return pht('Edit Countdown: %s', $object->getTitle()); } protected function getObjectEditShortText($object) { return pht('Edit Countdown'); } protected function getObjectCreateShortText() { return pht('Create Countdown'); } protected function getObjectName() { return pht('Countdown'); } protected function getCommentViewHeaderText($object) { return pht('Last Words'); } protected function getCommentViewButtonText($object) { return pht('Contemplate Infinity'); } protected function getObjectViewURI($object) { return $object->getURI(); } protected function buildCustomEditFields($object) { $epoch_value = $object->getEpoch(); if ($epoch_value === null) { $epoch_value = PhabricatorTime::getNow(); } return array( id(new PhabricatorTextEditField()) ->setKey('name') ->setLabel(pht('Name')) ->setIsRequired(true) ->setTransactionType( PhabricatorCountdownTitleTransaction::TRANSACTIONTYPE) ->setDescription(pht('The countdown name.')) ->setConduitDescription(pht('Rename the countdown.')) ->setConduitTypeDescription(pht('New countdown name.')) ->setValue($object->getTitle()), id(new PhabricatorEpochEditField()) ->setKey('epoch') ->setLabel(pht('End Date')) ->setTransactionType( PhabricatorCountdownEpochTransaction::TRANSACTIONTYPE) ->setDescription(pht('Date when the countdown ends.')) ->setConduitDescription(pht('Change the end date of the countdown.')) ->setConduitTypeDescription(pht('New countdown end date.')) ->setValue($epoch_value), id(new PhabricatorRemarkupEditField()) ->setKey('description') ->setLabel(pht('Description')) ->setTransactionType( PhabricatorCountdownDescriptionTransaction::TRANSACTIONTYPE) ->setDescription(pht('Description of the countdown.')) ->setConduitDescription(pht('Change the countdown description.')) ->setConduitTypeDescription(pht('New description.')) ->setValue($object->getDescription()), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/xaction/PhabricatorCountdownEpochTransaction.php
src/applications/countdown/xaction/PhabricatorCountdownEpochTransaction.php
<?php final class PhabricatorCountdownEpochTransaction extends PhabricatorCountdownTransactionType { const TRANSACTIONTYPE = 'countdown:epoch'; public function generateOldValue($object) { return (int)$object->getEpoch(); } public function generateNewValue($object, $value) { return $value->newPhutilDateTime() ->newAbsoluteDateTime() ->getEpoch(); } public function applyInternalEffects($object, $value) { $object->setEpoch($value); } public function getTitle() { return pht( '%s updated the countdown end from %s to %s.', $this->renderAuthor(), $this->renderOldDate(), $this->renderNewDate()); } public function getTitleForFeed() { return pht( '%s updated the countdown end for %s from %s to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderOldDate(), $this->renderNewDate()); } public function validateTransactions($object, array $xactions) { $errors = array(); if (!$object->getEpoch() && !$xactions) { $errors[] = $this->newRequiredError( pht('You must give the countdown an end date.')); return $errors; } foreach ($xactions as $xaction) { $value = $xaction->getNewValue(); if (!$value->isValid()) { $errors[] = $this->newInvalidError( pht('You must give the countdown an end date.')); } } return $errors; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/xaction/PhabricatorCountdownTransactionType.php
src/applications/countdown/xaction/PhabricatorCountdownTransactionType.php
<?php abstract class PhabricatorCountdownTransactionType extends PhabricatorModularTransactionType {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/xaction/PhabricatorCountdownTitleTransaction.php
src/applications/countdown/xaction/PhabricatorCountdownTitleTransaction.php
<?php final class PhabricatorCountdownTitleTransaction extends PhabricatorCountdownTransactionType { const TRANSACTIONTYPE = 'countdown:title'; public function generateOldValue($object) { return $object->getTitle(); } public function applyInternalEffects($object, $value) { $object->setTitle($value); } public function getTitle() { return pht( '%s updated the title for this countdown from %s to %s.', $this->renderAuthor(), $this->renderOldValue(), $this->renderNewValue()); } public function getTitleForFeed() { return pht( '%s updated the title for this countdown from %s to %s.', $this->renderAuthor(), $this->renderOldValue(), $this->renderNewValue()); } public function validateTransactions($object, array $xactions) { $errors = array(); if ($this->isEmptyTextTransaction($object->getTitle(), $xactions)) { $errors[] = $this->newRequiredError(pht('Countdowns must have a title.')); } $max_length = $object->getColumnMaximumByteLength('title'); foreach ($xactions as $xaction) { $new_value = $xaction->getNewValue(); $new_length = strlen($new_value); if ($new_length > $max_length) { $errors[] = $this->newInvalidError( pht( 'Countdown titles must not be longer than %s character(s).', new PhutilNumber($max_length))); } } return $errors; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/xaction/PhabricatorCountdownDescriptionTransaction.php
src/applications/countdown/xaction/PhabricatorCountdownDescriptionTransaction.php
<?php final class PhabricatorCountdownDescriptionTransaction extends PhabricatorCountdownTransactionType { const TRANSACTIONTYPE = 'countdown:description'; public function generateOldValue($object) { return $object->getDescription(); } public function applyInternalEffects($object, $value) { $object->setDescription($value); } public function getTitle() { return pht( '%s updated the countdown description.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s updated the countdown description for %s.', $this->renderAuthor(), $this->renderObject()); } public function hasChangeDetailView() { return true; } public function getMailDiffSectionHeader() { return pht('CHANGES TO COUNTDOWN DESCRIPTION'); } public function newChangeDetailView() { $viewer = $this->getViewer(); return id(new PhabricatorApplicationTransactionTextDiffDetailView()) ->setViewer($viewer) ->setOldText($this->getOldValue()) ->setNewText($this->getNewValue()); } public function newRemarkupChanges() { $changes = array(); $changes[] = $this->newRemarkupChange() ->setOldValue($this->getOldValue()) ->setNewValue($this->getNewValue()); return $changes; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/application/PhabricatorCountdownApplication.php
src/applications/countdown/application/PhabricatorCountdownApplication.php
<?php final class PhabricatorCountdownApplication extends PhabricatorApplication { public function getBaseURI() { return '/countdown/'; } public function getIcon() { return 'fa-rocket'; } public function getName() { return pht('Countdown'); } public function getShortDescription() { return pht('Countdown to Events'); } public function getTitleGlyph() { return "\xE2\x9A\xB2"; } public function getFlavorText() { return pht('Utilize the full capabilities of your ALU.'); } public function getApplicationGroup() { return self::GROUP_UTILITIES; } public function getRemarkupRules() { return array( new PhabricatorCountdownRemarkupRule(), ); } public function getRoutes() { return array( '/C(?P<id>[1-9]\d*)' => 'PhabricatorCountdownViewController', '/countdown/' => array( '(?:query/(?P<queryKey>[^/]+)/)?' => 'PhabricatorCountdownListController', $this->getEditRoutePattern('edit/') => 'PhabricatorCountdownEditController', ), ); } protected function getCustomCapabilities() { return array( PhabricatorCountdownDefaultViewCapability::CAPABILITY => array( 'caption' => pht('Default view policy for new countdowns.'), 'template' => PhabricatorCountdownCountdownPHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_VIEW, ), PhabricatorCountdownDefaultEditCapability::CAPABILITY => array( 'caption' => pht('Default edit policy for new countdowns.'), 'template' => PhabricatorCountdownCountdownPHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_EDIT, ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/view/PhabricatorCountdownView.php
src/applications/countdown/view/PhabricatorCountdownView.php
<?php final class PhabricatorCountdownView extends AphrontView { private $countdown; public function setCountdown(PhabricatorCountdown $countdown) { $this->countdown = $countdown; return $this; } public function render() { $countdown = $this->countdown; require_celerity_resource('phabricator-countdown-css'); $header_text = array( $countdown->getMonogram(), ' ', phutil_tag( 'a', array( 'href' => $countdown->getURI(), ), $countdown->getTitle()), ); $header = id(new PHUIHeaderView()) ->setHeader($header_text); $ths = array( phutil_tag('th', array(), pht('Days')), phutil_tag('th', array(), pht('Hours')), phutil_tag('th', array(), pht('Minutes')), phutil_tag('th', array(), pht('Seconds')), ); $dashes = array( javelin_tag('td', array('sigil' => 'phabricator-timer-days'), '-'), javelin_tag('td', array('sigil' => 'phabricator-timer-hours'), '-'), javelin_tag('td', array('sigil' => 'phabricator-timer-minutes'), '-'), javelin_tag('td', array('sigil' => 'phabricator-timer-seconds'), '-'), ); $epoch = $countdown->getEpoch(); $launch_date = phabricator_datetime($epoch, $this->getUser()); $foot = phutil_tag( 'td', array( 'colspan' => '4', 'class' => 'phabricator-timer-foot', ), $launch_date); $description = $countdown->getDescription(); if (strlen($description)) { $description = new PHUIRemarkupView($this->getUser(), $description); $description = phutil_tag( 'div', array( 'class' => 'countdown-description phabricator-remarkup', ), $description); } $container = celerity_generate_unique_node_id(); $content = phutil_tag( 'div', array('class' => 'phabricator-timer', 'id' => $container), array( $description, phutil_tag('table', array('class' => 'phabricator-timer-table'), array( phutil_tag('tr', array(), $ths), phutil_tag('tr', array(), $dashes), phutil_tag('tr', array(), $foot), )), )); Javelin::initBehavior('countdown-timer', array( 'timestamp' => $countdown->getEpoch(), 'container' => $container, )); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addClass('phabricator-timer-view') ->appendChild($content); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/phid/PhabricatorCountdownCountdownPHIDType.php
src/applications/countdown/phid/PhabricatorCountdownCountdownPHIDType.php
<?php final class PhabricatorCountdownCountdownPHIDType extends PhabricatorPHIDType { const TYPECONST = 'CDWN'; public function getTypeName() { return pht('Countdown'); } public function newObject() { return new PhabricatorCountdown(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorCountdownApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorCountdownQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $countdown = $objects[$phid]; $name = $countdown->getTitle(); $id = $countdown->getID(); $handle->setName($countdown->getMonogram()); $handle->setFullName(pht('%s: %s', $countdown->getMonogram(), $name)); $handle->setURI($countdown->getURI()); } } public function canLoadNamedObject($name) { return preg_match('/^C\d*[1-9]\d*$/i', $name); } public function loadNamedObjects( PhabricatorObjectQuery $query, array $names) { $id_map = array(); foreach ($names as $name) { $id = (int)substr($name, 1); $id_map[$id][] = $name; } $objects = id(new PhabricatorCountdownQuery()) ->setViewer($query->getViewer()) ->withIDs(array_keys($id_map)) ->execute(); $results = array(); foreach ($objects as $id => $object) { foreach (idx($id_map, $id, array()) as $name) { $results[$name] = $object; } } return $results; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/conduit/CountdownSearchConduitAPIMethod.php
src/applications/countdown/conduit/CountdownSearchConduitAPIMethod.php
<?php final class CountdownSearchConduitAPIMethod extends PhabricatorSearchEngineAPIMethod { public function getAPIMethodName() { return 'countdown.search'; } public function newSearchEngine() { return new PhabricatorCountdownSearchEngine(); } public function getMethodSummary() { return pht('Read information about countdowns.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/conduit/CountdownEditConduitAPIMethod.php
src/applications/countdown/conduit/CountdownEditConduitAPIMethod.php
<?php final class CountdownEditConduitAPIMethod extends PhabricatorEditEngineAPIMethod { public function getAPIMethodName() { return 'countdown.edit'; } public function newEditEngine() { return new PhabricatorCountdownEditEngine(); } public function getMethodSummary() { return pht( 'Apply transactions to create a new countdown or edit an existing one.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/capability/PhabricatorCountdownDefaultEditCapability.php
src/applications/countdown/capability/PhabricatorCountdownDefaultEditCapability.php
<?php final class PhabricatorCountdownDefaultEditCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'countdown.default.edit'; public function getCapabilityName() { return pht('Default Edit Policy'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/capability/PhabricatorCountdownDefaultViewCapability.php
src/applications/countdown/capability/PhabricatorCountdownDefaultViewCapability.php
<?php final class PhabricatorCountdownDefaultViewCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'countdown.default.view'; public function getCapabilityName() { return pht('Default View Policy'); } public function shouldAllowPublicPolicySetting() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/countdown/remarkup/PhabricatorCountdownRemarkupRule.php
src/applications/countdown/remarkup/PhabricatorCountdownRemarkupRule.php
<?php final class PhabricatorCountdownRemarkupRule extends PhabricatorObjectRemarkupRule { protected function getObjectNamePrefix() { return 'C'; } protected function loadObjects(array $ids) { $viewer = $this->getEngine()->getConfig('viewer'); return id(new PhabricatorCountdownQuery()) ->setViewer($viewer) ->withIDs($ids) ->execute(); } protected function renderObjectEmbed( $object, PhabricatorObjectHandle $handle, $options) { $viewer = $this->getEngine()->getConfig('viewer'); return id(new PhabricatorCountdownView()) ->setCountdown($object) ->setUser($viewer); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryURITransaction.php
src/applications/repository/storage/PhabricatorRepositoryURITransaction.php
<?php final class PhabricatorRepositoryURITransaction extends PhabricatorApplicationTransaction { const TYPE_REPOSITORY = 'diffusion.uri.repository'; const TYPE_URI = 'diffusion.uri.uri'; const TYPE_IO = 'diffusion.uri.io'; const TYPE_DISPLAY = 'diffusion.uri.display'; const TYPE_CREDENTIAL = 'diffusion.uri.credential'; const TYPE_DISABLE = 'diffusion.uri.disable'; public function getApplicationName() { return 'repository'; } public function getApplicationTransactionType() { return PhabricatorRepositoryURIPHIDType::TYPECONST; } public function getRequiredHandlePHIDs() { $phids = parent::getRequiredHandlePHIDs(); $old = $this->getOldValue(); $new = $this->getNewValue(); switch ($this->getTransactionType()) { case self::TYPE_CREDENTIAL: if ($old) { $phids[] = $old; } if ($new) { $phids[] = $new; } break; } return $phids; } public function getTitle() { $author_phid = $this->getAuthorPHID(); $old = $this->getOldValue(); $new = $this->getNewValue(); switch ($this->getTransactionType()) { case self::TYPE_URI: return pht( '%s changed this URI from "%s" to "%s".', $this->renderHandleLink($author_phid), $old, $new); case self::TYPE_IO: $map = PhabricatorRepositoryURI::getIOTypeMap(); $old_label = idx(idx($map, $old, array()), 'label', $old); $new_label = idx(idx($map, $new, array()), 'label', $new); return pht( '%s changed the display type for this URI from "%s" to "%s".', $this->renderHandleLink($author_phid), $old_label, $new_label); case self::TYPE_DISPLAY: $map = PhabricatorRepositoryURI::getDisplayTypeMap(); $old_label = idx(idx($map, $old, array()), 'label', $old); $new_label = idx(idx($map, $new, array()), 'label', $new); return pht( '%s changed the display type for this URI from "%s" to "%s".', $this->renderHandleLink($author_phid), $old_label, $new_label); case self::TYPE_DISABLE: if ($new) { return pht( '%s disabled this URI.', $this->renderHandleLink($author_phid)); } else { return pht( '%s enabled this URI.', $this->renderHandleLink($author_phid)); } case self::TYPE_CREDENTIAL: if ($old && $new) { return pht( '%s changed the credential for this URI from %s to %s.', $this->renderHandleLink($author_phid), $this->renderHandleLink($old), $this->renderHandleLink($new)); } else if ($old) { return pht( '%s removed %s as the credential for this URI.', $this->renderHandleLink($author_phid), $this->renderHandleLink($old)); } else if ($new) { return pht( '%s set the credential for this URI to %s.', $this->renderHandleLink($author_phid), $this->renderHandleLink($new)); } } return parent::getTitle(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryMirror.php
src/applications/repository/storage/PhabricatorRepositoryMirror.php
<?php /** * TODO: Remove this class and drop the underlying table after some time has * passed. It currently exists only so that "bin/storage adjust" does not * complain about the table. */ final class PhabricatorRepositoryMirror extends PhabricatorRepositoryDAO { protected $repositoryPHID; protected $remoteURI; protected $credentialPHID; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_COLUMN_SCHEMA => array( 'remoteURI' => 'text255', 'credentialPHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'key_repository' => array( 'columns' => array('repositoryPHID'), ), ), ) + parent::getConfiguration(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryCommit.php
src/applications/repository/storage/PhabricatorRepositoryCommit.php
<?php final class PhabricatorRepositoryCommit extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface, PhabricatorFlaggableInterface, PhabricatorProjectInterface, PhabricatorTokenReceiverInterface, PhabricatorSubscribableInterface, PhabricatorMentionableInterface, HarbormasterBuildableInterface, HarbormasterCircleCIBuildableInterface, HarbormasterBuildkiteBuildableInterface, PhabricatorCustomFieldInterface, PhabricatorApplicationTransactionInterface, PhabricatorTimelineInterface, PhabricatorFulltextInterface, PhabricatorFerretInterface, PhabricatorConduitResultInterface, PhabricatorDraftInterface { protected $repositoryID; protected $phid; protected $authorIdentityPHID; protected $committerIdentityPHID; protected $commitIdentifier; protected $epoch; protected $authorPHID; protected $auditStatus = DiffusionCommitAuditStatus::NONE; protected $summary = ''; protected $importStatus = 0; const IMPORTED_MESSAGE = 1; const IMPORTED_CHANGE = 2; const IMPORTED_PUBLISH = 8; const IMPORTED_ALL = 11; const IMPORTED_PERMANENT = 1024; const IMPORTED_UNREACHABLE = 2048; private $commitData = self::ATTACHABLE; private $audits = self::ATTACHABLE; private $repository = self::ATTACHABLE; private $customFields = self::ATTACHABLE; private $authorIdentity = self::ATTACHABLE; private $committerIdentity = self::ATTACHABLE; private $drafts = array(); private $auditAuthorityPHIDs = array(); public function attachRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getRepository($assert_attached = true) { if ($assert_attached) { return $this->assertAttached($this->repository); } return $this->repository; } public function isPartiallyImported($mask) { return (($mask & $this->getImportStatus()) == $mask); } public function isImported() { return $this->isPartiallyImported(self::IMPORTED_ALL); } public function isUnreachable() { return $this->isPartiallyImported(self::IMPORTED_UNREACHABLE); } public function writeImportStatusFlag($flag) { return $this->adjustImportStatusFlag($flag, true); } public function clearImportStatusFlag($flag) { return $this->adjustImportStatusFlag($flag, false); } private function adjustImportStatusFlag($flag, $set) { $conn_w = $this->establishConnection('w'); $table_name = $this->getTableName(); $id = $this->getID(); if ($set) { queryfx( $conn_w, 'UPDATE %T SET importStatus = (importStatus | %d) WHERE id = %d', $table_name, $flag, $id); $this->setImportStatus($this->getImportStatus() | $flag); } else { queryfx( $conn_w, 'UPDATE %T SET importStatus = (importStatus & ~%d) WHERE id = %d', $table_name, $flag, $id); $this->setImportStatus($this->getImportStatus() & ~$flag); } return $this; } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'commitIdentifier' => 'text40', 'authorPHID' => 'phid?', 'authorIdentityPHID' => 'phid?', 'committerIdentityPHID' => 'phid?', 'auditStatus' => 'text32', 'summary' => 'text255', 'importStatus' => 'uint32', ), self::CONFIG_KEY_SCHEMA => array( 'key_phid' => null, 'phid' => array( 'columns' => array('phid'), 'unique' => true, ), 'repositoryID' => array( 'columns' => array('repositoryID', 'importStatus'), ), 'authorPHID' => array( 'columns' => array('authorPHID', 'auditStatus', 'epoch'), ), 'repositoryID_2' => array( 'columns' => array('repositoryID', 'epoch'), ), 'key_commit_identity' => array( 'columns' => array('commitIdentifier', 'repositoryID'), 'unique' => true, ), 'key_epoch' => array( 'columns' => array('epoch'), ), 'key_author' => array( 'columns' => array('authorPHID', 'epoch'), ), ), self::CONFIG_NO_MUTATE => array( 'importStatus', ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorRepositoryCommitPHIDType::TYPECONST); } public function loadCommitData() { if (!$this->getID()) { return null; } return id(new PhabricatorRepositoryCommitData())->loadOneWhere( 'commitID = %d', $this->getID()); } public function attachCommitData( PhabricatorRepositoryCommitData $data = null) { $this->commitData = $data; return $this; } public function hasCommitData() { return ($this->commitData !== self::ATTACHABLE) && ($this->commitData !== null); } public function getCommitData() { return $this->assertAttached($this->commitData); } public function attachAudits(array $audits) { assert_instances_of($audits, 'PhabricatorRepositoryAuditRequest'); $this->audits = $audits; return $this; } public function getAudits() { return $this->assertAttached($this->audits); } public function hasAttachedAudits() { return ($this->audits !== self::ATTACHABLE); } public function attachIdentities( PhabricatorRepositoryIdentity $author = null, PhabricatorRepositoryIdentity $committer = null) { $this->authorIdentity = $author; $this->committerIdentity = $committer; return $this; } public function getAuthorIdentity() { return $this->assertAttached($this->authorIdentity); } public function getCommitterIdentity() { return $this->assertAttached($this->committerIdentity); } public function attachAuditAuthority( PhabricatorUser $user, array $authority) { $user_phid = $user->getPHID(); if (!$user->getPHID()) { throw new Exception( pht('You can not attach audit authority for a user with no PHID.')); } $this->auditAuthorityPHIDs[$user_phid] = $authority; return $this; } public function hasAuditAuthority( PhabricatorUser $user, PhabricatorRepositoryAuditRequest $audit) { $user_phid = $user->getPHID(); if (!$user_phid) { return false; } $map = $this->assertAttachedKey($this->auditAuthorityPHIDs, $user_phid); return isset($map[$audit->getAuditorPHID()]); } public function writeOwnersEdges(array $package_phids) { $src_phid = $this->getPHID(); $edge_type = DiffusionCommitHasPackageEdgeType::EDGECONST; $editor = new PhabricatorEdgeEditor(); $dst_phids = PhabricatorEdgeQuery::loadDestinationPHIDs( $src_phid, $edge_type); foreach ($dst_phids as $dst_phid) { $editor->removeEdge($src_phid, $edge_type, $dst_phid); } foreach ($package_phids as $package_phid) { $editor->addEdge($src_phid, $edge_type, $package_phid); } $editor->save(); return $this; } public function getAuditorPHIDsForEdit() { $audits = $this->getAudits(); return mpull($audits, 'getAuditorPHID'); } public function delete() { $data = $this->loadCommitData(); $audits = id(new PhabricatorRepositoryAuditRequest()) ->loadAllWhere('commitPHID = %s', $this->getPHID()); $this->openTransaction(); if ($data) { $data->delete(); } foreach ($audits as $audit) { $audit->delete(); } $result = parent::delete(); $this->saveTransaction(); return $result; } public function getDateCreated() { // This is primarily to make analysis of commits with the Fact engine work. return $this->getEpoch(); } public function getURI() { return '/'.$this->getMonogram(); } /** * Synchronize a commit's overall audit status with the individual audit * triggers. */ public function updateAuditStatus(array $requests) { assert_instances_of($requests, 'PhabricatorRepositoryAuditRequest'); $any_concern = false; $any_accept = false; $any_need = false; foreach ($requests as $request) { switch ($request->getAuditStatus()) { case PhabricatorAuditRequestStatus::AUDIT_REQUIRED: case PhabricatorAuditRequestStatus::AUDIT_REQUESTED: $any_need = true; break; case PhabricatorAuditRequestStatus::ACCEPTED: $any_accept = true; break; case PhabricatorAuditRequestStatus::CONCERNED: $any_concern = true; break; } } if ($any_concern) { if ($this->isAuditStatusNeedsVerification()) { // If the change is in "Needs Verification", we keep it there as // long as any auditors still have concerns. $status = DiffusionCommitAuditStatus::NEEDS_VERIFICATION; } else { $status = DiffusionCommitAuditStatus::CONCERN_RAISED; } } else if ($any_accept) { if ($any_need) { $status = DiffusionCommitAuditStatus::PARTIALLY_AUDITED; } else { $status = DiffusionCommitAuditStatus::AUDITED; } } else if ($any_need) { $status = DiffusionCommitAuditStatus::NEEDS_AUDIT; } else { $status = DiffusionCommitAuditStatus::NONE; } return $this->setAuditStatus($status); } public function getMonogram() { $repository = $this->getRepository(); $callsign = $repository->getCallsign(); $identifier = $this->getCommitIdentifier(); if ($callsign !== null) { return "r{$callsign}{$identifier}"; } else { $id = $repository->getID(); return "R{$id}:{$identifier}"; } } public function getDisplayName() { $repository = $this->getRepository(); $identifier = $this->getCommitIdentifier(); return $repository->formatCommitName($identifier); } /** * Return a local display name for use in the context of the containing * repository. * * In Git and Mercurial, this returns only a short hash, like "abcdef012345". * See @{method:getDisplayName} for a short name that always includes * repository context. * * @return string Short human-readable name for use inside a repository. */ public function getLocalName() { $repository = $this->getRepository(); $identifier = $this->getCommitIdentifier(); return $repository->formatCommitName($identifier, $local = true); } public function loadIdentities(PhabricatorUser $viewer) { if ($this->authorIdentity !== self::ATTACHABLE) { return $this; } $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withIDs(array($this->getID())) ->needIdentities(true) ->executeOne(); $author_identity = $commit->getAuthorIdentity(); $committer_identity = $commit->getCommitterIdentity(); return $this->attachIdentities($author_identity, $committer_identity); } public function hasCommitterIdentity() { return ($this->getCommitterIdentity() !== null); } public function hasAuthorIdentity() { return ($this->getAuthorIdentity() !== null); } public function getCommitterDisplayPHID() { if ($this->hasCommitterIdentity()) { return $this->getCommitterIdentity()->getIdentityDisplayPHID(); } $data = $this->getCommitData(); return $data->getCommitDetail('committerPHID'); } public function getAuthorDisplayPHID() { if ($this->hasAuthorIdentity()) { return $this->getAuthorIdentity()->getIdentityDisplayPHID(); } $data = $this->getCommitData(); return $data->getCommitDetail('authorPHID'); } public function getEffectiveAuthorPHID() { if ($this->hasAuthorIdentity()) { $identity = $this->getAuthorIdentity(); if ($identity->hasEffectiveUser()) { return $identity->getCurrentEffectiveUserPHID(); } } $data = $this->getCommitData(); return $data->getCommitDetail('authorPHID'); } public function getAuditStatusObject() { $status = $this->getAuditStatus(); return DiffusionCommitAuditStatus::newForStatus($status); } public function isAuditStatusNoAudit() { return $this->getAuditStatusObject()->isNoAudit(); } public function isAuditStatusNeedsAudit() { return $this->getAuditStatusObject()->isNeedsAudit(); } public function isAuditStatusConcernRaised() { return $this->getAuditStatusObject()->isConcernRaised(); } public function isAuditStatusNeedsVerification() { return $this->getAuditStatusObject()->isNeedsVerification(); } public function isAuditStatusPartiallyAudited() { return $this->getAuditStatusObject()->isPartiallyAudited(); } public function isAuditStatusAudited() { return $this->getAuditStatusObject()->isAudited(); } public function isPermanentCommit() { return (bool)$this->isPartiallyImported(self::IMPORTED_PERMANENT); } public function newCommitAuthorView(PhabricatorUser $viewer) { $author_phid = $this->getAuthorDisplayPHID(); if ($author_phid) { $handles = $viewer->loadHandles(array($author_phid)); return $handles[$author_phid]->renderLink(); } $author = $this->getRawAuthorStringForDisplay(); if ($author !== null && strlen($author)) { return DiffusionView::renderName($author); } return null; } public function newCommitCommitterView(PhabricatorUser $viewer) { $committer_phid = $this->getCommitterDisplayPHID(); if ($committer_phid) { $handles = $viewer->loadHandles(array($committer_phid)); return $handles[$committer_phid]->renderLink(); } $committer = $this->getRawCommitterStringForDisplay(); if ($committer !== null && strlen($committer)) { return DiffusionView::renderName($committer); } return null; } public function isAuthorSameAsCommitter() { $author_phid = $this->getAuthorDisplayPHID(); $committer_phid = $this->getCommitterDisplayPHID(); if ($author_phid && $committer_phid) { return ($author_phid === $committer_phid); } if ($author_phid || $committer_phid) { return false; } $author = $this->getRawAuthorStringForDisplay(); $committer = $this->getRawCommitterStringForDisplay(); return ($author === $committer); } private function getRawAuthorStringForDisplay() { $data = $this->getCommitData(); return $data->getAuthorString(); } private function getRawCommitterStringForDisplay() { $data = $this->getCommitData(); return $data->getCommitterString(); } public function getCommitMessageForDisplay() { $data = $this->getCommitData(); $message = $data->getCommitMessage(); return $message; } public function newCommitRef(PhabricatorUser $viewer) { $repository = $this->getRepository(); $future = $repository->newConduitFuture( $viewer, 'internal.commit.search', array( 'constraints' => array( 'repositoryPHIDs' => array($repository->getPHID()), 'phids' => array($this->getPHID()), ), )); $result = $future->resolve(); $commit_display = $this->getMonogram(); if (empty($result['data'])) { throw new Exception( pht( 'Unable to retrieve details for commit "%s"!', $commit_display)); } if (count($result['data']) !== 1) { throw new Exception( pht( 'Got too many results (%s) for commit "%s", expected %s.', phutil_count($result['data']), $commit_display, 1)); } $record = head($result['data']); $ref_record = idxv($record, array('fields', 'ref')); if (!$ref_record) { throw new Exception( pht( 'Unable to retrieve CommitRef record for commit "%s".', $commit_display)); } return DiffusionCommitRef::newFromDictionary($ref_record); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->getRepository()->getPolicy($capability); case PhabricatorPolicyCapability::CAN_EDIT: return PhabricatorPolicies::POLICY_USER; } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return $this->getRepository()->hasAutomaticCapability($capability, $viewer); } public function describeAutomaticCapability($capability) { return pht( 'Commits inherit the policies of the repository they belong to.'); } /* -( PhabricatorTokenReceiverInterface )---------------------------------- */ public function getUsersToNotifyOfTokenGiven() { return array( $this->getAuthorPHID(), ); } /* -( Stuff for serialization )---------------------------------------------- */ /** * NOTE: this is not a complete serialization; only the 'protected' fields are * involved. This is due to ease of (ab)using the Lisk abstraction to get this * done, as well as complexity of the other fields. */ public function toDictionary() { return array( 'repositoryID' => $this->getRepositoryID(), 'phid' => $this->getPHID(), 'commitIdentifier' => $this->getCommitIdentifier(), 'epoch' => $this->getEpoch(), 'authorPHID' => $this->getAuthorPHID(), 'auditStatus' => $this->getAuditStatus(), 'summary' => $this->getSummary(), 'importStatus' => $this->getImportStatus(), ); } public static function newFromDictionary(array $dict) { return id(new PhabricatorRepositoryCommit()) ->loadFromArray($dict); } /* -( HarbormasterBuildableInterface )------------------------------------- */ public function getHarbormasterBuildableDisplayPHID() { return $this->getHarbormasterBuildablePHID(); } public function getHarbormasterBuildablePHID() { return $this->getPHID(); } public function getHarbormasterContainerPHID() { return $this->getRepository()->getPHID(); } public function getBuildVariables() { $results = array(); $results['buildable.commit'] = $this->getCommitIdentifier(); $repo = $this->getRepository(); $results['repository.callsign'] = $repo->getCallsign(); $results['repository.phid'] = $repo->getPHID(); $results['repository.vcs'] = $repo->getVersionControlSystem(); $results['repository.uri'] = $repo->getPublicCloneURI(); return $results; } public function getAvailableBuildVariables() { return array( 'buildable.commit' => pht('The commit identifier, if applicable.'), 'repository.callsign' => pht('The callsign of the repository.'), 'repository.phid' => pht('The PHID of the repository.'), 'repository.vcs' => pht('The version control system, either "svn", "hg" or "git".'), 'repository.uri' => pht('The URI to clone or checkout the repository from.'), ); } public function newBuildableEngine() { return new DiffusionBuildableEngine(); } /* -( HarbormasterCircleCIBuildableInterface )----------------------------- */ public function getCircleCIGitHubRepositoryURI() { $repository = $this->getRepository(); $commit_phid = $this->getPHID(); $repository_phid = $repository->getPHID(); if ($repository->isHosted()) { throw new Exception( pht( 'This commit ("%s") is associated with a hosted repository '. '("%s"). Repositories must be imported from GitHub to be built '. 'with CircleCI.', $commit_phid, $repository_phid)); } $remote_uri = $repository->getRemoteURI(); $path = HarbormasterCircleCIBuildStepImplementation::getGitHubPath( $remote_uri); if (!$path) { throw new Exception( pht( 'This commit ("%s") is associated with a repository ("%s") which '. 'has a remote URI ("%s") that does not appear to be hosted on '. 'GitHub. Repositories must be hosted on GitHub to be built with '. 'CircleCI.', $commit_phid, $repository_phid, $remote_uri)); } return $remote_uri; } public function getCircleCIBuildIdentifierType() { return 'revision'; } public function getCircleCIBuildIdentifier() { return $this->getCommitIdentifier(); } /* -( HarbormasterBuildkiteBuildableInterface )---------------------------- */ public function getBuildkiteBranch() { $viewer = PhabricatorUser::getOmnipotentUser(); $repository = $this->getRepository(); $branches = DiffusionQuery::callConduitWithDiffusionRequest( $viewer, DiffusionRequest::newFromDictionary( array( 'repository' => $repository, 'user' => $viewer, )), 'diffusion.branchquery', array( 'contains' => $this->getCommitIdentifier(), 'repository' => $repository->getPHID(), )); if (!$branches) { throw new Exception( pht( 'Commit "%s" is not an ancestor of any branch head, so it can not '. 'be built with Buildkite.', $this->getCommitIdentifier())); } $branch = head($branches); return 'refs/heads/'.$branch['shortName']; } public function getBuildkiteCommit() { return $this->getCommitIdentifier(); } /* -( PhabricatorCustomFieldInterface )------------------------------------ */ public function getCustomFieldSpecificationForRole($role) { return PhabricatorEnv::getEnvConfig('diffusion.fields'); } public function getCustomFieldBaseClass() { return 'PhabricatorCommitCustomField'; } public function getCustomFields() { return $this->assertAttached($this->customFields); } public function attachCustomFields(PhabricatorCustomFieldAttachment $fields) { $this->customFields = $fields; return $this; } /* -( PhabricatorSubscribableInterface )----------------------------------- */ public function isAutomaticallySubscribed($phid) { // TODO: This should also list auditors, but handling that is a bit messy // right now because we are not guaranteed to have the data. (It should not // include resigned auditors.) return ($phid == $this->getAuthorPHID()); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhabricatorAuditEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorAuditTransaction(); } /* -( PhabricatorFulltextInterface )--------------------------------------- */ public function newFulltextEngine() { return new DiffusionCommitFulltextEngine(); } /* -( PhabricatorFerretInterface )----------------------------------------- */ public function newFerretEngine() { return new DiffusionCommitFerretEngine(); } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('identifier') ->setType('string') ->setDescription(pht('The commit identifier.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('repositoryPHID') ->setType('phid') ->setDescription(pht('The repository this commit belongs to.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('author') ->setType('map<string, wild>') ->setDescription(pht('Information about the commit author.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('committer') ->setType('map<string, wild>') ->setDescription(pht('Information about the committer.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('isImported') ->setType('bool') ->setDescription(pht('True if the commit is fully imported.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('isUnreachable') ->setType('bool') ->setDescription( pht( 'True if the commit is not the ancestor of any tag, branch, or '. 'ref.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('auditStatus') ->setType('map<string, wild>') ->setDescription(pht('Information about the current audit status.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('message') ->setType('string') ->setDescription(pht('The commit message.')), ); } public function getFieldValuesForConduit() { $data = $this->getCommitData(); $author_identity = $this->getAuthorIdentity(); if ($author_identity) { $author_name = $author_identity->getIdentityDisplayName(); $author_email = $author_identity->getIdentityEmailAddress(); $author_raw = $author_identity->getIdentityName(); $author_identity_phid = $author_identity->getPHID(); $author_user_phid = $author_identity->getCurrentEffectiveUserPHID(); } else { $author_name = null; $author_email = null; $author_raw = null; $author_identity_phid = null; $author_user_phid = null; } $committer_identity = $this->getCommitterIdentity(); if ($committer_identity) { $committer_name = $committer_identity->getIdentityDisplayName(); $committer_email = $committer_identity->getIdentityEmailAddress(); $committer_raw = $committer_identity->getIdentityName(); $committer_identity_phid = $committer_identity->getPHID(); $committer_user_phid = $committer_identity->getCurrentEffectiveUserPHID(); } else { $committer_name = null; $committer_email = null; $committer_raw = null; $committer_identity_phid = null; $committer_user_phid = null; } $author_epoch = $data->getAuthorEpoch(); $audit_status = $this->getAuditStatusObject(); return array( 'identifier' => $this->getCommitIdentifier(), 'repositoryPHID' => $this->getRepository()->getPHID(), 'author' => array( 'name' => $author_name, 'email' => $author_email, 'raw' => $author_raw, 'epoch' => $author_epoch, 'identityPHID' => $author_identity_phid, 'userPHID' => $author_user_phid, ), 'committer' => array( 'name' => $committer_name, 'email' => $committer_email, 'raw' => $committer_raw, 'epoch' => (int)$this->getEpoch(), 'identityPHID' => $committer_identity_phid, 'userPHID' => $committer_user_phid, ), 'isUnreachable' => (bool)$this->isUnreachable(), 'isImported' => (bool)$this->isImported(), 'auditStatus' => array( 'value' => $audit_status->getKey(), 'name' => $audit_status->getName(), 'closed' => (bool)$audit_status->getIsClosed(), 'color.ansi' => $audit_status->getAnsiColor(), ), 'message' => $data->getCommitMessage(), ); } public function getConduitSearchAttachments() { return array( id(new DiffusionAuditorsSearchEngineAttachment()) ->setAttachmentKey('auditors'), ); } /* -( PhabricatorDraftInterface )------------------------------------------ */ public function newDraftEngine() { return new DiffusionCommitDraftEngine(); } public function getHasDraft(PhabricatorUser $viewer) { return $this->assertAttachedKey($this->drafts, $viewer->getCacheFragment()); } public function attachHasDraft(PhabricatorUser $viewer, $has_draft) { $this->drafts[$viewer->getCacheFragment()] = $has_draft; return $this; } /* -( PhabricatorTimelineInterface )--------------------------------------- */ public function newTimelineEngine() { return new DiffusionCommitTimelineEngine(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryPullEvent.php
src/applications/repository/storage/PhabricatorRepositoryPullEvent.php
<?php final class PhabricatorRepositoryPullEvent extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface { protected $repositoryPHID; protected $epoch; protected $pullerPHID; protected $remoteAddress; protected $remoteProtocol; protected $resultType; protected $resultCode; protected $properties; private $repository = self::ATTACHABLE; const RESULT_PULL = 'pull'; const RESULT_ERROR = 'error'; const RESULT_EXCEPTION = 'exception'; const PROTOCOL_HTTP = 'http'; const PROTOCOL_HTTPS = 'https'; const PROTOCOL_SSH = 'ssh'; public static function initializeNewEvent(PhabricatorUser $viewer) { return id(new PhabricatorRepositoryPushEvent()) ->setPusherPHID($viewer->getPHID()); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_TIMESTAMPS => false, self::CONFIG_SERIALIZATION => array( 'properties' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'repositoryPHID' => 'phid?', 'pullerPHID' => 'phid?', 'remoteAddress' => 'ipaddress?', 'remoteProtocol' => 'text32?', 'resultType' => 'text32', 'resultCode' => 'uint32', ), self::CONFIG_KEY_SCHEMA => array( 'key_repository' => array( 'columns' => array('repositoryPHID'), ), 'key_epoch' => array( 'columns' => array('epoch'), ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorRepositoryPullEventPHIDType::TYPECONST); } public function attachRepository(PhabricatorRepository $repository = null) { $this->repository = $repository; return $this; } public function getRepository() { return $this->assertAttached($this->repository); } public function getRemoteProtocolDisplayName() { $map = array( self::PROTOCOL_SSH => pht('SSH'), self::PROTOCOL_HTTP => pht('HTTP'), self::PROTOCOL_HTTPS => pht('HTTPS'), ); $protocol = $this->getRemoteProtocol(); return idx($map, $protocol, $protocol); } public function newResultIcon() { $icon = new PHUIIconView(); $type = $this->getResultType(); $code = $this->getResultCode(); $protocol = $this->getRemoteProtocol(); $is_any_http = ($protocol === self::PROTOCOL_HTTP) || ($protocol === self::PROTOCOL_HTTPS); // If this was an HTTP request and we responded with a 401, that means // the user didn't provide credentials. This is technically an error, but // it's routine and just causes the client to prompt them. Show a more // comforting icon and description in the UI. if ($is_any_http) { if ($code == 401) { return $icon ->setIcon('fa-key blue') ->setTooltip(pht('Authentication Required')); } } switch ($type) { case self::RESULT_ERROR: $icon ->setIcon('fa-times red') ->setTooltip(pht('Error')); break; case self::RESULT_EXCEPTION: $icon ->setIcon('fa-exclamation-triangle red') ->setTooltip(pht('Exception')); break; case self::RESULT_PULL: $icon ->setIcon('fa-download green') ->setTooltip(pht('Pull')); break; default: $icon ->setIcon('fa-question indigo') ->setTooltip(pht('Unknown ("%s")', $type)); break; } return $icon; } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { if ($this->getRepository()) { return $this->getRepository()->getPolicy($capability); } return PhabricatorPolicies::POLICY_ADMIN; } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { if (!$this->getRepository()) { return false; } return $this->getRepository()->hasAutomaticCapability($capability, $viewer); } public function describeAutomaticCapability($capability) { return pht( "A repository's pull events are visible to users who can see the ". "repository."); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryOldRef.php
src/applications/repository/storage/PhabricatorRepositoryOldRef.php
<?php /** * Stores outdated refs which need to be checked for reachability. * * When a branch is deleted, the old HEAD ends up here and the discovery * engine marks all the commits that previously appeared on it as unreachable. */ final class PhabricatorRepositoryOldRef extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface { protected $repositoryPHID; protected $commitIdentifier; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'commitIdentifier' => 'text40', ), self::CONFIG_KEY_SCHEMA => array( 'key_repository' => array( 'columns' => array('repositoryPHID'), ), ), ) + parent::getConfiguration(); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { 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/applications/repository/storage/PhabricatorRepositoryURIIndex.php
src/applications/repository/storage/PhabricatorRepositoryURIIndex.php
<?php final class PhabricatorRepositoryURIIndex extends PhabricatorRepositoryDAO { protected $repositoryPHID; protected $repositoryURI; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'repositoryURI' => 'text', ), self::CONFIG_KEY_SCHEMA => array( 'key_repository' => array( 'columns' => array('repositoryPHID'), ), 'key_uri' => array( 'columns' => array('repositoryURI(128)'), ), ), ) + parent::getConfiguration(); } public static function updateRepositoryURIs( $repository_phid, array $uris) { $table = new self(); $conn_w = $table->establishConnection('w'); $sql = array(); foreach ($uris as $key => $uri) { if (!strlen($uri)) { unset($uris[$key]); continue; } $sql[] = qsprintf( $conn_w, '(%s, %s)', $repository_phid, $uri); } $table->openTransaction(); queryfx( $conn_w, 'DELETE FROM %R WHERE repositoryPHID = %s', $table, $repository_phid); if ($sql) { queryfx( $conn_w, 'INSERT INTO %R (repositoryPHID, repositoryURI) VALUES %LQ', $table, $sql); } $table->saveTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryDAO.php
src/applications/repository/storage/PhabricatorRepositoryDAO.php
<?php abstract class PhabricatorRepositoryDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'repository'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryCommitHint.php
src/applications/repository/storage/PhabricatorRepositoryCommitHint.php
<?php final class PhabricatorRepositoryCommitHint extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface { protected $repositoryPHID; protected $oldCommitIdentifier; protected $newCommitIdentifier; protected $hintType; const HINT_NONE = 'none'; const HINT_REWRITTEN = 'rewritten'; const HINT_UNREADABLE = 'unreadable'; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'oldCommitIdentifier' => 'text40', 'newCommitIdentifier' => 'text40?', 'hintType' => 'text32', ), self::CONFIG_KEY_SCHEMA => array( 'key_old' => array( 'columns' => array('repositoryPHID', 'oldCommitIdentifier'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public static function getAllHintTypes() { return array( self::HINT_NONE, self::HINT_REWRITTEN, self::HINT_UNREADABLE, ); } public static function updateHint($repository_phid, $old, $new, $type) { switch ($type) { case self::HINT_NONE: break; case self::HINT_REWRITTEN: if (!$new) { throw new Exception( pht( 'When hinting a commit ("%s") as rewritten, you must provide '. 'the commit it was rewritten into.', $old)); } break; case self::HINT_UNREADABLE: if ($new) { throw new Exception( pht( 'When hinting a commit ("%s") as unreadable, you must not '. 'provide a new commit ("%s").', $old, $new)); } break; default: $all_types = self::getAllHintTypes(); throw new Exception( pht( 'Hint type ("%s") for commit ("%s") is not valid. Valid hints '. 'are: %s.', $type, $old, implode(', ', $all_types))); } $table = new self(); $table_name = $table->getTableName(); $conn = $table->establishConnection('w'); if ($type == self::HINT_NONE) { queryfx( $conn, 'DELETE FROM %T WHERE repositoryPHID = %s AND oldCommitIdentifier = %s', $table_name, $repository_phid, $old); } else { queryfx( $conn, 'INSERT INTO %T (repositoryPHID, oldCommitIdentifier, newCommitIdentifier, hintType) VALUES (%s, %s, %ns, %s) ON DUPLICATE KEY UPDATE newCommitIdentifier = VALUES(newCommitIdentifier), hintType = VALUES(hintType)', $table_name, $repository_phid, $old, $new, $type); } } public function isUnreadable() { return ($this->getHintType() == self::HINT_UNREADABLE); } public function isRewritten() { return ($this->getHintType() == self::HINT_REWRITTEN); } /* -( 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/applications/repository/storage/PhabricatorRepositoryPushLog.php
src/applications/repository/storage/PhabricatorRepositoryPushLog.php
<?php /** * Records a push to a hosted repository. This allows us to store metadata * about who pushed commits, when, and from where. We can also record the * history of branches and tags, which is not normally persisted outside of * the reflog. * * This log is written by commit hooks installed into hosted repositories. * See @{class:DiffusionCommitHookEngine}. */ final class PhabricatorRepositoryPushLog extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface { const REFTYPE_BRANCH = 'branch'; const REFTYPE_TAG = 'tag'; const REFTYPE_BOOKMARK = 'bookmark'; const REFTYPE_COMMIT = 'commit'; const REFTYPE_REF = 'ref'; const REFTYPE_MAINTENANCE = 'maintenance'; const CHANGEFLAG_ADD = 1; const CHANGEFLAG_DELETE = 2; const CHANGEFLAG_APPEND = 4; const CHANGEFLAG_REWRITE = 8; const CHANGEFLAG_DANGEROUS = 16; const CHANGEFLAG_ENORMOUS = 32; const CHANGEFLAG_OVERSIZED = 64; const CHANGEFLAG_TOUCHES = 128; const CHANGEFLAG_MAINTENANCE = 256; const REJECT_ACCEPT = 0; const REJECT_DANGEROUS = 1; const REJECT_HERALD = 2; const REJECT_EXTERNAL = 3; const REJECT_BROKEN = 4; const REJECT_ENORMOUS = 5; const REJECT_OVERSIZED = 6; const REJECT_TOUCHES = 7; protected $repositoryPHID; protected $epoch; protected $pusherPHID; protected $pushEventPHID; protected $devicePHID; protected $refType; protected $refNameHash; protected $refNameRaw; protected $refNameEncoding; protected $refOld; protected $refNew; protected $mergeBase; protected $changeFlags; private $dangerousChangeDescription = self::ATTACHABLE; private $pushEvent = self::ATTACHABLE; private $repository = self::ATTACHABLE; public static function initializeNewLog(PhabricatorUser $viewer) { return id(new PhabricatorRepositoryPushLog()) ->setPusherPHID($viewer->getPHID()); } public static function getFlagDisplayNames() { return array( self::CHANGEFLAG_ADD => pht('Create'), self::CHANGEFLAG_DELETE => pht('Delete'), self::CHANGEFLAG_APPEND => pht('Append'), self::CHANGEFLAG_REWRITE => pht('Rewrite'), self::CHANGEFLAG_DANGEROUS => pht('Dangerous'), self::CHANGEFLAG_ENORMOUS => pht('Enormous'), self::CHANGEFLAG_OVERSIZED => pht('Oversized'), self::CHANGEFLAG_TOUCHES => pht('Touches Too Many Paths'), self::CHANGEFLAG_MAINTENANCE => pht('Maintenance'), ); } public static function getRejectCodeDisplayNames() { return array( self::REJECT_ACCEPT => pht('Accepted'), self::REJECT_DANGEROUS => pht('Rejected: Dangerous'), self::REJECT_HERALD => pht('Rejected: Herald'), self::REJECT_EXTERNAL => pht('Rejected: External Hook'), self::REJECT_BROKEN => pht('Rejected: Broken'), self::REJECT_ENORMOUS => pht('Rejected: Enormous'), self::REJECT_OVERSIZED => pht('Rejected: Oversized File'), self::REJECT_TOUCHES => pht('Rejected: Touches Too Many Paths'), ); } public static function getHeraldChangeFlagConditionOptions() { return array( self::CHANGEFLAG_ADD => pht('change creates ref'), self::CHANGEFLAG_DELETE => pht('change deletes ref'), self::CHANGEFLAG_REWRITE => pht('change rewrites ref'), self::CHANGEFLAG_DANGEROUS => pht('dangerous change'), ); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_TIMESTAMPS => false, self::CONFIG_BINARY => array( 'refNameRaw' => true, ), self::CONFIG_COLUMN_SCHEMA => array( 'refType' => 'text12', 'refNameHash' => 'bytes12?', 'refNameRaw' => 'bytes?', 'refNameEncoding' => 'text16?', 'refOld' => 'text40?', 'refNew' => 'text40', 'mergeBase' => 'text40?', 'changeFlags' => 'uint32', 'devicePHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'key_repository' => array( 'columns' => array('repositoryPHID'), ), 'key_ref' => array( 'columns' => array('repositoryPHID', 'refNew'), ), 'key_name' => array( 'columns' => array('repositoryPHID', 'refNameHash'), ), 'key_event' => array( 'columns' => array('pushEventPHID'), ), 'key_pusher' => array( 'columns' => array('pusherPHID'), ), 'key_epoch' => array( 'columns' => array('epoch'), ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorRepositoryPushLogPHIDType::TYPECONST); } public function attachPushEvent(PhabricatorRepositoryPushEvent $push_event) { $this->pushEvent = $push_event; return $this; } public function getPushEvent() { return $this->assertAttached($this->pushEvent); } public function getRefName() { if ($this->getRefNameRaw() === null) { return null; } return $this->getUTF8StringFromStorage( $this->getRefNameRaw(), $this->getRefNameEncoding()); } public function setRefName($ref_raw) { $this->setRefNameRaw($ref_raw); $this->setRefNameHash(PhabricatorHash::digestForIndex($ref_raw)); $this->setRefNameEncoding($this->detectEncodingForStorage($ref_raw)); return $this; } public function getRefOldShort() { if ($this->getRepository()->isSVN()) { return $this->getRefOld(); } if ($this->getRefOld() === null) { return null; } return substr($this->getRefOld(), 0, 12); } public function getRefNewShort() { if ($this->getRepository()->isSVN()) { return $this->getRefNew(); } return substr($this->getRefNew(), 0, 12); } public function hasChangeFlags($mask) { return ($this->changeFlags & $mask); } public function attachDangerousChangeDescription($description) { $this->dangerousChangeDescription = $description; return $this; } public function getDangerousChangeDescription() { return $this->assertAttached($this->dangerousChangeDescription); } public function attachRepository(PhabricatorRepository $repository) { // NOTE: Some gymnastics around this because of object construction order // in the hook engine. Particularly, web build the logs before we build // their push event. $this->repository = $repository; return $this; } public function getRepository() { if ($this->repository == self::ATTACHABLE) { return $this->getPushEvent()->getRepository(); } return $this->assertAttached($this->repository); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { // NOTE: We're passing through the repository rather than the push event // mostly because we need to do policy checks in Herald before we create // the event. The two approaches are equivalent in practice. return $this->getRepository()->getPolicy($capability); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return $this->getRepository()->hasAutomaticCapability($capability, $viewer); } public function describeAutomaticCapability($capability) { return pht( "A repository's push logs are visible to users who can see the ". "repository."); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryIdentityTransaction.php
src/applications/repository/storage/PhabricatorRepositoryIdentityTransaction.php
<?php final class PhabricatorRepositoryIdentityTransaction extends PhabricatorModularTransaction { public function getApplicationTransactionType() { return PhabricatorRepositoryIdentityPHIDType::TYPECONST; } public function getBaseTransactionClass() { return 'PhabricatorRepositoryIdentityTransactionType'; } public function getApplicationName() { return 'repository'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryRefPosition.php
src/applications/repository/storage/PhabricatorRepositoryRefPosition.php
<?php final class PhabricatorRepositoryRefPosition extends PhabricatorRepositoryDAO { protected $cursorID; protected $commitIdentifier; protected $isClosed = 0; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'commitIdentifier' => 'text40', 'isClosed' => 'bool', ), self::CONFIG_KEY_SCHEMA => array( 'key_position' => array( 'columns' => array('cursorID', 'commitIdentifier'), 'unique' => true, ), ), ) + parent::getConfiguration(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryPushEvent.php
src/applications/repository/storage/PhabricatorRepositoryPushEvent.php
<?php /** * Groups a set of push logs corresponding to changes which were all pushed in * the same transaction. */ final class PhabricatorRepositoryPushEvent extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface { protected $repositoryPHID; protected $epoch; protected $pusherPHID; protected $requestIdentifier; protected $remoteAddress; protected $remoteProtocol; protected $rejectCode; protected $rejectDetails; protected $writeWait; protected $readWait; protected $hostWait; protected $hookWait; private $repository = self::ATTACHABLE; private $logs = self::ATTACHABLE; public static function initializeNewEvent(PhabricatorUser $viewer) { return id(new PhabricatorRepositoryPushEvent()) ->setPusherPHID($viewer->getPHID()); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'requestIdentifier' => 'bytes12?', 'remoteAddress' => 'ipaddress?', 'remoteProtocol' => 'text32?', 'rejectCode' => 'uint32', 'rejectDetails' => 'text64?', 'writeWait' => 'uint64?', 'readWait' => 'uint64?', 'hostWait' => 'uint64?', 'hookWait' => 'uint64?', ), self::CONFIG_KEY_SCHEMA => array( 'key_repository' => array( 'columns' => array('repositoryPHID'), ), 'key_identifier' => array( 'columns' => array('requestIdentifier'), ), 'key_reject' => array( 'columns' => array('rejectCode', 'rejectDetails'), ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorRepositoryPushEventPHIDType::TYPECONST); } public function attachRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getRepository() { return $this->assertAttached($this->repository); } public function attachLogs(array $logs) { $this->logs = $logs; return $this; } public function getLogs() { return $this->assertAttached($this->logs); } public function saveWithLogs(array $logs) { assert_instances_of($logs, 'PhabricatorRepositoryPushLog'); $this->openTransaction(); $this->save(); foreach ($logs as $log) { $log->setPushEventPHID($this->getPHID()); $log->save(); } $this->saveTransaction(); $this->attachLogs($logs); return $this; } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return $this->getRepository()->getPolicy($capability); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return $this->getRepository()->hasAutomaticCapability($capability, $viewer); } public function describeAutomaticCapability($capability) { return pht( "A repository's push events are visible to users who can see the ". "repository."); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryCommitData.php
src/applications/repository/storage/PhabricatorRepositoryCommitData.php
<?php final class PhabricatorRepositoryCommitData extends PhabricatorRepositoryDAO { protected $commitID; protected $authorName = ''; protected $commitMessage = ''; protected $commitDetails = array(); private $commitRef; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_SERIALIZATION => array( 'commitDetails' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'authorName' => 'text', 'commitMessage' => 'text', ), self::CONFIG_KEY_SCHEMA => array( 'commitID' => array( 'columns' => array('commitID'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function getSummary() { $message = $this->getCommitMessage(); return self::summarizeCommitMessage($message); } public static function summarizeCommitMessage($message) { $max_bytes = id(new PhabricatorRepositoryCommit()) ->getColumnMaximumByteLength('summary'); $summary = phutil_split_lines($message, $retain_endings = false); $summary = head($summary); $summary = id(new PhutilUTF8StringTruncator()) ->setMaximumBytes($max_bytes) ->setMaximumGlyphs(80) ->truncateString($summary); return $summary; } public function getCommitDetail($key, $default = null) { return idx($this->commitDetails, $key, $default); } public function setCommitDetail($key, $value) { $this->commitDetails[$key] = $value; return $this; } public function toDictionary() { return array( 'commitID' => $this->commitID, 'authorName' => $this->authorName, 'commitMessage' => $this->commitMessage, 'commitDetails' => json_encode($this->commitDetails), ); } public static function newFromDictionary(array $dict) { return id(new PhabricatorRepositoryCommitData()) ->loadFromArray($dict); } public function newPublisherHoldReasons() { $holds = $this->getCommitDetail('holdReasons'); // Look for the legacy "autocloseReason" if we don't have a modern list // of hold reasons. if (!$holds) { $old_hold = $this->getCommitDetail('autocloseReason'); if ($old_hold) { $holds = array($old_hold); } } if (!$holds) { $holds = array(); } foreach ($holds as $key => $reason) { $holds[$key] = PhabricatorRepositoryPublisherHoldReason::newForHoldKey( $reason); } return array_values($holds); } public function getAuthorString() { $ref = $this->getCommitRef(); $author = $ref->getAuthor(); if ($author !== null && strlen($author)) { return $author; } $author = phutil_string_cast($this->authorName); if (strlen($author)) { return $author; } return null; } public function getAuthorDisplayName() { return $this->getCommitRef()->getAuthorName(); } public function getAuthorEmail() { return $this->getCommitRef()->getAuthorEmail(); } public function getAuthorEpoch() { $epoch = $this->getCommitRef()->getAuthorEpoch(); if ($epoch) { return (int)$epoch; } return null; } public function getCommitterString() { $ref = $this->getCommitRef(); $committer = $ref->getCommitter(); if ($committer !== null && strlen($committer)) { return $committer; } return $this->getCommitDetailString('committer'); } public function getCommitterDisplayName() { return $this->getCommitRef()->getCommitterName(); } public function getCommitterEmail() { return $this->getCommitRef()->getCommitterEmail(); } private function getCommitDetailString($key) { $string = $this->getCommitDetail($key); $string = phutil_string_cast($string); if (strlen($string)) { return $string; } return null; } public function setCommitRef(DiffusionCommitRef $ref) { $this->setCommitDetail('ref', $ref->newDictionary()); $this->commitRef = null; return $this; } public function getCommitRef() { if ($this->commitRef === null) { $map = $this->getCommitDetail('ref', array()); if (!is_array($map)) { $map = array(); } $map = $map + array( 'authorName' => $this->getCommitDetailString('authorName'), 'authorEmail' => $this->getCommitDetailString('authorEmail'), 'authorEpoch' => $this->getCommitDetailString('authorEpoch'), 'committerName' => $this->getCommitDetailString('committerName'), 'committerEmail' => $this->getCommitDetailString('committerEmail'), 'message' => $this->getCommitMessage(), ); $ref = DiffusionCommitRef::newFromDictionary($map); $this->commitRef = $ref; } return $this->commitRef; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositorySyncEvent.php
src/applications/repository/storage/PhabricatorRepositorySyncEvent.php
<?php final class PhabricatorRepositorySyncEvent extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface { protected $repositoryPHID; protected $epoch; protected $devicePHID; protected $fromDevicePHID; protected $deviceVersion; protected $fromDeviceVersion; protected $resultType; protected $resultCode; protected $syncWait; protected $properties = array(); private $repository = self::ATTACHABLE; const RESULT_SYNC = 'sync'; const RESULT_ERROR = 'error'; const RESULT_TIMEOUT = 'timeout'; const RESULT_EXCEPTION = 'exception'; public static function initializeNewEvent() { return new self(); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_TIMESTAMPS => false, self::CONFIG_SERIALIZATION => array( 'properties' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'deviceVersion' => 'uint32?', 'fromDeviceVersion' => 'uint32?', 'resultType' => 'text32', 'resultCode' => 'uint32', 'syncWait' => 'uint64', ), self::CONFIG_KEY_SCHEMA => array( 'key_repository' => array( 'columns' => array('repositoryPHID'), ), 'key_epoch' => array( 'columns' => array('epoch'), ), ), ) + parent::getConfiguration(); } public function getPHIDType() { return PhabricatorRepositorySyncEventPHIDType::TYPECONST; } public function attachRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getRepository() { return $this->assertAttached($this->repository); } public function setProperty($key, $value) { $this->properties[$key] = $value; return $this; } public function getProperty($key, $default = null) { return idx($this->properties, $key, $default); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return $this->getRepository()->getPolicy($capability); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return $this->getRepository()->hasAutomaticCapability($capability, $viewer); } public function describeAutomaticCapability($capability) { return pht( "A repository's sync events are visible to users who can see the ". "repository."); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryTransaction.php
src/applications/repository/storage/PhabricatorRepositoryTransaction.php
<?php final class PhabricatorRepositoryTransaction extends PhabricatorModularTransaction { public function getApplicationName() { return 'repository'; } public function getApplicationTransactionType() { return PhabricatorRepositoryRepositoryPHIDType::TYPECONST; } public function getBaseTransactionClass() { return 'PhabricatorRepositoryTransactionType'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryRefCursor.php
src/applications/repository/storage/PhabricatorRepositoryRefCursor.php
<?php /** * Stores the previous value of a ref (like a branch or tag) so we can figure * out how a repository has changed when we discover new commits or branch * heads. */ final class PhabricatorRepositoryRefCursor extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface { const TYPE_BRANCH = 'branch'; const TYPE_TAG = 'tag'; const TYPE_BOOKMARK = 'bookmark'; const TYPE_REF = 'ref'; protected $repositoryPHID; protected $refType; protected $refNameHash; protected $refNameRaw; protected $refNameEncoding; protected $isPermanent; private $repository = self::ATTACHABLE; private $positions = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_AUX_PHID => true, self::CONFIG_BINARY => array( 'refNameRaw' => true, ), self::CONFIG_COLUMN_SCHEMA => array( 'refType' => 'text32', 'refNameHash' => 'bytes12', 'refNameEncoding' => 'text16?', 'isPermanent' => 'bool', ), self::CONFIG_KEY_SCHEMA => array( 'key_ref' => array( 'columns' => array('repositoryPHID', 'refType', 'refNameHash'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorRepositoryRefCursorPHIDType::TYPECONST); } public function getRefName() { return $this->getUTF8StringFromStorage( $this->getRefNameRaw(), $this->getRefNameEncoding()); } public function setRefName($ref_raw) { $this->setRefNameRaw($ref_raw); $this->setRefNameHash(PhabricatorHash::digestForIndex($ref_raw)); $this->setRefNameEncoding($this->detectEncodingForStorage($ref_raw)); return $this; } public function attachRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getRepository() { return $this->assertAttached($this->repository); } public function attachPositions(array $positions) { assert_instances_of($positions, 'PhabricatorRepositoryRefPosition'); $this->positions = $positions; return $this; } public function getPositions() { return $this->assertAttached($this->positions); } public function getPositionIdentifiers() { return mpull($this->getPositions(), 'getCommitIdentifier'); } public function newDiffusionRepositoryRef() { return id(new DiffusionRepositoryRef()) ->setRefType($this->getRefType()) ->setShortName($this->getRefName()); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return $this->getRepository()->getPolicy($capability); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return $this->getRepository()->hasAutomaticCapability($capability, $viewer); } public function describeAutomaticCapability($capability) { return pht('Repository refs have the same policies as their repository.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositorySymbol.php
src/applications/repository/storage/PhabricatorRepositorySymbol.php
<?php /** * Records information about symbol locations in a codebase, like where classes * and functions are defined. * * Query symbols with @{class:DiffusionSymbolQuery}. */ final class PhabricatorRepositorySymbol extends PhabricatorRepositoryDAO { protected $repositoryPHID; protected $symbolContext; protected $symbolName; protected $symbolType; protected $symbolLanguage; protected $pathID; protected $lineNumber; private $isExternal; private $source; private $location; private $externalURI; private $path = self::ATTACHABLE; private $repository = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'id' => null, 'symbolContext' => 'text128', 'symbolName' => 'text128', 'symbolType' => 'text12', 'symbolLanguage' => 'text32', 'lineNumber' => 'uint32', ), self::CONFIG_KEY_SCHEMA => array( 'PRIMARY' => null, 'symbolName' => array( 'columns' => array('symbolName'), ), ), ) + parent::getConfiguration(); } public function getURI() { if ($this->isExternal) { return $this->externalURI; } $request = DiffusionRequest::newFromDictionary( array( 'user' => PhabricatorUser::getOmnipotentUser(), 'repository' => $this->getRepository(), )); return $request->generateURI( array( 'action' => 'browse', 'path' => $this->getPath(), 'line' => $this->getLineNumber(), )); } public function getPath() { return $this->assertAttached($this->path); } public function attachPath($path) { $this->path = $path; return $this; } public function getRepository() { return $this->assertAttached($this->repository); } public function attachRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function isExternal() { return $this->isExternal; } public function setIsExternal($is_external) { $this->isExternal = $is_external; return $this; } public function getSource() { return $this->source; } public function setSource($source) { $this->source = $source; return $this; } public function getLocation() { return $this->location; } public function setLocation($location) { $this->location = $location; return $this; } public function setExternalURI($external_uri) { $this->externalURI = $external_uri; return $this; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepository.php
src/applications/repository/storage/PhabricatorRepository.php
<?php /** * @task uri Repository URI Management * @task publishing Publishing * @task sync Cluster Synchronization */ final class PhabricatorRepository extends PhabricatorRepositoryDAO implements PhabricatorApplicationTransactionInterface, PhabricatorPolicyInterface, PhabricatorFlaggableInterface, PhabricatorMarkupInterface, PhabricatorDestructibleInterface, PhabricatorDestructibleCodexInterface, PhabricatorProjectInterface, PhabricatorSpacesInterface, PhabricatorConduitResultInterface, PhabricatorFulltextInterface, PhabricatorFerretInterface { /** * Shortest hash we'll recognize in raw "a829f32" form. */ const MINIMUM_UNQUALIFIED_HASH = 7; /** * Shortest hash we'll recognize in qualified "rXab7ef2f8" form. */ const MINIMUM_QUALIFIED_HASH = 5; /** * Minimum number of commits to an empty repository to trigger "import" mode. */ const IMPORT_THRESHOLD = 7; const LOWPRI_THRESHOLD = 64; const TABLE_PATH = 'repository_path'; const TABLE_PATHCHANGE = 'repository_pathchange'; const TABLE_FILESYSTEM = 'repository_filesystem'; const TABLE_SUMMARY = 'repository_summary'; const TABLE_LINTMESSAGE = 'repository_lintmessage'; const TABLE_PARENTS = 'repository_parents'; const TABLE_COVERAGE = 'repository_coverage'; const STATUS_ACTIVE = 'active'; const STATUS_INACTIVE = 'inactive'; protected $name; protected $callsign; protected $repositorySlug; protected $uuid; protected $viewPolicy; protected $editPolicy; protected $pushPolicy; protected $profileImagePHID; protected $versionControlSystem; protected $details = array(); protected $credentialPHID; protected $almanacServicePHID; protected $spacePHID; protected $localPath; private $commitCount = self::ATTACHABLE; private $mostRecentCommit = self::ATTACHABLE; private $projectPHIDs = self::ATTACHABLE; private $uris = self::ATTACHABLE; private $profileImageFile = self::ATTACHABLE; public static function initializeNewRepository(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery()) ->setViewer($actor) ->withClasses(array('PhabricatorDiffusionApplication')) ->executeOne(); $view_policy = $app->getPolicy(DiffusionDefaultViewCapability::CAPABILITY); $edit_policy = $app->getPolicy(DiffusionDefaultEditCapability::CAPABILITY); $push_policy = $app->getPolicy(DiffusionDefaultPushCapability::CAPABILITY); $repository = id(new PhabricatorRepository()) ->setViewPolicy($view_policy) ->setEditPolicy($edit_policy) ->setPushPolicy($push_policy) ->setSpacePHID($actor->getDefaultSpacePHID()); // Put the repository in "Importing" mode until we finish // parsing it. $repository->setDetail('importing', true); return $repository; } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'details' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'name' => 'sort255', 'callsign' => 'sort32?', 'repositorySlug' => 'sort64?', 'versionControlSystem' => 'text32', 'uuid' => 'text64?', 'pushPolicy' => 'policy', 'credentialPHID' => 'phid?', 'almanacServicePHID' => 'phid?', 'localPath' => 'text128?', 'profileImagePHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'callsign' => array( 'columns' => array('callsign'), 'unique' => true, ), 'key_name' => array( 'columns' => array('name(128)'), ), 'key_vcs' => array( 'columns' => array('versionControlSystem'), ), 'key_slug' => array( 'columns' => array('repositorySlug'), 'unique' => true, ), 'key_local' => array( 'columns' => array('localPath'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorRepositoryRepositoryPHIDType::TYPECONST); } public static function getStatusMap() { return array( self::STATUS_ACTIVE => array( 'name' => pht('Active'), 'isTracked' => 1, ), self::STATUS_INACTIVE => array( 'name' => pht('Inactive'), 'isTracked' => 0, ), ); } public static function getStatusNameMap() { return ipull(self::getStatusMap(), 'name'); } public function getStatus() { if ($this->isTracked()) { return self::STATUS_ACTIVE; } else { return self::STATUS_INACTIVE; } } public function toDictionary() { return array( 'id' => $this->getID(), 'name' => $this->getName(), 'phid' => $this->getPHID(), 'callsign' => $this->getCallsign(), 'monogram' => $this->getMonogram(), 'vcs' => $this->getVersionControlSystem(), 'uri' => PhabricatorEnv::getProductionURI($this->getURI()), 'remoteURI' => (string)$this->getRemoteURI(), 'description' => $this->getDetail('description'), 'isActive' => $this->isTracked(), 'isHosted' => $this->isHosted(), 'isImporting' => $this->isImporting(), 'encoding' => $this->getDefaultTextEncoding(), 'staging' => array( 'supported' => $this->supportsStaging(), 'prefix' => 'phabricator', 'uri' => $this->getStagingURI(), ), ); } public function getDefaultTextEncoding() { return $this->getDetail('encoding', 'UTF-8'); } public function getMonogram() { $callsign = $this->getCallsign(); if (phutil_nonempty_string($callsign)) { return "r{$callsign}"; } $id = $this->getID(); return "R{$id}"; } public function getDisplayName() { $slug = $this->getRepositorySlug(); if (phutil_nonempty_string($slug)) { return $slug; } return $this->getMonogram(); } public function getAllMonograms() { $monograms = array(); $monograms[] = 'R'.$this->getID(); $callsign = $this->getCallsign(); if (strlen($callsign)) { $monograms[] = 'r'.$callsign; } return $monograms; } public function setLocalPath($path) { // Convert any extra slashes ("//") in the path to a single slash ("/"). $path = preg_replace('(//+)', '/', $path); return parent::setLocalPath($path); } public function getDetail($key, $default = null) { return idx($this->details, $key, $default); } public function setDetail($key, $value) { $this->details[$key] = $value; return $this; } public function attachCommitCount($count) { $this->commitCount = $count; return $this; } public function getCommitCount() { return $this->assertAttached($this->commitCount); } public function attachMostRecentCommit( PhabricatorRepositoryCommit $commit = null) { $this->mostRecentCommit = $commit; return $this; } public function getMostRecentCommit() { return $this->assertAttached($this->mostRecentCommit); } public function getDiffusionBrowseURIForPath( PhabricatorUser $user, $path, $line = null, $branch = null) { $drequest = DiffusionRequest::newFromDictionary( array( 'user' => $user, 'repository' => $this, 'path' => $path, 'branch' => $branch, )); return $drequest->generateURI( array( 'action' => 'browse', 'line' => $line, )); } public function getSubversionBaseURI($commit = null) { $subpath = $this->getDetail('svn-subpath'); if (!phutil_nonempty_string($subpath)) { $subpath = null; } return $this->getSubversionPathURI($subpath, $commit); } public function getSubversionPathURI($path = null, $commit = null) { $vcs = $this->getVersionControlSystem(); if ($vcs != PhabricatorRepositoryType::REPOSITORY_TYPE_SVN) { throw new Exception(pht('Not a subversion repository!')); } if ($this->isHosted()) { $uri = 'file://'.$this->getLocalPath(); } else { $uri = $this->getDetail('remote-uri'); } $uri = rtrim($uri, '/'); if (phutil_nonempty_string($path)) { $path = rawurlencode($path); $path = str_replace('%2F', '/', $path); $uri = $uri.'/'.ltrim($path, '/'); } if ($path !== null || $commit !== null) { $uri .= '@'; } if ($commit !== null) { $uri .= $commit; } return $uri; } public function attachProjectPHIDs(array $project_phids) { $this->projectPHIDs = $project_phids; return $this; } public function getProjectPHIDs() { return $this->assertAttached($this->projectPHIDs); } /** * Get the name of the directory this repository should clone or checkout * into. For example, if the repository name is "Example Repository", a * reasonable name might be "example-repository". This is used to help users * get reasonable results when cloning repositories, since they generally do * not want to clone into directories called "X/" or "Example Repository/". * * @return string */ public function getCloneName() { $name = $this->getRepositorySlug(); // Make some reasonable effort to produce reasonable default directory // names from repository names. if ($name === null || !strlen($name)) { $name = $this->getName(); $name = phutil_utf8_strtolower($name); $name = preg_replace('@[ -/:->]+@', '-', $name); $name = trim($name, '-'); if (!strlen($name)) { $name = $this->getCallsign(); } } return $name; } public static function isValidRepositorySlug($slug) { try { self::assertValidRepositorySlug($slug); return true; } catch (Exception $ex) { return false; } } public static function assertValidRepositorySlug($slug) { if (!strlen($slug)) { throw new Exception( pht( 'The empty string is not a valid repository short name. '. 'Repository short names must be at least one character long.')); } if (strlen($slug) > 64) { throw new Exception( pht( 'The name "%s" is not a valid repository short name. Repository '. 'short names must not be longer than 64 characters.', $slug)); } if (preg_match('/[^a-zA-Z0-9._-]/', $slug)) { throw new Exception( pht( 'The name "%s" is not a valid repository short name. Repository '. 'short names may only contain letters, numbers, periods, hyphens '. 'and underscores.', $slug)); } if (!preg_match('/^[a-zA-Z0-9]/', $slug)) { throw new Exception( pht( 'The name "%s" is not a valid repository short name. Repository '. 'short names must begin with a letter or number.', $slug)); } if (!preg_match('/[a-zA-Z0-9]\z/', $slug)) { throw new Exception( pht( 'The name "%s" is not a valid repository short name. Repository '. 'short names must end with a letter or number.', $slug)); } if (preg_match('/__|--|\\.\\./', $slug)) { throw new Exception( pht( 'The name "%s" is not a valid repository short name. Repository '. 'short names must not contain multiple consecutive underscores, '. 'hyphens, or periods.', $slug)); } if (preg_match('/^[A-Z]+\z/', $slug)) { throw new Exception( pht( 'The name "%s" is not a valid repository short name. Repository '. 'short names may not contain only uppercase letters.', $slug)); } if (preg_match('/^\d+\z/', $slug)) { throw new Exception( pht( 'The name "%s" is not a valid repository short name. Repository '. 'short names may not contain only numbers.', $slug)); } if (preg_match('/\\.git/', $slug)) { throw new Exception( pht( 'The name "%s" is not a valid repository short name. Repository '. 'short names must not end in ".git". This suffix will be added '. 'automatically in appropriate contexts.', $slug)); } } public static function assertValidCallsign($callsign) { if (!strlen($callsign)) { throw new Exception( pht( 'A repository callsign must be at least one character long.')); } if (strlen($callsign) > 32) { throw new Exception( pht( 'The callsign "%s" is not a valid repository callsign. Callsigns '. 'must be no more than 32 bytes long.', $callsign)); } if (!preg_match('/^[A-Z]+\z/', $callsign)) { throw new Exception( pht( 'The callsign "%s" is not a valid repository callsign. Callsigns '. 'may only contain UPPERCASE letters.', $callsign)); } } public function getProfileImageURI() { return $this->getProfileImageFile()->getBestURI(); } public function attachProfileImageFile(PhabricatorFile $file) { $this->profileImageFile = $file; return $this; } public function getProfileImageFile() { return $this->assertAttached($this->profileImageFile); } /* -( Remote Command Execution )------------------------------------------- */ public function execRemoteCommand($pattern /* , $arg, ... */) { $args = func_get_args(); return $this->newRemoteCommandFuture($args)->resolve(); } public function execxRemoteCommand($pattern /* , $arg, ... */) { $args = func_get_args(); return $this->newRemoteCommandFuture($args)->resolvex(); } public function getRemoteCommandFuture($pattern /* , $arg, ... */) { $args = func_get_args(); return $this->newRemoteCommandFuture($args); } public function passthruRemoteCommand($pattern /* , $arg, ... */) { $args = func_get_args(); return $this->newRemoteCommandPassthru($args)->resolve(); } private function newRemoteCommandFuture(array $argv) { return $this->newRemoteCommandEngine($argv) ->newFuture(); } private function newRemoteCommandPassthru(array $argv) { return $this->newRemoteCommandEngine($argv) ->setPassthru(true) ->newFuture(); } private function newRemoteCommandEngine(array $argv) { return DiffusionCommandEngine::newCommandEngine($this) ->setArgv($argv) ->setCredentialPHID($this->getCredentialPHID()) ->setURI($this->getRemoteURIObject()); } /* -( Local Command Execution )-------------------------------------------- */ public function execLocalCommand($pattern /* , $arg, ... */) { $args = func_get_args(); return $this->newLocalCommandFuture($args)->resolve(); } public function execxLocalCommand($pattern /* , $arg, ... */) { $args = func_get_args(); return $this->newLocalCommandFuture($args)->resolvex(); } public function getLocalCommandFuture($pattern /* , $arg, ... */) { $args = func_get_args(); return $this->newLocalCommandFuture($args); } public function passthruLocalCommand($pattern /* , $arg, ... */) { $args = func_get_args(); return $this->newLocalCommandPassthru($args)->resolve(); } private function newLocalCommandFuture(array $argv) { $this->assertLocalExists(); $future = DiffusionCommandEngine::newCommandEngine($this) ->setArgv($argv) ->newFuture(); if ($this->usesLocalWorkingCopy()) { $future->setCWD($this->getLocalPath()); } return $future; } private function newLocalCommandPassthru(array $argv) { $this->assertLocalExists(); $future = DiffusionCommandEngine::newCommandEngine($this) ->setArgv($argv) ->setPassthru(true) ->newFuture(); if ($this->usesLocalWorkingCopy()) { $future->setCWD($this->getLocalPath()); } return $future; } public function getURI() { $short_name = $this->getRepositorySlug(); if (phutil_nonempty_string($short_name)) { return "/source/{$short_name}/"; } $callsign = $this->getCallsign(); if (phutil_nonempty_string($callsign)) { return "/diffusion/{$callsign}/"; } $id = $this->getID(); return "/diffusion/{$id}/"; } public function getPathURI($path) { return $this->getURI().ltrim($path, '/'); } public function getCommitURI($identifier) { $callsign = $this->getCallsign(); if (phutil_nonempty_string($callsign)) { return "/r{$callsign}{$identifier}"; } $id = $this->getID(); return "/R{$id}:{$identifier}"; } public static function parseRepositoryServicePath($request_path, $vcs) { $is_git = ($vcs == PhabricatorRepositoryType::REPOSITORY_TYPE_GIT); $patterns = array( '(^'. '(?P<base>/?(?:diffusion|source)/(?P<identifier>[^/]+))'. '(?P<path>.*)'. '\z)', ); $identifier = null; foreach ($patterns as $pattern) { $matches = null; if (!preg_match($pattern, $request_path, $matches)) { continue; } $identifier = $matches['identifier']; if ($is_git) { $identifier = preg_replace('/\\.git\z/', '', $identifier); } $base = $matches['base']; $path = $matches['path']; break; } if ($identifier === null) { return null; } return array( 'identifier' => $identifier, 'base' => $base, 'path' => $path, ); } public function getCanonicalPath($request_path) { $standard_pattern = '(^'. '(?P<prefix>/(?:diffusion|source)/)'. '(?P<identifier>[^/]+)'. '(?P<suffix>(?:/.*)?)'. '\z)'; $matches = null; if (preg_match($standard_pattern, $request_path, $matches)) { $suffix = $matches['suffix']; return $this->getPathURI($suffix); } $commit_pattern = '(^'. '(?P<prefix>/)'. '(?P<monogram>'. '(?:'. 'r(?P<repositoryCallsign>[A-Z]+)'. '|'. 'R(?P<repositoryID>[1-9]\d*):'. ')'. '(?P<commit>[a-f0-9]+)'. ')'. '\z)'; $matches = null; if (preg_match($commit_pattern, $request_path, $matches)) { $commit = $matches['commit']; return $this->getCommitURI($commit); } return null; } public function generateURI(array $params) { $req_branch = false; $req_commit = false; $action = idx($params, 'action'); switch ($action) { case 'history': case 'clone': case 'blame': case 'browse': case 'document': case 'change': case 'lastmodified': case 'tags': case 'branches': case 'lint': case 'pathtree': case 'refs': case 'compare': break; case 'branch': // NOTE: This does not actually require a branch, and won't have one // in Subversion. Possibly this should be more clear. break; case 'commit': case 'rendering-ref': $req_commit = true; break; default: throw new Exception( pht( 'Action "%s" is not a valid repository URI action.', $action)); } $path = idx($params, 'path'); $branch = idx($params, 'branch'); $commit = idx($params, 'commit'); $line = idx($params, 'line'); $head = idx($params, 'head'); $against = idx($params, 'against'); if ($req_commit && ($commit === null || !strlen($commit))) { throw new Exception( pht( 'Diffusion URI action "%s" requires commit!', $action)); } if ($req_branch && ($branch === null || !strlen($branch))) { throw new Exception( pht( 'Diffusion URI action "%s" requires branch!', $action)); } if ($action === 'commit') { return $this->getCommitURI($commit); } if (phutil_nonempty_string($path)) { $path = ltrim($path, '/'); $path = str_replace(array(';', '$'), array(';;', '$$'), $path); $path = phutil_escape_uri($path); } $raw_branch = $branch; if (phutil_nonempty_string($branch)) { $branch = phutil_escape_uri_path_component($branch); $path = "{$branch}/{$path}"; } $raw_commit = $commit; if (phutil_nonempty_scalar($commit)) { $commit = str_replace('$', '$$', $commit); $commit = ';'.phutil_escape_uri($commit); } $line = phutil_string_cast($line); if (phutil_nonempty_string($line)) { $line = '$'.phutil_escape_uri($line); } $query = array(); switch ($action) { case 'change': case 'history': case 'blame': case 'browse': case 'document': case 'lastmodified': case 'tags': case 'branches': case 'lint': case 'pathtree': case 'refs': $uri = $this->getPathURI("/{$action}/{$path}{$commit}{$line}"); break; case 'compare': $uri = $this->getPathURI("/{$action}/"); if ($head !== null && strlen($head)) { $query['head'] = $head; } else if ($raw_commit !== null && strlen($raw_commit)) { $query['commit'] = $raw_commit; } else if ($raw_branch !== null && strlen($raw_branch)) { $query['head'] = $raw_branch; } if ($against !== null && strlen($against)) { $query['against'] = $against; } break; case 'branch': if ($path != null && strlen($path)) { $uri = $this->getPathURI("/repository/{$path}"); } else { $uri = $this->getPathURI('/'); } break; case 'external': $commit = ltrim($commit, ';'); $uri = "/diffusion/external/{$commit}/"; break; case 'rendering-ref': // This isn't a real URI per se, it's passed as a query parameter to // the ajax changeset stuff but then we parse it back out as though // it came from a URI. $uri = rawurldecode("{$path}{$commit}"); break; case 'clone': $uri = $this->getPathURI("/{$action}/"); break; } if ($action == 'rendering-ref') { return $uri; } if (isset($params['lint'])) { $params['params'] = idx($params, 'params', array()) + array( 'lint' => $params['lint'], ); } $query = idx($params, 'params', array()) + $query; return new PhutilURI($uri, $query); } public function updateURIIndex() { $indexes = array(); $uris = $this->getURIs(); foreach ($uris as $uri) { if ($uri->getIsDisabled()) { continue; } $indexes[] = $uri->getNormalizedURI(); } PhabricatorRepositoryURIIndex::updateRepositoryURIs( $this->getPHID(), $indexes); return $this; } public function isTracked() { $status = $this->getDetail('tracking-enabled'); $map = self::getStatusMap(); $spec = idx($map, $status); if (!$spec) { if ($status) { $status = self::STATUS_ACTIVE; } else { $status = self::STATUS_INACTIVE; } $spec = idx($map, $status); } return (bool)idx($spec, 'isTracked', false); } public function getDefaultBranch() { $default = $this->getDetail('default-branch'); if (phutil_nonempty_string($default)) { return $default; } $default_branches = array( PhabricatorRepositoryType::REPOSITORY_TYPE_GIT => 'master', PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL => 'default', ); return idx($default_branches, $this->getVersionControlSystem()); } public function getDefaultArcanistBranch() { return coalesce($this->getDefaultBranch(), 'svn'); } private function isBranchInFilter($branch, $filter_key) { $vcs = $this->getVersionControlSystem(); $is_git = ($vcs == PhabricatorRepositoryType::REPOSITORY_TYPE_GIT); $use_filter = ($is_git); if (!$use_filter) { // If this VCS doesn't use filters, pass everything through. return true; } $filter = $this->getDetail($filter_key, array()); // If there's no filter set, let everything through. if (!$filter) { return true; } // If this branch isn't literally named `regexp(...)`, and it's in the // filter list, let it through. if (isset($filter[$branch])) { if (self::extractBranchRegexp($branch) === null) { return true; } } // If the branch matches a regexp, let it through. foreach ($filter as $pattern => $ignored) { $regexp = self::extractBranchRegexp($pattern); if ($regexp !== null) { if (preg_match($regexp, $branch)) { return true; } } } // Nothing matched, so filter this branch out. return false; } public static function extractBranchRegexp($pattern) { $matches = null; if (preg_match('/^regexp\\((.*)\\)\z/', $pattern, $matches)) { return $matches[1]; } return null; } public function shouldTrackRef(DiffusionRepositoryRef $ref) { // At least for now, don't track the staging area tags. if ($ref->isTag()) { if (preg_match('(^phabricator/)', $ref->getShortName())) { return false; } } if (!$ref->isBranch()) { return true; } return $this->shouldTrackBranch($ref->getShortName()); } public function shouldTrackBranch($branch) { return $this->isBranchInFilter($branch, 'branch-filter'); } public function isBranchPermanentRef($branch) { return $this->isBranchInFilter($branch, 'close-commits-filter'); } public function formatCommitName($commit_identifier, $local = false) { $vcs = $this->getVersionControlSystem(); $type_git = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; $type_hg = PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL; $is_git = ($vcs == $type_git); $is_hg = ($vcs == $type_hg); if ($is_git || $is_hg) { $name = substr($commit_identifier, 0, 12); $need_scope = false; } else { $name = $commit_identifier; $need_scope = true; } if (!$local) { $need_scope = true; } if ($need_scope) { $callsign = $this->getCallsign(); if ($callsign) { $scope = "r{$callsign}"; } else { $id = $this->getID(); $scope = "R{$id}:"; } $name = $scope.$name; } return $name; } public function isImporting() { return (bool)$this->getDetail('importing', false); } public function isNewlyInitialized() { return (bool)$this->getDetail('newly-initialized', false); } public function loadImportProgress() { $progress = queryfx_all( $this->establishConnection('r'), 'SELECT importStatus, count(*) N FROM %T WHERE repositoryID = %d GROUP BY importStatus', id(new PhabricatorRepositoryCommit())->getTableName(), $this->getID()); $done = 0; $total = 0; foreach ($progress as $row) { $total += $row['N'] * 3; $status = $row['importStatus']; if ($status & PhabricatorRepositoryCommit::IMPORTED_MESSAGE) { $done += $row['N']; } if ($status & PhabricatorRepositoryCommit::IMPORTED_CHANGE) { $done += $row['N']; } if ($status & PhabricatorRepositoryCommit::IMPORTED_PUBLISH) { $done += $row['N']; } } if ($total) { $ratio = ($done / $total); } else { $ratio = 0; } // Cap this at "99.99%", because it's confusing to users when the actual // fraction is "99.996%" and it rounds up to "100.00%". if ($ratio > 0.9999) { $ratio = 0.9999; } return $ratio; } /* -( Publishing )--------------------------------------------------------- */ public function newPublisher() { return id(new PhabricatorRepositoryPublisher()) ->setRepository($this); } public function isPublishingDisabled() { return $this->getDetail('herald-disabled'); } public function getPermanentRefRules() { return array_keys($this->getDetail('close-commits-filter', array())); } public function setPermanentRefRules(array $rules) { $rules = array_fill_keys($rules, true); $this->setDetail('close-commits-filter', $rules); return $this; } public function getTrackOnlyRules() { return array_keys($this->getDetail('branch-filter', array())); } public function setTrackOnlyRules(array $rules) { $rules = array_fill_keys($rules, true); $this->setDetail('branch-filter', $rules); return $this; } public function supportsFetchRules() { if ($this->isGit()) { return true; } return false; } public function getFetchRules() { return $this->getDetail('fetch-rules', array()); } public function setFetchRules(array $rules) { return $this->setDetail('fetch-rules', $rules); } /* -( Repository URI Management )------------------------------------------ */ /** * Get the remote URI for this repository. * * @return string * @task uri */ public function getRemoteURI() { return (string)$this->getRemoteURIObject(); } /** * Get the remote URI for this repository, including credentials if they're * used by this repository. * * @return PhutilOpaqueEnvelope URI, possibly including credentials. * @task uri */ public function getRemoteURIEnvelope() { $uri = $this->getRemoteURIObject(); $remote_protocol = $this->getRemoteProtocol(); if ($remote_protocol == 'http' || $remote_protocol == 'https') { // For SVN, we use `--username` and `--password` flags separately, so // don't add any credentials here. if (!$this->isSVN()) { $credential_phid = $this->getCredentialPHID(); if ($credential_phid) { $key = PassphrasePasswordKey::loadFromPHID( $credential_phid, PhabricatorUser::getOmnipotentUser()); $uri->setUser($key->getUsernameEnvelope()->openEnvelope()); $uri->setPass($key->getPasswordEnvelope()->openEnvelope()); } } } return new PhutilOpaqueEnvelope((string)$uri); } /** * Get the clone (or checkout) URI for this repository, without authentication * information. * * @return string Repository URI. * @task uri */ public function getPublicCloneURI() { return (string)$this->getCloneURIObject(); } /** * Get the protocol for the repository's remote. * * @return string Protocol, like "ssh" or "git". * @task uri */ public function getRemoteProtocol() { $uri = $this->getRemoteURIObject(); return $uri->getProtocol(); } /** * Get a parsed object representation of the repository's remote URI.. * * @return wild A @{class@arcanist:PhutilURI}. * @task uri */ public function getRemoteURIObject() { $raw_uri = $this->getDetail('remote-uri'); if ($raw_uri === null || !strlen($raw_uri)) { return new PhutilURI(''); } if (!strncmp($raw_uri, '/', 1)) { return new PhutilURI('file://'.$raw_uri); } return new PhutilURI($raw_uri); } /** * Get the "best" clone/checkout URI for this repository, on any protocol. */ public function getCloneURIObject() { if (!$this->isHosted()) { if ($this->isSVN()) { // Make sure we pick up the "Import Only" path for Subversion, so // the user clones the repository starting at the correct path, not // from the root. $base_uri = $this->getSubversionBaseURI(); $base_uri = new PhutilURI($base_uri); $path = $base_uri->getPath(); if (!$path) { $path = '/'; } // If the trailing "@" is not required to escape the URI, strip it for // readability. if (!preg_match('/@.*@/', $path)) { $path = rtrim($path, '@'); } $base_uri->setPath($path); return $base_uri; } else { return $this->getRemoteURIObject(); } } // TODO: This should be cleaned up to deal with all the new URI handling. $another_copy = id(new PhabricatorRepositoryQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($this->getPHID())) ->needURIs(true) ->executeOne(); $clone_uris = $another_copy->getCloneURIs(); if (!$clone_uris) { return null; } return head($clone_uris)->getEffectiveURI(); } private function getRawHTTPCloneURIObject() { $uri = PhabricatorEnv::getProductionURI($this->getURI()); $uri = new PhutilURI($uri); if ($this->isGit()) {
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
true
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryGitLFSRef.php
src/applications/repository/storage/PhabricatorRepositoryGitLFSRef.php
<?php final class PhabricatorRepositoryGitLFSRef extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface, PhabricatorDestructibleInterface { protected $repositoryPHID; protected $objectHash; protected $byteSize; protected $authorPHID; protected $filePHID; protected function getConfiguration() { return array( self::CONFIG_COLUMN_SCHEMA => array( 'objectHash' => 'bytes64', 'byteSize' => 'uint64', ), self::CONFIG_KEY_SCHEMA => array( 'key_hash' => array( 'columns' => array('repositoryPHID', 'objectHash'), 'unique' => true, ), ), ) + parent::getConfiguration(); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return PhabricatorPolicies::getMostOpenPolicy(); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return false; } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $file_phid = $this->getFilePHID(); $file = id(new PhabricatorFileQuery()) ->setViewer($engine->getViewer()) ->withPHIDs(array($file_phid)) ->executeOne(); if ($file) { $engine->destroyObject($file); } $this->delete(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryStatusMessage.php
src/applications/repository/storage/PhabricatorRepositoryStatusMessage.php
<?php final class PhabricatorRepositoryStatusMessage extends PhabricatorRepositoryDAO { const TYPE_INIT = 'init'; const TYPE_FETCH = 'fetch'; const TYPE_NEEDS_UPDATE = 'needs-update'; const CODE_ERROR = 'error'; const CODE_OKAY = 'okay'; protected $repositoryID; protected $statusType; protected $statusCode; protected $parameters = array(); protected $epoch; protected $messageCount; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_SERIALIZATION => array( 'parameters' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'statusType' => 'text32', 'statusCode' => 'text32', 'messageCount' => 'uint32', ), self::CONFIG_KEY_SCHEMA => array( 'repositoryID' => array( 'columns' => array('repositoryID', 'statusType'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function getParameter($key, $default = null) { return idx($this->parameters, $key, $default); } public function getStatusTypeName() { $names = array( self::TYPE_INIT => pht('Error While Initializing Repository'), self::TYPE_FETCH => pht('Error While Fetching Changes'), self::TYPE_NEEDS_UPDATE => pht('Repository Needs Update'), ); $type = $this->getStatusType(); return idx($names, $type, $type); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryIdentity.php
src/applications/repository/storage/PhabricatorRepositoryIdentity.php
<?php final class PhabricatorRepositoryIdentity extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface, PhabricatorApplicationTransactionInterface { protected $authorPHID; protected $identityNameHash; protected $identityNameRaw; protected $identityNameEncoding; protected $automaticGuessedUserPHID; protected $manuallySetUserPHID; protected $currentEffectiveUserPHID; protected $emailAddress; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_BINARY => array( 'identityNameRaw' => true, ), self::CONFIG_COLUMN_SCHEMA => array( 'identityNameHash' => 'bytes12', 'identityNameEncoding' => 'text16?', 'automaticGuessedUserPHID' => 'phid?', 'manuallySetUserPHID' => 'phid?', 'currentEffectiveUserPHID' => 'phid?', 'emailAddress' => 'sort255?', ), self::CONFIG_KEY_SCHEMA => array( 'key_identity' => array( 'columns' => array('identityNameHash'), 'unique' => true, ), 'key_email' => array( 'columns' => array('emailAddress(64)'), ), ), ) + parent::getConfiguration(); } public function getPHIDType() { return PhabricatorRepositoryIdentityPHIDType::TYPECONST; } public function setIdentityName($name_raw) { $this->setIdentityNameRaw($name_raw); $this->setIdentityNameHash(PhabricatorHash::digestForIndex($name_raw)); $this->setIdentityNameEncoding($this->detectEncodingForStorage($name_raw)); return $this; } public function getIdentityName() { return $this->getUTF8StringFromStorage( $this->getIdentityNameRaw(), $this->getIdentityNameEncoding()); } public function getIdentityEmailAddress() { $address = new PhutilEmailAddress($this->getIdentityName()); return $address->getAddress(); } public function getIdentityDisplayName() { $address = new PhutilEmailAddress($this->getIdentityName()); return $address->getDisplayName(); } public function getIdentityShortName() { // TODO return $this->getIdentityName(); } public function getObjectName() { return pht('Identity %d', $this->getID()); } public function getURI() { return '/diffusion/identity/view/'.$this->getID().'/'; } public function hasEffectiveUser() { return ($this->currentEffectiveUserPHID != null); } public function getIdentityDisplayPHID() { if ($this->hasEffectiveUser()) { return $this->getCurrentEffectiveUserPHID(); } else { return $this->getPHID(); } } public function save() { if ($this->manuallySetUserPHID) { $unassigned = DiffusionIdentityUnassignedDatasource::FUNCTION_TOKEN; if ($this->manuallySetUserPHID === $unassigned) { $effective_phid = null; } else { $effective_phid = $this->manuallySetUserPHID; } } else { $effective_phid = $this->automaticGuessedUserPHID; } $this->setCurrentEffectiveUserPHID($effective_phid); $email_address = $this->getIdentityEmailAddress(); // Raw identities are unrestricted binary data, and may consequently // have arbitrarily long, binary email address information. We can't // store this kind of information in the "emailAddress" column, which // has column type "sort255". // This kind of address almost certainly not legitimate and users can // manually set the target of the identity, so just discard it rather // than trying especially hard to make it work. $byte_limit = $this->getColumnMaximumByteLength('emailAddress'); $email_address = phutil_utf8ize($email_address); if (strlen($email_address) > $byte_limit) { $email_address = null; } $this->setEmailAddress($email_address); return parent::save(); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { return PhabricatorPolicies::getMostOpenPolicy(); } public function hasAutomaticCapability( $capability, PhabricatorUser $viewer) { return false; } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new DiffusionRepositoryIdentityEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorRepositoryIdentityTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryAuditRequest.php
src/applications/repository/storage/PhabricatorRepositoryAuditRequest.php
<?php final class PhabricatorRepositoryAuditRequest extends PhabricatorRepositoryDAO implements PhabricatorPolicyInterface { protected $auditorPHID; protected $commitPHID; protected $auditReasons = array(); protected $auditStatus; private $commit = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_SERIALIZATION => array( 'auditReasons' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'auditStatus' => 'text64', ), self::CONFIG_KEY_SCHEMA => array( 'commitPHID' => array( 'columns' => array('commitPHID'), ), 'auditorPHID' => array( 'columns' => array('auditorPHID', 'auditStatus'), ), 'key_unique' => array( 'columns' => array('commitPHID', 'auditorPHID'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function isUser() { $user_type = PhabricatorPeopleUserPHIDType::TYPECONST; return (phid_get_type($this->getAuditorPHID()) == $user_type); } public function attachCommit(PhabricatorRepositoryCommit $commit) { $this->commit = $commit; return $this; } public function getCommit() { return $this->assertAttached($this->commit); } public function isResigned() { return $this->getAuditRequestStatusObject()->isResigned(); } public function getAuditRequestStatusObject() { $status = $this->getAuditStatus(); return PhabricatorAuditRequestStatus::newForStatus($status); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return $this->getCommit()->getPolicy($capability); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return $this->getCommit()->hasAutomaticCapability($capability, $viewer); } public function describeAutomaticCapability($capability) { return pht( 'This audit is attached to a commit, and inherits its policies.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryURI.php
src/applications/repository/storage/PhabricatorRepositoryURI.php
<?php final class PhabricatorRepositoryURI extends PhabricatorRepositoryDAO implements PhabricatorApplicationTransactionInterface, PhabricatorPolicyInterface, PhabricatorExtendedPolicyInterface, PhabricatorConduitResultInterface { protected $repositoryPHID; protected $uri; protected $builtinProtocol; protected $builtinIdentifier; protected $credentialPHID; protected $ioType; protected $displayType; protected $isDisabled; private $repository = self::ATTACHABLE; const BUILTIN_PROTOCOL_SSH = 'ssh'; const BUILTIN_PROTOCOL_HTTP = 'http'; const BUILTIN_PROTOCOL_HTTPS = 'https'; const BUILTIN_IDENTIFIER_ID = 'id'; const BUILTIN_IDENTIFIER_SHORTNAME = 'shortname'; const BUILTIN_IDENTIFIER_CALLSIGN = 'callsign'; const DISPLAY_DEFAULT = 'default'; const DISPLAY_NEVER = 'never'; const DISPLAY_ALWAYS = 'always'; const IO_DEFAULT = 'default'; const IO_OBSERVE = 'observe'; const IO_MIRROR = 'mirror'; const IO_NONE = 'none'; const IO_READ = 'read'; const IO_READWRITE = 'readwrite'; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_COLUMN_SCHEMA => array( 'uri' => 'text255', 'builtinProtocol' => 'text32?', 'builtinIdentifier' => 'text32?', 'credentialPHID' => 'phid?', 'ioType' => 'text32', 'displayType' => 'text32', 'isDisabled' => 'bool', ), self::CONFIG_KEY_SCHEMA => array( 'key_builtin' => array( 'columns' => array( 'repositoryPHID', 'builtinProtocol', 'builtinIdentifier', ), 'unique' => true, ), ), ) + parent::getConfiguration(); } public static function initializeNewURI() { return id(new self()) ->setIoType(self::IO_DEFAULT) ->setDisplayType(self::DISPLAY_DEFAULT) ->setIsDisabled(0); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorRepositoryURIPHIDType::TYPECONST); } public function attachRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } public function getRepository() { return $this->assertAttached($this->repository); } public function getRepositoryURIBuiltinKey() { if (!$this->getBuiltinProtocol()) { return null; } $parts = array( $this->getBuiltinProtocol(), $this->getBuiltinIdentifier(), ); return implode('.', $parts); } public function isBuiltin() { return (bool)$this->getBuiltinProtocol(); } public function getEffectiveDisplayType() { $display = $this->getDisplayType(); if ($display != self::DISPLAY_DEFAULT) { return $display; } return $this->getDefaultDisplayType(); } public function getDefaultDisplayType() { switch ($this->getEffectiveIOType()) { case self::IO_MIRROR: case self::IO_OBSERVE: case self::IO_NONE: return self::DISPLAY_NEVER; case self::IO_READ: case self::IO_READWRITE: // By default, only show the "best" version of the builtin URI, not the // other redundant versions. $repository = $this->getRepository(); $other_uris = $repository->getURIs(); $identifier_value = array( self::BUILTIN_IDENTIFIER_SHORTNAME => 3, self::BUILTIN_IDENTIFIER_CALLSIGN => 2, self::BUILTIN_IDENTIFIER_ID => 1, ); $have_identifiers = array(); foreach ($other_uris as $other_uri) { if ($other_uri->getIsDisabled()) { continue; } $identifier = $other_uri->getBuiltinIdentifier(); if (!$identifier) { continue; } $have_identifiers[$identifier] = $identifier_value[$identifier]; } $best_identifier = max($have_identifiers); $this_identifier = $identifier_value[$this->getBuiltinIdentifier()]; if ($this_identifier < $best_identifier) { return self::DISPLAY_NEVER; } return self::DISPLAY_ALWAYS; } return self::DISPLAY_NEVER; } public function getEffectiveIOType() { $io = $this->getIoType(); if ($io != self::IO_DEFAULT) { return $io; } return $this->getDefaultIOType(); } public function getDefaultIOType() { if ($this->isBuiltin()) { $repository = $this->getRepository(); $other_uris = $repository->getURIs(); $any_observe = false; foreach ($other_uris as $other_uri) { if ($other_uri->getIoType() == self::IO_OBSERVE) { $any_observe = true; break; } } if ($any_observe) { return self::IO_READ; } else { return self::IO_READWRITE; } } return self::IO_NONE; } public function getNormalizedURI() { $vcs = $this->getRepository()->getVersionControlSystem(); $map = array( PhabricatorRepositoryType::REPOSITORY_TYPE_GIT => ArcanistRepositoryURINormalizer::TYPE_GIT, PhabricatorRepositoryType::REPOSITORY_TYPE_SVN => ArcanistRepositoryURINormalizer::TYPE_SVN, PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL => ArcanistRepositoryURINormalizer::TYPE_MERCURIAL, ); $type = $map[$vcs]; $display = (string)$this->getDisplayURI(); $normalizer = new ArcanistRepositoryURINormalizer($type, $display); $domain_map = self::getURINormalizerDomainMap(); $normalizer->setDomainMap($domain_map); return $normalizer->getNormalizedURI(); } public function getDisplayURI() { return $this->getURIObject(); } public function getEffectiveURI() { return $this->getURIObject(); } public function getURIEnvelope() { $uri = $this->getEffectiveURI(); $command_engine = $this->newCommandEngine(); $is_http = $command_engine->isAnyHTTPProtocol(); // For SVN, we use `--username` and `--password` flags separately in the // CommandEngine, so we don't need to add any credentials here. $is_svn = $this->getRepository()->isSVN(); $credential_phid = $this->getCredentialPHID(); if ($is_http && !$is_svn && $credential_phid) { $key = PassphrasePasswordKey::loadFromPHID( $credential_phid, PhabricatorUser::getOmnipotentUser()); $uri->setUser($key->getUsernameEnvelope()->openEnvelope()); $uri->setPass($key->getPasswordEnvelope()->openEnvelope()); } return new PhutilOpaqueEnvelope((string)$uri); } private function getURIObject() { // Users can provide Git/SCP-style URIs in the form "user@host:path". // In the general case, these are not equivalent to any "ssh://..." form // because the path is relative. if ($this->isBuiltin()) { $builtin_protocol = $this->getForcedProtocol(); $builtin_domain = $this->getForcedHost(); $raw_uri = "{$builtin_protocol}://{$builtin_domain}"; } else { $raw_uri = $this->getURI(); } $port = $this->getForcedPort(); $default_ports = array( 'ssh' => 22, 'http' => 80, 'https' => 443, ); $uri = new PhutilURI($raw_uri); // Make sure to remove any password from the URI before we do anything // with it; this should always be provided by the associated credential. $uri->setPass(null); $protocol = $this->getForcedProtocol(); if ($protocol) { $uri->setProtocol($protocol); } if ($port) { $uri->setPort($port); } // Remove any explicitly set default ports. $uri_port = $uri->getPort(); $uri_protocol = $uri->getProtocol(); $uri_default = idx($default_ports, $uri_protocol); if ($uri_default && ($uri_default == $uri_port)) { $uri->setPort(null); } $user = $this->getForcedUser(); if ($user) { $uri->setUser($user); } $host = $this->getForcedHost(); if ($host) { $uri->setDomain($host); } $path = $this->getForcedPath(); if ($path) { $uri->setPath($path); } return $uri; } private function getForcedProtocol() { $repository = $this->getRepository(); switch ($this->getBuiltinProtocol()) { case self::BUILTIN_PROTOCOL_SSH: if ($repository->isSVN()) { return 'svn+ssh'; } else { return 'ssh'; } case self::BUILTIN_PROTOCOL_HTTP: return 'http'; case self::BUILTIN_PROTOCOL_HTTPS: return 'https'; default: return null; } } private function getForcedUser() { switch ($this->getBuiltinProtocol()) { case self::BUILTIN_PROTOCOL_SSH: return AlmanacKeys::getClusterSSHUser(); default: return null; } } private function getForcedHost() { $phabricator_uri = PhabricatorEnv::getURI('/'); $phabricator_uri = new PhutilURI($phabricator_uri); $phabricator_host = $phabricator_uri->getDomain(); switch ($this->getBuiltinProtocol()) { case self::BUILTIN_PROTOCOL_SSH: $ssh_host = PhabricatorEnv::getEnvConfig('diffusion.ssh-host'); if ($ssh_host !== null) { return $ssh_host; } return $phabricator_host; case self::BUILTIN_PROTOCOL_HTTP: case self::BUILTIN_PROTOCOL_HTTPS: return $phabricator_host; default: return null; } } private function getForcedPort() { $protocol = $this->getBuiltinProtocol(); if ($protocol == self::BUILTIN_PROTOCOL_SSH) { return PhabricatorEnv::getEnvConfig('diffusion.ssh-port'); } // If Phabricator is running on a nonstandard port, use that as the default // port for URIs with the same protocol. $is_http = ($protocol == self::BUILTIN_PROTOCOL_HTTP); $is_https = ($protocol == self::BUILTIN_PROTOCOL_HTTPS); if ($is_http || $is_https) { $uri = PhabricatorEnv::getURI('/'); $uri = new PhutilURI($uri); $port = $uri->getPort(); if (!$port) { return null; } $uri_protocol = $uri->getProtocol(); $use_port = ($is_http && ($uri_protocol == 'http')) || ($is_https && ($uri_protocol == 'https')); if (!$use_port) { return null; } return $port; } return null; } private function getForcedPath() { if (!$this->isBuiltin()) { return null; } $repository = $this->getRepository(); $id = $repository->getID(); $callsign = $repository->getCallsign(); $short_name = $repository->getRepositorySlug(); $clone_name = $repository->getCloneName(); if ($repository->isGit()) { $suffix = '.git'; } else if ($repository->isHg()) { $suffix = '/'; } else { $suffix = ''; $clone_name = ''; } switch ($this->getBuiltinIdentifier()) { case self::BUILTIN_IDENTIFIER_ID: return "/diffusion/{$id}/{$clone_name}{$suffix}"; case self::BUILTIN_IDENTIFIER_SHORTNAME: return "/source/{$short_name}{$suffix}"; case self::BUILTIN_IDENTIFIER_CALLSIGN: return "/diffusion/{$callsign}/{$clone_name}{$suffix}"; default: return null; } } public function getViewURI() { $id = $this->getID(); return $this->getRepository()->getPathURI("uri/view/{$id}/"); } public function getEditURI() { $id = $this->getID(); return $this->getRepository()->getPathURI("uri/edit/{$id}/"); } public function getAvailableIOTypeOptions() { $options = array( self::IO_DEFAULT, self::IO_NONE, ); if ($this->isBuiltin()) { $options[] = self::IO_READ; $options[] = self::IO_READWRITE; } else { $options[] = self::IO_OBSERVE; $options[] = self::IO_MIRROR; } $map = array(); $io_map = self::getIOTypeMap(); foreach ($options as $option) { $spec = idx($io_map, $option, array()); $label = idx($spec, 'label', $option); $short = idx($spec, 'short'); $name = pht('%s: %s', $label, $short); $map[$option] = $name; } return $map; } public function getAvailableDisplayTypeOptions() { $options = array( self::DISPLAY_DEFAULT, self::DISPLAY_ALWAYS, self::DISPLAY_NEVER, ); $map = array(); $display_map = self::getDisplayTypeMap(); foreach ($options as $option) { $spec = idx($display_map, $option, array()); $label = idx($spec, 'label', $option); $short = idx($spec, 'short'); $name = pht('%s: %s', $label, $short); $map[$option] = $name; } return $map; } public static function getIOTypeMap() { return array( self::IO_DEFAULT => array( 'label' => pht('Default'), 'short' => pht('Use default behavior.'), ), self::IO_OBSERVE => array( 'icon' => 'fa-download', 'color' => 'green', 'label' => pht('Observe'), 'note' => pht( 'Changes to this URI will be observed and pulled.'), 'short' => pht('Copy from a remote.'), ), self::IO_MIRROR => array( 'icon' => 'fa-upload', 'color' => 'green', 'label' => pht('Mirror'), 'note' => pht( 'A copy of any changes will be pushed to this URI.'), 'short' => pht('Push a copy to a remote.'), ), self::IO_NONE => array( 'icon' => 'fa-times', 'color' => 'grey', 'label' => pht('No I/O'), 'note' => pht( 'No changes will be pushed or pulled from this URI.'), 'short' => pht('Do not perform any I/O.'), ), self::IO_READ => array( 'icon' => 'fa-folder', 'color' => 'blue', 'label' => pht('Read Only'), 'note' => pht( 'A read-only copy of the repository will be served from this URI.'), 'short' => pht('Serve repository in read-only mode.'), ), self::IO_READWRITE => array( 'icon' => 'fa-folder-open', 'color' => 'blue', 'label' => pht('Read/Write'), 'note' => pht( 'A read/write copy of the repository will be served from this URI.'), 'short' => pht('Serve repository in read/write mode.'), ), ); } public static function getDisplayTypeMap() { return array( self::DISPLAY_DEFAULT => array( 'label' => pht('Default'), 'short' => pht('Use default behavior.'), ), self::DISPLAY_ALWAYS => array( 'icon' => 'fa-eye', 'color' => 'green', 'label' => pht('Visible'), 'note' => pht('This URI will be shown to users as a clone URI.'), 'short' => pht('Show as a clone URI.'), ), self::DISPLAY_NEVER => array( 'icon' => 'fa-eye-slash', 'color' => 'grey', 'label' => pht('Hidden'), 'note' => pht( 'This URI will be hidden from users.'), 'short' => pht('Do not show as a clone URI.'), ), ); } public function newCommandEngine() { $repository = $this->getRepository(); return DiffusionCommandEngine::newCommandEngine($repository) ->setCredentialPHID($this->getCredentialPHID()) ->setURI($this->getEffectiveURI()); } public function getURIScore() { $score = 0; $io_points = array( self::IO_READWRITE => 200, self::IO_READ => 100, ); $score += idx($io_points, $this->getEffectiveIOType(), 0); $protocol_points = array( self::BUILTIN_PROTOCOL_SSH => 30, self::BUILTIN_PROTOCOL_HTTPS => 20, self::BUILTIN_PROTOCOL_HTTP => 10, ); $score += idx($protocol_points, $this->getBuiltinProtocol(), 0); $identifier_points = array( self::BUILTIN_IDENTIFIER_SHORTNAME => 3, self::BUILTIN_IDENTIFIER_CALLSIGN => 2, self::BUILTIN_IDENTIFIER_ID => 1, ); $score += idx($identifier_points, $this->getBuiltinIdentifier(), 0); return $score; } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new DiffusionURIEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorRepositoryURITransaction(); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: case PhabricatorPolicyCapability::CAN_EDIT: return PhabricatorPolicies::getMostOpenPolicy(); } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return false; } /* -( PhabricatorExtendedPolicyInterface )--------------------------------- */ public function getExtendedPolicy($capability, PhabricatorUser $viewer) { $extended = array(); switch ($capability) { case PhabricatorPolicyCapability::CAN_EDIT: // To edit a repository URI, you must be able to edit the // corresponding repository. $extended[] = array($this->getRepository(), $capability); break; } return $extended; } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('repositoryPHID') ->setType('phid') ->setDescription(pht('The associated repository PHID.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('uri') ->setType('map<string, string>') ->setDescription(pht('The raw and effective URI.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('io') ->setType('map<string, const>') ->setDescription( pht('The raw, default, and effective I/O Type settings.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('display') ->setType('map<string, const>') ->setDescription( pht('The raw, default, and effective Display Type settings.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('credentialPHID') ->setType('phid?') ->setDescription( pht('The associated credential PHID, if one exists.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('disabled') ->setType('bool') ->setDescription(pht('True if the URI is disabled.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('builtin') ->setType('map<string, string>') ->setDescription( pht('Information about builtin URIs.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('dateCreated') ->setType('int') ->setDescription( pht('Epoch timestamp when the object was created.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('dateModified') ->setType('int') ->setDescription( pht('Epoch timestamp when the object was last updated.')), ); } public function getFieldValuesForConduit() { return array( 'repositoryPHID' => $this->getRepositoryPHID(), 'uri' => array( 'raw' => $this->getURI(), 'display' => (string)$this->getDisplayURI(), 'effective' => (string)$this->getEffectiveURI(), 'normalized' => (string)$this->getNormalizedURI(), ), 'io' => array( 'raw' => $this->getIOType(), 'default' => $this->getDefaultIOType(), 'effective' => $this->getEffectiveIOType(), ), 'display' => array( 'raw' => $this->getDisplayType(), 'default' => $this->getDefaultDisplayType(), 'effective' => $this->getEffectiveDisplayType(), ), 'credentialPHID' => $this->getCredentialPHID(), 'disabled' => (bool)$this->getIsDisabled(), 'builtin' => array( 'protocol' => $this->getBuiltinProtocol(), 'identifier' => $this->getBuiltinIdentifier(), ), 'dateCreated' => $this->getDateCreated(), 'dateModified' => $this->getDateModified(), ); } public function getConduitSearchAttachments() { return array(); } public static function getURINormalizerDomainMap() { $domain_map = array(); // See T13435. If the domain for a repository URI is same as the install // base URI, store it as a "<base-uri>" token instead of the actual domain // so that the index does not fall out of date if the install moves. $base_uri = PhabricatorEnv::getURI('/'); $base_uri = new PhutilURI($base_uri); $base_domain = $base_uri->getDomain(); $domain_map['<base-uri>'] = $base_domain; // Likewise, store a token for the "SSH Host" domain so it can be changed // without requiring an index rebuild. $ssh_host = PhabricatorEnv::getEnvConfig('diffusion.ssh-host'); if ($ssh_host !== null && strlen($ssh_host)) { $domain_map['<ssh-host>'] = $ssh_host; } return $domain_map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositorySchemaSpec.php
src/applications/repository/storage/PhabricatorRepositorySchemaSpec.php
<?php final class PhabricatorRepositorySchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new PhabricatorRepository()); $this->buildRawSchema( id(new PhabricatorRepository())->getApplicationName(), PhabricatorRepository::TABLE_COVERAGE, array( 'id' => 'auto', 'branchID' => 'id', 'commitID' => 'id', 'pathID' => 'id', 'coverage' => 'bytes', ), array( 'PRIMARY' => array( 'columns' => array('id'), 'unique' => true, ), 'key_path' => array( 'columns' => array('branchID', 'pathID', 'commitID'), 'unique' => true, ), )); $this->buildRawSchema( id(new PhabricatorRepository())->getApplicationName(), PhabricatorRepository::TABLE_FILESYSTEM, array( 'repositoryID' => 'id', 'parentID' => 'id', 'svnCommit' => 'uint32', 'pathID' => 'id', 'existed' => 'bool', 'fileType' => 'uint32', ), array( 'PRIMARY' => array( 'columns' => array('repositoryID', 'parentID', 'pathID', 'svnCommit'), 'unique' => true, ), 'repositoryID' => array( 'columns' => array('repositoryID', 'svnCommit'), ), )); $this->buildRawSchema( id(new PhabricatorRepository())->getApplicationName(), PhabricatorRepository::TABLE_LINTMESSAGE, array( 'id' => 'auto', 'branchID' => 'id', 'path' => 'text', 'line' => 'uint32', 'authorPHID' => 'phid?', 'code' => 'text32', 'severity' => 'text16', 'name' => 'text255', 'description' => 'text', ), array( 'PRIMARY' => array( 'columns' => array('id'), 'unique' => true, ), 'branchID' => array( 'columns' => array('branchID', 'path(64)'), ), 'branchID_2' => array( 'columns' => array('branchID', 'code', 'path(64)'), ), 'key_author' => array( 'columns' => array('authorPHID'), ), )); $this->buildRawSchema( id(new PhabricatorRepository())->getApplicationName(), PhabricatorRepository::TABLE_PARENTS, array( 'id' => 'auto', 'childCommitID' => 'id', 'parentCommitID' => 'id', ), array( 'PRIMARY' => array( 'columns' => array('id'), 'unique' => true, ), 'key_child' => array( 'columns' => array('childCommitID', 'parentCommitID'), 'unique' => true, ), 'key_parent' => array( 'columns' => array('parentCommitID'), ), )); $this->buildRawSchema( id(new PhabricatorRepository())->getApplicationName(), PhabricatorRepository::TABLE_PATH, array( 'id' => 'auto', 'path' => 'text', 'pathHash' => 'bytes32', ), array( 'PRIMARY' => array( 'columns' => array('id'), 'unique' => true, ), 'pathHash' => array( 'columns' => array('pathHash'), 'unique' => true, ), )); $this->buildRawSchema( id(new PhabricatorRepository())->getApplicationName(), PhabricatorRepository::TABLE_PATHCHANGE, array( 'repositoryID' => 'id', 'pathID' => 'id', 'commitID' => 'id', 'targetPathID' => 'id?', 'targetCommitID' => 'id?', 'changeType' => 'uint32', 'fileType' => 'uint32', 'isDirect' => 'bool', 'commitSequence' => 'uint32', ), array( 'PRIMARY' => array( 'columns' => array('commitID', 'pathID'), 'unique' => true, ), 'repositoryID' => array( 'columns' => array('repositoryID', 'pathID', 'commitSequence'), ), )); $this->buildRawSchema( id(new PhabricatorRepository())->getApplicationName(), PhabricatorRepository::TABLE_SUMMARY, array( 'repositoryID' => 'id', 'size' => 'uint32', 'lastCommitID' => 'id', 'epoch' => 'epoch?', ), array( 'PRIMARY' => array( 'columns' => array('repositoryID'), 'unique' => true, ), 'key_epoch' => array( 'columns' => array('epoch'), ), )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryBranch.php
src/applications/repository/storage/PhabricatorRepositoryBranch.php
<?php final class PhabricatorRepositoryBranch extends PhabricatorRepositoryDAO { protected $repositoryID; protected $name; protected $lintCommit; protected function getConfiguration() { return array( self::CONFIG_COLUMN_SCHEMA => array( 'name' => 'text128', 'lintCommit' => 'text40?', ), self::CONFIG_KEY_SCHEMA => array( 'repositoryID' => array( 'columns' => array('repositoryID', 'name'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public static function loadBranch($repository_id, $branch_name) { return id(new PhabricatorRepositoryBranch())->loadOneWhere( 'repositoryID = %d AND name = %s', $repository_id, $branch_name); } public static function loadOrCreateBranch($repository_id, $branch_name) { $branch = self::loadBranch($repository_id, $branch_name); if ($branch) { return $branch; } return id(new PhabricatorRepositoryBranch()) ->setRepositoryID($repository_id) ->setName($branch_name) ->save(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
src/applications/repository/storage/PhabricatorRepositoryWorkingCopyVersion.php
<?php final class PhabricatorRepositoryWorkingCopyVersion extends PhabricatorRepositoryDAO { protected $repositoryPHID; protected $devicePHID; protected $repositoryVersion; protected $isWriting; protected $lockOwner; protected $writeProperties; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'repositoryVersion' => 'uint32', 'isWriting' => 'bool', 'writeProperties' => 'text?', 'lockOwner' => 'text255?', ), self::CONFIG_KEY_SCHEMA => array( 'key_workingcopy' => array( 'columns' => array('repositoryPHID', 'devicePHID'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function getWriteProperty($key, $default = null) { // The "writeProperties" don't currently get automatically serialized or // deserialized. Perhaps they should. try { $properties = phutil_json_decode($this->writeProperties); return idx($properties, $key, $default); } catch (Exception $ex) { return null; } } public static function loadVersions($repository_phid) { $version = new self(); $conn_w = $version->establishConnection('w'); $table = $version->getTableName(); // This is a normal read, but force it to come from the master. $rows = queryfx_all( $conn_w, 'SELECT * FROM %T WHERE repositoryPHID = %s', $table, $repository_phid); return $version->loadAllFromArray($rows); } public static function loadWriter($repository_phid) { $version = new self(); $conn_w = $version->establishConnection('w'); $table = $version->getTableName(); // We're forcing this read to go to the master. $row = queryfx_one( $conn_w, 'SELECT * FROM %T WHERE repositoryPHID = %s AND isWriting = 1 LIMIT 1', $table, $repository_phid); if (!$row) { return null; } return $version->loadFromArray($row); } public static function getReadLock($repository_phid, $device_phid) { $parameters = array( 'repositoryPHID' => $repository_phid, 'devicePHID' => $device_phid, ); return PhabricatorGlobalLock::newLock('repo.read', $parameters); } public static function getWriteLock($repository_phid) { $parameters = array( 'repositoryPHID' => $repository_phid, ); return PhabricatorGlobalLock::newLock('repo.write', $parameters); } /** * Before a write, set the "isWriting" flag. * * This allows us to detect when we lose a node partway through a write and * may have committed and acknowledged a write on a node that lost the lock * partway through the write and is no longer reachable. * * In particular, if a node loses its connection to the database the global * lock is released by default. This is a durable lock which stays locked * by default. */ public static function willWrite( AphrontDatabaseConnection $locked_connection, $repository_phid, $device_phid, array $write_properties, $lock_owner) { $version = new self(); $table = $version->getTableName(); queryfx( $locked_connection, 'INSERT INTO %T (repositoryPHID, devicePHID, repositoryVersion, isWriting, writeProperties, lockOwner) VALUES (%s, %s, %d, %d, %s, %s) ON DUPLICATE KEY UPDATE isWriting = VALUES(isWriting), writeProperties = VALUES(writeProperties), lockOwner = VALUES(lockOwner)', $table, $repository_phid, $device_phid, 0, 1, phutil_json_encode($write_properties), $lock_owner); } /** * After a write, update the version and release the "isWriting" lock. */ public static function didWrite( $repository_phid, $device_phid, $old_version, $new_version, $lock_owner) { $version = new self(); $conn_w = $version->establishConnection('w'); $table = $version->getTableName(); queryfx( $conn_w, 'UPDATE %T SET repositoryVersion = %d, isWriting = 0, lockOwner = NULL WHERE repositoryPHID = %s AND devicePHID = %s AND repositoryVersion = %d AND isWriting = 1 AND lockOwner = %s', $table, $new_version, $repository_phid, $device_phid, $old_version, $lock_owner); } /** * After a fetch, set the local version to the fetched version. */ public static function updateVersion( $repository_phid, $device_phid, $new_version) { $version = new self(); $conn_w = $version->establishConnection('w'); $table = $version->getTableName(); queryfx( $conn_w, 'INSERT INTO %T (repositoryPHID, devicePHID, repositoryVersion, isWriting) VALUES (%s, %s, %d, %d) ON DUPLICATE KEY UPDATE repositoryVersion = VALUES(repositoryVersion)', $table, $repository_phid, $device_phid, $new_version, 0); } /** * Explicitly demote a device. */ public static function demoteDevice( $repository_phid, $device_phid) { $version = new self(); $conn_w = $version->establishConnection('w'); $table = $version->getTableName(); queryfx( $conn_w, 'DELETE FROM %T WHERE repositoryPHID = %s AND devicePHID = %s', $table, $repository_phid, $device_phid); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/__tests__/PhabricatorRepositoryURITestCase.php
src/applications/repository/storage/__tests__/PhabricatorRepositoryURITestCase.php
<?php final class PhabricatorRepositoryURITestCase extends PhabricatorTestCase { protected function getPhabricatorTestCaseConfiguration() { return array( self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true, ); } public function testRepositoryURICanonicalization() { $repo = id(new PhabricatorRepository()) ->makeEphemeral() ->setID(123); $tests = array( '/diffusion/123' => '/diffusion/123/', '/diffusion/123/' => '/diffusion/123/', '/diffusion/123/browse/master/' => '/diffusion/123/browse/master/', '/kangaroo/' => null, ); foreach ($tests as $input => $expect) { $this->assertEqual( $expect, $repo->getCanonicalPath($input), pht('Canonical Path (ID, No Callsign): %s', $input)); } $repo->setCallsign('XYZ'); $tests = array( '/diffusion/123' => '/diffusion/XYZ/', '/diffusion/123/' => '/diffusion/XYZ/', '/diffusion/123/browse/master/' => '/diffusion/XYZ/browse/master/', '/diffusion/XYZ' => '/diffusion/XYZ/', '/diffusion/XYZ/' => '/diffusion/XYZ/', '/diffusion/XYZ/browse/master/' => '/diffusion/XYZ/browse/master/', '/diffusion/ABC/' => '/diffusion/XYZ/', '/kangaroo/' => null, '/R1:abcdef' => '/rXYZabcdef', ); foreach ($tests as $input => $expect) { $this->assertEqual( $expect, $repo->getCanonicalPath($input), pht('Canonical Path (ID, Callsign): %s', $input)); } } public function testURIGeneration() { $svn = PhabricatorRepositoryType::REPOSITORY_TYPE_SVN; $git = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; $hg = PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL; $user = $this->generateNewTestUser(); $http_secret = id(new PassphraseSecret())->setSecretData('quack')->save(); $http_credential = PassphraseCredential::initializeNewCredential($user) ->setCredentialType(PassphrasePasswordCredentialType::CREDENTIAL_TYPE) ->setProvidesType(PassphrasePasswordCredentialType::PROVIDES_TYPE) ->setUsername('duck') ->setSecretID($http_secret->getID()) ->save(); $repo = PhabricatorRepository::initializeNewRepository($user) ->setVersionControlSystem($svn) ->setName(pht('Test Repo')) ->setCallsign('TESTREPO') ->setCredentialPHID($http_credential->getPHID()) ->save(); // Test HTTP URIs. $repo->setDetail('remote-uri', 'http://example.com/'); $repo->setVersionControlSystem($svn); $this->assertEqual('http://example.com/', $repo->getRemoteURI()); $this->assertEqual('http://example.com/', $repo->getPublicCloneURI()); $this->assertEqual('http://example.com/', $repo->getRemoteURIEnvelope()->openEnvelope()); $repo->setVersionControlSystem($git); $this->assertEqual('http://example.com/', $repo->getRemoteURI()); $this->assertEqual('http://example.com/', $repo->getPublicCloneURI()); $this->assertEqual('http://duck:quack@example.com/', $repo->getRemoteURIEnvelope()->openEnvelope()); $repo->setVersionControlSystem($hg); $this->assertEqual('http://example.com/', $repo->getRemoteURI()); $this->assertEqual('http://example.com/', $repo->getPublicCloneURI()); $this->assertEqual('http://duck:quack@example.com/', $repo->getRemoteURIEnvelope()->openEnvelope()); // Test SSH URIs. $repo->setDetail('remote-uri', 'ssh://example.com/'); $repo->setVersionControlSystem($svn); $this->assertEqual('ssh://example.com/', $repo->getRemoteURI()); $this->assertEqual('ssh://example.com/', $repo->getPublicCloneURI()); $this->assertEqual('ssh://example.com/', $repo->getRemoteURIEnvelope()->openEnvelope()); $repo->setVersionControlSystem($git); $this->assertEqual('ssh://example.com/', $repo->getRemoteURI()); $this->assertEqual('ssh://example.com/', $repo->getPublicCloneURI()); $this->assertEqual('ssh://example.com/', $repo->getRemoteURIEnvelope()->openEnvelope()); $repo->setVersionControlSystem($hg); $this->assertEqual('ssh://example.com/', $repo->getRemoteURI()); $this->assertEqual('ssh://example.com/', $repo->getPublicCloneURI()); $this->assertEqual('ssh://example.com/', $repo->getRemoteURIEnvelope()->openEnvelope()); // Test Git URIs. $repo->setDetail('remote-uri', 'git@example.com:path.git'); $repo->setVersionControlSystem($git); $this->assertEqual('git@example.com:path.git', $repo->getRemoteURI()); $this->assertEqual('git@example.com:path.git', $repo->getPublicCloneURI()); $this->assertEqual('git@example.com:path.git', $repo->getRemoteURIEnvelope()->openEnvelope()); // Test SVN "Import Only" paths. $repo->setDetail('remote-uri', 'http://example.com/'); $repo->setVersionControlSystem($svn); $repo->setDetail('svn-subpath', 'projects/example/'); $this->assertEqual('http://example.com/', $repo->getRemoteURI()); $this->assertEqual( 'http://example.com/projects/example/', $repo->getPublicCloneURI()); $this->assertEqual('http://example.com/', $repo->getRemoteURIEnvelope()->openEnvelope()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/__tests__/PhabricatorRepositoryTestCase.php
src/applications/repository/storage/__tests__/PhabricatorRepositoryTestCase.php
<?php final class PhabricatorRepositoryTestCase extends PhabricatorTestCase { public function testRepositoryURIProtocols() { $tests = array( '/path/to/repo' => 'file', 'file:///path/to/repo' => 'file', 'ssh://user@domain.com/path' => 'ssh', 'git@example.com:path' => 'ssh', 'git://git@example.com/path' => 'git', 'svn+ssh://example.com/path' => 'svn+ssh', 'https://example.com/repo/' => 'https', 'http://example.com/' => 'http', 'https://user@example.com/' => 'https', ); foreach ($tests as $uri => $expect) { $repository = new PhabricatorRepository(); $repository->setDetail('remote-uri', $uri); $this->assertEqual( $expect, $repository->getRemoteProtocol(), pht("Protocol for '%s'.", $uri)); } } public function testBranchFilter() { $git = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; $repo = new PhabricatorRepository(); $repo->setVersionControlSystem($git); $this->assertTrue( $repo->shouldTrackBranch('imaginary'), pht('Track all branches by default.')); $repo->setTrackOnlyRules(array('master')); $this->assertTrue( $repo->shouldTrackBranch('master'), pht('Track listed branches.')); $this->assertFalse( $repo->shouldTrackBranch('imaginary'), pht('Do not track unlisted branches.')); } public function testSubversionPathInfo() { $svn = PhabricatorRepositoryType::REPOSITORY_TYPE_SVN; $repo = new PhabricatorRepository(); $repo->setVersionControlSystem($svn); $repo->setDetail('remote-uri', 'http://svn.example.com/repo'); $this->assertEqual( 'http://svn.example.com/repo', $repo->getSubversionPathURI()); $repo->setDetail('remote-uri', 'http://svn.example.com/repo/'); $this->assertEqual( 'http://svn.example.com/repo', $repo->getSubversionPathURI()); $repo->setDetail('hosting-enabled', true); $repo->setLocalPath('/var/repo/SVN'); $this->assertEqual( 'file:///var/repo/SVN', $repo->getSubversionPathURI()); $repo->setLocalPath('/var/repo/SVN/'); $this->assertEqual( 'file:///var/repo/SVN', $repo->getSubversionPathURI()); $this->assertEqual( 'file:///var/repo/SVN/a@', $repo->getSubversionPathURI('a')); $this->assertEqual( 'file:///var/repo/SVN/a@1', $repo->getSubversionPathURI('a', 1)); $this->assertEqual( 'file:///var/repo/SVN/%3F@22', $repo->getSubversionPathURI('?', 22)); $repo->setDetail('svn-subpath', 'quack/trunk/'); $this->assertEqual( 'file:///var/repo/SVN/quack/trunk/@', $repo->getSubversionBaseURI()); $this->assertEqual( 'file:///var/repo/SVN/quack/trunk/@HEAD', $repo->getSubversionBaseURI('HEAD')); } public function testRepositoryShortNameValidation() { $good = array( 'sensible-repository', 'AReasonableName', 'ACRONYM-project', 'sol-123', '46-helixes', 'node.io', 'internet.com', 'www.internet-site.com.repository', 'with_under-scores', // Can't win them all. 'A-_._-_._-_._-_._-_._-_._-1', // 64-character names are fine. str_repeat('a', 64), ); $poor = array( '', '1', '.', '-_-', 'AAAA', '..', 'a/b', '../../etc/passwd', '/', '!', '@', 'ca$hmoney', 'repo with spaces', 'hyphen-', '-ated', '_underscores_', 'yes!', 'quack.git', 'git.git', '.git.git.git', // 65-character names are no good. str_repeat('a', 65), ); foreach ($good as $nice_name) { $actual = PhabricatorRepository::isValidRepositorySlug($nice_name); $this->assertEqual( true, $actual, pht( 'Expected "%s" to be a valid repository short name.', $nice_name)); } foreach ($poor as $poor_name) { $actual = PhabricatorRepository::isValidRepositorySlug($poor_name); $this->assertEqual( false, $actual, pht( 'Expected "%s" to be rejected as an invalid repository '. 'short name.', $poor_name)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/storage/__tests__/PhabricatorRepositoryCommitTestCase.php
src/applications/repository/storage/__tests__/PhabricatorRepositoryCommitTestCase.php
<?php final class PhabricatorRepositoryCommitTestCase extends PhabricatorTestCase { public function testSummarizeCommits() { // Cyrillic "zhe". $zhe = "\xD0\xB6"; // Symbol "Snowman". $snowman = "\xE2\x98\x83"; // Emoji "boar". $boar = "\xF0\x9F\x90\x97"; // Proper unicode truncation is tested elsewhere, this is just making // sure column length handling is sane. $map = array( '' => 0, 'a' => 1, str_repeat('a', 81) => 82, str_repeat('a', 255) => 82, str_repeat('aa ', 30) => 80, str_repeat($zhe, 300) => 161, str_repeat($snowman, 300) => 240, str_repeat($boar, 300) => 255, ); foreach ($map as $input => $expect) { $actual = PhabricatorRepositoryCommitData::summarizeCommitMessage( $input); $this->assertEqual($expect, strlen($actual)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementListWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementListWorkflow.php
<?php final class PhabricatorRepositoryManagementListWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('list') ->setSynopsis(pht('Show a list of repositories.')) ->setArguments(array()); } public function execute(PhutilArgumentParser $args) { $console = PhutilConsole::getConsole(); $repos = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getViewer()) ->execute(); if ($repos) { foreach ($repos as $repo) { $console->writeOut("%s\n", $repo->getMonogram()); } } else { $console->writeErr("%s\n", pht('There are no repositories.')); } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementListPathsWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementListPathsWorkflow.php
<?php final class PhabricatorRepositoryManagementListPathsWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('list-paths') ->setSynopsis(pht('List repository local paths.')) ->setArguments(array()); } public function execute(PhutilArgumentParser $args) { $console = PhutilConsole::getConsole(); $repos = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getViewer()) ->execute(); if (!$repos) { $console->writeErr("%s\n", pht('There are no repositories.')); return 0; } $table = id(new PhutilConsoleTable()) ->addColumn( 'monogram', array( 'title' => pht('Repository'), )) ->addColumn( 'path', array( 'title' => pht('Path'), )) ->setBorders(true); foreach ($repos as $repo) { $table->addRow( array( 'monogram' => $repo->getMonogram(), 'path' => $repo->getLocalPath(), )); } $table->draw(); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementMaintenanceWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementMaintenanceWorkflow.php
<?php final class PhabricatorRepositoryManagementMaintenanceWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('maintenance') ->setExamples( "**maintenance** --start __message__ __repository__ ...\n". "**maintenance** --stop __repository__") ->setSynopsis( pht('Set or clear read-only mode for repository maintenance.')) ->setArguments( array( array( 'name' => 'start', 'param' => 'message', 'help' => pht( 'Put repositories into maintenance mode.'), ), array( 'name' => 'stop', 'help' => pht( 'Take repositories out of maintenance mode, returning them '. 'to normal serice.'), ), array( 'name' => 'repositories', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $repositories = $this->loadRepositories($args, 'repositories'); if (!$repositories) { throw new PhutilArgumentUsageException( pht('Specify one or more repositories to act on.')); } $message = $args->getArg('start'); $is_start = (bool)strlen($message); $is_stop = $args->getArg('stop'); if (!$is_start && !$is_stop) { throw new PhutilArgumentUsageException( pht( 'Use "--start <message>" to put repositories into maintenance '. 'mode, or "--stop" to take them out of maintenance mode.')); } if ($is_start && $is_stop) { throw new PhutilArgumentUsageException( pht( 'Specify either "--start" or "--stop", but not both.')); } $content_source = $this->newContentSource(); $diffusion_phid = id(new PhabricatorDiffusionApplication())->getPHID(); if ($is_start) { $new_value = $message; } else { $new_value = null; } foreach ($repositories as $repository) { $xactions = array(); $xactions[] = $repository->getApplicationTransactionTemplate() ->setTransactionType( PhabricatorRepositoryMaintenanceTransaction::TRANSACTIONTYPE) ->setNewValue($new_value); $repository->getApplicationTransactionEditor() ->setActor($viewer) ->setActingAsPHID($diffusion_phid) ->setContentSource($content_source) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->applyTransactions($repository, $xactions); if ($is_start) { echo tsprintf( "%s\n", pht( 'Put repository "%s" into maintenance mode.', $repository->getDisplayName())); } else { echo tsprintf( "%s\n", pht( 'Took repository "%s" out of maintenance mode.', $repository->getDisplayName())); } } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementUnpublishWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementUnpublishWorkflow.php
<?php final class PhabricatorRepositoryManagementUnpublishWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('unpublish') ->setExamples( '**unpublish** [__options__] __repository__') ->setSynopsis( pht( 'Unpublish all feed stories and notifications that a repository '. 'has generated. Keep expectations low; can not rewind time.')) ->setArguments( array( array( 'name' => 'force', 'help' => pht('Do not prompt for confirmation.'), ), array( 'name' => 'dry-run', 'help' => pht('Do not perform any writes.'), ), array( 'name' => 'repositories', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $is_force = $args->getArg('force'); $is_dry_run = $args->getArg('dry-run'); $repositories = $this->loadLocalRepositories($args, 'repositories'); if (count($repositories) !== 1) { throw new PhutilArgumentUsageException( pht('Specify exactly one repository to unpublish.')); } $repository = head($repositories); if (!$is_force) { echo tsprintf( "%s\n", pht( 'This script will unpublish all feed stories and notifications '. 'which a repository generated during import. This action can not '. 'be undone.')); $prompt = pht( 'Permanently unpublish "%s"?', $repository->getDisplayName()); if (!phutil_console_confirm($prompt)) { throw new PhutilArgumentUsageException( pht('User aborted workflow.')); } } $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepositoryPHIDs(array($repository->getPHID())) ->execute(); echo pht("Will unpublish %s commits.\n", count($commits)); foreach ($commits as $commit) { $this->unpublishCommit($commit, $is_dry_run); } return 0; } private function unpublishCommit( PhabricatorRepositoryCommit $commit, $is_dry_run) { $viewer = $this->getViewer(); echo tsprintf( "%s\n", pht( 'Unpublishing commit "%s".', $commit->getMonogram())); $stories = id(new PhabricatorFeedQuery()) ->setViewer($viewer) ->withFilterPHIDs(array($commit->getPHID())) ->execute(); if ($stories) { echo tsprintf( "%s\n", pht( 'Found %s feed storie(s).', count($stories))); if (!$is_dry_run) { $engine = new PhabricatorDestructionEngine(); foreach ($stories as $story) { $story_data = $story->getStoryData(); $engine->destroyObject($story_data); } echo tsprintf( "%s\n", pht( 'Destroyed %s feed storie(s).', count($stories))); } } $edge_types = array( PhabricatorObjectMentionsObjectEdgeType::EDGECONST => true, DiffusionCommitHasTaskEdgeType::EDGECONST => true, DiffusionCommitHasRevisionEdgeType::EDGECONST => true, DiffusionCommitRevertsCommitEdgeType::EDGECONST => true, ); $query = id(new PhabricatorEdgeQuery()) ->withSourcePHIDs(array($commit->getPHID())) ->withEdgeTypes(array_keys($edge_types)); $edges = $query->execute(); foreach ($edges[$commit->getPHID()] as $type => $edge_list) { foreach ($edge_list as $edge) { $dst = $edge['dst']; echo tsprintf( "%s\n", pht( 'Commit "%s" has edge of type "%s" to object "%s".', $commit->getMonogram(), $type, $dst)); $object = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withPHIDs(array($dst)) ->executeOne(); if ($object) { if ($object instanceof PhabricatorApplicationTransactionInterface) { $this->unpublishEdgeTransaction( $commit, $type, $object, $is_dry_run); } } } } } private function unpublishEdgeTransaction( $src, $type, PhabricatorApplicationTransactionInterface $dst, $is_dry_run) { $viewer = $this->getViewer(); $query = PhabricatorApplicationTransactionQuery::newQueryForObject($dst) ->setViewer($viewer) ->withObjectPHIDs(array($dst->getPHID())); $xactions = id(clone $query) ->withTransactionTypes( array( PhabricatorTransactions::TYPE_EDGE, )) ->execute(); $type_obj = PhabricatorEdgeType::getByConstant($type); $inverse_type = $type_obj->getInverseEdgeConstant(); $engine = new PhabricatorDestructionEngine(); foreach ($xactions as $xaction) { $edge_type = $xaction->getMetadataValue('edge:type'); if ($edge_type != $inverse_type) { // Some other type of edge was edited. continue; } $record = PhabricatorEdgeChangeRecord::newFromTransaction($xaction); $changed = $record->getChangedPHIDs(); if ($changed !== array($src->getPHID())) { // Affected objects were not just the object we're unpublishing. continue; } echo tsprintf( "%s\n", pht( 'Found edge transaction "%s" on object "%s" for type "%s".', $xaction->getPHID(), $dst->getPHID(), $type)); if (!$is_dry_run) { $engine->destroyObject($xaction); echo tsprintf( "%s\n", pht( 'Destroyed transaction "%s" on object "%s".', $xaction->getPHID(), $dst->getPHID())); } } if ($type === DiffusionCommitHasTaskEdgeType::EDGECONST) { $xactions = id(clone $query) ->withTransactionTypes( array( ManiphestTaskStatusTransaction::TRANSACTIONTYPE, )) ->execute(); if ($xactions) { foreach ($xactions as $xaction) { $metadata = $xaction->getMetadata(); if (idx($metadata, 'commitPHID') === $src->getPHID()) { echo tsprintf( "%s\n", pht( 'MANUAL Task "%s" was likely closed improperly by "%s".', $dst->getMonogram(), $src->getMonogram())); } } } } if ($type === DiffusionCommitHasRevisionEdgeType::EDGECONST) { $xactions = id(clone $query) ->withTransactionTypes( array( DifferentialRevisionCloseTransaction::TRANSACTIONTYPE, )) ->execute(); if ($xactions) { foreach ($xactions as $xaction) { $metadata = $xaction->getMetadata(); if (idx($metadata, 'commitPHID') === $src->getPHID()) { echo tsprintf( "%s\n", pht( 'MANUAL Revision "%s" was likely closed improperly by "%s".', $dst->getMonogram(), $src->getMonogram())); } } } } if (!$is_dry_run) { id(new PhabricatorEdgeEditor()) ->removeEdge($src->getPHID(), $type, $dst->getPHID()) ->save(); echo tsprintf( "%s\n", pht( 'Destroyed edge of type "%s" between "%s" and "%s".', $type, $src->getPHID(), $dst->getPHID())); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementHintWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementHintWorkflow.php
<?php final class PhabricatorRepositoryManagementHintWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('hint') ->setExamples('**hint** [options] ...') ->setSynopsis( pht( 'Write hints about unusual (rewritten or unreadable) commits.')) ->setArguments(array()); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); echo tsprintf( "%s\n", pht('Reading list of hints from stdin...')); $hints = file_get_contents('php://stdin'); if ($hints === false) { throw new PhutilArgumentUsageException(pht('Failed to read stdin.')); } try { $hints = phutil_json_decode($hints); } catch (Exception $ex) { throw new PhutilArgumentUsageException( pht( 'Expected a list of hints in JSON format: %s', $ex->getMessage())); } $repositories = array(); foreach ($hints as $idx => $hint) { if (!is_array($hint)) { throw new PhutilArgumentUsageException( pht( 'Each item in the list of hints should be a JSON object, but '. 'the item at index "%s" is not.', $idx)); } try { PhutilTypeSpec::checkMap( $hint, array( 'repository' => 'string|int', 'old' => 'string', 'new' => 'optional string|null', 'hint' => 'string', )); } catch (Exception $ex) { throw new PhutilArgumentUsageException( pht( 'Unexpected hint format at index "%s": %s', $idx, $ex->getMessage())); } $repository_identifier = $hint['repository']; $repository = idx($repositories, $repository_identifier); if (!$repository) { $repository = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withIdentifiers(array($repository_identifier)) ->executeOne(); if (!$repository) { throw new PhutilArgumentUsageException( pht( 'Repository identifier "%s" (in hint at index "%s") does not '. 'identify a valid repository.', $repository_identifier, $idx)); } $repositories[$repository_identifier] = $repository; } PhabricatorRepositoryCommitHint::updateHint( $repository->getPHID(), $hint['old'], idx($hint, 'new'), $hint['hint']); echo tsprintf( "%s\n", pht( 'Updated hint for "%s".', $hint['old'])); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementRefsWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementRefsWorkflow.php
<?php final class PhabricatorRepositoryManagementRefsWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('refs') ->setExamples('**refs** [__options__] __repository__ ...') ->setSynopsis(pht('Update refs in __repository__.')) ->setArguments( array( array( 'name' => 'verbose', 'help' => pht('Show additional debugging information.'), ), array( 'name' => 'rebuild', 'help' => pht( 'Publish commits currently reachable from any permanent ref, '. 'ignoring the cached ref state.'), ), array( 'name' => 'repos', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $repos = $this->loadLocalRepositories($args, 'repos'); if (!$repos) { throw new PhutilArgumentUsageException( pht( 'Specify one or more repositories to update refs for.')); } $console = PhutilConsole::getConsole(); foreach ($repos as $repo) { $console->writeOut( "%s\n", pht( 'Updating refs in "%s"...', $repo->getDisplayName())); $engine = id(new PhabricatorRepositoryRefEngine()) ->setRepository($repo) ->setVerbose($args->getArg('verbose')) ->setRebuild($args->getArg('rebuild')) ->updateRefs(); } $console->writeOut("%s\n", pht('Done.')); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementLockWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementLockWorkflow.php
<?php final class PhabricatorRepositoryManagementLockWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('lock') ->setExamples('**lock** [options] __repository__ ...') ->setSynopsis( pht( 'Temporarily lock clustered repositories to perform maintenance.')) ->setArguments( array( array( 'name' => 'repositories', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $repositories = $this->loadRepositories($args, 'repositories'); if (!$repositories) { throw new PhutilArgumentUsageException( pht('Specify one or more repositories to lock.')); } foreach ($repositories as $repository) { $display_name = $repository->getDisplayName(); if (!$repository->isHosted()) { throw new PhutilArgumentUsageException( pht( 'Unable to lock repository "%s": only hosted repositories may be '. 'locked.', $display_name)); } if (!$repository->supportsSynchronization()) { throw new PhutilArgumentUsageException( pht( 'Unable to lock repository "%s": only repositories that support '. 'clustering may be locked.', $display_name)); } if (!$repository->getAlmanacServicePHID()) { throw new PhutilArgumentUsageException( pht( 'Unable to lock repository "%s": only clustered repositories '. 'may be locked.', $display_name)); } } $diffusion_phid = id(new PhabricatorDiffusionApplication()) ->getPHID(); $locks = array(); foreach ($repositories as $repository) { $engine = id(new DiffusionRepositoryClusterEngine()) ->setViewer($viewer) ->setActingAsPHID($diffusion_phid) ->setRepository($repository); $event = $engine->newMaintenanceEvent(); $logs = array(); $logs[] = $engine->newMaintenanceLog(); $locks[] = array( 'repository' => $repository, 'engine' => $engine, 'event' => $event, 'logs' => $logs, ); } $display_list = new PhutilConsoleList(); foreach ($repositories as $repository) { $display_list->addItem( pht( '%s %s', $repository->getMonogram(), $repository->getName())); } echo tsprintf( "%s\n\n%B\n", pht('These repositories will be locked:'), $display_list->drawConsoleString()); echo tsprintf( "%s\n", pht( 'While the lock is held: users will be unable to write to this '. 'repository, and you may safely perform working copy maintenance '. 'on this node in another terminal window.')); $query = pht('Lock repositories and begin maintenance?'); if (!phutil_console_confirm($query)) { throw new ArcanistUserAbortException(); } foreach ($locks as $key => $lock) { $engine = $lock['engine']; $engine->synchronizeWorkingCopyBeforeWrite(); } echo tsprintf( "%s\n", pht( 'Repositories are now locked. You may begin maintenance in '. 'another terminal window. Keep this process running until '. 'you complete the maintenance, then confirm that you are ready to '. 'release the locks.')); while (!phutil_console_confirm('Ready to release the locks?')) { // Wait for the user to confirm that they're ready. } foreach ($locks as $key => $lock) { $lock['event']->saveWithLogs($lock['logs']); $engine = $lock['engine']; $engine->synchronizeWorkingCopyAfterWrite(); } echo tsprintf( "%s\n", pht('Done.')); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementReparseWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementReparseWorkflow.php
<?php final class PhabricatorRepositoryManagementReparseWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('reparse') ->setExamples('**reparse** [options] __commit__') ->setSynopsis( pht( '**reparse** __what__ __which_parts__ [--trace] [--force]'."\n\n". 'Rerun the Diffusion parser on specific commits and repositories. '. 'Mostly useful for debugging changes to Diffusion.'."\n\n". 'e.g. do same but exclude before yesterday (local time):'."\n". 'repository reparse --all TEST --change --min-date yesterday'."\n". 'repository reparse --all TEST --change --min-date "today -1 day".'. "\n\n". 'e.g. do same but exclude before 03/31/2013 (local time):'."\n". 'repository reparse --all TEST --change --min-date "03/31/2013"')) ->setArguments( array( array( 'name' => 'revision', 'wildcard' => true, ), array( 'name' => 'all', 'param' => 'repository', 'help' => pht( 'Reparse all commits in the specified repository.'), ), array( 'name' => 'min-date', 'param' => 'date', 'help' => pht( "Must be used with __%s__, this will exclude commits which ". "are earlier than __date__.\n". "Valid examples:\n". " 'today', 'today 2pm', '-1 hour', '-2 hours', '-24 hours',\n". " 'yesterday', 'today -1 day', 'yesterday 2pm', '2pm -1 day',\n". " 'last Monday', 'last Monday 14:00', 'last Monday 2pm',\n". " '31 March 2013', '31 Mar', '03/31', '03/31/2013',\n". "See __%s__ for more.", '--all', 'http://www.php.net/manual/en/datetime.formats.php'), ), array( 'name' => 'message', 'help' => pht('Reparse commit messages.'), ), array( 'name' => 'change', 'help' => pht('Reparse source changes.'), ), array( 'name' => 'publish', 'help' => pht( 'Publish changes: send email, publish Feed stories, run '. 'Herald rules, etc.'), ), array( 'name' => 'force', 'short' => 'f', 'help' => pht('Act noninteractively, without prompting.'), ), array( 'name' => 'background', 'help' => pht( 'Queue tasks for the daemons instead of running them in the '. 'foreground.'), ), array( 'name' => 'importing', 'help' => pht('Reparse all steps which have not yet completed.'), ), )); } public function execute(PhutilArgumentParser $args) { $console = PhutilConsole::getConsole(); $all_from_repo = $args->getArg('all'); $reparse_message = $args->getArg('message'); $reparse_change = $args->getArg('change'); $reparse_publish = $args->getArg('publish'); $reparse_what = $args->getArg('revision'); $force = $args->getArg('force'); $background = $args->getArg('background'); $min_date = $args->getArg('min-date'); $importing = $args->getArg('importing'); if (!$all_from_repo && !$reparse_what) { throw new PhutilArgumentUsageException( pht('Specify a commit or repository to reparse.')); } if ($all_from_repo && $reparse_what) { $commits = implode(', ', $reparse_what); throw new PhutilArgumentUsageException( pht( "Specify a commit or repository to reparse, not both:\n". "All from repo: %s\n". "Commit(s) to reparse: %s", $all_from_repo, $commits)); } $any_step = ($reparse_message || $reparse_change || $reparse_publish); if ($any_step && $importing) { throw new PhutilArgumentUsageException( pht( 'Choosing steps with "--importing" conflicts with flags which '. 'select specific steps.')); } else if ($any_step) { // OK. } else if ($importing) { // OK. } else if (!$any_step && !$importing) { throw new PhutilArgumentUsageException( pht( 'Specify which steps to reparse with "--message", "--change", '. 'and/or "--publish"; or "--importing" to run all missing steps.')); } $min_timestamp = false; if ($min_date) { $min_timestamp = strtotime($min_date); if (!$all_from_repo) { throw new PhutilArgumentUsageException( pht( 'You must use "--all" if you specify "--min-date".')); } // previous to PHP 5.1.0 you would compare with -1, instead of false if (false === $min_timestamp) { throw new PhutilArgumentUsageException( pht( "Supplied --min-date is not valid. See help for valid examples.\n". "Supplied value: '%s'\n", $min_date)); } } $commits = array(); if ($all_from_repo) { $repository = id(new PhabricatorRepositoryQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withIdentifiers(array($all_from_repo)) ->executeOne(); if (!$repository) { throw new PhutilArgumentUsageException( pht('Unknown repository "%s"!', $all_from_repo)); } $query = id(new DiffusionCommitQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withRepository($repository); if ($min_timestamp) { $query->withEpochRange($min_timestamp, null); } if ($importing) { $query->withImporting(true); } $commits = $query->execute(); if (!$commits) { throw new PhutilArgumentUsageException( pht( 'No commits have been discovered in the "%s" repository!', $repository->getDisplayName())); } } else { $commits = $this->loadNamedCommits($reparse_what); } if (!$background) { PhabricatorWorker::setRunAllTasksInProcess(true); } $progress = new PhutilConsoleProgressBar(); $progress->setTotal(count($commits)); $tasks = array(); foreach ($commits as $commit) { $repository = $commit->getRepository(); if ($importing) { $status = $commit->getImportStatus(); // Find the first missing import step and queue that up. $reparse_message = false; $reparse_change = false; $reparse_publish = false; if (!($status & PhabricatorRepositoryCommit::IMPORTED_MESSAGE)) { $reparse_message = true; } else if (!($status & PhabricatorRepositoryCommit::IMPORTED_CHANGE)) { $reparse_change = true; } else if (!($status & PhabricatorRepositoryCommit::IMPORTED_PUBLISH)) { $reparse_publish = true; } else { continue; } } $classes = array(); switch ($repository->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: if ($reparse_message) { $classes[] = 'PhabricatorRepositoryGitCommitMessageParserWorker'; } if ($reparse_change) { $classes[] = 'PhabricatorRepositoryGitCommitChangeParserWorker'; } break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: if ($reparse_message) { $classes[] = 'PhabricatorRepositoryMercurialCommitMessageParserWorker'; } if ($reparse_change) { $classes[] = 'PhabricatorRepositoryMercurialCommitChangeParserWorker'; } break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: if ($reparse_message) { $classes[] = 'PhabricatorRepositorySvnCommitMessageParserWorker'; } if ($reparse_change) { $classes[] = 'PhabricatorRepositorySvnCommitChangeParserWorker'; } break; } if ($reparse_publish) { $classes[] = 'PhabricatorRepositoryCommitPublishWorker'; } // NOTE: With "--importing", we queue the first unparsed step and let // it queue the other ones normally. Without "--importing", we queue // all the requested steps explicitly. $spec = array( 'commitPHID' => $commit->getPHID(), 'only' => !$importing, 'via' => 'reparse', ); foreach ($classes as $class) { try { PhabricatorWorker::scheduleTask( $class, $spec, array( 'priority' => PhabricatorWorker::PRIORITY_IMPORT, 'objectPHID' => $commit->getPHID(), 'containerPHID' => $repository->getPHID(), )); } catch (PhabricatorWorkerPermanentFailureException $ex) { // See T13315. We expect some reparse steps to occasionally raise // permanent failures: for example, because they are no longer // reachable. This is a routine condition, not a catastrophic // failure, so let the user know something happened but continue // reparsing any remaining commits. echo tsprintf( "<bg:yellow>** %s **</bg> %s\n", pht('WARN'), $ex->getMessage()); } } $progress->update(1); } $progress->done(); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementClusterizeWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementClusterizeWorkflow.php
<?php final class PhabricatorRepositoryManagementClusterizeWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('clusterize') ->setExamples('**clusterize** [options] __repository__ ...') ->setSynopsis( pht('Convert existing repositories into cluster repositories.')) ->setArguments( array( array( 'name' => 'service', 'param' => 'service', 'help' => pht( 'Cluster repository service in Almanac to move repositories '. 'into.'), ), array( 'name' => 'remove-service', 'help' => pht('Take repositories out of a cluster.'), ), array( 'name' => 'repositories', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $repositories = $this->loadRepositories($args, 'repositories'); if (!$repositories) { throw new PhutilArgumentUsageException( pht('Specify one or more repositories to clusterize.')); } $service_name = $args->getArg('service'); $remove_service = $args->getArg('remove-service'); if ($remove_service && $service_name) { throw new PhutilArgumentUsageException( pht('Specify --service or --remove-service, but not both.')); } if (!$service_name && !$remove_service) { throw new PhutilArgumentUsageException( pht('Specify --service or --remove-service.')); } if ($remove_service) { $service = null; } else { $service = id(new AlmanacServiceQuery()) ->setViewer($viewer) ->withNames(array($service_name)) ->withServiceTypes( array( AlmanacClusterRepositoryServiceType::SERVICETYPE, )) ->needActiveBindings(true) ->executeOne(); if (!$service) { throw new PhutilArgumentUsageException( pht( 'No repository service "%s" exists.', $service_name)); } } if ($service) { $service_phid = $service->getPHID(); $bindings = $service->getActiveBindings(); $unique_devices = array(); foreach ($bindings as $binding) { $unique_devices[$binding->getDevicePHID()] = $binding->getDevice(); } if (count($unique_devices) > 1) { $device_names = mpull($unique_devices, 'getName'); echo id(new PhutilConsoleBlock()) ->addParagraph( pht( 'Service "%s" is actively bound to more than one device (%s).', $service_name, implode(', ', $device_names))) ->addParagraph( pht( 'If you clusterize a repository onto this service it may be '. 'unclear which devices have up-to-date copies of the '. 'repository. If so, leader/follower ambiguity will freeze the '. 'repository. You may need to manually promote a device to '. 'unfreeze it. See "Ambiguous Leaders" in the documentation '. 'for discussion.')) ->drawConsoleString(); $prompt = pht('Continue anyway?'); if (!phutil_console_confirm($prompt)) { throw new PhutilArgumentUsageException( pht('User aborted the workflow.')); } } } else { $service_phid = null; } $content_source = $this->newContentSource(); $diffusion_phid = id(new PhabricatorDiffusionApplication())->getPHID(); foreach ($repositories as $repository) { $xactions = array(); $xactions[] = id(new PhabricatorRepositoryTransaction()) ->setTransactionType( PhabricatorRepositoryServiceTransaction::TRANSACTIONTYPE) ->setNewValue($service_phid); id(new PhabricatorRepositoryEditor()) ->setActor($viewer) ->setActingAsPHID($diffusion_phid) ->setContentSource($content_source) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->applyTransactions($repository, $xactions); if ($service) { echo tsprintf( "%s\n", pht( 'Moved repository "%s" to cluster service "%s".', $repository->getDisplayName(), $service->getName())); } else { echo tsprintf( "%s\n", pht( 'Removed repository "%s" from cluster service.', $repository->getDisplayName())); } } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementPullWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementPullWorkflow.php
<?php final class PhabricatorRepositoryManagementPullWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('pull') ->setExamples('**pull** __repository__ ...') ->setSynopsis(pht('Pull __repository__.')) ->setArguments( array( array( 'name' => 'verbose', 'help' => pht('Show additional debugging information.'), ), array( 'name' => 'ignore-locality', 'help' => pht( 'Pull even if the repository should not be present on this '. 'host according to repository cluster configuration.'), ), array( 'name' => 'repos', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $ignore_locality = (bool)$args->getArg('ignore-locality'); $repos = $this->loadLocalRepositories($args, 'repos', $ignore_locality); if (!$repos) { throw new PhutilArgumentUsageException( pht('Specify one or more repositories to pull.')); } $console = PhutilConsole::getConsole(); foreach ($repos as $repo) { $console->writeOut( "%s\n", pht( 'Pulling "%s"...', $repo->getDisplayName())); id(new PhabricatorRepositoryPullEngine()) ->setRepository($repo) ->setVerbose($args->getArg('verbose')) ->pullRepository(); } $console->writeOut("%s\n", pht('Done.')); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementParentsWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementParentsWorkflow.php
<?php final class PhabricatorRepositoryManagementParentsWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('parents') ->setExamples('**parents** [options] [__repository__] ...') ->setSynopsis( pht( 'Build parent caches in repositories that are missing the data, '. 'or rebuild them in a specific __repository__.')) ->setArguments( array( array( 'name' => 'repos', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $repos = $this->loadRepositories($args, 'repos'); if (!$repos) { $repos = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getViewer()) ->execute(); } $console = PhutilConsole::getConsole(); foreach ($repos as $repo) { $monogram = $repo->getMonogram(); if ($repo->isSVN()) { $console->writeOut( "%s\n", pht( 'Skipping "%s": Subversion repositories do not require this '. 'cache to be built.', $monogram)); continue; } $this->rebuildRepository($repo); } return 0; } private function rebuildRepository(PhabricatorRepository $repo) { $console = PhutilConsole::getConsole(); $console->writeOut("%s\n", pht('Rebuilding "%s"...', $repo->getMonogram())); $refs = id(new PhabricatorRepositoryRefCursorQuery()) ->setViewer($this->getViewer()) ->withRefTypes(array(PhabricatorRepositoryRefCursor::TYPE_BRANCH)) ->withRepositoryPHIDs(array($repo->getPHID())) ->needPositions(true) ->execute(); $graph = array(); foreach ($refs as $ref) { if (!$repo->shouldTrackBranch($ref->getRefName())) { continue; } $console->writeOut( "%s\n", pht('Rebuilding branch "%s"...', $ref->getRefName())); foreach ($ref->getPositionIdentifiers() as $commit) { if ($repo->isGit()) { $stream = new PhabricatorGitGraphStream($repo, $commit); } else { $stream = new PhabricatorMercurialGraphStream($repo, $commit); } $discover = array($commit); while ($discover) { $target = array_pop($discover); if (isset($graph[$target])) { continue; } $graph[$target] = $stream->getParents($target); foreach ($graph[$target] as $parent) { $discover[] = $parent; } } } } $console->writeOut( "%s\n", pht( 'Found %s total commit(s); updating...', phutil_count($graph))); $commit_table = id(new PhabricatorRepositoryCommit()); $commit_table_name = $commit_table->getTableName(); $conn_w = $commit_table->establishConnection('w'); $bar = id(new PhutilConsoleProgressBar()) ->setTotal(count($graph)); $need = array(); foreach ($graph as $child => $parents) { foreach ($parents as $parent) { $need[$parent] = $parent; } $need[$child] = $child; } $map = array(); foreach (array_chunk($need, 2048) as $chunk) { $rows = queryfx_all( $conn_w, 'SELECT id, commitIdentifier FROM %T WHERE commitIdentifier IN (%Ls) AND repositoryID = %d', $commit_table_name, $chunk, $repo->getID()); foreach ($rows as $row) { $map[$row['commitIdentifier']] = $row['id']; } } $insert_sql = array(); $delete_sql = array(); foreach ($graph as $child => $parents) { $names = $parents; $names[] = $child; foreach ($names as $name) { if (empty($map[$name])) { throw new Exception(pht('Unknown commit "%s"!', $name)); } } if (!$parents) { // Write an explicit 0 to indicate "no parents" instead of "no data". $insert_sql[] = qsprintf( $conn_w, '(%d, 0)', $map[$child]); } else { foreach ($parents as $parent) { $insert_sql[] = qsprintf( $conn_w, '(%d, %d)', $map[$child], $map[$parent]); } } $delete_sql[] = $map[$child]; $bar->update(1); } $commit_table->openTransaction(); foreach (PhabricatorLiskDAO::chunkSQL($delete_sql) as $chunk) { queryfx( $conn_w, 'DELETE FROM %T WHERE childCommitID IN (%LQ)', PhabricatorRepository::TABLE_PARENTS, $chunk); } foreach (PhabricatorLiskDAO::chunkSQL($insert_sql) as $chunk) { queryfx( $conn_w, 'INSERT INTO %T (childCommitID, parentCommitID) VALUES %LQ', PhabricatorRepository::TABLE_PARENTS, $chunk); } $commit_table->saveTransaction(); $bar->done(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementCacheWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementCacheWorkflow.php
<?php final class PhabricatorRepositoryManagementCacheWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('cache') ->setExamples( '**cache** [__options__] --commit __commit__ --path __path__') ->setSynopsis(pht('Manage the repository graph cache.')) ->setArguments( array( array( 'name' => 'commit', 'param' => 'commit', 'help' => pht('Specify a commit to look up.'), ), array( 'name' => 'path', 'param' => 'path', 'help' => pht('Specify a path to look up.'), ), )); } public function execute(PhutilArgumentParser $args) { $commit_name = $args->getArg('commit'); if ($commit_name === null) { throw new PhutilArgumentUsageException( pht( 'Specify a commit to look up with `%s`.', '--commit')); } $commit = $this->loadNamedCommit($commit_name); $path_name = $args->getArg('path'); if ($path_name === null) { throw new PhutilArgumentUsageException( pht( 'Specify a path to look up with `%s`.', '--path')); } $path_map = id(new DiffusionPathIDQuery(array($path_name))) ->loadPathIDs(); if (empty($path_map[$path_name])) { throw new PhutilArgumentUsageException( pht('Path "%s" is not unknown.', $path_name)); } $path_id = $path_map[$path_name]; $graph_cache = new PhabricatorRepositoryGraphCache(); $t_start = microtime(true); $cache_result = $graph_cache->loadLastModifiedCommitID( $commit->getID(), $path_id); $t_end = microtime(true); $console = PhutilConsole::getConsole(); $console->writeOut( "%s\n", pht('Query took %s ms.', new PhutilNumber(1000 * ($t_end - $t_start)))); if ($cache_result === false) { $console->writeOut("%s\n", pht('Not found in graph cache.')); } else if ($cache_result === null) { $console->writeOut( "%s\n", pht('Path not modified in any ancestor commit.')); } else { $last = id(new DiffusionCommitQuery()) ->setViewer($this->getViewer()) ->withIDs(array($cache_result)) ->executeOne(); if (!$last) { throw new Exception(pht('Cache returned bogus result!')); } $console->writeOut( "%s\n", pht( 'Path was last changed at %s.', $commit->getRepository()->formatCommitName( $last->getcommitIdentifier()))); } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementMarkReachableWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementMarkReachableWorkflow.php
<?php final class PhabricatorRepositoryManagementMarkReachableWorkflow extends PhabricatorRepositoryManagementWorkflow { private $untouchedCount = 0; protected function didConstruct() { $this ->setName('mark-reachable') ->setExamples('**mark-reachable** [__options__] __repository__ ...') ->setSynopsis( pht( 'Rebuild "unreachable" flags for commits in __repository__.')) ->setArguments( array( array( 'name' => 'repos', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $repos = $this->loadRepositories($args, 'repos'); if (!$repos) { throw new PhutilArgumentUsageException( pht( 'Specify one or more repositories to correct reachability status '. 'for.')); } foreach ($repos as $repo) { $this->markReachable($repo); } echo tsprintf( "%s\n", pht( 'Examined %s commits already in the correct state.', new PhutilNumber($this->untouchedCount))); echo tsprintf( "%s\n", pht('Done.')); return 0; } private function markReachable(PhabricatorRepository $repository) { if (!$repository->isGit() && !$repository->isHg()) { throw new PhutilArgumentUsageException( pht( 'Only Git and Mercurial repositories are supported, unable to '. 'operate on this repository ("%s").', $repository->getDisplayName())); } $viewer = $this->getViewer(); $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($repository) ->execute(); $flag = PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE; if ($repository->isGit()) { $graph = new PhabricatorGitGraphStream($repository); } else if ($repository->isHg()) { $graph = new PhabricatorMercurialGraphStream($repository); } foreach ($commits as $commit) { $identifier = $commit->getCommitIdentifier(); try { $graph->getCommitDate($identifier); $unreachable = false; } catch (Exception $ex) { $unreachable = true; } // The commit has proper reachability, so do nothing. if ($commit->isUnreachable() === $unreachable) { $this->untouchedCount++; continue; } if ($unreachable) { echo tsprintf( "%s: %s\n", $commit->getMonogram(), pht('Marking commit unreachable.')); $commit->writeImportStatusFlag($flag); } else { echo tsprintf( "%s: %s\n", $commit->getMonogram(), pht('Marking commit reachable.')); $commit->clearImportStatusFlag($flag); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementMovePathsWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementMovePathsWorkflow.php
<?php final class PhabricatorRepositoryManagementMovePathsWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('move-paths') ->setSynopsis(pht('Move repository local paths.')) ->setArguments( array( array( 'name' => 'from', 'param' => 'prefix', 'help' => pht('Move paths with this prefix.'), ), array( 'name' => 'to', 'param' => 'prefix', 'help' => pht('Replace matching prefixes with this string.'), ), array( 'name' => 'force', 'help' => pht('Apply changes without prompting.'), ), )); } public function execute(PhutilArgumentParser $args) { $console = PhutilConsole::getConsole(); $repos = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getViewer()) ->execute(); if (!$repos) { $console->writeErr("%s\n", pht('There are no repositories.')); return 0; } $from = $args->getArg('from'); if (!strlen($from)) { throw new Exception( pht( 'You must specify a path prefix to move from with --from.')); } $to = $args->getArg('to'); if (!strlen($to)) { throw new Exception( pht( 'You must specify a path prefix to move to with --to.')); } $is_force = $args->getArg('force'); $rows = array(); $any_changes = false; foreach ($repos as $repo) { $src = $repo->getLocalPath(); $row = array( 'repository' => $repo, 'move' => false, 'monogram' => $repo->getMonogram(), 'src' => $src, 'dst' => '', ); if (strncmp($src, $from, strlen($from))) { $row['action'] = pht('Ignore'); } else { $dst = $to.substr($src, strlen($from)); $row['action'] = tsprintf('**%s**', pht('Move')); $row['dst'] = $dst; $row['move'] = true; $any_changes = true; } $rows[] = $row; } $table = id(new PhutilConsoleTable()) ->addColumn( 'action', array( 'title' => pht('Action'), )) ->addColumn( 'monogram', array( 'title' => pht('Repository'), )) ->addColumn( 'src', array( 'title' => pht('Src'), )) ->addColumn( 'dst', array( 'title' => pht('Dst'), )) ->setBorders(true); foreach ($rows as $row) { $display = array_select_keys( $row, array( 'action', 'monogram', 'src', 'dst', )); $table->addRow($display); } $table->draw(); if (!$any_changes) { $console->writeOut(pht('No matching repositories.')."\n"); return 0; } $prompt = pht('Apply these changes?'); if (!$is_force && !phutil_console_confirm($prompt)) { throw new Exception(pht('Declining to apply changes.')); } foreach ($rows as $row) { if (empty($row['move'])) { continue; } $repo = $row['repository']; queryfx( $repo->establishConnection('w'), 'UPDATE %T SET localPath = %s WHERE id = %d', $repo->getTableName(), $row['dst'], $repo->getID()); } $console->writeOut(pht('Applied changes.')."\n"); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementImportingWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementImportingWorkflow.php
<?php final class PhabricatorRepositoryManagementImportingWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('importing') ->setExamples('**importing** __repository__ ...') ->setSynopsis( pht( 'Show commits in __repository__ which are still importing.')) ->setArguments( array( array( 'name' => 'simple', 'help' => pht('Show simpler output.'), ), array( 'name' => 'repos', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $repos = $this->loadRepositories($args, 'repos'); if (!$repos) { throw new PhutilArgumentUsageException( pht( 'Specify one or more repositories to find importing commits for.')); } $repos = mpull($repos, null, 'getID'); $table = new PhabricatorRepositoryCommit(); $conn_r = $table->establishConnection('r'); $rows = queryfx_all( $conn_r, 'SELECT repositoryID, commitIdentifier, importStatus FROM %T WHERE repositoryID IN (%Ld) AND (importStatus & %d) != %d AND (importStatus & %d) != %d', $table->getTableName(), array_keys($repos), PhabricatorRepositoryCommit::IMPORTED_ALL, PhabricatorRepositoryCommit::IMPORTED_ALL, PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE, PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE); $console = PhutilConsole::getConsole(); if ($rows) { foreach ($rows as $row) { $repo = $repos[$row['repositoryID']]; $identifier = $row['commitIdentifier']; $console->writeOut('%s', $repo->formatCommitName($identifier)); if (!$args->getArg('simple')) { $status = $row['importStatus']; $need = array(); if (!($status & PhabricatorRepositoryCommit::IMPORTED_MESSAGE)) { $need[] = pht('Message'); } if (!($status & PhabricatorRepositoryCommit::IMPORTED_CHANGE)) { $need[] = pht('Change'); } if (!($status & PhabricatorRepositoryCommit::IMPORTED_PUBLISH)) { $need[] = pht('Publish'); } $console->writeOut(' %s', implode(', ', $need)); } $console->writeOut("\n"); } } else { $console->writeErr( "%s\n", pht('No importing commits found.')); } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/management/PhabricatorRepositoryManagementDiscoverWorkflow.php
src/applications/repository/management/PhabricatorRepositoryManagementDiscoverWorkflow.php
<?php final class PhabricatorRepositoryManagementDiscoverWorkflow extends PhabricatorRepositoryManagementWorkflow { protected function didConstruct() { $this ->setName('discover') ->setExamples('**discover** [__options__] __repository__ ...') ->setSynopsis(pht('Discover commits in __repository__.')) ->setArguments( array( array( 'name' => 'verbose', 'help' => pht('Show additional debugging information.'), ), array( 'name' => 'repair', 'help' => pht( 'Discover all commits, even if they are ancestors of known '. 'commits. This can repair gaps in repository history.'), ), array( 'name' => 'repos', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $repos = $this->loadLocalRepositories($args, 'repos'); if (!$repos) { throw new PhutilArgumentUsageException( pht('Specify one or more repositories to discover.')); } $console = PhutilConsole::getConsole(); foreach ($repos as $repo) { $console->writeOut( "%s\n", pht( 'Discovering "%s"...', $repo->getDisplayName())); id(new PhabricatorRepositoryDiscoveryEngine()) ->setRepository($repo) ->setVerbose($args->getArg('verbose')) ->setRepairMode($args->getArg('repair')) ->discoverCommits(); } $console->writeOut("%s\n", pht('Done.')); return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false