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/repository/engine/PhabricatorRepositoryMirrorEngine.php
src/applications/repository/engine/PhabricatorRepositoryMirrorEngine.php
<?php /** * Pushes a repository to its mirrors. */ final class PhabricatorRepositoryMirrorEngine extends PhabricatorRepositoryEngine { public function pushToMirrors() { $viewer = $this->getViewer(); $repository = $this->getRepository(); if (!$repository->canMirror()) { return; } if (PhabricatorEnv::getEnvConfig('phabricator.silent')) { $this->log( pht('This software is running in silent mode; declining to mirror.')); return; } $uris = id(new PhabricatorRepositoryURIQuery()) ->setViewer($viewer) ->withRepositories(array($repository)) ->execute(); $io_mirror = PhabricatorRepositoryURI::IO_MIRROR; $exceptions = array(); foreach ($uris as $mirror) { if ($mirror->getIsDisabled()) { continue; } $io_type = $mirror->getEffectiveIOType(); if ($io_type != $io_mirror) { continue; } try { $this->pushRepositoryToMirror($repository, $mirror); } catch (Exception $ex) { $exceptions[] = $ex; } } if ($exceptions) { throw new PhutilAggregateException( pht( 'Exceptions occurred while mirroring the "%s" repository.', $repository->getDisplayName()), $exceptions); } } private function pushRepositoryToMirror( PhabricatorRepository $repository, PhabricatorRepositoryURI $mirror_uri) { $this->log( pht( 'Pushing to remote "%s"...', $mirror_uri->getEffectiveURI())); if ($repository->isGit()) { $this->pushToGitRepository($repository, $mirror_uri); } else if ($repository->isHg()) { $this->pushToHgRepository($repository, $mirror_uri); } else { throw new Exception(pht('Unsupported VCS!')); } } private function pushToGitRepository( PhabricatorRepository $repository, PhabricatorRepositoryURI $mirror_uri) { // See T5965. Test if we have any refs to mirror. If we have nothing, git // will exit with an error ("No refs in common and none specified; ...") // when we run "git push --mirror". // If we don't have any refs, we just bail out. (This is arguably sort of // the wrong behavior: to mirror an empty repository faithfully we should // delete everything in the remote.) list($stdout) = $repository->execxLocalCommand( 'for-each-ref --count 1 --'); if (!strlen($stdout)) { return; } $argv = array( 'push --verbose --mirror -- %P', $mirror_uri->getURIEnvelope(), ); $future = $mirror_uri->newCommandEngine() ->setArgv($argv) ->newFuture(); $future ->setCWD($repository->getLocalPath()) ->resolvex(); } private function pushToHgRepository( PhabricatorRepository $repository, PhabricatorRepositoryURI $mirror_uri) { $argv = array( 'push --verbose --rev tip -- %P', $mirror_uri->getURIEnvelope(), ); $future = $mirror_uri->newCommandEngine() ->setArgv($argv) ->newFuture(); try { $future ->setCWD($repository->getLocalPath()) ->resolvex(); } catch (CommandException $ex) { if (preg_match('/no changes found/', $ex->getStdout())) { // mercurial says nothing changed, but that's good } else { throw $ex; } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/engine/__tests__/PhabricatorWorkingCopyTestCase.php
src/applications/repository/engine/__tests__/PhabricatorWorkingCopyTestCase.php
<?php abstract class PhabricatorWorkingCopyTestCase extends PhabricatorTestCase { private $dirs = array(); protected function getPhabricatorTestCaseConfiguration() { return array( self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true, ); } protected function buildBareRepository($callsign) { $existing_repository = id(new PhabricatorRepositoryQuery()) ->withCallsigns(array($callsign)) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->executeOne(); if ($existing_repository) { $existing_repository->delete(); } $data_dir = dirname(__FILE__).'/data/'; $types = array( 'svn' => PhabricatorRepositoryType::REPOSITORY_TYPE_SVN, 'hg' => PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL, 'git' => PhabricatorRepositoryType::REPOSITORY_TYPE_GIT, ); $hits = array(); foreach ($types as $type => $const) { $path = $data_dir.$callsign.'.'.$type.'.tgz'; if (Filesystem::pathExists($path)) { $hits[$const] = $path; } } if (!$hits) { throw new Exception( pht( "No test data for callsign '%s'. Expected an archive ". "like '%s' in '%s'.", $callsign, "{$callsign}.git.tgz", $data_dir)); } if (count($hits) > 1) { throw new Exception( pht( "Expected exactly one archive matching callsign '%s', ". "found too many: %s", $callsign, implode(', ', $hits))); } $path = head($hits); $vcs_type = head_key($hits); $dir = PhutilDirectoryFixture::newFromArchive($path); $local = new TempFile('.ignore'); $user = $this->generateNewTestUser(); $repo = PhabricatorRepository::initializeNewRepository($user) ->setCallsign($callsign) ->setName(pht('Test Repo "%s"', $callsign)) ->setVersionControlSystem($vcs_type) ->setLocalPath(dirname($local).'/'.$callsign) ->setDetail('remote-uri', 'file://'.$dir->getPath().'/'); $this->didConstructRepository($repo); $repo->save(); // Keep the disk resources around until we exit. $this->dirs[] = $dir; $this->dirs[] = $local; return $repo; } protected function didConstructRepository(PhabricatorRepository $repository) { return; } protected function buildPulledRepository($callsign) { $repository = $this->buildBareRepository($callsign); id(new PhabricatorRepositoryPullEngine()) ->setRepository($repository) ->pullRepository(); return $repository; } protected function buildDiscoveredRepository($callsign) { $repository = $this->buildPulledRepository($callsign); id(new PhabricatorRepositoryDiscoveryEngine()) ->setRepository($repository) ->discoverCommits(); 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/engine/__tests__/PhabricatorWorkingCopyPullTestCase.php
src/applications/repository/engine/__tests__/PhabricatorWorkingCopyPullTestCase.php
<?php final class PhabricatorWorkingCopyPullTestCase extends PhabricatorWorkingCopyTestCase { public function testGitPullBasic() { $repo = $this->buildPulledRepository('GT'); $this->assertTrue(Filesystem::pathExists($repo->getLocalPath().'/HEAD')); } public function testHgPullBasic() { $this->requireBinaryForTest('hg'); $repo = $this->buildPulledRepository('HT'); $this->assertTrue(Filesystem::pathExists($repo->getLocalPath().'/.hg')); } public function testSVNPullBasic() { $repo = $this->buildPulledRepository('ST'); // We don't pull local clones for SVN, so we don't expect there to be // a working copy. $this->assertFalse(Filesystem::pathExists($repo->getLocalPath())); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/engine/__tests__/PhabricatorWorkingCopyDiscoveryTestCase.php
src/applications/repository/engine/__tests__/PhabricatorWorkingCopyDiscoveryTestCase.php
<?php final class PhabricatorWorkingCopyDiscoveryTestCase extends PhabricatorWorkingCopyTestCase { public function testSubversionCommitDiscovery() { $this->requireBinaryForTest('svn'); $refs = $this->discoverRefs('ST'); $this->assertEqual( array( 1368319433, 1368319448, ), mpull($refs, 'getEpoch'), pht('Commit Epochs')); } public function testMercurialCommitDiscovery() { $this->requireBinaryForTest('hg'); $refs = $this->discoverRefs('HT'); $this->assertEqual( array( '4a110ae879f473f2e82ffd032475caedd6cdba91', ), mpull($refs, 'getIdentifier')); } public function testGitCommitDiscovery() { $refs = $this->discoverRefs('GT'); $this->assertEqual( array( '763d4ab372445551c95fb5cccd1a7a223f5b2ac8', '41fa35914aa19c1aa6e57004d9745c05929c3563', ), mpull($refs, 'getIdentifier')); } private function discoverRefs($callsign) { $repo = $this->buildPulledRepository($callsign); $engine = id(new PhabricatorRepositoryDiscoveryEngine()) ->setRepository($repo); $refs = $engine->discoverCommits($repo); // The next time through, these should be cached as already discovered. $new_refs = $engine->discoverCommits($repo); $this->assertEqual(array(), $new_refs); return $refs; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/codex/PhabricatorRepositoryDestructibleCodex.php
src/applications/repository/codex/PhabricatorRepositoryDestructibleCodex.php
<?php final class PhabricatorRepositoryDestructibleCodex extends PhabricatorDestructibleCodex { public function getDestructionNotes() { $repository = $this->getObject(); $notes = array(); if ($repository->hasLocalWorkingCopy()) { $notes[] = pht( 'Database records for repository "%s" were destroyed, but this '. 'script does not remove working copies on disk. If you also want to '. 'destroy the repository working copy, manually remove "%s".', $repository->getDisplayName(), $repository->getLocalPath()); } return $notes; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/response/PhabricatorVCSResponse.php
src/applications/repository/response/PhabricatorVCSResponse.php
<?php /** * In Git, there appears to be no way to send a message which will be output * by `git clone http://...`, although the response code is visible. We send * the message in a header which is visible with "GIT_CURL_VERBOSE" if you * know where to look. * * In Mercurial, the HTTP status response message is printed to the console, so * we send human-readable text there. * * In Subversion, we can get it to print a custom message if we send an * invalid/unknown response code, although the output is ugly and difficult * to read. For known codes like 404, it prints a canned message. * * All VCS binaries ignore the response body; we include it only for * completeness. */ final class PhabricatorVCSResponse extends AphrontResponse { private $code; private $message; public function __construct($code, $message) { $this->code = $code; $message = head(phutil_split_lines($message)); $this->message = $message; } public function getMessage() { return $this->message; } public function buildResponseString() { return $this->code.' '.$this->message; } public function getHeaders() { $headers = array(); if ($this->getHTTPResponseCode() == 401) { $headers[] = array( 'WWW-Authenticate', 'Basic realm="Phabricator Repositories"', ); } $message = $this->getMessage(); if (strlen($message)) { foreach (phutil_split_lines($message, false) as $line) { $headers[] = array( 'X-Phabricator-Message', $line, ); } } return $headers; } public function getCacheHeaders() { return array(); } public function getHTTPResponseCode() { return $this->code; } public function getHTTPResponseMessage() { return $this->message; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/repository/constants/PhabricatorRepositoryType.php
src/applications/repository/constants/PhabricatorRepositoryType.php
<?php final class PhabricatorRepositoryType extends Phobject { const REPOSITORY_TYPE_GIT = 'git'; const REPOSITORY_TYPE_SVN = 'svn'; const REPOSITORY_TYPE_MERCURIAL = 'hg'; public static function getAllRepositoryTypes() { $map = self::getRepositoryTypeMap(); return ipull($map, 'name'); } public static function getNameForRepositoryType($type) { $spec = self::getRepositoryTypeSpec($type); return idx($spec, 'name', pht('Unknown ("%s")', $type)); } public static function getRepositoryTypeSpec($type) { $map = self::getRepositoryTypeMap(); return idx($map, $type, array()); } public static function getRepositoryTypeMap() { return array( self::REPOSITORY_TYPE_GIT => array( 'name' => pht('Git'), 'icon' => 'fa-git', 'image' => 'repo/repo-git.png', 'create.header' => pht('Create Git Repository'), 'create.subheader' => pht('Create a new Git repository.'), ), self::REPOSITORY_TYPE_MERCURIAL => array( 'name' => pht('Mercurial'), 'icon' => 'fa-code-fork', 'image' => 'repo/repo-hg.png', 'create.header' => pht('Create Mercurial Repository'), 'create.subheader' => pht('Create a new Mercurial repository.'), ), self::REPOSITORY_TYPE_SVN => array( 'name' => pht('Subversion'), 'icon' => 'fa-database', 'image' => 'repo/repo-svn.png', 'create.header' => pht('Create Subversion Repository'), 'create.subheader' => pht('Create a new Subversion repository.'), ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/home/controller/PhabricatorHomeMenuItemController.php
src/applications/home/controller/PhabricatorHomeMenuItemController.php
<?php final class PhabricatorHomeMenuItemController extends PhabricatorHomeController { public function shouldAllowPublic() { return true; } public function isGlobalDragAndDropUploadEnabled() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); // Test if we should show mobile users the menu or the page content: // if you visit "/", you just get the menu. If you visit "/home/", you // get the content. $is_content = $request->getURIData('content'); $application = 'PhabricatorHomeApplication'; $home_app = id(new PhabricatorApplicationQuery()) ->setViewer($viewer) ->withClasses(array($application)) ->withInstalled(true) ->executeOne(); $engine = id(new PhabricatorHomeProfileMenuEngine()) ->setProfileObject($home_app) ->setCustomPHID($viewer->getPHID()) ->setController($this) ->setShowContentCrumbs(false); if (!$is_content) { $engine->addContentPageClass('phabricator-home'); } return $engine->buildResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/home/controller/PhabricatorHomeController.php
src/applications/home/controller/PhabricatorHomeController.php
<?php abstract class PhabricatorHomeController extends PhabricatorController {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/home/menuitem/PhabricatorHomeProfileMenuItem.php
src/applications/home/menuitem/PhabricatorHomeProfileMenuItem.php
<?php final class PhabricatorHomeProfileMenuItem extends PhabricatorProfileMenuItem { const MENUITEMKEY = 'home.dashboard'; public function getMenuItemTypeName() { return pht('Built-in Homepage'); } private function getDefaultName() { return pht('Home'); } public function getDisplayName( PhabricatorProfileMenuItemConfiguration $config) { $default = $this->getDefaultName(); return $this->getNameFromConfig($config, $default); } public function getMenuItemTypeIcon() { return 'fa-home'; } public function canMakeDefault( PhabricatorProfileMenuItemConfiguration $config) { return true; } public function newPageContent( PhabricatorProfileMenuItemConfiguration $config) { $viewer = $this->getViewer(); return id(new PHUIHomeView()) ->setViewer($viewer); } public function buildEditEngineFields( PhabricatorProfileMenuItemConfiguration $config) { return array( id(new PhabricatorTextEditField()) ->setKey('name') ->setLabel(pht('Name')) ->setPlaceholder($this->getDefaultName()) ->setValue($config->getMenuItemProperty('name')), ); } protected function newMenuItemViewList( PhabricatorProfileMenuItemConfiguration $config) { $viewer = $this->getViewer(); $name = $this->getDisplayName($config); $icon = 'fa-home'; $uri = $this->getItemViewURI($config); $item = $this->newItemView() ->setURI($uri) ->setName($name) ->setIcon($icon); return array( $item, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/home/menuitem/PhabricatorHomeLauncherProfileMenuItem.php
src/applications/home/menuitem/PhabricatorHomeLauncherProfileMenuItem.php
<?php final class PhabricatorHomeLauncherProfileMenuItem extends PhabricatorProfileMenuItem { const MENUITEMKEY = 'home.launcher.menu'; public function getMenuItemTypeName() { return pht('More Applications'); } private function getDefaultName() { return pht('More Applications'); } public function getDisplayName( PhabricatorProfileMenuItemConfiguration $config) { $default = $this->getDefaultName(); return $this->getNameFromConfig($config, $default); } public function getMenuItemTypeIcon() { return 'fa-ellipsis-h'; } public function canHideMenuItem( PhabricatorProfileMenuItemConfiguration $config) { return false; } public function canMakeDefault( PhabricatorProfileMenuItemConfiguration $config) { return false; } public function buildEditEngineFields( PhabricatorProfileMenuItemConfiguration $config) { return array( id(new PhabricatorTextEditField()) ->setKey('name') ->setLabel(pht('Name')) ->setPlaceholder($this->getDefaultName()) ->setValue($config->getMenuItemProperty('name')), ); } protected function newMenuItemViewList( PhabricatorProfileMenuItemConfiguration $config) { $viewer = $this->getViewer(); $name = $this->getDisplayName($config); $icon = 'fa-ellipsis-h'; $uri = '/applications/'; $item = $this->newItemView() ->setURI($uri) ->setName($name) ->setIcon($icon); return array( $item, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/home/application/PhabricatorHomeApplication.php
src/applications/home/application/PhabricatorHomeApplication.php
<?php final class PhabricatorHomeApplication extends PhabricatorApplication { const DASHBOARD_DEFAULT = 'dashboard:default'; public function getBaseURI() { return '/home/'; } public function getName() { return pht('Home'); } public function getShortDescription() { return pht('Command Center'); } public function getIcon() { return 'fa-home'; } public function getRoutes() { return array( '/' => 'PhabricatorHomeMenuItemController', // NOTE: If you visit "/" on mobile, you get just the menu. If you visit // "/home/" on mobile, you get the content. From the normal desktop // UI, there's no difference between these pages. '/(?P<content>home)/' => array( '' => 'PhabricatorHomeMenuItemController', 'menu/' => $this->getProfileMenuRouting( 'PhabricatorHomeMenuItemController'), ), ); } public function isLaunchable() { return false; } public function getApplicationOrder() { return 9; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/home/view/PHUIHomeView.php
src/applications/home/view/PHUIHomeView.php
<?php final class PHUIHomeView extends AphrontTagView { protected function getTagName() { return null; } protected function getTagAttributes() { return array(); } protected function getTagContent() { require_celerity_resource('phabricator-dashboard-css'); $viewer = $this->getViewer(); $has_maniphest = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorManiphestApplication', $viewer); $has_diffusion = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorDiffusionApplication', $viewer); $has_differential = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorDifferentialApplication', $viewer); $revision_panel = null; if ($has_differential) { $revision_panel = $this->buildRevisionPanel(); } $tasks_panel = null; if ($has_maniphest) { $tasks_panel = $this->buildTasksPanel(); } $repository_panel = null; if ($has_diffusion) { $repository_panel = $this->buildRepositoryPanel(); } $feed_panel = $this->buildFeedPanel(); $dashboard = id(new AphrontMultiColumnView()) ->setFluidlayout(true) ->setGutter(AphrontMultiColumnView::GUTTER_LARGE); $main_panel = phutil_tag( 'div', array( 'class' => 'homepage-panel', ), array( $revision_panel, $tasks_panel, $repository_panel, )); $dashboard->addColumn($main_panel, 'thirds'); $side_panel = phutil_tag( 'div', array( 'class' => 'homepage-side-panel', ), array( $feed_panel, )); $dashboard->addColumn($side_panel, 'third'); $view = id(new PHUIBoxView()) ->addClass('dashboard-view') ->appendChild($dashboard); return $view; } private function buildRevisionPanel() { $viewer = $this->getViewer(); if (!$viewer->isLoggedIn()) { return null; } $panel = $this->newQueryPanel() ->setName(pht('Active Revisions')) ->setProperty('class', 'DifferentialRevisionSearchEngine') ->setProperty('key', 'active'); return $this->renderPanel($panel); } private function buildTasksPanel() { $viewer = $this->getViewer(); if ($viewer->isLoggedIn()) { $name = pht('Assigned Tasks'); $query = 'assigned'; } else { $name = pht('Open Tasks'); $query = 'open'; } $panel = $this->newQueryPanel() ->setName($name) ->setProperty('class', 'ManiphestTaskSearchEngine') ->setProperty('key', $query) ->setProperty('limit', 15); return $this->renderPanel($panel); } public function buildFeedPanel() { $panel = $this->newQueryPanel() ->setName(pht('Recent Activity')) ->setProperty('class', 'PhabricatorFeedSearchEngine') ->setProperty('key', 'all') ->setProperty('limit', 40); return $this->renderPanel($panel); } public function buildRepositoryPanel() { $panel = $this->newQueryPanel() ->setName(pht('Active Repositories')) ->setProperty('class', 'PhabricatorRepositorySearchEngine') ->setProperty('key', 'active') ->setProperty('limit', 5); return $this->renderPanel($panel); } private function newQueryPanel() { $panel_type = id(new PhabricatorDashboardQueryPanelType()) ->getPanelTypeKey(); return id(new PhabricatorDashboardPanel()) ->setPanelType($panel_type); } private function renderPanel(PhabricatorDashboardPanel $panel) { $viewer = $this->getViewer(); return id(new PhabricatorDashboardPanelRenderingEngine()) ->setViewer($viewer) ->setPanel($panel) ->setParentPanelPHIDs(array()) ->renderPanel(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/home/engine/PhabricatorHomeProfileMenuEngine.php
src/applications/home/engine/PhabricatorHomeProfileMenuEngine.php
<?php final class PhabricatorHomeProfileMenuEngine extends PhabricatorProfileMenuEngine { protected function isMenuEngineConfigurable() { return true; } public function getItemURI($path) { return "/home/menu/{$path}"; } protected function buildItemViewContent( PhabricatorProfileMenuItemConfiguration $item) { $viewer = $this->getViewer(); // Add content to the document so that you can drag-and-drop files onto // the home page or any home dashboard to upload them. $upload = id(new PhabricatorGlobalUploadTargetView()) ->setUser($viewer); $content = parent::buildItemViewContent($item); return array( $content, $upload, ); } protected function getBuiltinProfileItems($object) { $viewer = $this->getViewer(); $items = array(); $custom_phid = $this->getCustomPHID(); $applications = id(new PhabricatorApplicationQuery()) ->setViewer($viewer) ->withInstalled(true) ->withUnlisted(false) ->withLaunchable(true) ->execute(); // Default Home Dashboard $items[] = $this->newItem() ->setBuiltinKey(PhabricatorHomeConstants::ITEM_HOME) ->setMenuItemKey(PhabricatorHomeProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorHomeConstants::ITEM_APPS_LABEL) ->setMenuItemKey(PhabricatorLabelProfileMenuItem::MENUITEMKEY) ->setMenuItemProperties(array('name' => pht('Favorites'))); foreach ($applications as $application) { if (!$application->isPinnedByDefault($viewer)) { continue; } $properties = array( 'name' => '', 'application' => $application->getPHID(), ); $items[] = $this->newItem() ->setBuiltinKey($application->getPHID()) ->setMenuItemKey(PhabricatorApplicationProfileMenuItem::MENUITEMKEY) ->setMenuItemProperties($properties); } $items[] = $this->newItem() ->setBuiltinKey(PhabricatorHomeConstants::ITEM_LAUNCHER) ->setMenuItemKey(PhabricatorHomeLauncherProfileMenuItem::MENUITEMKEY); $items[] = $this->newDividerItem('tail'); $items[] = $this->newManageItem(); return $items; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/home/constants/PhabricatorHomeConstants.php
src/applications/home/constants/PhabricatorHomeConstants.php
<?php final class PhabricatorHomeConstants extends PhabricatorHomeController { const ITEM_HOME = 'home.dashboard'; const ITEM_LAUNCHER = 'home.launcher'; const ITEM_MANAGE = 'home.manage.menu'; const ITEM_APPS_LABEL = 'home.apps.label'; }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/DiffusionCommitAuditStatus.php
src/applications/diffusion/DiffusionCommitAuditStatus.php
<?php final class DiffusionCommitAuditStatus extends Phobject { private $key; private $spec = array(); const NONE = 'none'; const NEEDS_AUDIT = 'needs-audit'; const CONCERN_RAISED = 'concern-raised'; const PARTIALLY_AUDITED = 'partially-audited'; const AUDITED = 'audited'; const NEEDS_VERIFICATION = 'needs-verification'; public static function newModernKeys(array $values) { $map = self::getMap(); $modern = array(); foreach ($map as $key => $spec) { if (isset($spec['legacy'])) { $modern[$spec['legacy']] = $key; } } foreach ($values as $key => $value) { $values[$key] = idx($modern, $value, $value); } return $values; } public static function newForStatus($status) { $result = new self(); $result->key = $status; $map = self::getMap(); if (isset($map[$status])) { $result->spec = $map[$status]; } return $result; } public function getKey() { return $this->key; } public function getIcon() { return idx($this->spec, 'icon'); } public function getColor() { return idx($this->spec, 'color'); } public function getAnsiColor() { return idx($this->spec, 'color.ansi'); } public function getName() { return idx($this->spec, 'name', pht('Unknown ("%s")', $this->key)); } public function isNoAudit() { return ($this->key == self::NONE); } public function isNeedsAudit() { return ($this->key == self::NEEDS_AUDIT); } public function isConcernRaised() { return ($this->key == self::CONCERN_RAISED); } public function isNeedsVerification() { return ($this->key == self::NEEDS_VERIFICATION); } public function isPartiallyAudited() { return ($this->key == self::PARTIALLY_AUDITED); } public function isAudited() { return ($this->key == self::AUDITED); } public function getIsClosed() { return idx($this->spec, 'closed'); } public static function getOpenStatusConstants() { $constants = array(); foreach (self::getMap() as $key => $map) { if (!$map['closed']) { $constants[] = $key; } } return $constants; } public static function newOptions() { $map = self::getMap(); return ipull($map, 'name'); } public static function newDeprecatedOptions() { $map = self::getMap(); $results = array(); foreach ($map as $key => $spec) { if (isset($spec['legacy'])) { $results[$spec['legacy']] = $key; } } return $results; } private static function getMap() { return array( self::NONE => array( 'name' => pht('No Audits'), 'legacy' => 0, 'icon' => 'fa-check', 'color' => 'bluegrey', 'closed' => true, 'color.ansi' => null, ), self::NEEDS_AUDIT => array( 'name' => pht('Audit Required'), 'legacy' => 1, 'icon' => 'fa-exclamation-circle', 'color' => 'orange', 'closed' => false, 'color.ansi' => 'magenta', ), self::CONCERN_RAISED => array( 'name' => pht('Concern Raised'), 'legacy' => 2, 'icon' => 'fa-times-circle', 'color' => 'red', 'closed' => false, 'color.ansi' => 'red', ), self::PARTIALLY_AUDITED => array( 'name' => pht('Partially Audited'), 'legacy' => 3, 'icon' => 'fa-check-circle-o', 'color' => 'yellow', 'closed' => false, 'color.ansi' => 'yellow', ), self::AUDITED => array( 'name' => pht('Audited'), 'legacy' => 4, 'icon' => 'fa-check-circle', 'color' => 'green', 'closed' => true, 'color.ansi' => 'green', ), self::NEEDS_VERIFICATION => array( 'name' => pht('Needs Verification'), 'legacy' => 5, 'icon' => 'fa-refresh', 'color' => 'indigo', 'closed' => false, 'color.ansi' => 'magenta', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/DiffusionLintSaveRunner.php
src/applications/diffusion/DiffusionLintSaveRunner.php
<?php final class DiffusionLintSaveRunner extends Phobject { private $arc = 'arc'; private $severity = ArcanistLintSeverity::SEVERITY_ADVICE; private $all = false; private $chunkSize = 256; private $needsBlame = false; private $svnRoot; private $lintCommit; private $branch; private $conn; private $deletes = array(); private $inserts = array(); private $blame = array(); public function setArc($path) { $this->arc = $path; return $this; } public function setSeverity($string) { $this->severity = $string; return $this; } public function setAll($bool) { $this->all = $bool; return $this; } public function setChunkSize($number) { $this->chunkSize = $number; return $this; } public function setNeedsBlame($boolean) { $this->needsBlame = $boolean; return $this; } public function run($dir) { $working_copy = ArcanistWorkingCopyIdentity::newFromPath($dir); $configuration_manager = new ArcanistConfigurationManager(); $configuration_manager->setWorkingCopyIdentity($working_copy); $api = ArcanistRepositoryAPI::newAPIFromConfigurationManager( $configuration_manager); $this->svnRoot = id(new PhutilURI($api->getSourceControlPath()))->getPath(); if ($api instanceof ArcanistGitAPI) { $svn_fetch = $api->getGitConfig('svn-remote.svn.fetch'); list($this->svnRoot) = explode(':', $svn_fetch); if ($this->svnRoot != '') { $this->svnRoot = '/'.$this->svnRoot; } } $callsign = $configuration_manager->getConfigFromAnySource( 'repository.callsign'); $uuid = $api->getRepositoryUUID(); $remote_uri = $api->getRemoteURI(); $repository_query = id(new PhabricatorRepositoryQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()); if ($callsign) { $repository_query->withCallsigns(array($callsign)); } else if ($uuid) { $repository_query->withUUIDs(array($uuid)); } else if ($remote_uri) { $repository_query->withURIs(array($remote_uri)); } $repository = $repository_query->executeOne(); $branch_name = $api->getBranchName(); if (!$repository) { throw new Exception(pht('No repository was found.')); } $this->branch = PhabricatorRepositoryBranch::loadOrCreateBranch( $repository->getID(), $branch_name); $this->conn = $this->branch->establishConnection('w'); $this->lintCommit = null; if (!$this->all) { $this->lintCommit = $this->branch->getLintCommit(); } if ($this->lintCommit) { try { $commit = $this->lintCommit; if ($this->svnRoot) { $commit = $api->getCanonicalRevisionName('@'.$commit); } $all_files = $api->getChangedFiles($commit); } catch (ArcanistCapabilityNotSupportedException $ex) { $this->lintCommit = null; } } if (!$this->lintCommit) { $where = ($this->svnRoot ? qsprintf($this->conn, 'AND path LIKE %>', $this->svnRoot.'/') : ''); queryfx( $this->conn, 'DELETE FROM %T WHERE branchID = %d %Q', PhabricatorRepository::TABLE_LINTMESSAGE, $this->branch->getID(), $where); $all_files = $api->getAllFiles(); } $count = 0; $files = array(); foreach ($all_files as $file => $val) { $count++; if (!$this->lintCommit) { $file = $val; } else { $this->deletes[] = $this->svnRoot.'/'.$file; if ($val & ArcanistRepositoryAPI::FLAG_DELETED) { continue; } } $files[$file] = $file; if (count($files) >= $this->chunkSize) { $this->runArcLint($files); $files = array(); } } $this->runArcLint($files); $this->saveLintMessages(); $this->lintCommit = $api->getUnderlyingWorkingCopyRevision(); $this->branch->setLintCommit($this->lintCommit); $this->branch->save(); if ($this->blame) { $this->blameAuthors(); $this->blame = array(); } return $count; } private function runArcLint(array $files) { if (!$files) { return; } echo '.'; try { $future = new ExecFuture( '%C lint --severity %s --output json %Ls', $this->arc, $this->severity, $files); foreach (new LinesOfALargeExecFuture($future) as $json) { $paths = null; try { $paths = phutil_json_decode($json); } catch (PhutilJSONParserException $ex) { fprintf(STDERR, pht('Invalid JSON: %s', $json)."\n"); continue; } foreach ($paths as $path => $messages) { if (!isset($files[$path])) { continue; } foreach ($messages as $message) { $line = idx($message, 'line', 0); $this->inserts[] = qsprintf( $this->conn, '(%d, %s, %d, %s, %s, %s, %s)', $this->branch->getID(), $this->svnRoot.'/'.$path, $line, idx($message, 'code', ''), idx($message, 'severity', ''), idx($message, 'name', ''), idx($message, 'description', '')); if ($line && $this->needsBlame) { $this->blame[$path][$line] = true; } } if (count($this->deletes) >= 1024 || count($this->inserts) >= 256) { $this->saveLintMessages(); } } } } catch (Exception $ex) { fprintf(STDERR, $ex->getMessage()."\n"); } } private function saveLintMessages() { $this->conn->openTransaction(); foreach (array_chunk($this->deletes, 1024) as $paths) { queryfx( $this->conn, 'DELETE FROM %T WHERE branchID = %d AND path IN (%Ls)', PhabricatorRepository::TABLE_LINTMESSAGE, $this->branch->getID(), $paths); } foreach (array_chunk($this->inserts, 256) as $values) { queryfx( $this->conn, 'INSERT INTO %T (branchID, path, line, code, severity, name, description) VALUES %LQ', PhabricatorRepository::TABLE_LINTMESSAGE, $values); } $this->conn->saveTransaction(); $this->deletes = array(); $this->inserts = array(); } private function blameAuthors() { $repository = id(new PhabricatorRepositoryQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withIDs(array($this->branch->getRepositoryID())) ->executeOne(); $queries = array(); $futures = array(); foreach ($this->blame as $path => $lines) { $drequest = DiffusionRequest::newFromDictionary(array( 'user' => PhabricatorUser::getOmnipotentUser(), 'repository' => $repository, 'branch' => $this->branch->getName(), 'path' => $path, 'commit' => $this->lintCommit, )); // TODO: Restore blame information / generally fix this workflow. $query = DiffusionFileContentQuery::newFromDiffusionRequest($drequest); $queries[$path] = $query; $futures[$path] = new ImmediateFuture($query->executeInline()); } $authors = array(); $futures = id(new FutureIterator($futures)) ->limit(8); foreach ($futures as $path => $future) { $queries[$path]->loadFileContentFromFuture($future); list(, $rev_list, $blame_dict) = $queries[$path]->getBlameData(); foreach (array_keys($this->blame[$path]) as $line) { $commit_identifier = $rev_list[$line - 1]; $author = idx($blame_dict[$commit_identifier], 'authorPHID'); if ($author) { $authors[$author][$path][] = $line; } } } if ($authors) { $this->conn->openTransaction(); foreach ($authors as $author => $paths) { $where = array(); foreach ($paths as $path => $lines) { $where[] = qsprintf( $this->conn, '(path = %s AND line IN (%Ld))', $this->svnRoot.'/'.$path, $lines); } queryfx( $this->conn, 'UPDATE %T SET authorPHID = %s WHERE %LO', PhabricatorRepository::TABLE_LINTMESSAGE, $author, $where); } $this->conn->saveTransaction(); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionPushLogListController.php
src/applications/diffusion/controller/DiffusionPushLogListController.php
<?php final class DiffusionPushLogListController extends DiffusionLogController { public function handleRequest(AphrontRequest $request) { return id(new PhabricatorRepositoryPushLogSearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { return parent::buildApplicationCrumbs() ->addTextCrumb(pht('Push Logs'), $this->getApplicationURI('pushlog/')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionExternalController.php
src/applications/diffusion/controller/DiffusionExternalController.php
<?php final class DiffusionExternalController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $uri = $request->getStr('uri'); $id = $request->getStr('id'); $repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($request->getUser()) ->execute(); if ($uri) { $uri_path = id(new PhutilURI($uri))->getPath(); $matches = array(); // Try to figure out which tracked repository this external lives in by // comparing repository metadata. We look for an exact match, but accept // a partial match. foreach ($repositories as $key => $repository) { $remote_uri = new PhutilURI($repository->getRemoteURI()); if ($remote_uri->getPath() == $uri_path) { $matches[$key] = 1; } if ($repository->getPublicCloneURI() == $uri) { $matches[$key] = 2; } if ($repository->getRemoteURI() == $uri) { $matches[$key] = 3; } } arsort($matches); $best_match = head_key($matches); if ($best_match) { $repository = $repositories[$best_match]; $redirect = $repository->generateURI( array( 'action' => 'browse', 'branch' => $repository->getDefaultBranch(), 'commit' => $id, )); return id(new AphrontRedirectResponse())->setURI($redirect); } } // TODO: This is a rare query but does a table scan, add a key? $commits = id(new PhabricatorRepositoryCommit())->loadAllWhere( 'commitIdentifier = %s', $id); if (empty($commits)) { $desc = null; if (strlen($uri)) { $desc = pht('"%s", at "%s"', $uri, $id); } else { $desc = pht('"%s"', $id); } $content = id(new PHUIInfoView()) ->setTitle(pht('Unknown External')) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->appendChild(phutil_tag( 'p', array(), pht( 'This external (%s) does not appear in any tracked '. 'repository. It may exist in an untracked repository that '. 'Diffusion does not know about.', $desc))); } else if (count($commits) == 1) { $commit = head($commits); $repo = $repositories[$commit->getRepositoryID()]; $redirect = $repo->generateURI( array( 'action' => 'browse', 'branch' => $repo->getDefaultBranch(), 'commit' => $commit->getCommitIdentifier(), )); return id(new AphrontRedirectResponse())->setURI($redirect); } else { $rows = array(); foreach ($commits as $commit) { $repo = $repositories[$commit->getRepositoryID()]; $href = $repo->generateURI( array( 'action' => 'browse', 'branch' => $repo->getDefaultBranch(), 'commit' => $commit->getCommitIdentifier(), )); $rows[] = array( phutil_tag( 'a', array( 'href' => $href, ), $commit->getURI()), $commit->loadCommitData()->getSummary(), ); } $table = new AphrontTableView($rows); $table->setHeaders( array( pht('Commit'), pht('Description'), )); $table->setColumnClasses( array( 'pri', 'wide', )); $caption = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->appendChild( pht('This external reference matches multiple known commits.')); $content = new PHUIObjectBoxView(); $content->setHeaderText(pht('Multiple Matching Commits')); $content->setInfoView($caption); $content->setTable($table); } $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb(pht('External')); return $this->newPage() ->setTitle(pht('Unresolvable External')) ->setCrumbs($crumbs) ->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/diffusion/controller/DiffusionCompareController.php
src/applications/diffusion/controller/DiffusionCompareController.php
<?php final class DiffusionCompareController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); require_celerity_resource('diffusion-css'); if (!$repository->supportsBranchComparison()) { return $this->newDialog() ->setTitle(pht('Not Supported')) ->appendParagraph( pht( 'Branch comparison is not supported for this version control '. 'system.')) ->addCancelButton($this->getApplicationURI(), pht('Okay')); } $head_ref = $request->getStr('head'); $against_ref = $request->getStr('against'); $must_prompt = false; if (!$request->isFormPost()) { if (!strlen($head_ref)) { $head_ref = $drequest->getSymbolicCommit(); if (!strlen($head_ref)) { $head_ref = $drequest->getBranch(); } } if (!strlen($against_ref)) { $default_branch = $repository->getDefaultBranch(); if ($default_branch != $head_ref) { $against_ref = $default_branch; // If we filled this in by default, we want to prompt the user to // confirm that this is really what they want. $must_prompt = true; } } } $refs = $drequest->resolveRefs( array_filter( array( $head_ref, $against_ref, ))); $identical = false; if ($head_ref === $against_ref) { $identical = true; } else { if (count($refs) == 2) { if ($refs[$head_ref] === $refs[$against_ref]) { $identical = true; } } } if ($must_prompt || count($refs) != 2 || $identical) { return $this->buildCompareDialog( $head_ref, $against_ref, $refs, $identical); } if ($request->isFormPost()) { // Redirect to a stable URI that can be copy/pasted. $compare_uri = $drequest->generateURI( array( 'action' => 'compare', 'head' => $head_ref, 'against' => $against_ref, )); return id(new AphrontRedirectResponse())->setURI($compare_uri); } $crumbs = $this->buildCrumbs( array( 'view' => 'compare', )); $crumbs->setBorder(true); $pager = id(new PHUIPagerView()) ->readFromRequest($request); $history = null; try { $history_results = $this->callConduitWithDiffusionRequest( 'diffusion.historyquery', array( 'commit' => $head_ref, 'against' => $against_ref, 'path' => $drequest->getPath(), 'offset' => $pager->getOffset(), 'limit' => $pager->getPageSize() + 1, )); $history = DiffusionPathChange::newFromConduit( $history_results['pathChanges']); $history = $pager->sliceResults($history); $history_view = $this->newHistoryView( $history_results, $history, $pager, $head_ref, $against_ref); } catch (Exception $ex) { if ($repository->isImporting()) { $history_view = $this->renderStatusMessage( pht('Still Importing...'), pht( 'This repository is still importing. History is not yet '. 'available.')); } else { $history_view = $this->renderStatusMessage( pht('Unable to Retrieve History'), $ex->getMessage()); } } $header = id(new PHUIHeaderView()) ->setHeader( pht( 'Changes on %s but not %s', phutil_tag('em', array(), $head_ref), phutil_tag('em', array(), $against_ref))); $curtain = $this->buildCurtain($head_ref, $against_ref); $column_view = id(new PHUITwoColumnView()) ->setHeader($header) ->setCurtain($curtain) ->setMainColumn( array( $history_view, )); return $this->newPage() ->setTitle( array( $repository->getName(), $repository->getDisplayName(), )) ->setCrumbs($crumbs) ->appendChild($column_view); } private function buildCompareDialog( $head_ref, $against_ref, array $resolved, $identical) { $viewer = $this->getViewer(); $request = $this->getRequest(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $e_head = null; $e_against = null; $errors = array(); if ($request->isFormPost()) { if (!strlen($head_ref)) { $e_head = pht('Required'); $errors[] = pht( 'You must provide two different commits to compare.'); } else if (!isset($resolved[$head_ref])) { $e_head = pht('Not Found'); $errors[] = pht( 'Commit "%s" is not a valid commit in this repository.', $head_ref); } if (!strlen($against_ref)) { $e_against = pht('Required'); $errors[] = pht( 'You must provide two different commits to compare.'); } else if (!isset($resolved[$against_ref])) { $e_against = pht('Not Found'); $errors[] = pht( 'Commit "%s" is not a valid commit in this repository.', $against_ref); } if ($identical) { $e_head = pht('Identical'); $e_against = pht('Identical'); $errors[] = pht( 'Both references identify the same commit. You can not compare a '. 'commit against itself.'); } } $form = id(new AphrontFormView()) ->setViewer($viewer) ->appendControl( id(new AphrontFormTextControl()) ->setLabel(pht('Head')) ->setName('head') ->setError($e_head) ->setValue($head_ref)) ->appendControl( id(new AphrontFormTextControl()) ->setLabel(pht('Against')) ->setName('against') ->setError($e_against) ->setValue($against_ref)); $cancel_uri = $repository->generateURI( array( 'action' => 'browse', )); return $this->newDialog() ->setTitle(pht('Compare Against')) ->setWidth(AphrontDialogView::WIDTH_FORM) ->setErrors($errors) ->appendForm($form) ->addSubmitButton(pht('Compare')) ->addCancelButton($cancel_uri, pht('Cancel')); } private function buildCurtain($head_ref, $against_ref) { $viewer = $this->getViewer(); $request = $this->getRequest(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $curtain = $this->newCurtainView(null); $reverse_uri = $drequest->generateURI( array( 'action' => 'compare', 'head' => $against_ref, 'against' => $head_ref, )); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Reverse Comparison')) ->setHref($reverse_uri) ->setIcon('fa-refresh')); $compare_uri = $drequest->generateURI( array( 'action' => 'compare', 'head' => $head_ref, )); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Compare Against...')) ->setIcon('fa-code-fork') ->setWorkflow(true) ->setHref($compare_uri)); // TODO: Provide a "Show Diff" action. return $curtain; } private function newHistoryView( array $results, array $history, PHUIPagerView $pager, $head_ref, $against_ref) { $request = $this->getRequest(); $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); if (!$history) { return $this->renderStatusMessage( pht('Up To Date'), pht( 'There are no commits on %s that are not already on %s.', phutil_tag('strong', array(), $head_ref), phutil_tag('strong', array(), $against_ref))); } $history_view = id(new DiffusionCommitGraphView()) ->setViewer($viewer) ->setDiffusionRequest($drequest) ->setHistory($history) ->setParents($results['parents']) ->setFilterParents(true) ->setIsHead(!$pager->getOffset()) ->setIsTail(!$pager->getHasMorePages()); return $history_view; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionCommitController.php
src/applications/diffusion/controller/DiffusionCommitController.php
<?php final class DiffusionCommitController extends DiffusionController { const CHANGES_LIMIT = 100; private $commitParents; private $commitRefs; private $commitMerges; private $commitErrors; private $commitExists; public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); $viewer = $request->getUser(); $repository = $drequest->getRepository(); $commit_identifier = $drequest->getCommit(); // If this page is being accessed via "/source/xyz/commit/...", redirect // to the canonical URI. $repo_callsign = $request->getURIData('repositoryCallsign'); $has_callsign = $repo_callsign !== null && strlen($repo_callsign); $repo_id = $request->getURIData('repositoryID'); $has_id = $repo_id !== null && strlen($repo_id); if (!$has_callsign && !$has_id) { $canonical_uri = $repository->getCommitURI($commit_identifier); return id(new AphrontRedirectResponse()) ->setURI($canonical_uri); } if ($request->getStr('diff')) { return $this->buildRawDiffResponse($drequest); } $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($repository) ->withIdentifiers(array($commit_identifier)) ->needCommitData(true) ->needAuditRequests(true) ->needAuditAuthority(array($viewer)) ->setLimit(100) ->needIdentities(true) ->execute(); $multiple_results = count($commits) > 1; $crumbs = $this->buildCrumbs(array( 'commit' => !$multiple_results, )); $crumbs->setBorder(true); if (!$commits) { if (!$this->getCommitExists()) { return new Aphront404Response(); } $error = id(new PHUIInfoView()) ->setTitle(pht('Commit Still Parsing')) ->appendChild( pht( 'Failed to load the commit because the commit has not been '. 'parsed yet.')); $title = pht('Commit Still Parsing'); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($error); } else if ($multiple_results) { $warning_message = pht( 'The identifier %s is ambiguous and matches more than one commit.', phutil_tag( 'strong', array(), $commit_identifier)); $error = id(new PHUIInfoView()) ->setTitle(pht('Ambiguous Commit')) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->appendChild($warning_message); $list = id(new DiffusionCommitGraphView()) ->setViewer($viewer) ->setCommits($commits); $crumbs->addTextCrumb(pht('Ambiguous Commit')); $matched_commits = id(new PHUITwoColumnView()) ->setFooter(array( $error, $list, )); return $this->newPage() ->setTitle(pht('Ambiguous Commit')) ->setCrumbs($crumbs) ->appendChild($matched_commits); } else { $commit = head($commits); } $audit_requests = $commit->getAudits(); $commit_data = $commit->getCommitData(); $is_foreign = $commit_data->getCommitDetail('foreign-svn-stub'); $error_panel = null; $unpublished_panel = null; $hard_limit = 1000; if ($commit->isImported()) { $change_query = DiffusionPathChangeQuery::newFromDiffusionRequest( $drequest); $change_query->setLimit($hard_limit + 1); $changes = $change_query->loadChanges(); } else { $changes = array(); } $was_limited = (count($changes) > $hard_limit); if ($was_limited) { $changes = array_slice($changes, 0, $hard_limit); } $count = count($changes); $is_unreadable = false; $hint = null; if (!$count || $commit->isUnreachable()) { $hint = id(new DiffusionCommitHintQuery()) ->setViewer($viewer) ->withRepositoryPHIDs(array($repository->getPHID())) ->withOldCommitIdentifiers(array($commit->getCommitIdentifier())) ->executeOne(); if ($hint) { $is_unreadable = $hint->isUnreadable(); } } if ($is_foreign) { $subpath = $commit_data->getCommitDetail('svn-subpath'); $error_panel = new PHUIInfoView(); $error_panel->setTitle(pht('Commit Not Tracked')); $error_panel->setSeverity(PHUIInfoView::SEVERITY_WARNING); $error_panel->appendChild( pht( "This Diffusion repository is configured to track only one ". "subdirectory of the entire Subversion repository, and this commit ". "didn't affect the tracked subdirectory ('%s'), so no ". "information is available.", $subpath)); } else { $engine = PhabricatorMarkupEngine::newDifferentialMarkupEngine(); $engine->setConfig('viewer', $viewer); $commit_tag = $this->renderCommitHashTag($drequest); $header = id(new PHUIHeaderView()) ->setHeader(nonempty($commit->getSummary(), pht('Commit Detail'))) ->setHeaderIcon('fa-code-fork') ->addTag($commit_tag); if (!$commit->isAuditStatusNoAudit()) { $status = $commit->getAuditStatusObject(); $icon = $status->getIcon(); $color = $status->getColor(); $status = $status->getName(); $header->setStatus($icon, $color, $status); } $curtain = $this->buildCurtain($commit, $repository); $details = $this->buildPropertyListView( $commit, $commit_data, $audit_requests); $message = $commit_data->getCommitMessage(); $revision = $commit->getCommitIdentifier(); $message = $this->linkBugtraq($message); $message = $engine->markupText($message); $detail_list = new PHUIPropertyListView(); $detail_list->addTextContent( phutil_tag( 'div', array( 'class' => 'diffusion-commit-message phabricator-remarkup', ), $message)); if ($commit->isUnreachable()) { $did_rewrite = false; if ($hint) { if ($hint->isRewritten()) { $rewritten = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($repository) ->withIdentifiers(array($hint->getNewCommitIdentifier())) ->executeOne(); if ($rewritten) { $did_rewrite = true; $rewritten_uri = $rewritten->getURI(); $rewritten_name = $rewritten->getLocalName(); $rewritten_link = phutil_tag( 'a', array( 'href' => $rewritten_uri, ), $rewritten_name); $this->commitErrors[] = pht( 'This commit was rewritten after it was published, which '. 'changed the commit hash. This old version of the commit is '. 'no longer reachable from any branch, tag or ref. The new '. 'version of this commit is %s.', $rewritten_link); } } } if (!$did_rewrite) { $this->commitErrors[] = pht( 'This commit has been deleted in the repository: it is no longer '. 'reachable from any branch, tag, or ref.'); } } if (!$commit->isPermanentCommit()) { $nonpermanent_tag = id(new PHUITagView()) ->setType(PHUITagView::TYPE_SHADE) ->setName(pht('Unpublished')) ->setColor(PHUITagView::COLOR_ORANGE); $header->addTag($nonpermanent_tag); $holds = $commit_data->newPublisherHoldReasons(); $reasons = array(); foreach ($holds as $hold) { $reasons[] = array( phutil_tag('strong', array(), pht('%s:', $hold->getName())), ' ', $hold->getSummary(), ); } if (!$holds) { $reasons[] = pht('No further details are available.'); } $doc_href = PhabricatorEnv::getDoclink( 'Diffusion User Guide: Permanent Refs'); $doc_link = phutil_tag( 'a', array( 'href' => $doc_href, 'target' => '_blank', ), pht('Learn More')); $title = array( pht('Unpublished Commit'), pht(" \xC2\xB7 "), $doc_link, ); $unpublished_panel = id(new PHUIInfoView()) ->setTitle($title) ->setErrors($reasons) ->setSeverity(PHUIInfoView::SEVERITY_WARNING); } if ($this->getCommitErrors()) { $error_panel = id(new PHUIInfoView()) ->appendChild($this->getCommitErrors()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING); } } $timeline = $this->buildComments($commit); $merge_table = $this->buildMergesTable($commit); $show_changesets = false; $info_panel = null; $change_list = null; $change_table = null; if ($is_unreadable) { $info_panel = $this->renderStatusMessage( pht('Unreadable Commit'), pht( 'This commit has been marked as unreadable by an administrator. '. 'It may have been corrupted or created improperly by an external '. 'tool.')); } else if ($is_foreign) { // Don't render anything else. } else if (!$commit->isImported()) { $info_panel = $this->renderStatusMessage( pht('Still Importing...'), pht( 'This commit is still importing. Changes will be visible once '. 'the import finishes.')); } else if (!count($changes)) { $info_panel = $this->renderStatusMessage( pht('Empty Commit'), pht( 'This commit is empty and does not affect any paths.')); } else if ($was_limited) { $info_panel = $this->renderStatusMessage( pht('Very Large Commit'), pht( 'This commit is very large, and affects more than %d files. '. 'Changes are not shown.', $hard_limit)); } else if (!$this->getCommitExists()) { $info_panel = $this->renderStatusMessage( pht('Commit No Longer Exists'), pht('This commit no longer exists in the repository.')); } else { $show_changesets = true; // The user has clicked "Show All Changes", and we should show all the // changes inline even if there are more than the soft limit. $show_all_details = $request->getBool('show_all'); $change_header = id(new PHUIHeaderView()) ->setHeader(pht('Changes (%s)', new PhutilNumber($count))); $warning_view = null; if ($count > self::CHANGES_LIMIT && !$show_all_details) { $button = id(new PHUIButtonView()) ->setText(pht('Show All Changes')) ->setHref('?show_all=true') ->setTag('a') ->setIcon('fa-files-o'); $warning_view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setTitle(pht('Very Large Commit')) ->appendChild( pht('This commit is very large. Load each file individually.')); $change_header->addActionLink($button); } $changesets = DiffusionPathChange::convertToDifferentialChangesets( $viewer, $changes); // TODO: This table and panel shouldn't really be separate, but we need // to clean up the "Load All Files" interaction first. $change_table = $this->buildTableOfContents( $changesets, $change_header, $warning_view); $vcs = $repository->getVersionControlSystem(); switch ($vcs) { case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $vcs_supports_directory_changes = true; break; case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $vcs_supports_directory_changes = false; break; default: throw new Exception(pht('Unknown VCS.')); } $references = array(); foreach ($changesets as $key => $changeset) { $file_type = $changeset->getFileType(); if ($file_type == DifferentialChangeType::FILE_DIRECTORY) { if (!$vcs_supports_directory_changes) { unset($changesets[$key]); continue; } } $references[$key] = $drequest->generateURI( array( 'action' => 'rendering-ref', 'path' => $changeset->getFilename(), )); } // TODO: Some parts of the views still rely on properties of the // DifferentialChangeset. Make the objects ephemeral to make sure we don't // accidentally save them, and then set their ID to the appropriate ID for // this application (the path IDs). $path_ids = array_flip(mpull($changes, 'getPath')); foreach ($changesets as $changeset) { $changeset->makeEphemeral(); $changeset->setID($path_ids[$changeset->getFilename()]); } if ($count <= self::CHANGES_LIMIT || $show_all_details) { $visible_changesets = $changesets; } else { $visible_changesets = array(); $inlines = id(new DiffusionDiffInlineCommentQuery()) ->setViewer($viewer) ->withCommitPHIDs(array($commit->getPHID())) ->withPublishedComments(true) ->withPublishableComments(true) ->execute(); $inlines = mpull($inlines, 'newInlineCommentObject'); $path_ids = mpull($inlines, null, 'getPathID'); foreach ($changesets as $key => $changeset) { if (array_key_exists($changeset->getID(), $path_ids)) { $visible_changesets[$key] = $changeset; } } } $change_list_title = $commit->getDisplayName(); $change_list = new DifferentialChangesetListView(); $change_list->setTitle($change_list_title); $change_list->setChangesets($changesets); $change_list->setVisibleChangesets($visible_changesets); $change_list->setRenderingReferences($references); $change_list->setRenderURI($repository->getPathURI('diff/')); $change_list->setRepository($repository); $change_list->setUser($viewer); $change_list->setBackground(PHUIObjectBoxView::BLUE_PROPERTY); // TODO: Try to setBranch() to something reasonable here? $change_list->setStandaloneURI( $repository->getPathURI('diff/')); $change_list->setRawFileURIs( // TODO: Implement this, somewhat tricky if there's an octopus merge // or whatever? null, $repository->getPathURI('diff/?view=r')); $change_list->setInlineCommentControllerURI( '/diffusion/inline/edit/'.phutil_escape_uri($commit->getPHID()).'/'); } $add_comment = $this->renderAddCommentPanel( $commit, $timeline); $filetree = id(new DifferentialFileTreeEngine()) ->setViewer($viewer) ->setDisabled(!$show_changesets); if ($show_changesets) { $filetree->setChangesets($changesets); } $description_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Description')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild($detail_list); $detail_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Details')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild($details); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setCurtain($curtain) ->setMainColumn( array( $unpublished_panel, $error_panel, $description_box, $detail_box, $timeline, $merge_table, $info_panel, )) ->setFooter( array( $change_table, $change_list, $add_comment, )); $main_content = array( $crumbs, $view, ); $main_content = $filetree->newView($main_content); if (!$filetree->getDisabled()) { $change_list->setFormationView($main_content); } $page = $this->newPage() ->setTitle($commit->getDisplayName()) ->setPageObjectPHIDS(array($commit->getPHID())) ->appendChild($main_content); return $page; } private function buildPropertyListView( PhabricatorRepositoryCommit $commit, PhabricatorRepositoryCommitData $data, array $audit_requests) { $viewer = $this->getViewer(); $commit_phid = $commit->getPHID(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $view = id(new PHUIPropertyListView()) ->setUser($this->getRequest()->getUser()) ->setObject($commit); $edge_query = id(new PhabricatorEdgeQuery()) ->withSourcePHIDs(array($commit_phid)) ->withEdgeTypes(array( DiffusionCommitHasTaskEdgeType::EDGECONST, DiffusionCommitHasRevisionEdgeType::EDGECONST, DiffusionCommitRevertsCommitEdgeType::EDGECONST, DiffusionCommitRevertedByCommitEdgeType::EDGECONST, )); $edges = $edge_query->execute(); $task_phids = array_keys( $edges[$commit_phid][DiffusionCommitHasTaskEdgeType::EDGECONST]); $revision_phid = key( $edges[$commit_phid][DiffusionCommitHasRevisionEdgeType::EDGECONST]); $reverts_phids = array_keys( $edges[$commit_phid][DiffusionCommitRevertsCommitEdgeType::EDGECONST]); $reverted_by_phids = array_keys( $edges[$commit_phid][DiffusionCommitRevertedByCommitEdgeType::EDGECONST]); $phids = $edge_query->getDestinationPHIDs(array($commit_phid)); if ($data->getCommitDetail('reviewerPHID')) { $phids[] = $data->getCommitDetail('reviewerPHID'); } $phids[] = $commit->getCommitterDisplayPHID(); $phids[] = $commit->getAuthorDisplayPHID(); // NOTE: We should never normally have more than a single push log, but // it can occur naturally if a commit is pushed, then the branch it was // on is deleted, then the commit is pushed again (or through other similar // chains of events). This should be rare, but does not indicate a bug // or data issue. // NOTE: We never query push logs in SVN because the committer is always // the pusher and the commit time is always the push time; the push log // is redundant and we save a query by skipping it. $push_logs = array(); if ($repository->isHosted() && !$repository->isSVN()) { $push_logs = id(new PhabricatorRepositoryPushLogQuery()) ->setViewer($viewer) ->withRepositoryPHIDs(array($repository->getPHID())) ->withNewRefs(array($commit->getCommitIdentifier())) ->withRefTypes(array(PhabricatorRepositoryPushLog::REFTYPE_COMMIT)) ->execute(); foreach ($push_logs as $log) { $phids[] = $log->getPusherPHID(); } } $handles = array(); if ($phids) { $handles = $this->loadViewerHandles($phids); } $props = array(); if ($audit_requests) { $user_requests = array(); $other_requests = array(); foreach ($audit_requests as $audit_request) { if ($audit_request->isUser()) { $user_requests[] = $audit_request; } else { $other_requests[] = $audit_request; } } if ($user_requests) { $view->addProperty( pht('Auditors'), $this->renderAuditStatusView($commit, $user_requests)); } if ($other_requests) { $view->addProperty( pht('Group Auditors'), $this->renderAuditStatusView($commit, $other_requests)); } } $provenance_list = new PHUIStatusListView(); $author_view = $commit->newCommitAuthorView($viewer); if ($author_view) { $author_date = $data->getAuthorEpoch(); $author_date = phabricator_datetime($author_date, $viewer); $provenance_list->addItem( id(new PHUIStatusItemView()) ->setTarget($author_view) ->setNote(pht('Authored on %s', $author_date))); } if (!$commit->isAuthorSameAsCommitter()) { $committer_view = $commit->newCommitCommitterView($viewer); if ($committer_view) { $committer_date = $commit->getEpoch(); $committer_date = phabricator_datetime($committer_date, $viewer); $provenance_list->addItem( id(new PHUIStatusItemView()) ->setTarget($committer_view) ->setNote(pht('Committed on %s', $committer_date))); } } if ($push_logs) { $pushed_list = new PHUIStatusListView(); foreach ($push_logs as $push_log) { $pusher_date = $push_log->getEpoch(); $pusher_date = phabricator_datetime($pusher_date, $viewer); $pusher_view = $handles[$push_log->getPusherPHID()]->renderLink(); $provenance_list->addItem( id(new PHUIStatusItemView()) ->setTarget($pusher_view) ->setNote(pht('Pushed on %s', $pusher_date))); } } $view->addProperty(pht('Provenance'), $provenance_list); $reviewer_phid = $data->getCommitDetail('reviewerPHID'); if ($reviewer_phid) { $view->addProperty( pht('Reviewer'), $handles[$reviewer_phid]->renderLink()); } if ($revision_phid) { $view->addProperty( pht('Differential Revision'), $handles[$revision_phid]->renderLink()); } $parents = $this->getCommitParents(); if ($parents) { $view->addProperty( pht('Parents'), $viewer->renderHandleList(mpull($parents, 'getPHID'))); } if ($this->getCommitExists()) { $view->addProperty( pht('Branches'), phutil_tag( 'span', array( 'id' => 'commit-branches', ), pht('Unknown'))); $view->addProperty( pht('Tags'), phutil_tag( 'span', array( 'id' => 'commit-tags', ), pht('Unknown'))); $identifier = $commit->getCommitIdentifier(); $root = $repository->getPathURI("commit/{$identifier}"); Javelin::initBehavior( 'diffusion-commit-branches', array( $root.'/branches/' => 'commit-branches', $root.'/tags/' => 'commit-tags', )); } $refs = $this->getCommitRefs(); if ($refs) { $ref_links = array(); foreach ($refs as $ref_data) { $ref_links[] = phutil_tag( 'a', array( 'href' => $ref_data['href'], ), $ref_data['ref']); } $view->addProperty( pht('References'), phutil_implode_html(', ', $ref_links)); } if ($reverts_phids) { $view->addProperty( pht('Reverts'), $viewer->renderHandleList($reverts_phids)); } if ($reverted_by_phids) { $view->addProperty( pht('Reverted By'), $viewer->renderHandleList($reverted_by_phids)); } if ($task_phids) { $task_list = array(); foreach ($task_phids as $phid) { $task_list[] = $handles[$phid]->renderLink(); } $task_list = phutil_implode_html(phutil_tag('br'), $task_list); $view->addProperty( pht('Tasks'), $task_list); } return $view; } private function buildComments(PhabricatorRepositoryCommit $commit) { $timeline = $this->buildTransactionTimeline( $commit, new PhabricatorAuditTransactionQuery()); $timeline->setQuoteRef($commit->getMonogram()); return $timeline; } private function renderAddCommentPanel( PhabricatorRepositoryCommit $commit, $timeline) { $request = $this->getRequest(); $viewer = $request->getUser(); // TODO: This is pretty awkward, unify the CSS between Diffusion and // Differential better. require_celerity_resource('differential-core-view-css'); $comment_view = id(new DiffusionCommitEditEngine()) ->setViewer($viewer) ->buildEditEngineCommentView($commit); $comment_view->setTransactionTimeline($timeline); return $comment_view; } private function buildMergesTable(PhabricatorRepositoryCommit $commit) { $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $merges = $this->getCommitMerges(); if (!$merges) { return null; } $limit = $this->getMergeDisplayLimit(); $caption = null; if (count($merges) > $limit) { $merges = array_slice($merges, 0, $limit); $caption = new PHUIInfoView(); $caption->setSeverity(PHUIInfoView::SEVERITY_NOTICE); $caption->appendChild( pht( 'This commit merges a very large number of changes. '. 'Only the first %s are shown.', new PhutilNumber($limit))); } $commit_list = id(new DiffusionCommitGraphView()) ->setViewer($viewer) ->setDiffusionRequest($drequest) ->setHistory($merges); $panel = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Merged Changes')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setObjectList($commit_list->newObjectItemListView()); if ($caption) { $panel->setInfoView($caption); } return $panel; } private function buildCurtain( PhabricatorRepositoryCommit $commit, PhabricatorRepository $repository) { $request = $this->getRequest(); $viewer = $this->getViewer(); $curtain = $this->newCurtainView($commit); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $commit, PhabricatorPolicyCapability::CAN_EDIT); $id = $commit->getID(); $edit_uri = $this->getApplicationURI("/commit/edit/{$id}/"); $action = id(new PhabricatorActionView()) ->setName(pht('Edit Commit')) ->setHref($edit_uri) ->setIcon('fa-pencil') ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit); $curtain->addAction($action); $action = id(new PhabricatorActionView()) ->setName(pht('Download Raw Diff')) ->setHref($request->getRequestURI()->alter('diff', true)) ->setIcon('fa-download'); $curtain->addAction($action); $relationship_list = PhabricatorObjectRelationshipList::newForObject( $viewer, $commit); $relationship_submenu = $relationship_list->newActionMenu(); if ($relationship_submenu) { $curtain->addAction($relationship_submenu); } return $curtain; } private function buildRawDiffResponse(DiffusionRequest $drequest) { $diff_info = $this->callConduitWithDiffusionRequest( 'diffusion.rawdiffquery', array( 'commit' => $drequest->getCommit(), 'path' => $drequest->getPath(), )); $file_phid = $diff_info['filePHID']; $file = id(new PhabricatorFileQuery()) ->setViewer($this->getViewer()) ->withPHIDs(array($file_phid)) ->executeOne(); if (!$file) { throw new Exception( pht( 'Failed to load file ("%s") returned by "%s".', $file_phid, 'diffusion.rawdiffquery')); } return $file->getRedirectResponse(); } private function renderAuditStatusView( PhabricatorRepositoryCommit $commit, array $audit_requests) { assert_instances_of($audit_requests, 'PhabricatorRepositoryAuditRequest'); $viewer = $this->getViewer(); $view = new PHUIStatusListView(); foreach ($audit_requests as $request) { $status = $request->getAuditRequestStatusObject(); $item = new PHUIStatusItemView(); $item->setIcon( $status->getIconIcon(), $status->getIconColor(), $status->getStatusName()); $auditor_phid = $request->getAuditorPHID(); $target = $viewer->renderHandle($auditor_phid); $item->setTarget($target); if ($commit->hasAuditAuthority($viewer, $request)) { $item->setHighlighted(true); } $view->addItem($item); } return $view; } private function linkBugtraq($corpus) { $url = PhabricatorEnv::getEnvConfig('bugtraq.url'); if ($url === null || !strlen($url)) { return $corpus; } $regexes = PhabricatorEnv::getEnvConfig('bugtraq.logregex'); if (!$regexes) { return $corpus; } $parser = id(new PhutilBugtraqParser()) ->setBugtraqPattern("[[ {$url} | %BUGID% ]]") ->setBugtraqCaptureExpression(array_shift($regexes)); $select = array_shift($regexes); if ($select) { $parser->setBugtraqSelectExpression($select); } return $parser->processCorpus($corpus); } private function buildTableOfContents( array $changesets, $header, $info_view) { $drequest = $this->getDiffusionRequest(); $viewer = $this->getViewer(); $toc_view = id(new PHUIDiffTableOfContentsListView()) ->setUser($viewer) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY); if ($info_view) { $toc_view->setInfoView($info_view); } // TODO: This is hacky, we just want access to the linkX() methods on // DiffusionView. $diffusion_view = id(new DiffusionEmptyResultView()) ->setDiffusionRequest($drequest); $have_owners = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorOwnersApplication', $viewer); if (!$changesets) { $have_owners = false; } if ($have_owners) { if ($viewer->getPHID()) { $packages = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withStatuses(array(PhabricatorOwnersPackage::STATUS_ACTIVE)) ->withAuthorityPHIDs(array($viewer->getPHID())) ->execute(); $toc_view->setAuthorityPackages($packages); } $repository = $drequest->getRepository(); $repository_phid = $repository->getPHID(); $control_query = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withStatuses(array(PhabricatorOwnersPackage::STATUS_ACTIVE)) ->withControl($repository_phid, mpull($changesets, 'getFilename')); $control_query->execute(); } foreach ($changesets as $changeset_id => $changeset) { $path = $changeset->getFilename(); $anchor = $changeset->getAnchorName(); $history_link = $diffusion_view->linkHistory($path); $browse_link = $diffusion_view->linkBrowse( $path, array( 'type' => $changeset->getFileType(), )); $item = id(new PHUIDiffTableOfContentsItemView()) ->setChangeset($changeset) ->setAnchor($anchor) ->setContext( array( $history_link, ' ', $browse_link, )); if ($have_owners) { $packages = $control_query->getControllingPackagesForPath( $repository_phid, $changeset->getFilename()); $item->setPackages($packages); } $toc_view->addItem($item); } return $toc_view; } private function loadCommitState() { $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $commit = $drequest->getCommit(); // TODO: We could use futures here and resolve these calls in parallel. $exceptions = array(); try { $parent_refs = $this->callConduitWithDiffusionRequest( 'diffusion.commitparentsquery', array( 'commit' => $commit, )); if ($parent_refs) { $parents = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($repository) ->withIdentifiers($parent_refs) ->execute(); } else { $parents = array(); } $this->commitParents = $parents; } catch (Exception $ex) { $this->commitParents = false; $exceptions[] = $ex; } $merge_limit = $this->getMergeDisplayLimit(); try { if ($repository->isSVN()) { $this->commitMerges = array(); } else { $merges = $this->callConduitWithDiffusionRequest( 'diffusion.mergedcommitsquery', array( 'commit' => $commit, 'limit' => $merge_limit + 1, )); $this->commitMerges = DiffusionPathChange::newFromConduit($merges); } } catch (Exception $ex) { $this->commitMerges = false; $exceptions[] = $ex; } try { if ($repository->isGit()) { $refs = $this->callConduitWithDiffusionRequest( 'diffusion.refsquery', array( 'commit' => $commit, )); } else {
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
true
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionHistoryController.php
src/applications/diffusion/controller/DiffusionHistoryController.php
<?php final class DiffusionHistoryController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } require_celerity_resource('diffusion-css'); $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $pager = id(new PHUIPagerView()) ->readFromRequest($request); $params = array( 'commit' => $drequest->getCommit(), 'path' => $drequest->getPath(), 'offset' => $pager->getOffset(), 'limit' => $pager->getPageSize() + 1, ); $history_results = $this->callConduitWithDiffusionRequest( 'diffusion.historyquery', $params); $history = DiffusionPathChange::newFromConduit( $history_results['pathChanges']); $history = $pager->sliceResults($history); $history_list = id(new DiffusionCommitGraphView()) ->setViewer($viewer) ->setDiffusionRequest($drequest) ->setHistory($history); // NOTE: If we have a path (like "src/"), many nodes in the graph are // likely to be missing (since the path wasn't touched by those commits). // If we draw the graph, commits will often appear to be unrelated because // intermediate nodes are omitted. Just drop the graph. // The ideal behavior would be to load the entire graph and then connect // ancestors appropriately, but this would currrently be prohibitively // expensive in the general case. $show_graph = ($drequest->getPath() === null || !strlen($drequest->getPath())); if ($show_graph) { $history_list ->setParents($history_results['parents']) ->setIsHead(!$pager->getOffset()) ->setIsTail(!$pager->getHasMorePages()); } $header = $this->buildHeader($drequest); $crumbs = $this->buildCrumbs( array( 'branch' => true, 'path' => true, 'view' => 'history', )); $crumbs->setBorder(true); $title = array( pht('History'), $repository->getDisplayName(), ); $pager = id(new PHUIBoxView()) ->addClass('mlb') ->appendChild($pager); $tabs = $this->buildTabsView('history'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setTabs($tabs) ->setFooter(array( $history_list, $pager, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view) ->addClass('diffusion-history-view'); } private function buildHeader(DiffusionRequest $drequest) { $viewer = $this->getViewer(); $repository = $drequest->getRepository(); $no_path = $drequest->getPath() === null || !strlen($drequest->getPath()); if ($no_path) { $header_text = pht('History'); } else { $header_text = $this->renderPathLinks($drequest, $mode = 'history'); } $header = id(new PHUIHeaderView()) ->setUser($viewer) ->setHeader($header_text) ->setHeaderIcon('fa-clock-o'); if (!$repository->isSVN()) { $branch_tag = $this->renderBranchTag($drequest); $header->addTag($branch_tag); } if ($drequest->getSymbolicCommit()) { $symbolic_tag = $this->renderSymbolicCommit($drequest); $header->addTag($symbolic_tag); } return $header; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionPathCompleteController.php
src/applications/diffusion/controller/DiffusionPathCompleteController.php
<?php final class DiffusionPathCompleteController extends DiffusionController { protected function getRepositoryIdentifierFromRequest( AphrontRequest $request) { return $request->getStr('repositoryPHID'); } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $query_path = $request->getStr('q'); if (preg_match('@/$@', $query_path)) { $query_dir = $query_path; } else { $query_dir = dirname($query_path).'/'; } $query_dir = ltrim($query_dir, '/'); $browse_results = DiffusionBrowseResultSet::newFromConduit( $this->callConduitWithDiffusionRequest( 'diffusion.browsequery', array( 'path' => $query_dir, 'commit' => $drequest->getCommit(), ))); $paths = $browse_results->getPaths(); $output = array(); foreach ($paths as $path) { $full_path = $query_dir.$path->getPath(); if ($path->getFileType() == DifferentialChangeType::FILE_DIRECTORY) { $full_path .= '/'; } $output[] = array('/'.$full_path, null, substr(md5($full_path), 0, 7)); } return id(new AphrontAjaxResponse())->setContent($output); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionCommitBranchesController.php
src/applications/diffusion/controller/DiffusionCommitBranchesController.php
<?php final class DiffusionCommitBranchesController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $branch_limit = 10; $branches = DiffusionRepositoryRef::loadAllFromDictionaries( $this->callConduitWithDiffusionRequest( 'diffusion.branchquery', array( 'contains' => $drequest->getCommit(), 'limit' => $branch_limit + 1, 'branch' => null, ))); $has_more_branches = (count($branches) > $branch_limit); $branches = array_slice($branches, 0, $branch_limit); $branch_links = array(); foreach ($branches as $branch) { $branch_links[] = phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => 'browse', 'branch' => $branch->getShortName(), )), ), $branch->getShortName()); } if ($has_more_branches) { $branch_links[] = phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => 'branches', )), ), pht("More Branches\xE2\x80\xA6")); } return id(new AphrontAjaxResponse()) ->setContent($branch_links ? implode(', ', $branch_links) : pht('None')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryProfilePictureController.php
src/applications/diffusion/controller/DiffusionRepositoryProfilePictureController.php
<?php final class DiffusionRepositoryProfilePictureController extends DiffusionController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $id = $request->getURIData('id'); $repository = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->needProfileImage(true) ->needURIs(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$repository) { return new Aphront404Response(); } $supported_formats = PhabricatorFile::getTransformableImageFormats(); $e_file = true; $errors = array(); $done_uri = $repository->getURI(); if ($request->isFormPost()) { $phid = $request->getStr('phid'); $is_default = false; if ($phid == PhabricatorPHIDConstants::PHID_VOID) { $phid = null; $is_default = true; } else if ($phid) { $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($phid)) ->executeOne(); } else { if ($request->getFileExists('picture')) { $file = PhabricatorFile::newFromPHPUpload( $_FILES['picture'], array( 'authorPHID' => $viewer->getPHID(), 'canCDN' => true, )); } else { $e_file = pht('Required'); $errors[] = pht( 'You must choose a file when uploading a new profile picture.'); } } if (!$errors && !$is_default) { if (!$file->isTransformableImage()) { $e_file = pht('Not Supported'); $errors[] = pht( 'This server only supports these image formats: %s.', implode(', ', $supported_formats)); } else { $xform = PhabricatorFileTransform::getTransformByKey( PhabricatorFileThumbnailTransform::TRANSFORM_PROFILE); $xformed = $xform->executeTransform($file); } } if (!$errors) { if ($is_default) { $repository->setProfileImagePHID(null); } else { $repository->setProfileImagePHID($xformed->getPHID()); $xformed->attachToObject($repository->getPHID()); } $repository->save(); return id(new AphrontRedirectResponse())->setURI($done_uri); } } $title = pht('Edit Picture'); $form = id(new PHUIFormLayoutView()) ->setUser($viewer); $default_image = PhabricatorFile::loadBuiltin( $viewer, 'repo/code.png'); $images = array(); $current = $repository->getProfileImagePHID(); $has_current = false; if ($current) { $files = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($current)) ->execute(); if ($files) { $file = head($files); if ($file->isTransformableImage()) { $has_current = true; $images[$current] = array( 'uri' => $file->getBestURI(), 'tip' => pht('Current Picture'), ); } } } $builtins = array( 'repo/repo-git.png', 'repo/repo-svn.png', 'repo/repo-hg.png', 'repo/building.png', 'repo/cloud.png', 'repo/commit.png', 'repo/database.png', 'repo/desktop.png', 'repo/gears.png', 'repo/globe.png', 'repo/locked.png', 'repo/microchip.png', 'repo/mobile.png', 'repo/repo.png', 'repo/servers.png', ); foreach ($builtins as $builtin) { $file = PhabricatorFile::loadBuiltin($viewer, $builtin); $images[$file->getPHID()] = array( 'uri' => $file->getBestURI(), 'tip' => pht('Builtin Image'), ); } $images[PhabricatorPHIDConstants::PHID_VOID] = array( 'uri' => $default_image->getBestURI(), 'tip' => pht('Default Picture'), ); require_celerity_resource('people-profile-css'); Javelin::initBehavior('phabricator-tooltips', array()); $buttons = array(); foreach ($images as $phid => $spec) { $style = null; if (isset($spec['style'])) { $style = $spec['style']; } $button = javelin_tag( 'button', array( 'class' => 'button-grey profile-image-button', 'sigil' => 'has-tooltip', 'meta' => array( 'tip' => $spec['tip'], 'size' => 300, ), ), phutil_tag( 'img', array( 'height' => 50, 'width' => 50, 'src' => $spec['uri'], ))); $button = array( phutil_tag( 'input', array( 'type' => 'hidden', 'name' => 'phid', 'value' => $phid, )), $button, ); $button = phabricator_form( $viewer, array( 'class' => 'profile-image-form', 'method' => 'POST', ), $button); $buttons[] = $button; } if ($has_current) { $form->appendChild( id(new AphrontFormMarkupControl()) ->setLabel(pht('Current Picture')) ->setValue(array_shift($buttons))); } $form->appendChild( id(new AphrontFormMarkupControl()) ->setLabel(pht('Use Picture')) ->setValue($buttons)); $form_box = id(new PHUIObjectBoxView()) ->setHeaderText($title) ->setFormErrors($errors) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setForm($form); $upload_form = id(new AphrontFormView()) ->setUser($viewer) ->setEncType('multipart/form-data') ->appendChild( id(new AphrontFormFileControl()) ->setName('picture') ->setLabel(pht('Upload Picture')) ->setError($e_file) ->setCaption( pht('Supported formats: %s', implode(', ', $supported_formats)))) ->appendChild( id(new AphrontFormSubmitControl()) ->addCancelButton($done_uri) ->setValue(pht('Upload Picture'))); $header = id(new PHUIHeaderView()) ->setHeader(pht('Edit Repository Picture')) ->setHeaderIcon('fa-camera-retro'); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($repository->getName(), $repository->getURI()); $crumbs->addTextCrumb(pht('Edit Picture')); $crumbs->setBorder(true); $upload_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Upload New Picture')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setForm($upload_form); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $form_box, $upload_box, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionIdentityViewController.php
src/applications/diffusion/controller/DiffusionIdentityViewController.php
<?php final class DiffusionIdentityViewController extends DiffusionController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $identity = id(new PhabricatorRepositoryIdentityQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); if (!$identity) { return new Aphront404Response(); } $title = pht('Identity %d', $identity->getID()); $curtain = $this->buildCurtain($identity); $header = id(new PHUIHeaderView()) ->setUser($viewer) ->setHeader($identity->getIdentityShortName()) ->setHeaderIcon('fa-globe'); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb( pht('Identities'), $this->getApplicationURI('identity/')); $crumbs->addTextCrumb($identity->getObjectName()); $crumbs->setBorder(true); $timeline = $this->buildTransactionTimeline( $identity, new PhabricatorRepositoryIdentityTransactionQuery()); $timeline->setShouldTerminate(true); $properties = $this->buildPropertyList($identity); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setCurtain($curtain) ->setMainColumn(array( $properties, $timeline, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild( array( $view, )); } private function buildCurtain(PhabricatorRepositoryIdentity $identity) { $viewer = $this->getViewer(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $identity, PhabricatorPolicyCapability::CAN_EDIT); $id = $identity->getID(); $edit_uri = $this->getApplicationURI("identity/edit/{$id}/"); $curtain = $this->newCurtainView($identity); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Identity')) ->setHref($edit_uri) ->setWorkflow(!$can_edit) ->setDisabled(!$can_edit)); return $curtain; } private function buildPropertyList( PhabricatorRepositoryIdentity $identity) { $viewer = $this->getViewer(); $properties = id(new PHUIPropertyListView()) ->setViewer($viewer); $properties->addProperty( pht('Email Address'), $identity->getEmailAddress()); $effective_phid = $identity->getCurrentEffectiveUserPHID(); $automatic_phid = $identity->getAutomaticGuessedUserPHID(); $manual_phid = $identity->getManuallySetUserPHID(); if ($effective_phid) { $tag = id(new PHUITagView()) ->setType(PHUITagView::TYPE_SHADE) ->setColor('green') ->setIcon('fa-check') ->setName('Assigned'); } else { $tag = id(new PHUITagView()) ->setType(PHUITagView::TYPE_SHADE) ->setColor('indigo') ->setIcon('fa-bomb') ->setName('Unassigned'); } $properties->addProperty( pht('Effective User'), $this->buildPropertyValue($effective_phid)); $properties->addProperty( pht('Automatically Detected User'), $this->buildPropertyValue($automatic_phid)); $properties->addProperty( pht('Assigned To'), $this->buildPropertyValue($manual_phid)); $header = id(new PHUIHeaderView()) ->setHeader(array(pht('Identity Assignments'), $tag)); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addPropertyList($properties); } private function buildPropertyValue($value) { $viewer = $this->getViewer(); if ($value == DiffusionIdentityUnassignedDatasource::FUNCTION_TOKEN) { return phutil_tag('em', array(), pht('Explicitly Unassigned')); } else if (!$value) { return phutil_tag('em', array(), pht('None')); } else { return $viewer->renderHandle($value); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryEditPublishingController.php
src/applications/diffusion/controller/DiffusionRepositoryEditPublishingController.php
<?php final class DiffusionRepositoryEditPublishingController extends DiffusionRepositoryManageController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $panel_uri = id(new DiffusionRepositoryBasicsManagementPanel()) ->setRepository($repository) ->getPanelURI(); if ($request->isFormPost()) { if ($repository->isPublishingDisabled()) { $new_status = true; } else { $new_status = false; } $xaction = id(new PhabricatorRepositoryTransaction()) ->setTransactionType( PhabricatorRepositoryNotifyTransaction::TRANSACTIONTYPE) ->setNewValue($new_status); $editor = id(new PhabricatorRepositoryEditor()) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSourceFromRequest($request) ->setActor($viewer) ->applyTransactions($repository, array($xaction)); return id(new AphrontReloadResponse())->setURI($panel_uri); } $body = array(); if (!$repository->isPublishingDisabled()) { $title = pht('Disable Publishing'); $body[] = pht( 'If you disable publishing for this repository, new commits '. 'will not: send email, publish feed stories, trigger audits, or '. 'trigger Herald.'); $body[] = pht( 'This option is most commonly used to temporarily allow a major '. 'repository maintenance operation (like a history rewrite) to '. 'occur with minimal disruption to users.'); $submit = pht('Disable Publishing'); } else { $title = pht('Reactivate Publishing'); $body[] = pht( 'If you reactivate publishing for this repository, new commits '. 'that become reachable from permanent refs will: send email, '. 'publish feed stories, trigger audits, and trigger Herald.'); $body[] = pht( 'Commits which became reachable from a permanent ref while '. 'publishing was disabled will not trigger these actions '. 'retroactively.'); $submit = pht('Reactivate Publishing'); } $dialog = $this->newDialog() ->setTitle($title) ->addSubmitButton($submit) ->addCancelButton($panel_uri); foreach ($body as $graph) { $dialog->appendParagraph($graph); } return $dialog; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryURIDisableController.php
src/applications/diffusion/controller/DiffusionRepositoryURIDisableController.php
<?php final class DiffusionRepositoryURIDisableController extends DiffusionController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $id = $request->getURIData('id'); $uri = id(new PhabricatorRepositoryURIQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->withRepositories(array($repository)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$uri) { return new Aphront404Response(); } $is_disabled = $uri->getIsDisabled(); $view_uri = $uri->getViewURI(); if ($uri->isBuiltin()) { return $this->newDialog() ->setTitle(pht('Builtin URI')) ->appendParagraph( pht( 'You can not manually disable builtin URIs. To hide a builtin '. 'URI, configure its "Display" behavior instead.')) ->addCancelButton($view_uri); } if ($request->isFormPost()) { $xactions = array(); $xactions[] = id(new PhabricatorRepositoryURITransaction()) ->setTransactionType(PhabricatorRepositoryURITransaction::TYPE_DISABLE) ->setNewValue(!$is_disabled); $editor = id(new DiffusionURIEditor()) ->setActor($viewer) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSourceFromRequest($request) ->applyTransactions($uri, $xactions); return id(new AphrontRedirectResponse())->setURI($view_uri); } if ($is_disabled) { $title = pht('Enable URI'); $body = pht( 'Enable this URI? Any configured behaviors will begin working '. 'again.'); $button = pht('Enable URI'); } else { $title = pht('Disable URI'); $body = pht( 'Disable this URI? It will no longer be observed, fetched, mirrored, '. 'served or shown to users.'); $button = pht('Disable URI'); } return $this->newDialog() ->setTitle($title) ->appendParagraph($body) ->addCancelButton($view_uri) ->addSubmitButton($button); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryListController.php
src/applications/diffusion/controller/DiffusionRepositoryListController.php
<?php final class DiffusionRepositoryListController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $items = array(); $items[] = id(new PHUIListItemView()) ->setType(PHUIListItemView::TYPE_LABEL) ->setName(pht('Commits')); $items[] = id(new PHUIListItemView()) ->setName(pht('Browse Commits')) ->setHref($this->getApplicationURI('commit/')); $items[] = id(new PHUIListItemView()) ->setType(PHUIListItemView::TYPE_LABEL) ->setName(pht('Identities')); $items[] = id(new PHUIListItemView()) ->setName(pht('Browse Identities')) ->setHref($this->getApplicationURI('identity/')); return id(new PhabricatorRepositorySearchEngine()) ->setController($this) ->setNavigationItems($items) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); id(new DiffusionRepositoryEditEngine()) ->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/diffusion/controller/DiffusionRepositoryManageController.php
src/applications/diffusion/controller/DiffusionRepositoryManageController.php
<?php abstract class DiffusionRepositoryManageController extends DiffusionController { protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); if ($this->hasDiffusionRequest()) { $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $crumbs->addTextCrumb( $repository->getDisplayName(), $repository->getURI()); $crumbs->addTextCrumb( pht('Manage'), $repository->getPathURI('manage/')); } return $crumbs; } public function newBox($title, $content, $action = null) { $header = id(new PHUIHeaderView()) ->setHeader($title); if ($action) { $header->addActionItem($action); } $view = id(new PHUIObjectBoxView()) ->setHeader($header) ->appendChild($content) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG); 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/diffusion/controller/DiffusionRepositoryDefaultController.php
src/applications/diffusion/controller/DiffusionRepositoryDefaultController.php
<?php final class DiffusionRepositoryDefaultController extends DiffusionController { public function shouldAllowPublic() { // NOTE: We allow public access to this controller because it handles // redirecting paths that are missing a trailing "/". We need to manually // redirect these instead of relying on the automatic redirect because // some VCS requests may omit the slashes. See T12035, and below, for some // discussion. return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } // NOTE: This controller is just here to make sure we call // willBeginExecution() on any /diffusion/X/ URI, so we can intercept // `git`, `hg` and `svn` HTTP protocol requests. // If we made it here, it's probably because the user copy-pasted a // clone URI with "/anything.git" at the end into their web browser. // Send them to the canonical repository URI. $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); return id(new AphrontRedirectResponse()) ->setURI($repository->getURI()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionInlineCommentController.php
src/applications/diffusion/controller/DiffusionInlineCommentController.php
<?php final class DiffusionInlineCommentController extends PhabricatorInlineCommentController { protected function newInlineCommentQuery() { return new DiffusionDiffInlineCommentQuery(); } protected function newContainerObject() { return $this->loadCommit(); } private function getCommitPHID() { return $this->getRequest()->getURIData('phid'); } private function loadCommit() { $viewer = $this->getViewer(); $commit_phid = $this->getCommitPHID(); $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withPHIDs(array($commit_phid)) ->executeOne(); if (!$commit) { throw new Exception(pht('Invalid commit PHID "%s"!', $commit_phid)); } return $commit; } protected function createComment() { $commit = $this->loadCommit(); // TODO: Write a real PathQuery object? $path_id = $this->getChangesetID(); $path = queryfx_one( id(new PhabricatorRepository())->establishConnection('r'), 'SELECT path FROM %T WHERE id = %d', PhabricatorRepository::TABLE_PATH, $path_id); if (!$path) { throw new Exception(pht('Invalid path ID!')); } return id(new PhabricatorAuditInlineComment()) ->setCommitPHID($commit->getPHID()) ->setPathID($path_id); } protected function loadCommentForDone($id) { $viewer = $this->getViewer(); $inline = $this->loadCommentByID($id); if (!$inline) { throw new Exception(pht('Failed to load comment "%d".', $id)); } $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withPHIDs(array($inline->getCommitPHID())) ->executeOne(); if (!$commit) { throw new Exception(pht('Failed to load commit.')); } $owner_phid = $commit->getAuthorPHID(); $viewer_phid = $viewer->getPHID(); $viewer_is_owner = ($owner_phid && ($owner_phid == $viewer_phid)); $viewer_is_author = ($viewer_phid == $inline->getAuthorPHID()); $is_draft = $inline->isDraft(); if ($viewer_is_owner) { // You can mark inlines on your own commits as "Done". } else if ($viewer_is_author && $is_draft) { // You can mark your own unsubmitted inlines as "Done". } else { throw new Exception( pht( 'You can not mark this comment as complete: you did not author '. 'the commit and the comment is not a draft you wrote.')); } return $inline; } protected function canEditInlineComment( PhabricatorUser $viewer, PhabricatorAuditInlineComment $inline) { // Only the author may edit a comment. if ($inline->getAuthorPHID() != $viewer->getPHID()) { return false; } // Saved comments may not be edited. if ($inline->getTransactionPHID()) { return false; } // Inline must be attached to the active revision. if ($inline->getCommitPHID() != $this->getCommitPHID()) { return false; } return true; } protected function loadObjectOwnerPHID( PhabricatorInlineComment $inline) { return $this->loadCommit()->getAuthorPHID(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryEditUpdateController.php
src/applications/diffusion/controller/DiffusionRepositoryEditUpdateController.php
<?php final class DiffusionRepositoryEditUpdateController extends DiffusionRepositoryManageController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $panel_uri = id(new DiffusionRepositoryBasicsManagementPanel()) ->setRepository($repository) ->getPanelURI(); if ($request->isFormPost()) { $params = array( 'repositories' => array( $repository->getPHID(), ), ); id(new ConduitCall('diffusion.looksoon', $params)) ->setUser($viewer) ->execute(); return id(new AphrontRedirectResponse())->setURI($panel_uri); } $doc_name = 'Diffusion User Guide: Repository Updates'; $doc_href = PhabricatorEnv::getDoclink($doc_name); $doc_link = phutil_tag( 'a', array( 'href' => $doc_href, 'target' => '_blank', ), $doc_name); return $this->newDialog() ->setTitle(pht('Update Repository Now')) ->appendParagraph( pht( 'Normally, repositories are automatically updated '. 'based on how much time has elapsed since the last commit. '. 'This helps reduce load if you have a large number of mostly '. 'inactive repositories, which is common.')) ->appendParagraph( pht( 'You can manually schedule an update for this repository. The '. 'daemons will perform the update as soon as possible. This may '. 'be helpful if you have just made a commit to a rarely used '. 'repository.')) ->appendParagraph( pht( 'To learn more about how repositories are updated, '. 'read %s in the documentation.', $doc_link)) ->addCancelButton($panel_uri) ->addSubmitButton(pht('Schedule Update')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryEditEnormousController.php
src/applications/diffusion/controller/DiffusionRepositoryEditEnormousController.php
<?php final class DiffusionRepositoryEditEnormousController extends DiffusionRepositoryManageController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $panel_uri = id(new DiffusionRepositoryBasicsManagementPanel()) ->setRepository($repository) ->getPanelURI(); if (!$repository->canAllowEnormousChanges()) { return $this->newDialog() ->setTitle(pht('Unprotectable Repository')) ->appendParagraph( pht( 'This repository can not be protected from enormous changes '. 'because this server does not control what users are allowed '. 'to push to it.')) ->addCancelButton($panel_uri); } if ($request->isFormPost()) { $xaction = id(new PhabricatorRepositoryTransaction()) ->setTransactionType( PhabricatorRepositoryEnormousTransaction::TRANSACTIONTYPE) ->setNewValue(!$repository->shouldAllowEnormousChanges()); $editor = id(new PhabricatorRepositoryEditor()) ->setContinueOnNoEffect(true) ->setContentSourceFromRequest($request) ->setActor($viewer) ->applyTransactions($repository, array($xaction)); return id(new AphrontReloadResponse())->setURI($panel_uri); } if ($repository->shouldAllowEnormousChanges()) { $title = pht('Prevent Enormous Changes'); $body = pht( 'It will no longer be possible to push enormous changes to this '. 'repository.'); $submit = pht('Prevent Enormous Changes'); } else { $title = pht('Allow Enormous Changes'); $body = array( pht( 'If you allow enormous changes, users can push commits which are '. 'too large for Herald to process content rules for. This can allow '. 'users to evade content rules implemented in Herald.'), pht( 'You can selectively configure Herald by adding rules to prevent a '. 'subset of enormous changes (for example, based on who is trying '. 'to push the change).'), ); $submit = pht('Allow Enormous Changes'); } $more_help = pht( 'Enormous changes are commits which are too large to process with '. 'content rules because: the diff text for the change is larger than '. '%s bytes; or the diff text takes more than %s seconds to extract.', new PhutilNumber(HeraldCommitAdapter::getEnormousByteLimit()), new PhutilNumber(HeraldCommitAdapter::getEnormousTimeLimit())); $response = $this->newDialog(); foreach ((array)$body as $paragraph) { $response->appendParagraph($paragraph); } return $response ->setTitle($title) ->appendParagraph($more_help) ->addSubmitButton($submit) ->addCancelButton($panel_uri); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryEditActivateController.php
src/applications/diffusion/controller/DiffusionRepositoryEditActivateController.php
<?php final class DiffusionRepositoryEditActivateController extends DiffusionRepositoryManageController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $panel_uri = id(new DiffusionRepositoryBasicsManagementPanel()) ->setRepository($repository) ->getPanelURI(); if ($request->isFormPost()) { if (!$repository->isTracked()) { $new_status = PhabricatorRepository::STATUS_ACTIVE; } else { $new_status = PhabricatorRepository::STATUS_INACTIVE; } $xaction = id(new PhabricatorRepositoryTransaction()) ->setTransactionType( PhabricatorRepositoryActivateTransaction::TRANSACTIONTYPE) ->setNewValue($new_status); $editor = id(new PhabricatorRepositoryEditor()) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSourceFromRequest($request) ->setActor($viewer) ->applyTransactions($repository, array($xaction)); return id(new AphrontReloadResponse())->setURI($panel_uri); } if ($repository->isTracked()) { $title = pht('Deactivate Repository'); $body = pht( 'If you deactivate this repository, it will no longer be updated. '. 'Observation and mirroring will cease, and pushing and pulling will '. 'be disabled. You can reactivate the repository later.'); $submit = pht('Deactivate Repository'); } else { $title = pht('Activate Repository'); $is_new = $repository->isNewlyInitialized(); if ($is_new) { if ($repository->isHosted()) { $body = pht( 'This repository will become a new hosted repository. '. 'It will begin serving read and write traffic.'); } else { $body = pht( 'This repository will observe an existing remote repository. '. 'It will begin fetching changes from the remote.'); } } else { $body = pht( 'This repository will resume updates, observation, mirroring, '. 'and serving any configured read and write traffic.'); } $submit = pht('Activate Repository'); } return $this->newDialog() ->setTitle($title) ->appendChild($body) ->addSubmitButton($submit) ->addCancelButton($panel_uri); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryURICredentialController.php
src/applications/diffusion/controller/DiffusionRepositoryURICredentialController.php
<?php final class DiffusionRepositoryURICredentialController extends DiffusionController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $id = $request->getURIData('id'); $uri = id(new PhabricatorRepositoryURIQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->withRepositories(array($repository)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$uri) { return new Aphront404Response(); } $is_builtin = $uri->isBuiltin(); $has_credential = (bool)$uri->getCredentialPHID(); $view_uri = $uri->getViewURI(); $is_remove = ($request->getURIData('action') == 'remove'); if ($is_builtin) { return $this->newDialog() ->setTitle(pht('Builtin URIs Do Not Use Credentials')) ->appendParagraph( pht( 'You can not set a credential for builtin URIs which this '. 'server hosts. These URIs are not fetched from or pushed to, '. 'and credentials are not required to authenticate any '. 'activity against them.')) ->addCancelButton($view_uri); } if ($request->isFormPost()) { $xactions = array(); if ($is_remove) { $new_phid = null; } else { $new_phid = $request->getStr('credentialPHID'); } $type_credential = PhabricatorRepositoryURITransaction::TYPE_CREDENTIAL; $xactions[] = id(new PhabricatorRepositoryURITransaction()) ->setTransactionType($type_credential) ->setNewValue($new_phid); $editor = id(new DiffusionURIEditor()) ->setActor($viewer) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setContentSourceFromRequest($request) ->applyTransactions($uri, $xactions); return id(new AphrontRedirectResponse())->setURI($view_uri); } $command_engine = $uri->newCommandEngine(); $is_supported = $command_engine->isCredentialSupported(); $body = null; $form = null; $width = AphrontDialogView::WIDTH_DEFAULT; if ($is_remove) { if ($has_credential) { $title = pht('Remove Credential'); $body = pht( 'This credential will no longer be used to authenticate activity '. 'against this URI.'); $button = pht('Remove Credential'); } else { $title = pht('No Credential'); $body = pht( 'This URI does not have an associated credential.'); $button = null; } } else if (!$is_supported) { $title = pht('Unauthenticated Protocol'); $body = pht( 'The protocol for this URI ("%s") does not use authentication, so '. 'you can not provide a credential.', $command_engine->getDisplayProtocol()); $button = null; } else { $effective_uri = $uri->getEffectiveURI(); $label = $command_engine->getPassphraseCredentialLabel(); $credential_type = $command_engine->getPassphraseDefaultCredentialType(); $provides_type = $command_engine->getPassphraseProvidesCredentialType(); $options = id(new PassphraseCredentialQuery()) ->setViewer($viewer) ->withIsDestroyed(false) ->withProvidesTypes(array($provides_type)) ->execute(); $control = id(new PassphraseCredentialControl()) ->setName('credentialPHID') ->setLabel($label) ->setValue($uri->getCredentialPHID()) ->setCredentialType($credential_type) ->setOptions($options); $default_user = $effective_uri->getUser(); if (strlen($default_user)) { $control->setDefaultUsername($default_user); } $form = id(new AphrontFormView()) ->setViewer($viewer) ->appendControl($control); if ($has_credential) { $title = pht('Update Credential'); $button = pht('Update Credential'); } else { $title = pht('Set Credential'); $button = pht('Set Credential'); } $width = AphrontDialogView::WIDTH_FORM; } $dialog = $this->newDialog() ->setWidth($width) ->setTitle($title) ->addCancelButton($view_uri); if ($body) { $dialog->appendParagraph($body); } if ($form) { $dialog->appendForm($form); } if ($button) { $dialog->addSubmitButton($button); } return $dialog; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryController.php
src/applications/diffusion/controller/DiffusionRepositoryController.php
<?php final class DiffusionRepositoryController extends DiffusionController { private $browseFuture; private $branchButton = null; private $branchFuture; public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } require_celerity_resource('diffusion-css'); $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $crumbs = $this->buildCrumbs(); $crumbs->setBorder(true); $header = $this->buildHeaderView($repository); $actions = $this->buildActionList($repository); $description = $this->buildDescriptionView($repository); $locate_file = $this->buildLocateFile(); // Before we do any work, make sure we're looking at a some content: we're // on a valid branch, and the repository is not empty. $page_has_content = false; $empty_title = null; $empty_message = null; // If this VCS supports branches, check that the selected branch actually // exists. if ($drequest->supportsBranches()) { // NOTE: Mercurial may have multiple branch heads with the same name. $ref_cursors = id(new PhabricatorRepositoryRefCursorQuery()) ->setViewer($viewer) ->withRepositoryPHIDs(array($repository->getPHID())) ->withRefTypes(array(PhabricatorRepositoryRefCursor::TYPE_BRANCH)) ->withRefNames(array($drequest->getBranch())) ->needPositions(true) ->execute(); // It's possible that this branch previously existed, but has been // deleted. Make sure we have valid cursor positions, not just cursors. $any_positions = false; foreach ($ref_cursors as $ref_cursor) { if ($ref_cursor->getPositions()) { $any_positions = true; break; } } if ($any_positions) { // This is a valid branch, so we necessarily have some content. $page_has_content = true; } else { $default = $repository->getDefaultBranch(); if ($default != $drequest->getBranch()) { $empty_title = pht('No Such Branch'); $empty_message = pht( 'There is no branch named "%s" in this repository.', $drequest->getBranch()); } else { $empty_title = pht('No Default Branch'); $empty_message = pht( 'This repository is configured with default branch "%s" but '. 'there is no branch with that name in this repository.', $default); } } } // If we didn't find any branches, check if there are any commits at all. // This can tailor the message for empty repositories. $any_commit = null; if (!$page_has_content) { $any_commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($repository) ->setLimit(1) ->execute(); if ($any_commit) { if (!$drequest->supportsBranches()) { $page_has_content = true; } } else { $empty_title = pht('Empty Repository'); $empty_message = pht('This repository does not have any commits yet.'); } } if ($page_has_content) { $content = $this->buildNormalContent($drequest); } else { // If we have a commit somewhere, find branches. // TODO: Evan will replace // $this->buildNormalContent($drequest); $content = id(new PHUIInfoView()) ->setTitle($empty_title) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors(array($empty_message)); } $tabs = $this->buildTabsView('code'); $clone_uri = $drequest->generateURI( array( 'action' => 'clone', )); if ($repository->isSVN()) { $clone_text = pht('Checkout'); } else { $clone_text = pht('Clone'); } $actions_button = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Actions')) ->setIcon('fa-bars') ->addClass('mmr') ->setColor(PHUIButtonView::GREY) ->setDropdown(true) ->setDropdownMenu($actions); $clone_button = id(new PHUIButtonView()) ->setTag('a') ->setText($clone_text) ->setColor(PHUIButtonView::GREEN) ->setIcon('fa-download') ->setWorkflow(true) ->setHref($clone_uri); $bar = id(new PHUILeftRightView()) ->setLeft($locate_file) ->setRight(array($this->branchButton, $actions_button, $clone_button)) ->addClass('diffusion-action-bar'); $status_view = null; if ($repository->isReadOnly()) { $status_view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors( array( phutil_escape_html_newlines( $repository->getReadOnlyMessageForDisplay()), )); } $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter( array( $status_view, $bar, $description, $content, )); if ($page_has_content) { $view->setTabs($tabs); } return $this->newPage() ->setTitle( array( $repository->getName(), $repository->getDisplayName(), )) ->setCrumbs($crumbs) ->appendChild(array( $view, )); } private function buildNormalContent(DiffusionRequest $drequest) { $request = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $drequest->getCommit(); $path = $drequest->getPath(); $futures = array(); $browse_pager = id(new PHUIPagerView()) ->readFromRequest($request); $this->browseFuture = $this->callConduitMethod( 'diffusion.browsequery', array( 'commit' => $commit, 'path' => $path, 'limit' => $browse_pager->getPageSize() + 1, )); $futures[] = $this->browseFuture; if ($this->needBranchFuture()) { $branch_limit = $this->getBranchLimit(); $this->branchFuture = $this->callConduitMethod( 'diffusion.branchquery', array( 'closed' => false, 'limit' => $branch_limit + 1, )); $futures[] = $this->branchFuture; } $futures = array_filter($futures); $futures = new FutureIterator($futures); foreach ($futures as $future) { // Just resolve all the futures before continuing. } $content = array(); try { $browse_results = $this->browseFuture->resolve(); $browse_results = DiffusionBrowseResultSet::newFromConduit( $browse_results); $browse_paths = $browse_results->getPaths(); $browse_paths = $browse_pager->sliceResults($browse_paths); $browse_exception = null; } catch (Exception $ex) { $browse_results = null; $browse_paths = null; $browse_exception = $ex; } if ($browse_results) { $readme = $this->renderDirectoryReadme($browse_results); } else { $readme = null; } $content[] = $this->buildBrowseTable( $browse_results, $browse_paths, $browse_exception, $browse_pager); if ($readme) { $content[] = $readme; } try { $branch_button = $this->buildBranchList($drequest); $this->branchButton = $branch_button; } catch (Exception $ex) { if (!$repository->isImporting()) { $content[] = $this->renderStatusMessage( pht('Unable to Load Branches'), $ex->getMessage()); } } return $content; } private function buildHeaderView(PhabricatorRepository $repository) { $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $search = $this->renderSearchForm(); $header = id(new PHUIHeaderView()) ->setHeader($repository->getName()) ->setUser($viewer) ->setPolicyObject($repository) ->setProfileHeader(true) ->setImage($repository->getProfileImageURI()) ->setImageEditURL('/diffusion/picture/'.$repository->getID().'/') ->addActionItem($search) ->addClass('diffusion-profile-header'); if (!$repository->isTracked()) { $header->setStatus('fa-ban', 'dark', pht('Inactive')); } else if ($repository->isReadOnly()) { $header->setStatus('fa-wrench', 'indigo', pht('Under Maintenance')); } else if ($repository->isImporting()) { $ratio = $repository->loadImportProgress(); $percentage = sprintf('%.2f%%', 100 * $ratio); $header->setStatus( 'fa-clock-o', 'indigo', pht('Importing (%s)...', $percentage)); } else if ($repository->isPublishingDisabled()) { $header->setStatus('fa-minus', 'bluegrey', pht('Publishing Disabled')); } else { $header->setStatus('fa-check', 'bluegrey', pht('Active')); } if (!$repository->isSVN()) { $default = $repository->getDefaultBranch(); if ($default != $drequest->getBranch()) { $branch_tag = $this->renderBranchTag($drequest); $header->addTag($branch_tag); } } return $header; } private function buildActionList(PhabricatorRepository $repository) { $viewer = $this->getViewer(); $edit_uri = $repository->getPathURI('manage/'); $action_view = id(new PhabricatorActionListView()) ->setUser($viewer) ->setObject($repository); $action_view->addAction( id(new PhabricatorActionView()) ->setName(pht('Manage Repository')) ->setIcon('fa-cogs') ->setHref($edit_uri)); if ($repository->isHosted()) { $push_uri = $this->getApplicationURI( 'pushlog/?repositories='.$repository->getPHID()); $action_view->addAction( id(new PhabricatorActionView()) ->setName(pht('View Push Logs')) ->setIcon('fa-upload') ->setHref($push_uri)); $pull_uri = $this->getApplicationURI( 'synclog/?repositories='.$repository->getPHID()); $action_view->addAction( id(new PhabricatorActionView()) ->setName(pht('View Sync Logs')) ->setIcon('fa-exchange') ->setHref($pull_uri)); } $pull_uri = $this->getApplicationURI( 'pulllog/?repositories='.$repository->getPHID()); $action_view->addAction( id(new PhabricatorActionView()) ->setName(pht('View Pull Logs')) ->setIcon('fa-download') ->setHref($pull_uri)); return $action_view; } private function buildDescriptionView(PhabricatorRepository $repository) { $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setUser($viewer); $description = $repository->getDetail('description'); if (strlen($description)) { $description = new PHUIRemarkupView($viewer, $description); $view->addTextContent($description); return id(new PHUIObjectBoxView()) ->appendChild($view) ->addClass('diffusion-profile-description'); } return null; } private function buildBranchList(DiffusionRequest $drequest) { $viewer = $this->getViewer(); if (!$this->needBranchFuture()) { return null; } $branches = $this->branchFuture->resolve(); if (!$branches) { return null; } $limit = $this->getBranchLimit(); $more_branches = (count($branches) > $limit); $branches = array_slice($branches, 0, $limit); $branches = DiffusionRepositoryRef::loadAllFromDictionaries($branches); $actions = id(new PhabricatorActionListView()) ->setViewer($viewer); foreach ($branches as $branch) { $branch_uri = $drequest->generateURI( array( 'action' => 'browse', 'branch' => $branch->getShortname(), )); $actions->addAction( id(new PhabricatorActionView()) ->setName($branch->getShortname()) ->setIcon('fa-code-fork') ->setHref($branch_uri)); } if ($more_branches) { $more_uri = $drequest->generateURI( array( 'action' => 'branches', )); $actions->addAction( id(new PhabricatorActionView()) ->setType(PhabricatorActionView::TYPE_DIVIDER)); $actions->addAction( id(new PhabricatorActionView()) ->setName(pht('See More Branches')) ->setIcon('fa-external-link') ->setHref($more_uri)); } $button = id(new PHUIButtonView()) ->setText(pht('Branch: %s', $drequest->getBranch())) ->setTag('a') ->addClass('mmr') ->setIcon('fa-code-fork') ->setColor(PHUIButtonView::GREY) ->setDropdown(true) ->setDropdownMenu($actions); return $button; } private function buildLocateFile() { $request = $this->getRequest(); $viewer = $request->getUser(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $form_box = null; if ($repository->canUsePathTree()) { Javelin::initBehavior( 'diffusion-locate-file', array( 'controlID' => 'locate-control', 'inputID' => 'locate-input', 'browseBaseURI' => (string)$drequest->generateURI( array( 'action' => 'browse', )), 'uri' => (string)$drequest->generateURI( array( 'action' => 'pathtree', )), )); $form = id(new AphrontFormView()) ->setUser($viewer) ->appendChild( id(new AphrontFormTypeaheadControl()) ->setHardpointID('locate-control') ->setID('locate-input') ->setPlaceholder(pht('Locate File'))); $form_box = id(new PHUIBoxView()) ->appendChild($form->buildLayoutView()) ->addClass('diffusion-profile-locate'); } return $form_box; } private function buildBrowseTable( $browse_results, $browse_paths, $browse_exception, PHUIPagerView $pager) { require_celerity_resource('diffusion-icons-css'); $request = $this->getRequest(); $viewer = $request->getUser(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); if ($browse_exception) { if ($repository->isImporting()) { // The history table renders a useful message. return null; } else { return $this->renderStatusMessage( pht('Unable to Retrieve Paths'), $browse_exception->getMessage()); } } $browse_table = id(new DiffusionBrowseTableView()) ->setUser($viewer) ->setDiffusionRequest($drequest); if ($browse_paths) { $browse_table->setPaths($browse_paths); } else { $browse_table->setPaths(array()); } $browse_uri = $drequest->generateURI(array('action' => 'browse')); $pager->setURI($browse_uri, 'offset'); $repository_name = $repository->getName(); $branch_name = $drequest->getBranch(); if (strlen($branch_name)) { $repository_name .= ' ('.$branch_name.')'; } $header = phutil_tag( 'a', array( 'href' => $browse_uri, 'class' => 'diffusion-view-browse-header', ), $repository_name); return id(new PHUIObjectBoxView()) ->setHeaderText($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($browse_table) ->addClass('diffusion-mobile-view') ->setPager($pager); } private function needBranchFuture() { $drequest = $this->getDiffusionRequest(); if ($drequest->getBranch() === null) { return false; } return true; } private function getBranchLimit() { return 15; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryTestAutomationController.php
src/applications/diffusion/controller/DiffusionRepositoryTestAutomationController.php
<?php final class DiffusionRepositoryTestAutomationController extends DiffusionRepositoryManageController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $panel_uri = id(new DiffusionRepositoryAutomationManagementPanel()) ->setRepository($repository) ->getPanelURI(); if (!$repository->canPerformAutomation()) { return $this->newDialog() ->setTitle(pht('Automation Not Configured')) ->appendParagraph( pht( 'You can not run a configuration test for this repository '. 'because you have not configured repository automation yet. '. 'Configure it first, then test the configuration.')) ->addCancelButton($panel_uri); } if ($request->isFormPost()) { $op = new DrydockTestRepositoryOperation(); $operation = DrydockRepositoryOperation::initializeNewOperation($op) ->setAuthorPHID($viewer->getPHID()) ->setObjectPHID($repository->getPHID()) ->setRepositoryPHID($repository->getPHID()) ->setRepositoryTarget('none:') ->save(); $operation->scheduleUpdate(); $operation_id = $operation->getID(); $operation_uri = "/drydock/operation/{$operation_id}/"; return id(new AphrontRedirectResponse()) ->setURI($operation_uri); } return $this->newDialog() ->setTitle(pht('Test Automation Configuration')) ->appendParagraph( pht( 'This configuration test will build a working copy of the '. 'repository and perform some basic validation. If it works, '. 'your configuration is substantially correct.')) ->appendParagraph( pht( 'The test will not perform any writes against the repository, so '. 'write operations may still fail even if the test passes. This '. 'test covers building and reading working copies, but not writing '. 'to them.')) ->appendParagraph( pht( 'If you run into write failures despite passing this test, '. 'it suggests that your setup is nearly correct but authentication '. 'is probably not fully configured.')) ->addCancelButton($panel_uri) ->addSubmitButton(pht('Start Test')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionTagListController.php
src/applications/diffusion/controller/DiffusionTagListController.php
<?php final class DiffusionTagListController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } require_celerity_resource('diffusion-css'); $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $pager = id(new PHUIPagerView()) ->readFromRequest($request); $params = array( 'limit' => $pager->getPageSize() + 1, 'offset' => $pager->getOffset(), ); if ($drequest->getSymbolicCommit() !== null && strlen($drequest->getSymbolicCommit())) { $is_commit = true; $params['commit'] = $drequest->getSymbolicCommit(); } else { $is_commit = false; } switch ($repository->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $tags = array(); break; default: $conduit_result = $this->callConduitWithDiffusionRequest( 'diffusion.tagsquery', $params); $tags = DiffusionRepositoryTag::newFromConduit($conduit_result); break; } $tags = $pager->sliceResults($tags); $content = null; $header = id(new PHUIHeaderView()) ->setHeader(pht('Tags')) ->setHeaderIcon('fa-tags'); if (!$repository->isSVN()) { $branch_tag = $this->renderBranchTag($drequest); $header->addTag($branch_tag); } if (!$tags) { $content = $this->renderStatusMessage( pht('No Tags'), $is_commit ? pht('This commit has no tags.') : pht('This repository has no tags.')); } else { $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($repository) ->withIdentifiers(mpull($tags, 'getCommitIdentifier')) ->needCommitData(true) ->execute(); $tag_list = id(new DiffusionTagListView()) ->setTags($tags) ->setUser($viewer) ->setCommits($commits) ->setDiffusionRequest($drequest); $phids = $tag_list->getRequiredHandlePHIDs(); $handles = $this->loadViewerHandles($phids); $tag_list->setHandles($handles); $content = id(new PHUIObjectBoxView()) ->setHeaderText($repository->getDisplayName()) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($tag_list) ->setPager($pager); } $crumbs = $this->buildCrumbs( array( 'tags' => true, 'commit' => $drequest->getSymbolicCommit(), )); $crumbs->setBorder(true); $tabs = $this->buildTabsView('tags'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setTabs($tabs) ->setFooter($content); return $this->newPage() ->setTitle( array( pht('Tags'), $repository->getDisplayName(), )) ->setCrumbs($crumbs) ->appendChild($view) ->addClass('diffusion-history-view'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionController.php
src/applications/diffusion/controller/DiffusionController.php
<?php abstract class DiffusionController extends PhabricatorController { private $diffusionRequest; protected function getDiffusionRequest() { if (!$this->diffusionRequest) { throw new PhutilInvalidStateException('loadDiffusionContext'); } return $this->diffusionRequest; } protected function hasDiffusionRequest() { return (bool)$this->diffusionRequest; } public function willBeginExecution() { $request = $this->getRequest(); // Check if this is a VCS request, e.g. from "git clone", "hg clone", or // "svn checkout". If it is, we jump off into repository serving code to // process the request. $serve_controller = new DiffusionServeController(); if ($serve_controller->isVCSRequest($request)) { return $this->delegateToController($serve_controller); } return parent::willBeginExecution(); } protected function loadDiffusionContextForEdit() { return $this->loadContext( array( 'edit' => true, )); } protected function loadDiffusionContext() { return $this->loadContext(array()); } private function loadContext(array $options) { $request = $this->getRequest(); $viewer = $this->getViewer(); require_celerity_resource('diffusion-repository-css'); $identifier = $this->getRepositoryIdentifierFromRequest($request); $params = $options + array( 'repository' => $identifier, 'user' => $viewer, 'blob' => $this->getDiffusionBlobFromRequest($request), 'commit' => $request->getURIData('commit'), 'path' => $request->getURIData('path'), 'line' => $request->getURIData('line'), 'branch' => $request->getURIData('branch'), 'lint' => $request->getStr('lint'), ); $drequest = DiffusionRequest::newFromDictionary($params); if (!$drequest) { return new Aphront404Response(); } // If the client is making a request like "/diffusion/1/...", but the // repository has a different canonical path like "/diffusion/XYZ/...", // redirect them to the canonical path. // Skip this redirect if the request is an AJAX request, like the requests // that Owners makes to complete and validate paths. if (!$request->isAjax()) { $request_path = $request->getPath(); $repository = $drequest->getRepository(); $canonical_path = $repository->getCanonicalPath($request_path); if ($canonical_path !== null) { if ($canonical_path != $request_path) { return id(new AphrontRedirectResponse())->setURI($canonical_path); } } } $this->diffusionRequest = $drequest; return null; } protected function getDiffusionBlobFromRequest(AphrontRequest $request) { return $request->getURIData('dblob'); } protected function getRepositoryIdentifierFromRequest( AphrontRequest $request) { $short_name = $request->getURIData('repositoryShortName'); if ($short_name !== null && strlen($short_name)) { // If the short name ends in ".git", ignore it. $short_name = preg_replace('/\\.git\z/', '', $short_name); return $short_name; } $identifier = $request->getURIData('repositoryCallsign'); if ($identifier !== null && strlen($identifier)) { return $identifier; } $id = $request->getURIData('repositoryID'); if ($id !== null && strlen($id)) { return (int)$id; } return null; } public function buildCrumbs(array $spec = array()) { $crumbs = $this->buildApplicationCrumbs(); $crumb_list = $this->buildCrumbList($spec); foreach ($crumb_list as $crumb) { $crumbs->addCrumb($crumb); } return $crumbs; } private function buildCrumbList(array $spec = array()) { $spec = $spec + array( 'commit' => null, 'tags' => null, 'branches' => null, 'view' => null, ); $crumb_list = array(); // On the home page, we don't have a DiffusionRequest. if ($this->hasDiffusionRequest()) { $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); } else { $drequest = null; $repository = null; } if (!$repository) { return $crumb_list; } $repository_name = $repository->getName(); if (!$spec['commit'] && !$spec['tags'] && !$spec['branches']) { $branch_name = $drequest->getBranch(); if (strlen($branch_name)) { $repository_name .= ' ('.$branch_name.')'; } } $crumb = id(new PHUICrumbView()) ->setName($repository_name); if (!$spec['view'] && !$spec['commit'] && !$spec['tags'] && !$spec['branches']) { $crumb_list[] = $crumb; return $crumb_list; } $crumb->setHref( $drequest->generateURI( array( 'action' => 'branch', 'path' => '/', ))); $crumb_list[] = $crumb; $stable_commit = $drequest->getStableCommit(); $commit_name = $repository->formatCommitName($stable_commit, $local = true); $commit_uri = $repository->getCommitURI($stable_commit); if ($spec['tags']) { $crumb = new PHUICrumbView(); if ($spec['commit']) { $crumb->setName(pht('Tags for %s', $commit_name)); $crumb->setHref($commit_uri); } else { $crumb->setName(pht('Tags')); } $crumb_list[] = $crumb; return $crumb_list; } if ($spec['branches']) { $crumb = id(new PHUICrumbView()) ->setName(pht('Branches')); $crumb_list[] = $crumb; return $crumb_list; } if ($spec['commit']) { $crumb = id(new PHUICrumbView()) ->setName($commit_name); $crumb_list[] = $crumb; return $crumb_list; } $crumb = new PHUICrumbView(); $view = $spec['view']; switch ($view) { case 'history': $view_name = pht('History'); break; case 'browse': $view_name = pht('Browse'); break; case 'lint': $view_name = pht('Lint'); break; case 'change': $view_name = pht('Change'); break; case 'compare': $view_name = pht('Compare'); break; } $crumb = id(new PHUICrumbView()) ->setName($view_name); $crumb_list[] = $crumb; return $crumb_list; } protected function callConduitWithDiffusionRequest( $method, array $params = array()) { $user = $this->getRequest()->getUser(); $drequest = $this->getDiffusionRequest(); return DiffusionQuery::callConduitWithDiffusionRequest( $user, $drequest, $method, $params); } protected function callConduitMethod($method, array $params = array()) { $user = $this->getViewer(); $drequest = $this->getDiffusionRequest(); return DiffusionQuery::callConduitWithDiffusionRequest( $user, $drequest, $method, $params, true); } protected function getRepositoryControllerURI( PhabricatorRepository $repository, $path) { return $repository->getPathURI($path); } protected function renderPathLinks(DiffusionRequest $drequest, $action) { $path = $drequest->getPath(); $path_parts = array(); if ($path !== null && strlen($path)) { $path_parts = array_filter(explode('/', trim($path, '/'))); } $divider = phutil_tag( 'span', array( 'class' => 'phui-header-divider', ), '/'); $links = array(); if ($path_parts) { $links[] = phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => $action, 'path' => '', )), ), $drequest->getRepository()->getDisplayName()); $links[] = $divider; $accum = ''; $last_key = last_key($path_parts); foreach ($path_parts as $key => $part) { $accum .= '/'.$part; if ($key === $last_key) { $links[] = $part; } else { $links[] = phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => $action, 'path' => $accum.'/', )), ), $part); $links[] = $divider; } } } else { $links[] = $drequest->getRepository()->getDisplayName(); $links[] = $divider; } return $links; } protected function renderStatusMessage($title, $body) { return id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->setTitle($title) ->setFlush(true) ->appendChild($body); } protected function renderCommitHashTag(DiffusionRequest $drequest) { $stable_commit = $drequest->getStableCommit(); $commit = phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => 'commit', 'commit' => $stable_commit, )), ), $drequest->getRepository()->formatCommitName($stable_commit, true)); $tag = id(new PHUITagView()) ->setName($commit) ->setColor(PHUITagView::COLOR_INDIGO) ->setBorder(PHUITagView::BORDER_NONE) ->setType(PHUITagView::TYPE_SHADE); return $tag; } protected function renderBranchTag(DiffusionRequest $drequest) { $branch = $drequest->getBranch(); $branch = id(new PhutilUTF8StringTruncator()) ->setMaximumGlyphs(24) ->truncateString($branch); $tag = id(new PHUITagView()) ->setName($branch) ->setColor(PHUITagView::COLOR_INDIGO) ->setBorder(PHUITagView::BORDER_NONE) ->setType(PHUITagView::TYPE_OUTLINE) ->addClass('diffusion-header-branch-tag'); return $tag; } protected function renderSymbolicCommit(DiffusionRequest $drequest) { $symbolic_tag = $drequest->getSymbolicCommit(); $symbolic_tag = id(new PhutilUTF8StringTruncator()) ->setMaximumGlyphs(24) ->truncateString($symbolic_tag); $tag = id(new PHUITagView()) ->setName($symbolic_tag) ->setIcon('fa-tag') ->setColor(PHUITagView::COLOR_INDIGO) ->setBorder(PHUITagView::BORDER_NONE) ->setType(PHUITagView::TYPE_SHADE); return $tag; } protected function renderDirectoryReadme(DiffusionBrowseResultSet $browse) { $readme_path = $browse->getReadmePath(); if ($readme_path === null) { return null; } $drequest = $this->getDiffusionRequest(); $viewer = $this->getViewer(); $repository = $drequest->getRepository(); $repository_phid = $repository->getPHID(); $stable_commit = $drequest->getStableCommit(); $stable_commit_hash = PhabricatorHash::digestForIndex($stable_commit); $readme_path_hash = PhabricatorHash::digestForIndex($readme_path); $cache = PhabricatorCaches::getMutableStructureCache(); $cache_key = "diffusion". ".repository({$repository_phid})". ".commit({$stable_commit_hash})". ".readme({$readme_path_hash})"; $readme_cache = $cache->getKey($cache_key); if (!$readme_cache) { try { $result = $this->callConduitWithDiffusionRequest( 'diffusion.filecontentquery', array( 'path' => $readme_path, 'commit' => $drequest->getStableCommit(), )); } catch (Exception $ex) { return null; } $file_phid = $result['filePHID']; if (!$file_phid) { return null; } $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($file_phid)) ->executeOne(); if (!$file) { return null; } $corpus = $file->loadFileData(); $readme_cache = array( 'corpus' => $corpus, ); $cache->setKey($cache_key, $readme_cache); } $readme_corpus = $readme_cache['corpus']; if (!strlen($readme_corpus)) { return null; } return id(new DiffusionReadmeView()) ->setUser($this->getViewer()) ->setPath($readme_path) ->setContent($readme_corpus); } protected function renderSearchForm($path = '/') { $drequest = $this->getDiffusionRequest(); $viewer = $this->getViewer(); switch ($drequest->getRepository()->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: return null; } $search_term = $this->getRequest()->getStr('grep'); require_celerity_resource('diffusion-icons-css'); require_celerity_resource('diffusion-css'); $href = $drequest->generateURI(array( 'action' => 'browse', 'path' => $path, )); $bar = javelin_tag( 'input', array( 'type' => 'text', 'id' => 'diffusion-search-input', 'name' => 'grep', 'class' => 'diffusion-search-input', 'sigil' => 'diffusion-search-input', 'placeholder' => pht('Pattern Search'), 'value' => $search_term, )); $form = phabricator_form( $viewer, array( 'method' => 'GET', 'action' => $href, 'sigil' => 'diffusion-search-form', 'class' => 'diffusion-search-form', 'id' => 'diffusion-search-form', ), array( $bar, )); $form_view = phutil_tag( 'div', array( 'class' => 'diffusion-search-form-view', ), $form); return $form_view; } protected function buildTabsView($key) { $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $view = new PHUIListView(); $view->addMenuItem( id(new PHUIListItemView()) ->setKey('code') ->setName(pht('Code')) ->setIcon('fa-code') ->setHref($drequest->generateURI( array( 'action' => 'browse', ))) ->setSelected($key == 'code')); if (!$repository->isSVN()) { $view->addMenuItem( id(new PHUIListItemView()) ->setKey('branch') ->setName(pht('Branches')) ->setIcon('fa-code-fork') ->setHref($drequest->generateURI( array( 'action' => 'branches', ))) ->setSelected($key == 'branch')); } if (!$repository->isSVN()) { $view->addMenuItem( id(new PHUIListItemView()) ->setKey('tags') ->setName(pht('Tags')) ->setIcon('fa-tags') ->setHref($drequest->generateURI( array( 'action' => 'tags', ))) ->setSelected($key == 'tags')); } $view->addMenuItem( id(new PHUIListItemView()) ->setKey('history') ->setName(pht('History')) ->setIcon('fa-history') ->setHref($drequest->generateURI( array( 'action' => 'history', ))) ->setSelected($key == 'history')); 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/diffusion/controller/DiffusionIdentityListController.php
src/applications/diffusion/controller/DiffusionIdentityListController.php
<?php final class DiffusionIdentityListController extends DiffusionController { public function handleRequest(AphrontRequest $request) { return id(new DiffusionRepositoryIdentitySearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); id(new PhabricatorRepositoryIdentityEditEngine()) ->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/diffusion/controller/DiffusionPullLogListController.php
src/applications/diffusion/controller/DiffusionPullLogListController.php
<?php final class DiffusionPullLogListController extends DiffusionLogController { public function handleRequest(AphrontRequest $request) { return id(new DiffusionPullLogSearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { return parent::buildApplicationCrumbs() ->addTextCrumb(pht('Pull Logs'), $this->getApplicationURI('pulllog/')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryManagePanelsController.php
src/applications/diffusion/controller/DiffusionRepositoryManagePanelsController.php
<?php final class DiffusionRepositoryManagePanelsController extends DiffusionRepositoryManageController { private $navigation; public function buildApplicationMenu() { // TODO: This is messy for now; the mobile menu should be set automatically // when the body content is a two-column view with navigation. if ($this->navigation) { return $this->navigation->getMenu(); } return parent::buildApplicationMenu(); } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $panels = DiffusionRepositoryManagementPanel::getAllPanels(); foreach ($panels as $key => $panel) { $panel ->setViewer($viewer) ->setRepository($repository) ->setController($this); if (!$panel->shouldEnableForRepository($repository)) { unset($panels[$key]); continue; } } $selected = $request->getURIData('panel'); if ($selected === null || !strlen($selected)) { $selected = head_key($panels); } if (empty($panels[$selected])) { return new Aphront404Response(); } $nav = $this->renderSideNav($repository, $panels, $selected); $this->navigation = $nav; $panel = $panels[$selected]; $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($panel->getManagementPanelLabel()); $crumbs->setBorder(true); $content = $panel->buildManagementPanelContent(); $title = array( $panel->getManagementPanelLabel(), $repository->getDisplayName(), ); $header = $this->buildHeaderView($repository->getDisplayName()); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setMainColumn($content); $curtain = $panel->buildManagementPanelCurtain(); if ($curtain) { $view->setCurtain($curtain); } return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->setNavigation($nav) ->appendChild($view); } private function renderSideNav( PhabricatorRepository $repository, array $panels, $selected) { $base_uri = $repository->getPathURI('manage/'); $base_uri = new PhutilURI($base_uri); $nav = id(new AphrontSideNavFilterView()) ->setBaseURI($base_uri); $groups = DiffusionRepositoryManagementPanelGroup::getAllPanelGroups(); $panel_groups = mgroup($panels, 'getManagementPanelGroupKey'); $other_key = DiffusionRepositoryManagementOtherPanelGroup::PANELGROUPKEY; foreach ($groups as $group_key => $group) { // If this is the "Other" group, include everything else that isn't in // some actual group. if ($group_key === $other_key) { $group_panels = array_mergev($panel_groups); $panel_groups = array(); } else { $group_panels = idx($panel_groups, $group_key); unset($panel_groups[$group_key]); } if (!$group_panels) { continue; } $label = $group->getManagementPanelGroupLabel(); if ($label) { $nav->addLabel($label); } foreach ($group_panels as $panel) { $key = $panel->getManagementPanelKey(); $label = $panel->getManagementPanelLabel(); $icon = $panel->getManagementPanelIcon(); $href = $panel->getPanelNavigationURI(); $item = id(new PHUIListItemView()) ->setKey($key) ->setName($label) ->setType(PHUIListItemView::TYPE_LINK) ->setHref($href) ->setIcon($icon); $nav->addMenuItem($item); } } $nav->selectFilter($selected); return $nav; } public function buildHeaderView($title) { $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $header = id(new PHUIHeaderView()) ->setHeader($title) ->setProfileHeader(true) ->setHref($repository->getURI()) ->setImage($repository->getProfileImageURI()); if ($repository->isTracked()) { $header->setStatus('fa-check', 'bluegrey', pht('Active')); } else { $header->setStatus('fa-ban', 'dark', pht('Inactive')); } $doc_href = PhabricatorEnv::getDoclink( 'Diffusion User Guide: Managing Repositories'); $header->addActionLink( id(new PHUIButtonView()) ->setTag('a') ->setText(pht('View Repository')) ->setHref($repository->getURI()) ->setIcon('fa-code') ->setColor(PHUIButtonView::GREY)); $header->addActionLink( id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-book') ->setHref($doc_href) ->setText(pht('Help')) ->setColor(PHUIButtonView::GREY)); return $header; } public function newTimeline(PhabricatorRepository $repository) { $timeline = $this->buildTransactionTimeline( $repository, new PhabricatorRepositoryTransactionQuery()); $timeline->setShouldTerminate(true); return $timeline; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionBranchTableController.php
src/applications/diffusion/controller/DiffusionBranchTableController.php
<?php final class DiffusionBranchTableController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $pager = id(new PHUIPagerView()) ->readFromRequest($request); $params = array( 'offset' => $pager->getOffset(), 'limit' => $pager->getPageSize() + 1, 'branch' => null, ); $contains = $drequest->getSymbolicCommit(); if ($contains !== null && strlen($contains)) { $params['contains'] = $contains; } $branches = $this->callConduitWithDiffusionRequest( 'diffusion.branchquery', $params); $branches = $pager->sliceResults($branches); $branches = DiffusionRepositoryRef::loadAllFromDictionaries($branches); // If there is one page of results or fewer, sort branches so the default // branch is on top and permanent branches are below it. if (!$pager->getOffset() && !$pager->getHasMorePages()) { $branches = $this->sortBranches($repository, $branches); } $content = null; if (!$branches) { $content = $this->renderStatusMessage( pht('No Branches'), pht('This repository has no branches.')); } else { $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withIdentifiers(mpull($branches, 'getCommitIdentifier')) ->withRepository($repository) ->execute(); $list = id(new DiffusionBranchListView()) ->setUser($viewer) ->setBranches($branches) ->setCommits($commits) ->setDiffusionRequest($drequest); $content = id(new PHUIObjectBoxView()) ->setHeaderText($repository->getName()) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addClass('diffusion-mobile-view') ->setTable($list) ->setPager($pager); } $crumbs = $this->buildCrumbs( array( 'branches' => true, )); $crumbs->setBorder(true); $header = id(new PHUIHeaderView()) ->setHeader(pht('Branches')) ->setHeaderIcon('fa-code-fork'); if (!$repository->isSVN()) { $branch_tag = $this->renderBranchTag($drequest); $header->addTag($branch_tag); } $tabs = $this->buildTabsView('branch'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setTabs($tabs) ->setFooter(array( $content, )); return $this->newPage() ->setTitle( array( pht('Branches'), $repository->getDisplayName(), )) ->setCrumbs($crumbs) ->appendChild($view); } private function sortBranches( PhabricatorRepository $repository, array $branches) { $publisher = $repository->newPublisher(); $default_branch = $repository->getDefaultBranch(); $vectors = array(); foreach ($branches as $key => $branch) { $short_name = $branch->getShortName(); if ($short_name === $default_branch) { $order_default = 0; } else { $order_default = 1; } if ($publisher->shouldPublishRef($branch)) { $order_permanent = 0; } else { $order_permanent = 1; } $vectors[$key] = id(new PhutilSortVector()) ->addInt($order_default) ->addInt($order_permanent) ->addString($short_name); } $vectors = msortv($vectors, 'getSelf'); return array_select_keys($branches, array_keys($vectors)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryEditController.php
src/applications/diffusion/controller/DiffusionRepositoryEditController.php
<?php final class DiffusionRepositoryEditController extends DiffusionRepositoryManageController { public function handleRequest(AphrontRequest $request) { $engine = id(new DiffusionRepositoryEditEngine()) ->setController($this); $id = $request->getURIData('id'); if (!$id) { $this->requireApplicationCapability( DiffusionCreateRepositoriesCapability::CAPABILITY); $vcs = $request->getStr('vcs'); $vcs_types = PhabricatorRepositoryType::getRepositoryTypeMap(); if (empty($vcs_types[$vcs])) { return $this->buildVCSTypeResponse(); } $engine ->addContextParameter('vcs', $vcs) ->setVersionControlSystem($vcs); } return $engine->buildResponse(); } private function buildVCSTypeResponse() { $vcs_types = PhabricatorRepositoryType::getRepositoryTypeMap(); $request = $this->getRequest(); $viewer = $this->getViewer(); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb(pht('Create Repository')); $crumbs->setBorder(true); $title = pht('Choose Repository Type'); $layout = id(new AphrontMultiColumnView()) ->setFluidLayout(true); $create_uri = $request->getRequestURI(); foreach ($vcs_types as $vcs_key => $vcs_type) { $image = idx($vcs_type, 'image'); $image = PhabricatorFile::loadBuiltin($viewer, $image); $action = id(new PHUIActionPanelView()) ->setImage($image->getBestURI()) ->setHeader(idx($vcs_type, 'create.header')) ->setHref($create_uri->alter('vcs', $vcs_key)) ->setSubheader(idx($vcs_type, 'create.subheader')); $layout->addColumn($action); } $hints = id(new AphrontMultiColumnView()) ->setFluidLayout(true); $observe_href = PhabricatorEnv::getDoclink( 'Diffusion User Guide: Existing Repositories'); require_celerity_resource('diffusion-css'); $image = PhabricatorFile::loadBuiltin($viewer, 'repo/repo.png'); $hints->addColumn( id(new PHUIActionPanelView()) ->setImage($image->getBestURI()) ->setHeader(pht('Import or Observe an Existing Repository')) ->setHref($observe_href) ->setSubheader( pht( 'Review the documentation describing how to import or observe an '. 'existing repository.'))); $layout = id(new PHUIBoxView()) ->addClass('diffusion-create-repo') ->appendChild($layout); $launcher_view = id(new PHUILauncherView()) ->appendChild( array( $layout, $hints, )); $view = id(new PHUITwoColumnView()) ->setFooter($launcher_view); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryURIEditController.php
src/applications/diffusion/controller/DiffusionRepositoryURIEditController.php
<?php final class DiffusionRepositoryURIEditController extends DiffusionController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); return id(new DiffusionURIEditEngine()) ->setController($this) ->setRepository($repository) ->buildResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionServeController.php
src/applications/diffusion/controller/DiffusionServeController.php
<?php final class DiffusionServeController extends DiffusionController { private $serviceViewer; private $serviceRepository; private $isGitLFSRequest; private $gitLFSToken; private $gitLFSInput; public function setServiceViewer(PhabricatorUser $viewer) { $this->getRequest()->setUser($viewer); $this->serviceViewer = $viewer; return $this; } public function getServiceViewer() { return $this->serviceViewer; } public function setServiceRepository(PhabricatorRepository $repository) { $this->serviceRepository = $repository; return $this; } public function getServiceRepository() { return $this->serviceRepository; } public function getIsGitLFSRequest() { return $this->isGitLFSRequest; } public function getGitLFSToken() { return $this->gitLFSToken; } public function isVCSRequest(AphrontRequest $request) { $identifier = $this->getRepositoryIdentifierFromRequest($request); if ($identifier === null) { return null; } $content_type = $request->getHTTPHeader('Content-Type'); $user_agent = idx($_SERVER, 'HTTP_USER_AGENT'); $request_type = $request->getHTTPHeader('X-Phabricator-Request-Type'); // This may have a "charset" suffix, so only match the prefix. $lfs_pattern = '(^application/vnd\\.git-lfs\\+json(;|\z))'; $vcs = null; if ($request->getExists('service')) { $service = $request->getStr('service'); // We get this initially for `info/refs`. // Git also gives us a User-Agent like "git/1.8.2.3". $vcs = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; } else if (strncmp($user_agent, 'git/', 4) === 0) { $vcs = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; } else if ($content_type == 'application/x-git-upload-pack-request') { // We get this for `git-upload-pack`. $vcs = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; } else if ($content_type == 'application/x-git-receive-pack-request') { // We get this for `git-receive-pack`. $vcs = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; } else if (preg_match($lfs_pattern, $content_type)) { // This is a Git LFS HTTP API request. $vcs = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; $this->isGitLFSRequest = true; } else if ($request_type == 'git-lfs') { // This is a Git LFS object content request. $vcs = PhabricatorRepositoryType::REPOSITORY_TYPE_GIT; $this->isGitLFSRequest = true; } else if ($request->getExists('cmd')) { // Mercurial also sends an Accept header like // "application/mercurial-0.1", and a User-Agent like // "mercurial/proto-1.0". $vcs = PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL; } else { // Subversion also sends an initial OPTIONS request (vs GET/POST), and // has a User-Agent like "SVN/1.8.3 (x86_64-apple-darwin11.4.2) // serf/1.3.2". $dav = $request->getHTTPHeader('DAV'); $dav = new PhutilURI($dav); if ($dav->getDomain() === 'subversion.tigris.org') { $vcs = PhabricatorRepositoryType::REPOSITORY_TYPE_SVN; } } return $vcs; } public function handleRequest(AphrontRequest $request) { $service_exception = null; $response = null; try { $response = $this->serveRequest($request); } catch (Exception $ex) { $service_exception = $ex; } try { $remote_addr = $request->getRemoteAddress(); if ($request->isHTTPS()) { $remote_protocol = PhabricatorRepositoryPullEvent::PROTOCOL_HTTPS; } else { $remote_protocol = PhabricatorRepositoryPullEvent::PROTOCOL_HTTP; } $pull_event = id(new PhabricatorRepositoryPullEvent()) ->setEpoch(PhabricatorTime::getNow()) ->setRemoteAddress($remote_addr) ->setRemoteProtocol($remote_protocol); if ($response) { $response_code = $response->getHTTPResponseCode(); if ($response_code == 200) { $pull_event ->setResultType(PhabricatorRepositoryPullEvent::RESULT_PULL) ->setResultCode($response_code); } else { $pull_event ->setResultType(PhabricatorRepositoryPullEvent::RESULT_ERROR) ->setResultCode($response_code); } if ($response instanceof PhabricatorVCSResponse) { $pull_event->setProperties( array( 'response.message' => $response->getMessage(), )); } } else { $pull_event ->setResultType(PhabricatorRepositoryPullEvent::RESULT_EXCEPTION) ->setResultCode(500) ->setProperties( array( 'exception.class' => get_class($ex), 'exception.message' => $ex->getMessage(), )); } $viewer = $this->getServiceViewer(); if ($viewer) { $pull_event->setPullerPHID($viewer->getPHID()); } $repository = $this->getServiceRepository(); if ($repository) { $pull_event->setRepositoryPHID($repository->getPHID()); } $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $pull_event->save(); unset($unguarded); } catch (Exception $ex) { if ($service_exception) { throw $service_exception; } throw $ex; } if ($service_exception) { throw $service_exception; } return $response; } private function serveRequest(AphrontRequest $request) { $identifier = $this->getRepositoryIdentifierFromRequest($request); // If authentication credentials have been provided, try to find a user // that actually matches those credentials. // We require both the username and password to be nonempty, because Git // won't prompt users who provide a username but no password otherwise. // See T10797 for discussion. $http_user = idx($_SERVER, 'PHP_AUTH_USER'); $http_pass = idx($_SERVER, 'PHP_AUTH_PW'); $have_user = $http_user !== null && strlen($http_user); $have_pass = $http_pass !== null && strlen($http_pass); if ($have_user && $have_pass) { $username = $http_user; $password = new PhutilOpaqueEnvelope($http_pass); // Try Git LFS auth first since we can usually reject it without doing // any queries, since the username won't match the one we expect or the // request won't be LFS. $viewer = $this->authenticateGitLFSUser( $username, $password, $identifier); // If that failed, try normal auth. Note that we can use normal auth on // LFS requests, so this isn't strictly an alternative to LFS auth. if (!$viewer) { $viewer = $this->authenticateHTTPRepositoryUser($username, $password); } if (!$viewer) { return new PhabricatorVCSResponse( 403, pht('Invalid credentials.')); } } else { // User hasn't provided credentials, which means we count them as // being "not logged in". $viewer = new PhabricatorUser(); } // See T13590. Some pathways, like error handling, may require unusual // access to things like timezone information. These are fine to build // inline; this pathway is not lightweight anyway. $viewer->setAllowInlineCacheGeneration(true); $this->setServiceViewer($viewer); $allow_public = PhabricatorEnv::getEnvConfig('policy.allow-public'); $allow_auth = PhabricatorEnv::getEnvConfig('diffusion.allow-http-auth'); if (!$allow_public) { if (!$viewer->isLoggedIn()) { if ($allow_auth) { return new PhabricatorVCSResponse( 401, pht('You must log in to access repositories.')); } else { return new PhabricatorVCSResponse( 403, pht('Public and authenticated HTTP access are both forbidden.')); } } } try { $repository = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withIdentifiers(array($identifier)) ->needURIs(true) ->executeOne(); if (!$repository) { return new PhabricatorVCSResponse( 404, pht('No such repository exists.')); } } catch (PhabricatorPolicyException $ex) { if ($viewer->isLoggedIn()) { return new PhabricatorVCSResponse( 403, pht('You do not have permission to access this repository.')); } else { if ($allow_auth) { return new PhabricatorVCSResponse( 401, pht('You must log in to access this repository.')); } else { return new PhabricatorVCSResponse( 403, pht( 'This repository requires authentication, which is forbidden '. 'over HTTP.')); } } } $response = $this->validateGitLFSRequest($repository, $viewer); if ($response) { return $response; } $this->setServiceRepository($repository); if (!$repository->isTracked()) { return new PhabricatorVCSResponse( 403, pht('This repository is inactive.')); } $is_push = !$this->isReadOnlyRequest($repository); if ($this->getIsGitLFSRequest() && $this->getGitLFSToken()) { // We allow git LFS requests over HTTP even if the repository does not // otherwise support HTTP reads or writes, as long as the user is using a // token from SSH. If they're using HTTP username + password auth, they // have to obey the normal HTTP rules. } else { // For now, we don't distinguish between HTTP and HTTPS-originated // requests that are proxied within the cluster, so the user can connect // with HTTPS but we may be on HTTP by the time we reach this part of // the code. Allow things to move forward as long as either protocol // can be served. $proto_https = PhabricatorRepositoryURI::BUILTIN_PROTOCOL_HTTPS; $proto_http = PhabricatorRepositoryURI::BUILTIN_PROTOCOL_HTTP; $can_read = $repository->canServeProtocol($proto_https, false) || $repository->canServeProtocol($proto_http, false); if (!$can_read) { return new PhabricatorVCSResponse( 403, pht('This repository is not available over HTTP.')); } if ($is_push) { if ($repository->isReadOnly()) { return new PhabricatorVCSResponse( 503, $repository->getReadOnlyMessageForDisplay()); } $can_write = $repository->canServeProtocol($proto_https, true) || $repository->canServeProtocol($proto_http, true); if (!$can_write) { return new PhabricatorVCSResponse( 403, pht('This repository is read-only over HTTP.')); } } } if ($is_push) { $can_push = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, DiffusionPushCapability::CAPABILITY); if (!$can_push) { if ($viewer->isLoggedIn()) { $error_code = 403; $error_message = pht( 'You do not have permission to push to this repository ("%s").', $repository->getDisplayName()); if ($this->getIsGitLFSRequest()) { return DiffusionGitLFSResponse::newErrorResponse( $error_code, $error_message); } else { return new PhabricatorVCSResponse( $error_code, $error_message); } } else { if ($allow_auth) { return new PhabricatorVCSResponse( 401, pht('You must log in to push to this repository.')); } else { return new PhabricatorVCSResponse( 403, pht( 'Pushing to this repository requires authentication, '. 'which is forbidden over HTTP.')); } } } } $vcs_type = $repository->getVersionControlSystem(); $req_type = $this->isVCSRequest($request); if ($vcs_type != $req_type) { switch ($req_type) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $result = new PhabricatorVCSResponse( 500, pht( 'This repository ("%s") is not a Git repository.', $repository->getDisplayName())); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $result = new PhabricatorVCSResponse( 500, pht( 'This repository ("%s") is not a Mercurial repository.', $repository->getDisplayName())); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $result = new PhabricatorVCSResponse( 500, pht( 'This repository ("%s") is not a Subversion repository.', $repository->getDisplayName())); break; default: $result = new PhabricatorVCSResponse( 500, pht('Unknown request type.')); break; } } else { switch ($vcs_type) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $caught = null; try { $result = $this->serveVCSRequest($repository, $viewer); } catch (Exception $ex) { $caught = $ex; } catch (Throwable $ex) { $caught = $ex; } if ($caught) { // We never expect an uncaught exception here, so dump it to the // log. All routine errors should have been converted into Response // objects by a lower layer. phlog($caught); $result = new PhabricatorVCSResponse( 500, phutil_string_cast($caught->getMessage())); } break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $result = new PhabricatorVCSResponse( 500, pht( 'This server does not support HTTP access to Subversion '. 'repositories.')); break; default: $result = new PhabricatorVCSResponse( 500, pht('Unknown version control system.')); break; } } $code = $result->getHTTPResponseCode(); if ($is_push && ($code == 200)) { $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $repository->writeStatusMessage( PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE, PhabricatorRepositoryStatusMessage::CODE_OKAY); unset($unguarded); } return $result; } private function serveVCSRequest( PhabricatorRepository $repository, PhabricatorUser $viewer) { // We can serve Git LFS requests first, since we don't need to proxy them. // It's also important that LFS requests never fall through to standard // service pathways, because that would let you use LFS tokens to read // normal repository data. if ($this->getIsGitLFSRequest()) { return $this->serveGitLFSRequest($repository, $viewer); } // If this repository is hosted on a service, we need to proxy the request // to a host which can serve it. $is_cluster_request = $this->getRequest()->isProxiedClusterRequest(); $uri = $repository->getAlmanacServiceURI( $viewer, array( 'neverProxy' => $is_cluster_request, 'protocols' => array( 'http', 'https', ), 'writable' => !$this->isReadOnlyRequest($repository), )); if ($uri) { $future = $this->getRequest()->newClusterProxyFuture($uri); return id(new AphrontHTTPProxyResponse()) ->setHTTPFuture($future); } // Otherwise, we're going to handle the request locally. $vcs_type = $repository->getVersionControlSystem(); switch ($vcs_type) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $result = $this->serveGitRequest($repository, $viewer); break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $result = $this->serveMercurialRequest($repository, $viewer); break; } return $result; } private function isReadOnlyRequest( PhabricatorRepository $repository) { $request = $this->getRequest(); $method = $_SERVER['REQUEST_METHOD']; // TODO: This implementation is safe by default, but very incomplete. if ($this->getIsGitLFSRequest()) { return $this->isGitLFSReadOnlyRequest($repository); } switch ($repository->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $service = $request->getStr('service'); $path = $this->getRequestDirectoryPath($repository); // NOTE: Service names are the reverse of what you might expect, as they // are from the point of view of the server. The main read service is // "git-upload-pack", and the main write service is "git-receive-pack". if ($method == 'GET' && $path == '/info/refs' && $service == 'git-upload-pack') { return true; } if ($path == '/git-upload-pack') { return true; } break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $cmd = $request->getStr('cmd'); if ($cmd === null) { return false; } if ($cmd == 'batch') { $cmds = idx($this->getMercurialArguments(), 'cmds'); if ($cmds !== null) { return DiffusionMercurialWireProtocol::isReadOnlyBatchCommand( $cmds); } } return DiffusionMercurialWireProtocol::isReadOnlyCommand($cmd); case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: break; } return false; } /** * @phutil-external-symbol class PhabricatorStartup */ private function serveGitRequest( PhabricatorRepository $repository, PhabricatorUser $viewer) { $request = $this->getRequest(); $request_path = $this->getRequestDirectoryPath($repository); $repository_root = $repository->getLocalPath(); // Rebuild the query string to strip `__magic__` parameters and prevent // issues where we might interpret inputs like "service=read&service=write" // differently than the server does and pass it an unsafe command. // NOTE: This does not use getPassthroughRequestParameters() because // that code is HTTP-method agnostic and will encode POST data. $query_data = $_GET; foreach ($query_data as $key => $value) { if (!strncmp($key, '__', 2)) { unset($query_data[$key]); } } $query_string = phutil_build_http_querystring($query_data); // We're about to wipe out PATH with the rest of the environment, so // resolve the binary first. $bin = Filesystem::resolveBinary('git-http-backend'); if (!$bin) { throw new Exception( pht( 'Unable to find `%s` in %s!', 'git-http-backend', '$PATH')); } // NOTE: We do not set HTTP_CONTENT_ENCODING here, because we already // decompressed the request when we read the request body, so the body is // just plain data with no encoding. $env = array( 'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'], 'QUERY_STRING' => $query_string, 'CONTENT_TYPE' => $request->getHTTPHeader('Content-Type'), 'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'], 'GIT_PROJECT_ROOT' => $repository_root, 'GIT_HTTP_EXPORT_ALL' => '1', 'PATH_INFO' => $request_path, 'REMOTE_USER' => $viewer->getUsername(), // TODO: Set these correctly. // GIT_COMMITTER_NAME // GIT_COMMITTER_EMAIL ) + $this->getCommonEnvironment($viewer); $input = PhabricatorStartup::getRawInput(); $command = csprintf('%s', $bin); $command = PhabricatorDaemon::sudoCommandAsDaemonUser($command); $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $cluster_engine = id(new DiffusionRepositoryClusterEngine()) ->setViewer($viewer) ->setRepository($repository); $did_write_lock = false; if ($this->isReadOnlyRequest($repository)) { $cluster_engine->synchronizeWorkingCopyBeforeRead(); } else { $did_write_lock = true; $cluster_engine->synchronizeWorkingCopyBeforeWrite(); } $caught = null; try { list($err, $stdout, $stderr) = id(new ExecFuture('%C', $command)) ->setEnv($env, true) ->write($input) ->resolve(); } catch (Exception $ex) { $caught = $ex; } if ($did_write_lock) { $cluster_engine->synchronizeWorkingCopyAfterWrite(); } unset($unguarded); if ($caught) { throw $caught; } if ($err) { if ($this->isValidGitShallowCloneResponse($stdout, $stderr)) { // Ignore the error if the response passes this special check for // validity. $err = 0; } } if ($err) { return new PhabricatorVCSResponse( 500, pht( 'Error %d: %s', $err, phutil_utf8ize($stderr))); } return id(new DiffusionGitResponse())->setGitData($stdout); } private function getRequestDirectoryPath(PhabricatorRepository $repository) { $request = $this->getRequest(); $request_path = $request->getRequestURI()->getPath(); $info = PhabricatorRepository::parseRepositoryServicePath( $request_path, $repository->getVersionControlSystem()); $base_path = $info['path']; // For Git repositories, strip an optional directory component if it // isn't the name of a known Git resource. This allows users to clone // repositories as "/diffusion/X/anything.git", for example. if ($repository->isGit()) { $known = array( 'info', 'git-upload-pack', 'git-receive-pack', ); foreach ($known as $key => $path) { $known[$key] = preg_quote($path, '@'); } $known = implode('|', $known); if (preg_match('@^/([^/]+)/('.$known.')(/|$)@', $base_path)) { $base_path = preg_replace('@^/([^/]+)@', '', $base_path); } } return $base_path; } private function authenticateGitLFSUser( $username, PhutilOpaqueEnvelope $password, $identifier) { // Never accept these credentials for requests which aren't LFS requests. if (!$this->getIsGitLFSRequest()) { return null; } // If we have the wrong username, don't bother checking if the token // is right. if ($username !== DiffusionGitLFSTemporaryTokenType::HTTP_USERNAME) { return null; } // See PHI1123. We need to be able to constrain the token query with // "withTokenResources(...)" to take advantage of the key on the table. // In this case, the repository PHID is the "resource" we're after. // In normal workflows, we figure out the viewer first, then use the // viewer to load the repository, but that won't work here. Load the // repository as the omnipotent viewer, then use the repository PHID to // look for a token. $omnipotent_viewer = PhabricatorUser::getOmnipotentUser(); $repository = id(new PhabricatorRepositoryQuery()) ->setViewer($omnipotent_viewer) ->withIdentifiers(array($identifier)) ->executeOne(); if (!$repository) { return null; } $lfs_pass = $password->openEnvelope(); $lfs_hash = PhabricatorHash::weakDigest($lfs_pass); $token = id(new PhabricatorAuthTemporaryTokenQuery()) ->setViewer($omnipotent_viewer) ->withTokenResources(array($repository->getPHID())) ->withTokenTypes(array(DiffusionGitLFSTemporaryTokenType::TOKENTYPE)) ->withTokenCodes(array($lfs_hash)) ->withExpired(false) ->executeOne(); if (!$token) { return null; } $user = id(new PhabricatorPeopleQuery()) ->setViewer($omnipotent_viewer) ->withPHIDs(array($token->getUserPHID())) ->executeOne(); if (!$user) { return null; } if (!$user->isUserActivated()) { return null; } $this->gitLFSToken = $token; return $user; } private function authenticateHTTPRepositoryUser( $username, PhutilOpaqueEnvelope $password) { if (!PhabricatorEnv::getEnvConfig('diffusion.allow-http-auth')) { // No HTTP auth permitted. return null; } if (!strlen($username)) { // No username. return null; } if (!strlen($password->openEnvelope())) { // No password. return null; } $user = id(new PhabricatorPeopleQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withUsernames(array($username)) ->executeOne(); if (!$user) { // Username doesn't match anything. return null; } if (!$user->isUserActivated()) { // User is not activated. return null; } $request = $this->getRequest(); $content_source = PhabricatorContentSource::newFromRequest($request); $engine = id(new PhabricatorAuthPasswordEngine()) ->setViewer($user) ->setContentSource($content_source) ->setPasswordType(PhabricatorAuthPassword::PASSWORD_TYPE_VCS) ->setObject($user); if (!$engine->isValidPassword($password)) { return null; } return $user; } private function serveMercurialRequest( PhabricatorRepository $repository, PhabricatorUser $viewer) { $request = $this->getRequest(); $bin = Filesystem::resolveBinary('hg'); if (!$bin) { throw new Exception( pht( 'Unable to find `%s` in %s!', 'hg', '$PATH')); } $env = $this->getCommonEnvironment($viewer); $input = PhabricatorStartup::getRawInput(); $cmd = $request->getStr('cmd'); $args = $this->getMercurialArguments(); $args = $this->formatMercurialArguments($cmd, $args); if (strlen($input)) { $input = strlen($input)."\n".$input."0\n"; } $command = csprintf( '%s -R %s serve --stdio', $bin, $repository->getLocalPath()); $command = PhabricatorDaemon::sudoCommandAsDaemonUser($command); list($err, $stdout, $stderr) = id(new ExecFuture('%C', $command)) ->setEnv($env, true) ->setCWD($repository->getLocalPath()) ->write("{$cmd}\n{$args}{$input}") ->resolve(); if ($err) { return new PhabricatorVCSResponse( 500, pht('Error %d: %s', $err, $stderr)); } if ($cmd == 'getbundle' || $cmd == 'changegroup' || $cmd == 'changegroupsubset') { // We're not completely sure that "changegroup" and "changegroupsubset" // actually work, they're for very old Mercurial. $body = gzcompress($stdout); } else if ($cmd == 'unbundle') { // This includes diagnostic information and anything echoed by commit // hooks. We ignore `stdout` since it just has protocol garbage, and // substitute `stderr`. $body = strlen($stderr)."\n".$stderr; } else { list($length, $body) = explode("\n", $stdout, 2); if ($cmd == 'capabilities') { $body = DiffusionMercurialWireProtocol::filterBundle2Capability($body); } } return id(new DiffusionMercurialResponse())->setContent($body); } private function getMercurialArguments() { // Mercurial sends arguments in HTTP headers. "Why?", you might wonder, // "Why would you do this?". $args_raw = array(); for ($ii = 1;; $ii++) { $header = 'HTTP_X_HGARG_'.$ii; if (!array_key_exists($header, $_SERVER)) { break; } $args_raw[] = $_SERVER[$header]; } if ($args_raw) { $args_raw = implode('', $args_raw); return id(new PhutilQueryStringParser()) ->parseQueryString($args_raw); } // Sometimes arguments come in via the query string. Note that this will // not handle multi-value entries e.g. "a[]=1,a[]=2" however it's unclear // whether or how the mercurial protocol should handle this. $query = idx($_SERVER, 'QUERY_STRING', ''); $query_pairs = id(new PhutilQueryStringParser()) ->parseQueryString($query); foreach ($query_pairs as $key => $value) { // Filter out private/internal keys as well as the command itself. if (strncmp($key, '__', 2) && $key != 'cmd') { $args_raw[$key] = $value; } } // TODO: Arguments can also come in via request body for POST requests. The // body would be all arguments, url-encoded. return $args_raw; } private function formatMercurialArguments($command, array $arguments) { $spec = DiffusionMercurialWireProtocol::getCommandArgs($command); $out = array(); // Mercurial takes normal arguments like this: // // name <length(value)> // value $has_star = false; foreach ($spec as $arg_key) { if ($arg_key == '*') { $has_star = true; continue; } if (isset($arguments[$arg_key])) { $value = $arguments[$arg_key]; $size = strlen($value); $out[] = "{$arg_key} {$size}\n{$value}"; unset($arguments[$arg_key]); } } if ($has_star) { // Mercurial takes arguments for variable argument lists roughly like // this: // // * <count(args)> // argname1 <length(argvalue1)> // argvalue1 // argname2 <length(argvalue2)> // argvalue2 $count = count($arguments); $out[] = "* {$count}\n"; foreach ($arguments as $key => $value) { if (in_array($key, $spec)) { // We already added this argument above, so skip it. continue; } $size = strlen($value); $out[] = "{$key} {$size}\n{$value}"; } } return implode('', $out); } private function isValidGitShallowCloneResponse($stdout, $stderr) { // If you execute `git clone --depth N ...`, git sends a request which // `git-http-backend` responds to by emitting valid output and then exiting // with a failure code and an error message. If we ignore this error, // everything works. // This is a pretty funky fix: it would be nice to more precisely detect // that a request is a `--depth N` clone request, but we don't have any code // to decode protocol frames yet. Instead, look for reasonable evidence // in the output that we're looking at a `--depth` clone. // A valid x-git-upload-pack-result response during packfile negotiation // should end with a flush packet ("0000"). As long as that packet // terminates the response body in the response, we'll assume the response // is correct and complete. // See https://git-scm.com/docs/pack-protocol#_packfile_negotiation $stdout_regexp = '(^Content-Type: application/x-git-upload-pack-result)m'; $has_pack = preg_match($stdout_regexp, $stdout); if (strlen($stdout) >= 4) { $has_flush_packet = (substr($stdout, -4) === "0000"); } else { $has_flush_packet = false; } return ($has_pack && $has_flush_packet); } private function getCommonEnvironment(PhabricatorUser $viewer) { $remote_address = $this->getRequest()->getRemoteAddress(); return array( DiffusionCommitHookEngine::ENV_USER => $viewer->getUsername(), DiffusionCommitHookEngine::ENV_REMOTE_ADDRESS => $remote_address, DiffusionCommitHookEngine::ENV_REMOTE_PROTOCOL => 'http', ); } private function validateGitLFSRequest( PhabricatorRepository $repository, PhabricatorUser $viewer) { if (!$this->getIsGitLFSRequest()) { return null; } if (!$repository->canUseGitLFS()) { return new PhabricatorVCSResponse( 403, pht( 'The requested repository ("%s") does not support Git LFS.', $repository->getDisplayName())); } // If this is using an LFS token, sanity check that we're using it on the // correct repository. This shouldn't really matter since the user could // just request a proper token anyway, but it suspicious and should not // be permitted. $token = $this->getGitLFSToken(); if ($token) { $resource = $token->getTokenResource(); if ($resource !== $repository->getPHID()) { return new PhabricatorVCSResponse( 403, pht( 'The authentication token provided in the request is bound to '. 'a different repository than the requested repository ("%s").', $repository->getDisplayName())); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
true
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryURIViewController.php
src/applications/diffusion/controller/DiffusionRepositoryURIViewController.php
<?php final class DiffusionRepositoryURIViewController extends DiffusionController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $id = $request->getURIData('id'); $uri = id(new PhabricatorRepositoryURIQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->withRepositories(array($repository)) ->executeOne(); if (!$uri) { return new Aphront404Response(); } // For display, access the URI by loading it through the repository. This // may adjust builtin URIs for repository configuration, so we may end up // with a different view of builtin URIs than we'd see if we loaded them // directly from the database. See T12884. $repository_uris = $repository->getURIs(); $repository_uris = mpull($repository_uris, null, 'getID'); $uri = idx($repository_uris, $uri->getID()); if (!$uri) { return new Aphront404Response(); } $title = array( pht('URI'), $repository->getDisplayName(), ); $crumbs = $this->buildApplicationCrumbs(); $crumbs->setBorder(true); $crumbs->addTextCrumb( $repository->getDisplayName(), $repository->getURI()); $crumbs->addTextCrumb( pht('Manage'), $repository->getPathURI('manage/')); $panel_label = id(new DiffusionRepositoryURIsManagementPanel()) ->getManagementPanelLabel(); $panel_uri = $repository->getPathURI('manage/uris/'); $crumbs->addTextCrumb($panel_label, $panel_uri); $crumbs->addTextCrumb(pht('URI %d', $uri->getID())); $header_text = pht( '%s: URI %d', $repository->getDisplayName(), $uri->getID()); $header = id(new PHUIHeaderView()) ->setHeader($header_text) ->setHeaderIcon('fa-pencil'); if ($uri->getIsDisabled()) { $header->setStatus('fa-ban', 'dark', pht('Disabled')); } else { $header->setStatus('fa-check', 'bluegrey', pht('Active')); } $curtain = $this->buildCurtain($uri); $details = $this->buildPropertySection($uri); $timeline = $this->buildTransactionTimeline( $uri, new PhabricatorRepositoryURITransactionQuery()); $timeline->setShouldTerminate(true); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setMainColumn( array( $details, $timeline, )) ->setCurtain($curtain); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } private function buildCurtain(PhabricatorRepositoryURI $uri) { $viewer = $this->getViewer(); $repository = $uri->getRepository(); $id = $uri->getID(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $uri, PhabricatorPolicyCapability::CAN_EDIT); $curtain = $this->newCurtainView($uri); $edit_uri = $uri->getEditURI(); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit URI')) ->setHref($edit_uri) ->setWorkflow(!$can_edit) ->setDisabled(!$can_edit)); $credential_uri = $repository->getPathURI("uri/credential/{$id}/edit/"); $remove_uri = $repository->getPathURI("uri/credential/{$id}/remove/"); $has_credential = (bool)$uri->getCredentialPHID(); if ($uri->isBuiltin()) { $can_credential = false; } else if (!$uri->newCommandEngine()->isCredentialSupported()) { $can_credential = false; } else { $can_credential = true; } $can_update = ($can_edit && $can_credential); $can_remove = ($can_edit && $has_credential); if ($has_credential) { $credential_name = pht('Update Credential'); } else { $credential_name = pht('Set Credential'); } $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-key') ->setName($credential_name) ->setHref($credential_uri) ->setWorkflow(true) ->setDisabled(!$can_edit)); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-times') ->setName(pht('Remove Credential')) ->setHref($remove_uri) ->setWorkflow(true) ->setDisabled(!$can_remove)); if ($uri->getIsDisabled()) { $disable_name = pht('Enable URI'); $disable_icon = 'fa-check'; } else { $disable_name = pht('Disable URI'); $disable_icon = 'fa-ban'; } $can_disable = ($can_edit && !$uri->isBuiltin()); $disable_uri = $repository->getPathURI("uri/disable/{$id}/"); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon($disable_icon) ->setName($disable_name) ->setHref($disable_uri) ->setWorkflow(true) ->setDisabled(!$can_disable)); return $curtain; } private function buildPropertySection(PhabricatorRepositoryURI $uri) { $viewer = $this->getViewer(); $properties = id(new PHUIPropertyListView()) ->setUser($viewer); $properties->addProperty(pht('URI'), $uri->getDisplayURI()); $credential_phid = $uri->getCredentialPHID(); $command_engine = $uri->newCommandEngine(); $is_optional = $command_engine->isCredentialOptional(); $is_supported = $command_engine->isCredentialSupported(); $is_builtin = $uri->isBuiltin(); if ($is_builtin) { $credential_icon = 'fa-circle-o'; $credential_color = 'grey'; $credential_label = pht('Builtin'); $credential_note = pht('Builtin URIs do not use credentials.'); } else if (!$is_supported) { $credential_icon = 'fa-circle-o'; $credential_color = 'grey'; $credential_label = pht('Not Supported'); $credential_note = pht('This protocol does not support authentication.'); } else if (!$credential_phid) { if ($is_optional) { $credential_icon = 'fa-circle-o'; $credential_color = 'green'; $credential_label = pht('No Credential'); $credential_note = pht('Configured for anonymous access.'); } else { $credential_icon = 'fa-times'; $credential_color = 'red'; $credential_label = pht('Required'); $credential_note = pht('Credential required but not configured.'); } } else { // Don't raise a policy exception if we can't see the credential. $credentials = id(new PassphraseCredentialQuery()) ->setViewer($viewer) ->withPHIDs(array($credential_phid)) ->execute(); $credential = head($credentials); if (!$credential) { $handles = $viewer->loadHandles(array($credential_phid)); $handle = $handles[$credential_phid]; if ($handle->getPolicyFiltered()) { $credential_icon = 'fa-lock'; $credential_color = 'grey'; $credential_label = pht('Restricted'); $credential_note = pht( 'You do not have permission to view the configured '. 'credential.'); } else { $credential_icon = 'fa-times'; $credential_color = 'red'; $credential_label = pht('Invalid'); $credential_note = pht('Configured credential is invalid.'); } } else { $provides = $credential->getProvidesType(); $needs = $command_engine->getPassphraseProvidesCredentialType(); if ($provides != $needs) { $credential_icon = 'fa-times'; $credential_color = 'red'; $credential_label = pht('Wrong Type'); } else { $credential_icon = 'fa-check'; $credential_color = 'green'; $credential_label = $command_engine->getPassphraseCredentialLabel(); } $credential_note = $viewer->renderHandle($credential_phid); } } $credential_item = id(new PHUIStatusItemView()) ->setIcon($credential_icon, $credential_color) ->setTarget(phutil_tag('strong', array(), $credential_label)) ->setNote($credential_note); $credential_view = id(new PHUIStatusListView()) ->addItem($credential_item); $properties->addProperty(pht('Credential'), $credential_view); $io_type = $uri->getEffectiveIOType(); $io_map = PhabricatorRepositoryURI::getIOTypeMap(); $io_spec = idx($io_map, $io_type, array()); $io_icon = idx($io_spec, 'icon'); $io_color = idx($io_spec, 'color'); $io_label = idx($io_spec, 'label', $io_type); $io_note = idx($io_spec, 'note'); $io_item = id(new PHUIStatusItemView()) ->setIcon($io_icon, $io_color) ->setTarget(phutil_tag('strong', array(), $io_label)) ->setNote($io_note); $io_view = id(new PHUIStatusListView()) ->addItem($io_item); $properties->addProperty(pht('I/O'), $io_view); $display_type = $uri->getEffectiveDisplayType(); $display_map = PhabricatorRepositoryURI::getDisplayTypeMap(); $display_spec = idx($display_map, $display_type, array()); $display_icon = idx($display_spec, 'icon'); $display_color = idx($display_spec, 'color'); $display_label = idx($display_spec, 'label', $display_type); $display_note = idx($display_spec, 'note'); $display_item = id(new PHUIStatusItemView()) ->setIcon($display_icon, $display_color) ->setTarget(phutil_tag('strong', array(), $display_label)) ->setNote($display_note); $display_view = id(new PHUIStatusListView()) ->addItem($display_item); $properties->addProperty(pht('Display'), $display_view); 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/diffusion/controller/DiffusionIdentityEditController.php
src/applications/diffusion/controller/DiffusionIdentityEditController.php
<?php final class DiffusionIdentityEditController extends DiffusionController { public function handleRequest(AphrontRequest $request) { return id(new PhabricatorRepositoryIdentityEditEngine()) ->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/diffusion/controller/DiffusionCommitTagsController.php
src/applications/diffusion/controller/DiffusionCommitTagsController.php
<?php final class DiffusionCommitTagsController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $tag_limit = 10; $tags = DiffusionRepositoryTag::newFromConduit( $this->callConduitWithDiffusionRequest( 'diffusion.tagsquery', array( 'commit' => $drequest->getCommit(), 'limit' => $tag_limit + 1, ))); $has_more_tags = (count($tags) > $tag_limit); $tags = array_slice($tags, 0, $tag_limit); $tag_links = array(); foreach ($tags as $tag) { $tag_links[] = phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => 'browse', 'commit' => $tag->getName(), )), ), $tag->getName()); } if ($has_more_tags) { $tag_links[] = phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => 'tags', )), ), pht("More Tags\xE2\x80\xA6")); } return id(new AphrontAjaxResponse()) ->setContent($tag_links ? implode(', ', $tag_links) : pht('None')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryEditDangerousController.php
src/applications/diffusion/controller/DiffusionRepositoryEditDangerousController.php
<?php final class DiffusionRepositoryEditDangerousController extends DiffusionRepositoryManageController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $panel_uri = id(new DiffusionRepositoryBasicsManagementPanel()) ->setRepository($repository) ->getPanelURI(); if (!$repository->canAllowDangerousChanges()) { return $this->newDialog() ->setTitle(pht('Unprotectable Repository')) ->appendParagraph( pht( 'This repository can not be protected from dangerous changes '. 'because this server does not control what users are allowed '. 'to push to it.')) ->addCancelButton($panel_uri); } if ($request->isFormPost()) { $xaction = id(new PhabricatorRepositoryTransaction()) ->setTransactionType( PhabricatorRepositoryDangerousTransaction::TRANSACTIONTYPE) ->setNewValue(!$repository->shouldAllowDangerousChanges()); $editor = id(new PhabricatorRepositoryEditor()) ->setContinueOnNoEffect(true) ->setContentSourceFromRequest($request) ->setActor($viewer) ->applyTransactions($repository, array($xaction)); return id(new AphrontReloadResponse())->setURI($panel_uri); } $force = phutil_tag('tt', array(), '--force'); if ($repository->shouldAllowDangerousChanges()) { $title = pht('Prevent Dangerous Changes'); if ($repository->isSVN()) { $body = pht( 'It will no longer be possible to edit revprops in this '. 'repository.'); } else { $body = pht( 'It will no longer be possible to delete branches from this '. 'repository, or %s push to this repository.', $force); } $submit = pht('Prevent Dangerous Changes'); } else { $title = pht('Allow Dangerous Changes'); if ($repository->isSVN()) { $body = pht( 'If you allow dangerous changes, it will be possible to edit '. 'reprops in this repository, including arbitrarily rewriting '. 'commit messages. These operations can alter a repository in a '. 'way that is difficult to recover from.'); } else { $body = pht( 'If you allow dangerous changes, it will be possible to delete '. 'branches and %s push this repository. These operations can '. 'alter a repository in a way that is difficult to recover from.', $force); } $submit = pht('Allow Dangerous Changes'); } return $this->newDialog() ->setTitle($title) ->appendParagraph($body) ->addSubmitButton($submit) ->addCancelButton($panel_uri); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRepositoryEditDeleteController.php
src/applications/diffusion/controller/DiffusionRepositoryEditDeleteController.php
<?php final class DiffusionRepositoryEditDeleteController extends DiffusionRepositoryManageController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContextForEdit(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $panel_uri = id(new DiffusionRepositoryBasicsManagementPanel()) ->setRepository($repository) ->getPanelURI(); $doc_uri = PhabricatorEnv::getDoclink( 'Permanently Destroying Data'); return $this->newDialog() ->setTitle(pht('Delete Repository')) ->appendParagraph( pht( 'To permanently destroy this repository, run this command from '. 'the command line:')) ->appendCommand( csprintf( 'phabricator/ $ ./bin/remove destroy %R', $repository->getMonogram())) ->appendParagraph( pht( 'Repositories can not be permanently destroyed from the web '. 'interface. See %s in the documentation for more information.', phutil_tag( 'a', array( 'href' => $doc_uri, 'target' => '_blank', ), pht('Permanently Destroying Data')))) ->addCancelButton($panel_uri, pht('Close')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionCommitEditController.php
src/applications/diffusion/controller/DiffusionCommitEditController.php
<?php final class DiffusionCommitEditController extends DiffusionController { public function handleRequest(AphrontRequest $request) { return id(new DiffusionCommitEditEngine()) ->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/diffusion/controller/DiffusionCommitListController.php
src/applications/diffusion/controller/DiffusionCommitListController.php
<?php final class DiffusionCommitListController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { return id(new PhabricatorCommitSearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); $crumbs->addTextCrumb( pht('Commits'), $this->getApplicationURI('commit/')); 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/diffusion/controller/DiffusionDocumentController.php
src/applications/diffusion/controller/DiffusionDocumentController.php
<?php final class DiffusionDocumentController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); $engine = id(new DiffusionDocumentRenderingEngine()) ->setRequest($request) ->setDiffusionRequest($drequest) ->setController($this); $viewer = $this->getViewer(); $request = $this->getRequest(); $repository = $drequest->getRepository(); $file_phid = $request->getStr('filePHID'); $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($file_phid)) ->executeOne(); if (!$file) { return $engine->newErrorResponse( pht( 'This file ("%s") does not exist or could not be loaded.', $file_phid)); } $ref = id(new PhabricatorDocumentRef()) ->setFile($file); return $engine->newRenderResponse($ref); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionLogController.php
src/applications/diffusion/controller/DiffusionLogController.php
<?php abstract class DiffusionLogController extends DiffusionController { protected function shouldLoadDiffusionRequest() { 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/diffusion/controller/DiffusionPathTreeController.php
src/applications/diffusion/controller/DiffusionPathTreeController.php
<?php final class DiffusionPathTreeController extends DiffusionController { public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); if (!$repository->canUsePathTree()) { return new Aphront404Response(); } $paths = $this->callConduitWithDiffusionRequest( 'diffusion.querypaths', array( 'path' => $drequest->getPath(), 'commit' => $drequest->getCommit(), )); $tree = array(); foreach ($paths as $path) { $parts = preg_split('((?<=/))', $path); $cursor = &$tree; foreach ($parts as $part) { if (!is_array($cursor)) { $cursor = array(); } if (!isset($cursor[$part])) { $cursor[$part] = 1; } $cursor = &$cursor[$part]; } } return id(new AphrontAjaxResponse())->setContent(array('tree' => $tree)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionCloneController.php
src/applications/diffusion/controller/DiffusionCloneController.php
<?php final class DiffusionCloneController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $response = $this->loadDiffusionContext(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $view = id(new PHUIPropertyListView()) ->setUser($viewer); $display_never = PhabricatorRepositoryURI::DISPLAY_NEVER; $warning = null; $uris = $repository->getURIs(); foreach ($uris as $uri) { if ($uri->getIsDisabled()) { continue; } if ($uri->getEffectiveDisplayType() == $display_never) { continue; } if ($repository->isSVN()) { $label = phutil_tag_div('diffusion-clone-label', pht('Checkout')); } else { $label = phutil_tag_div('diffusion-clone-label', pht('Clone')); } $view->addProperty( $label, $this->renderCloneURI($repository, $uri)); } if (!$view->hasAnyProperties()) { $view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->appendChild(pht('Repository has no URIs set.')); } $info = null; // Try to load alternatives. This may fail for repositories which have not // cloned yet. If it does, just ignore it and continue. try { $alternatives = $drequest->getRefAlternatives(); } catch (ConduitClientException $ex) { $alternatives = array(); } if ($alternatives) { $message = array( pht( 'The ref "%s" is ambiguous in this repository.', $drequest->getBranch()), ' ', phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => 'refs', )), ), pht('View Alternatives')), ); $messages = array($message); $warning = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors(array($message)); } $cancel_uri = $drequest->generateURI( array( 'action' => 'branch', 'path' => '/', )); return $this->newDialog() ->setTitle(pht('Clone Repository')) ->setWidth(AphrontDialogView::WIDTH_FORM) ->addCancelButton($cancel_uri, pht('Close')) ->appendChild(array($view, $warning)); } private function renderCloneURI( PhabricatorRepository $repository, PhabricatorRepositoryURI $uri) { if ($repository->isSVN()) { $display = csprintf( 'svn checkout %R %R', (string)$uri->getDisplayURI(), $repository->getCloneName()); } else { $display = csprintf('%R', (string)$uri->getDisplayURI()); } $display = (string)$display; $viewer = $this->getViewer(); return id(new DiffusionCloneURIView()) ->setViewer($viewer) ->setRepository($repository) ->setRepositoryURI($uri) ->setDisplayURI($display); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionBrowseController.php
src/applications/diffusion/controller/DiffusionBrowseController.php
<?php final class DiffusionBrowseController extends DiffusionController { private $lintCommit; private $lintMessages; private $corpusButtons = array(); public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); // Figure out if we're browsing a directory, a file, or a search result // list. $grep = $request->getStr('grep'); if (phutil_nonempty_string($grep)) { return $this->browseSearch(); } $pager = id(new PHUIPagerView()) ->readFromRequest($request); $results = DiffusionBrowseResultSet::newFromConduit( $this->callConduitWithDiffusionRequest( 'diffusion.browsequery', array( 'path' => $drequest->getPath(), 'commit' => $drequest->getStableCommit(), 'offset' => $pager->getOffset(), 'limit' => $pager->getPageSize() + 1, ))); $reason = $results->getReasonForEmptyResultSet(); $is_file = ($reason == DiffusionBrowseResultSet::REASON_IS_FILE); if ($is_file) { return $this->browseFile(); } $paths = $results->getPaths(); $paths = $pager->sliceResults($paths); $results->setPaths($paths); return $this->browseDirectory($results, $pager); } private function browseSearch() { $drequest = $this->getDiffusionRequest(); $header = $this->buildHeaderView($drequest); $path = nonempty(basename($drequest->getPath()), '/'); $search_results = $this->renderSearchResults(); $search_form = $this->renderSearchForm($path); $search_form = phutil_tag( 'div', array( 'class' => 'diffusion-mobile-search-form', ), $search_form); $crumbs = $this->buildCrumbs( array( 'branch' => true, 'path' => true, 'view' => 'browse', )); $crumbs->setBorder(true); $tabs = $this->buildTabsView('code'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setTabs($tabs) ->setFooter( array( $search_form, $search_results, )); return $this->newPage() ->setTitle( array( nonempty(basename($drequest->getPath()), '/'), $drequest->getRepository()->getDisplayName(), )) ->setCrumbs($crumbs) ->appendChild($view); } private function browseFile() { $viewer = $this->getViewer(); $request = $this->getRequest(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $before = $request->getStr('before'); if ($before) { return $this->buildBeforeResponse($before); } $path = $drequest->getPath(); $params = array( 'commit' => $drequest->getCommit(), 'path' => $drequest->getPath(), ); $view = $request->getStr('view'); $byte_limit = null; if ($view !== 'raw') { $byte_limit = PhabricatorFileStorageEngine::getChunkThreshold(); $time_limit = 10; $params += array( 'timeout' => $time_limit, 'byteLimit' => $byte_limit, ); } $response = $this->callConduitWithDiffusionRequest( 'diffusion.filecontentquery', $params); $hit_byte_limit = $response['tooHuge']; $hit_time_limit = $response['tooSlow']; $file_phid = $response['filePHID']; $show_editor = false; if ($hit_byte_limit) { $corpus = $this->buildErrorCorpus( pht( 'This file is larger than %s byte(s), and too large to display '. 'in the web UI.', phutil_format_bytes($byte_limit))); } else if ($hit_time_limit) { $corpus = $this->buildErrorCorpus( pht( 'This file took too long to load from the repository (more than '. '%s second(s)).', new PhutilNumber($time_limit))); } else { $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($file_phid)) ->executeOne(); if (!$file) { throw new Exception(pht('Failed to load content file!')); } if ($view === 'raw') { return $file->getRedirectResponse(); } $data = $file->loadFileData(); $lfs_ref = $this->getGitLFSRef($repository, $data); if ($lfs_ref) { if ($view == 'git-lfs') { $file = $this->loadGitLFSFile($lfs_ref); // Rename the file locally so we generate a better vanity URI for // it. In storage, it just has a name like "lfs-13f9a94c0923...", // since we don't get any hints about possible human-readable names // at upload time. $basename = basename($drequest->getPath()); $file->makeEphemeral(); $file->setName($basename); return $file->getRedirectResponse(); } $corpus = $this->buildGitLFSCorpus($lfs_ref); } else { $show_editor = true; $ref = id(new PhabricatorDocumentRef()) ->setFile($file); $engine = id(new DiffusionDocumentRenderingEngine()) ->setRequest($request) ->setDiffusionRequest($drequest); $corpus = $engine->newDocumentView($ref); $this->corpusButtons[] = $this->renderFileButton(); } } $bar = $this->buildButtonBar($drequest, $show_editor); $header = $this->buildHeaderView($drequest); $header->setHeaderIcon('fa-file-code-o'); $follow = $request->getStr('follow'); $follow_notice = null; if ($follow) { $follow_notice = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setTitle(pht('Unable to Continue')); switch ($follow) { case 'first': $follow_notice->appendChild( pht( 'Unable to continue tracing the history of this file because '. 'this commit is the first commit in the repository.')); break; case 'created': $follow_notice->appendChild( pht( 'Unable to continue tracing the history of this file because '. 'this commit created the file.')); break; } } $renamed = $request->getStr('renamed'); $renamed_notice = null; if ($renamed) { $renamed_notice = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->setTitle(pht('File Renamed')) ->appendChild( pht( 'File history passes through a rename from "%s" to "%s".', $drequest->getPath(), $renamed)); } $open_revisions = $this->buildOpenRevisions(); $owners_list = $this->buildOwnersList($drequest); $crumbs = $this->buildCrumbs( array( 'branch' => true, 'path' => true, 'view' => 'browse', )); $crumbs->setBorder(true); $basename = basename($this->getDiffusionRequest()->getPath()); $tabs = $this->buildTabsView('code'); $bar->setRight($this->corpusButtons); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setTabs($tabs) ->setFooter(array( $bar, $follow_notice, $renamed_notice, $corpus, $open_revisions, $owners_list, )); $title = array($basename, $repository->getDisplayName()); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild( array( $view, )); } public function browseDirectory( DiffusionBrowseResultSet $results, PHUIPagerView $pager) { $request = $this->getRequest(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $reason = $results->getReasonForEmptyResultSet(); $this->buildActionButtons($drequest, true); $details = $this->buildPropertyView($drequest); $header = $this->buildHeaderView($drequest); $header->setHeaderIcon('fa-folder-open'); $title = '/'; if ($drequest->getPath() !== null) { $title = nonempty(basename($drequest->getPath()), '/'); } $empty_result = null; $browse_panel = null; if (!$results->isValidResults()) { $empty_result = new DiffusionEmptyResultView(); $empty_result->setDiffusionRequest($drequest); $empty_result->setDiffusionBrowseResultSet($results); $empty_result->setView($request->getStr('view')); } else { $browse_table = id(new DiffusionBrowseTableView()) ->setDiffusionRequest($drequest) ->setPaths($results->getPaths()) ->setUser($request->getUser()); $icon = 'fa-folder-open'; $browse_header = $this->buildPanelHeaderView($title, $icon); $browse_panel = id(new PHUIObjectBoxView()) ->setHeader($browse_header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($browse_table) ->addClass('diffusion-mobile-view') ->setPager($pager); } $open_revisions = $this->buildOpenRevisions(); $readme = $this->renderDirectoryReadme($results); $crumbs = $this->buildCrumbs( array( 'branch' => true, 'path' => true, 'view' => 'browse', )); $crumbs->setBorder(true); $tabs = $this->buildTabsView('code'); $owners_list = $this->buildOwnersList($drequest); $bar = id(new PHUILeftRightView()) ->setRight($this->corpusButtons) ->addClass('diffusion-action-bar'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setTabs($tabs) ->setFooter( array( $bar, $empty_result, $browse_panel, $open_revisions, $owners_list, $readme, )); if ($details) { $view->addPropertySection(pht('Details'), $details); } return $this->newPage() ->setTitle(array( $title, $repository->getDisplayName(), )) ->setCrumbs($crumbs) ->appendChild( array( $view, )); } private function renderSearchResults() { $request = $this->getRequest(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $results = array(); $pager = id(new PHUIPagerView()) ->readFromRequest($request); $search_mode = null; switch ($repository->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $results = array(); break; default: if (strlen($this->getRequest()->getStr('grep'))) { $search_mode = 'grep'; $query_string = $request->getStr('grep'); $results = $this->callConduitWithDiffusionRequest( 'diffusion.searchquery', array( 'grep' => $query_string, 'commit' => $drequest->getStableCommit(), 'path' => $drequest->getPath(), 'limit' => $pager->getPageSize() + 1, 'offset' => $pager->getOffset(), )); } break; } $results = $pager->sliceResults($results); $table = null; $header = null; if ($search_mode == 'grep') { $table = $this->renderGrepResults($results, $query_string); $title = pht( 'File content matching "%s" under "%s"', $query_string, nonempty($drequest->getPath(), '/')); $header = id(new PHUIHeaderView()) ->setHeader($title) ->addClass('diffusion-search-result-header'); } return array($header, $table, $pager); } private function renderGrepResults(array $results, $pattern) { $drequest = $this->getDiffusionRequest(); require_celerity_resource('phabricator-search-results-css'); if (!$results) { return id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NODATA) ->appendChild( pht( 'The pattern you searched for was not found in the content of any '. 'files.')); } $grouped = array(); foreach ($results as $file) { list($path, $line, $string) = $file; $grouped[$path][] = array($line, $string); } $view = array(); foreach ($grouped as $path => $matches) { $view[] = id(new DiffusionPatternSearchView()) ->setPath($path) ->setMatches($matches) ->setPattern($pattern) ->setDiffusionRequest($drequest) ->render(); } return $view; } private function buildButtonBar( DiffusionRequest $drequest, $show_editor) { $viewer = $this->getViewer(); $base_uri = $this->getRequest()->getRequestURI(); $repository = $drequest->getRepository(); $path = $drequest->getPath(); $line = nonempty((int)$drequest->getLine(), 1); $buttons = array(); $editor_uri = null; $editor_template = null; $link_engine = PhabricatorEditorURIEngine::newForViewer($viewer); if ($link_engine) { $link_engine->setRepository($repository); $editor_uri = $link_engine->getURIForPath($path, $line); $editor_template = $link_engine->getURITokensForPath($path); } $buttons[] = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Last Change')) ->setColor(PHUIButtonView::GREY) ->setHref( $drequest->generateURI( array( 'action' => 'change', ))) ->setIcon('fa-backward'); if ($editor_uri) { $buttons[] = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Open File')) ->setHref($editor_uri) ->setIcon('fa-pencil') ->setID('editor_link') ->setMetadata(array('template' => $editor_template)) ->setDisabled(!$editor_uri) ->setColor(PHUIButtonView::GREY); } $bar = id(new PHUILeftRightView()) ->setLeft($buttons) ->addClass('diffusion-action-bar full-mobile-buttons'); return $bar; } private function buildOwnersList(DiffusionRequest $drequest) { $viewer = $this->getViewer(); $have_owners = PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorOwnersApplication', $viewer); if (!$have_owners) { return null; } $repository = $drequest->getRepository(); $package_query = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withStatuses(array(PhabricatorOwnersPackage::STATUS_ACTIVE)) ->withControl( $repository->getPHID(), array( $drequest->getPath(), )); $package_query->execute(); $packages = $package_query->getControllingPackagesForPath( $repository->getPHID(), $drequest->getPath()); $ownership = id(new PHUIObjectItemListView()) ->setUser($viewer) ->setNoDataString(pht('No Owners')); if ($packages) { foreach ($packages as $package) { $item = id(new PHUIObjectItemView()) ->setObject($package) ->setObjectName($package->getMonogram()) ->setHeader($package->getName()) ->setHref($package->getURI()); $owners = $package->getOwners(); if ($owners) { $owner_list = $viewer->renderHandleList( mpull($owners, 'getUserPHID')); } else { $owner_list = phutil_tag('em', array(), pht('None')); } $item->addAttribute(pht('Owners: %s', $owner_list)); $auto = $package->getAutoReview(); $autoreview_map = PhabricatorOwnersPackage::getAutoreviewOptionsMap(); $spec = idx($autoreview_map, $auto, array()); $name = idx($spec, 'name', $auto); $item->addIcon('fa-code', $name); $rule = $package->newAuditingRule(); $item->addIcon($rule->getIconIcon(), $rule->getDisplayName()); if ($package->isArchived()) { $item->setDisabled(true); } $ownership->addItem($item); } } $view = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Owner Packages')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addClass('diffusion-mobile-view') ->setObjectList($ownership); return $view; } private function renderFileButton($file_uri = null, $label = null) { $base_uri = $this->getRequest()->getRequestURI(); if ($file_uri) { $text = pht('Download File'); $href = $file_uri; $icon = 'fa-download'; } else { $text = pht('Raw File'); $href = $base_uri->alter('view', 'raw'); $icon = 'fa-file-text'; } if ($label !== null) { $text = $label; } $button = id(new PHUIButtonView()) ->setTag('a') ->setText($text) ->setHref($href) ->setIcon($icon) ->setColor(PHUIButtonView::GREY); return $button; } private function renderGitLFSButton() { $viewer = $this->getViewer(); $uri = $this->getRequest()->getRequestURI(); $href = $uri->alter('view', 'git-lfs'); $text = pht('Download from Git LFS'); $icon = 'fa-download'; return id(new PHUIButtonView()) ->setTag('a') ->setText($text) ->setHref($href) ->setIcon($icon) ->setColor(PHUIButtonView::GREY); } private function buildErrorCorpus($message) { $text = id(new PHUIBoxView()) ->addPadding(PHUI::PADDING_LARGE) ->appendChild($message); $header = id(new PHUIHeaderView()) ->setHeader(pht('Details')); $box = id(new PHUIObjectBoxView()) ->setHeader($header) ->appendChild($text); return $box; } private function buildBeforeResponse($before) { $request = $this->getRequest(); $drequest = $this->getDiffusionRequest(); // NOTE: We need to get the grandparent so we can capture filename changes // in the parent. $parent = $this->loadParentCommitOf($before); $old_filename = null; $was_created = false; if ($parent) { $grandparent = $this->loadParentCommitOf($parent); if ($grandparent) { $rename_query = new DiffusionRenameHistoryQuery(); $rename_query->setRequest($drequest); $rename_query->setOldCommit($grandparent); $rename_query->setViewer($request->getUser()); $old_filename = $rename_query->loadOldFilename(); $was_created = $rename_query->getWasCreated(); } } $follow = null; if ($was_created) { // If the file was created in history, that means older commits won't // have it. Since we know it existed at 'before', it must have been // created then; jump there. $target_commit = $before; $follow = 'created'; } else if ($parent) { // If we found a parent, jump to it. This is the normal case. $target_commit = $parent; } else { // If there's no parent, this was probably created in the initial commit? // And the "was_created" check will fail because we can't identify the // grandparent. Keep the user at 'before'. $target_commit = $before; $follow = 'first'; } $path = $drequest->getPath(); $renamed = null; if ($old_filename !== null && $old_filename !== '/'.$path) { $renamed = $path; $path = $old_filename; } $line = null; // If there's a follow error, drop the line so the user sees the message. if (!$follow) { $line = $this->getBeforeLineNumber($target_commit); } $before_uri = $drequest->generateURI( array( 'action' => 'browse', 'commit' => $target_commit, 'line' => $line, 'path' => $path, )); if ($renamed === null) { $before_uri->removeQueryParam('renamed'); } else { $before_uri->replaceQueryParam('renamed', $renamed); } if ($follow === null) { $before_uri->removeQueryParam('follow'); } else { $before_uri->replaceQueryParam('follow', $follow); } return id(new AphrontRedirectResponse())->setURI($before_uri); } private function getBeforeLineNumber($target_commit) { $drequest = $this->getDiffusionRequest(); $viewer = $this->getViewer(); $line = $drequest->getLine(); if (!$line) { return null; } $diff_info = $this->callConduitWithDiffusionRequest( 'diffusion.rawdiffquery', array( 'commit' => $drequest->getCommit(), 'path' => $drequest->getPath(), 'againstCommit' => $target_commit, )); $file_phid = $diff_info['filePHID']; $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($file_phid)) ->executeOne(); if (!$file) { throw new Exception( pht( 'Failed to load file ("%s") returned by "%s".', $file_phid, 'diffusion.rawdiffquery.')); } $raw_diff = $file->loadFileData(); $old_line = 0; $new_line = 0; foreach (explode("\n", $raw_diff) as $text) { if ($text[0] == '-' || $text[0] == ' ') { $old_line++; } if ($text[0] == '+' || $text[0] == ' ') { $new_line++; } if ($new_line == $line) { return $old_line; } } // We didn't find the target line. return $line; } private function loadParentCommitOf($commit) { $drequest = $this->getDiffusionRequest(); $user = $this->getRequest()->getUser(); $before_req = DiffusionRequest::newFromDictionary( array( 'user' => $user, 'repository' => $drequest->getRepository(), 'commit' => $commit, )); $parents = DiffusionQuery::callConduitWithDiffusionRequest( $user, $before_req, 'diffusion.commitparentsquery', array( 'commit' => $commit, )); return head($parents); } protected function markupText($text) { $engine = PhabricatorMarkupEngine::newDiffusionMarkupEngine(); $engine->setConfig('viewer', $this->getRequest()->getUser()); $text = $engine->markupText($text); $text = phutil_tag( 'div', array( 'class' => 'phabricator-remarkup', ), $text); return $text; } protected function buildHeaderView(DiffusionRequest $drequest) { $viewer = $this->getViewer(); $repository = $drequest->getRepository(); $commit_tag = $this->renderCommitHashTag($drequest); $path = nonempty($drequest->getPath(), '/'); $search = $this->renderSearchForm($path); $header = id(new PHUIHeaderView()) ->setUser($viewer) ->setHeader($this->renderPathLinks($drequest, $mode = 'browse')) ->addActionItem($search) ->addTag($commit_tag) ->addClass('diffusion-browse-header'); if (!$repository->isSVN()) { $branch_tag = $this->renderBranchTag($drequest); $header->addTag($branch_tag); } return $header; } protected function buildPanelHeaderView($title, $icon) { $header = id(new PHUIHeaderView()) ->setHeader($title) ->setHeaderIcon($icon) ->addClass('diffusion-panel-header-view'); return $header; } protected function buildActionButtons( DiffusionRequest $drequest, $is_directory = false) { $viewer = $this->getViewer(); $repository = $drequest->getRepository(); $history_uri = $drequest->generateURI(array('action' => 'history')); $behind_head = $drequest->getSymbolicCommit(); $compare = null; $head_uri = $drequest->generateURI( array( 'commit' => '', 'action' => 'browse', )); if ($repository->supportsBranchComparison() && $is_directory) { $compare_uri = $drequest->generateURI(array('action' => 'compare')); $compare = id(new PHUIButtonView()) ->setText(pht('Compare')) ->setIcon('fa-code-fork') ->setWorkflow(true) ->setTag('a') ->setHref($compare_uri) ->setColor(PHUIButtonView::GREY); $this->corpusButtons[] = $compare; } $head = null; if ($behind_head) { $head = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Back to HEAD')) ->setHref($head_uri) ->setIcon('fa-home') ->setColor(PHUIButtonView::GREY); $this->corpusButtons[] = $head; } $history = id(new PHUIButtonView()) ->setText(pht('History')) ->setHref($history_uri) ->setTag('a') ->setIcon('fa-history') ->setColor(PHUIButtonView::GREY); $this->corpusButtons[] = $history; } protected function buildPropertyView( DiffusionRequest $drequest) { $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setUser($viewer); if ($drequest->getSymbolicType() == 'tag') { $symbolic = $drequest->getSymbolicCommit(); $view->addProperty(pht('Tag'), $symbolic); $tags = $this->callConduitWithDiffusionRequest( 'diffusion.tagsquery', array( 'names' => array($symbolic), 'needMessages' => true, )); $tags = DiffusionRepositoryTag::newFromConduit($tags); $tags = mpull($tags, null, 'getName'); $tag = idx($tags, $symbolic); if ($tag && strlen($tag->getMessage())) { $view->addSectionHeader( pht('Tag Content'), 'fa-tag'); $view->addTextContent($this->markupText($tag->getMessage())); } } if ($view->hasAnyProperties()) { return $view; } return null; } private function buildOpenRevisions() { $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $path = $drequest->getPath(); $recent = (PhabricatorTime::getNow() - phutil_units('30 days in seconds')); $revisions = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withPaths(array($path)) ->withRepositoryPHIDs(array($repository->getPHID())) ->withIsOpen(true) ->withUpdatedEpochBetween($recent, null) ->setOrder(DifferentialRevisionQuery::ORDER_MODIFIED) ->setLimit(10) ->needReviewers(true) ->needFlags(true) ->needDrafts(true) ->execute(); if (!$revisions) { return null; } $header = id(new PHUIHeaderView()) ->setHeader(pht('Recent Open Revisions')); $list = id(new DifferentialRevisionListView()) ->setViewer($viewer) ->setRevisions($revisions) ->setNoBox(true); $view = id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addClass('diffusion-mobile-view') ->appendChild($list); return $view; } private function getGitLFSRef(PhabricatorRepository $repository, $data) { if (!$repository->canUseGitLFS()) { return null; } $lfs_pattern = '(^version https://git-lfs\\.github\\.com/spec/v1[\r\n])'; if (!preg_match($lfs_pattern, $data)) { return null; } $matches = null; if (!preg_match('(^oid sha256:(.*)$)m', $data, $matches)) { return null; } $hash = $matches[1]; $hash = trim($hash); return id(new PhabricatorRepositoryGitLFSRefQuery()) ->setViewer($this->getViewer()) ->withRepositoryPHIDs(array($repository->getPHID())) ->withObjectHashes(array($hash)) ->executeOne(); } private function buildGitLFSCorpus(PhabricatorRepositoryGitLFSRef $ref) { // TODO: We should probably test if we can load the file PHID here and // show the user an error if we can't, rather than making them click // through to hit an error. $title = basename($this->getDiffusionRequest()->getPath()); $icon = 'fa-archive'; $drequest = $this->getDiffusionRequest(); $this->buildActionButtons($drequest); $header = $this->buildPanelHeaderView($title, $icon); $severity = PHUIInfoView::SEVERITY_NOTICE; $messages = array(); $messages[] = pht( 'This %s file is stored in Git Large File Storage.', phutil_format_bytes($ref->getByteSize())); try { $file = $this->loadGitLFSFile($ref); $this->corpusButtons[] = $this->renderGitLFSButton(); } catch (Exception $ex) { $severity = PHUIInfoView::SEVERITY_ERROR; $messages[] = pht('The data for this file could not be loaded.'); } $this->corpusButtons[] = $this->renderFileButton( null, pht('View Raw LFS Pointer')); $corpus = id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addClass('diffusion-mobile-view') ->setCollapsed(true); if ($messages) { $corpus->setInfoView( id(new PHUIInfoView()) ->setSeverity($severity) ->setErrors($messages)); } return $corpus; } private function loadGitLFSFile(PhabricatorRepositoryGitLFSRef $ref) { $viewer = $this->getViewer(); $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($ref->getFilePHID())) ->executeOne(); if (!$file) { throw new Exception( pht( 'Failed to load file object for Git LFS ref "%s"!', $ref->getObjectHash())); } return $file; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionBlameController.php
src/applications/diffusion/controller/DiffusionBlameController.php
<?php final class DiffusionBlameController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $blame = $this->loadBlame(); $identifiers = array_fuse($blame); if ($identifiers) { $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($repository) ->withIdentifiers($identifiers) ->needIdentities(true) // See PHI1014. If identities haven't been built yet, we may need to // fall back to raw commit data. ->needCommitData(true) ->execute(); $commits = mpull($commits, null, 'getCommitIdentifier'); } else { $commits = array(); } $commit_map = mpull($commits, 'getCommitIdentifier', 'getPHID'); $revision_map = DiffusionCommitRevisionQuery::loadRevisionMapForCommits( $viewer, $commits); $base_href = (string)$drequest->generateURI( array( 'action' => 'browse', 'stable' => true, )); $skip_text = pht('Skip Past This Commit'); $skip_icon = id(new PHUIIconView()) ->setIcon('fa-backward'); Javelin::initBehavior('phabricator-tooltips'); $handle_phids = array(); foreach ($commits as $commit) { $handle_phids[] = $commit->getAuthorDisplayPHID(); } foreach ($revision_map as $revisions) { foreach ($revisions as $revision) { $handle_phids[] = $revision->getAuthorPHID(); } } $handles = $viewer->loadHandles($handle_phids); $map = array(); $epochs = array(); foreach ($identifiers as $identifier) { $skip_href = $base_href.'?before='.$identifier; $skip_link = javelin_tag( 'a', array( 'href' => $skip_href, 'sigil' => 'has-tooltip', 'meta' => array( 'tip' => $skip_text, 'align' => 'E', 'size' => 300, ), ), $skip_icon); // We may not have a commit object for a given identifier if the commit // has not imported yet. // At time of writing, this can also happen if a line was part of the // initial import: blame produces a "^abc123" identifier in Git, which // doesn't correspond to a real commit. $commit = idx($commits, $identifier); $revision = null; if ($commit) { $revisions = idx($revision_map, $commit->getPHID()); // There may be multiple edges between this commit and revisions in the // database. If there are, just pick one arbitrarily. if ($revisions) { $revision = head($revisions); } } $author_phid = null; if ($commit) { $author_phid = $commit->getAuthorDisplayPHID(); } if (!$author_phid) { // This means we couldn't identify an author for the commit or the // revision. We just render a blank for alignment. $author_style = null; $author_href = null; $author_sigil = null; $author_meta = null; } else { $author_src = $handles[$author_phid]->getImageURI(); $author_style = 'background-image: url('.$author_src.');'; $author_href = $handles[$author_phid]->getURI(); $author_sigil = 'has-tooltip'; $author_meta = array( 'tip' => $handles[$author_phid]->getName(), 'align' => 'E', 'size' => 'auto', ); } $author_link = javelin_tag( $author_href ? 'a' : 'span', array( 'class' => 'phabricator-source-blame-author', 'style' => $author_style, 'href' => $author_href, 'sigil' => $author_sigil, 'meta' => $author_meta, )); if ($commit) { $commit_link = javelin_tag( 'a', array( 'href' => $commit->getURI(), 'sigil' => 'has-tooltip', 'meta' => array( 'tip' => $this->renderCommitTooltip($commit, $handles), 'align' => 'E', 'size' => 600, ), ), $commit->getLocalName()); } else { $commit_link = null; } $info = array( $author_link, $commit_link, ); if ($revision) { $revision_link = javelin_tag( 'a', array( 'href' => $revision->getURI(), 'sigil' => 'has-tooltip', 'meta' => array( 'tip' => $this->renderRevisionTooltip($revision, $handles), 'align' => 'E', 'size' => 600, ), ), $revision->getMonogram()); $info = array( $info, " \xC2\xB7 ", $revision_link, ); } if ($commit) { $epoch = $commit->getEpoch(); } else { $epoch = 0; } $epochs[] = $epoch; $data = array( 'skip' => $skip_link, 'info' => hsprintf('%s', $info), 'epoch' => $epoch, ); $map[$identifier] = $data; } $epoch_min = min($epochs); $epoch_max = max($epochs); return id(new AphrontAjaxResponse())->setContent( array( 'blame' => $blame, 'map' => $map, 'epoch' => array( 'min' => $epoch_min, 'max' => $epoch_max, ), )); } private function loadBlame() { $drequest = $this->getDiffusionRequest(); $commit = $drequest->getCommit(); $path = $drequest->getPath(); $blame_timeout = 15; $blame = $this->callConduitWithDiffusionRequest( 'diffusion.blame', array( 'commit' => $commit, 'paths' => array($path), 'timeout' => $blame_timeout, )); return idx($blame, $path, array()); } private function renderRevisionTooltip( DifferentialRevision $revision, $handles) { $viewer = $this->getViewer(); $date = phabricator_date($revision->getDateModified(), $viewer); $monogram = $revision->getMonogram(); $title = $revision->getTitle(); $header = "{$monogram} {$title}"; $author = $handles[$revision->getAuthorPHID()]->getName(); return "{$header}\n{$date} \xC2\xB7 {$author}"; } private function renderCommitTooltip( PhabricatorRepositoryCommit $commit, $handles) { $viewer = $this->getViewer(); $date = phabricator_date($commit->getEpoch(), $viewer); $summary = trim($commit->getSummary()); $author_phid = $commit->getAuthorPHID(); if ($author_phid && isset($handles[$author_phid])) { $author_name = $handles[$author_phid]->getName(); } else { $author_name = null; } if ($author_name) { return "{$summary}\n{$date} \xC2\xB7 {$author_name}"; } else { return "{$summary}\n{$date}"; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionPushEventViewController.php
src/applications/diffusion/controller/DiffusionPushEventViewController.php
<?php final class DiffusionPushEventViewController extends DiffusionLogController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $event = id(new PhabricatorRepositoryPushEventQuery()) ->setViewer($viewer) ->withIDs(array($request->getURIData('id'))) ->needLogs(true) ->executeOne(); if (!$event) { return new Aphront404Response(); } $repository = $event->getRepository(); $title = pht('Push %d', $event->getID()); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb( $repository->getName(), $repository->getURI()); $crumbs->addTextCrumb( pht('Push Logs'), $this->getApplicationURI( 'pushlog/?repositories='.$repository->getMonogram())); $crumbs->addTextCrumb($title); $event_properties = $this->buildPropertyList($event); $detail_box = id(new PHUIObjectBoxView()) ->setHeaderText($title) ->addPropertyList($event_properties); $commits = $this->loadCommits($event); $commits_table = $this->renderCommitsTable($event, $commits); $commits_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Pushed Commits')) ->setTable($commits_table); $logs = $event->getLogs(); $updates_table = id(new DiffusionPushLogListView()) ->setUser($viewer) ->setLogs($logs); $update_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('All Pushed Updates')) ->setTable($updates_table); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild( array( $detail_box, $commits_box, $update_box, )); } private function buildPropertyList(PhabricatorRepositoryPushEvent $event) { $viewer = $this->getRequest()->getUser(); $view = new PHUIPropertyListView(); $view->addProperty( pht('Pushed At'), phabricator_datetime($event->getEpoch(), $viewer)); $view->addProperty( pht('Pushed By'), $viewer->renderHandle($event->getPusherPHID())); $view->addProperty( pht('Pushed Via'), $event->getRemoteProtocol()); return $view; } private function loadCommits(PhabricatorRepositoryPushEvent $event) { $viewer = $this->getRequest()->getUser(); $identifiers = array(); foreach ($event->getLogs() as $log) { if ($log->getRefType() == PhabricatorRepositoryPushLog::REFTYPE_COMMIT) { $identifiers[] = $log->getRefNew(); } } if (!$identifiers) { return array(); } // NOTE: Commits may not have been parsed/discovered yet. We need to return // the identifiers no matter what. If possible, we'll also return the // corresponding commits. $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($event->getRepository()) ->withIdentifiers($identifiers) ->execute(); $commits = mpull($commits, null, 'getCommitIdentifier'); $results = array(); foreach ($identifiers as $identifier) { $results[$identifier] = idx($commits, $identifier); } return $results; } private function renderCommitsTable( PhabricatorRepositoryPushEvent $event, array $commits) { $viewer = $this->getRequest()->getUser(); $repository = $event->getRepository(); $rows = array(); foreach ($commits as $identifier => $commit) { if ($commit) { $partial_import = PhabricatorRepositoryCommit::IMPORTED_MESSAGE | PhabricatorRepositoryCommit::IMPORTED_CHANGE; if ($commit->isPartiallyImported($partial_import)) { $summary = AphrontTableView::renderSingleDisplayLine( $commit->getSummary()); } else { $summary = phutil_tag('em', array(), pht('Importing...')); } } else { $summary = phutil_tag('em', array(), pht('Discovering...')); } $commit_name = $repository->formatCommitName($identifier); if ($commit) { $commit_name = phutil_tag( 'a', array( 'href' => '/'.$commit_name, ), $commit_name); } $rows[] = array( $commit_name, $summary, ); } $table = id(new AphrontTableView($rows)) ->setNoDataString(pht("This push didn't push any new commits.")) ->setHeaders( array( pht('Commit'), pht('Summary'), )) ->setColumnClasses( array( 'n', 'wide', )); return $table; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionSymbolController.php
src/applications/diffusion/controller/DiffusionSymbolController.php
<?php final class DiffusionSymbolController extends DiffusionController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); // See T13638 for discussion of escaping. $name = $request->getURIData('name'); $name = phutil_unescape_uri_path_component($name); $query = id(new DiffusionSymbolQuery()) ->setViewer($viewer) ->setName($name); if ($request->getStr('context')) { $query->setContext($request->getStr('context')); } if ($request->getStr('type')) { $query->setType($request->getStr('type')); } if ($request->getStr('lang')) { $query->setLanguage($request->getStr('lang')); } $repos = array(); if ($request->getStr('repositories')) { $phids = $request->getStr('repositories'); $phids = explode(',', $phids); $phids = array_filter($phids); if ($phids) { $repos = id(new PhabricatorRepositoryQuery()) ->setViewer($request->getUser()) ->withPHIDs($phids) ->execute(); $repo_phids = mpull($repos, 'getPHID'); if ($repo_phids) { $query->withRepositoryPHIDs($repo_phids); } } } $query->needPaths(true); $query->needRepositories(true); $symbols = $query->execute(); $external_query = id(new DiffusionExternalSymbolQuery()) ->withNames(array($name)); if ($request->getStr('context')) { $external_query->withContexts(array($request->getStr('context'))); } if ($request->getStr('type')) { $external_query->withTypes(array($request->getStr('type'))); } if ($request->getStr('lang')) { $external_query->withLanguages(array($request->getStr('lang'))); } if ($request->getStr('path')) { $external_query->withPaths(array($request->getStr('path'))); } if ($request->getInt('line')) { $external_query->withLines(array($request->getInt('line'))); } if ($request->getInt('char')) { $external_query->withCharacterPositions( array( $request->getInt('char'), )); } if ($repos) { $external_query->withRepositories($repos); } $external_sources = id(new PhutilClassMapQuery()) ->setAncestorClass('DiffusionExternalSymbolsSource') ->execute(); $results = array($symbols); foreach ($external_sources as $source) { $source_results = $source->executeQuery($external_query); if (!is_array($source_results)) { throw new Exception( pht( 'Expected a list of results from external symbol source "%s".', get_class($source))); } try { assert_instances_of($source_results, 'PhabricatorRepositorySymbol'); } catch (InvalidArgumentException $ex) { throw new Exception( pht( 'Expected a list of PhabricatorRepositorySymbol objects '. 'from external symbol source "%s".', get_class($source))); } $results[] = $source_results; } $symbols = array_mergev($results); if ($request->getBool('jump') && count($symbols) == 1) { // If this is a clickthrough from Differential, just jump them // straight to the target if we got a single hit. $symbol = head($symbols); return id(new AphrontRedirectResponse()) ->setIsExternal($symbol->isExternal()) ->setURI($symbol->getURI()); } $rows = array(); foreach ($symbols as $symbol) { $href = $symbol->getURI(); if ($symbol->isExternal()) { $source = $symbol->getSource(); $location = $symbol->getLocation(); } else { $repo = $symbol->getRepository(); $file = $symbol->getPath(); $line = $symbol->getLineNumber(); $source = $repo->getMonogram(); $location = $file.':'.$line; } $location = phutil_tag( 'a', array( 'href' => $href, ), $location); $rows[] = array( $symbol->getSymbolType(), $symbol->getSymbolContext(), $symbol->getSymbolName(), $symbol->getSymbolLanguage(), $source, $location, ); } $table = new AphrontTableView($rows); $table->setHeaders( array( pht('Type'), pht('Context'), pht('Name'), pht('Language'), pht('Source'), pht('Location'), )); $table->setColumnClasses( array( '', '', 'pri', '', '', '', )); $table->setNoDataString( pht('No matching symbol could be found in any indexed repository.')); $header = id(new PHUIHeaderView()) ->setHeader(pht('Similar Symbols')) ->setHeaderIcon('fa-bullseye'); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb(pht('Find Symbol')); $crumbs->setBorder(true); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $table, )); return $this->newPage() ->setTitle(pht('Find Symbol')) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionSyncLogListController.php
src/applications/diffusion/controller/DiffusionSyncLogListController.php
<?php final class DiffusionSyncLogListController extends DiffusionLogController { public function handleRequest(AphrontRequest $request) { return id(new DiffusionSyncLogSearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { return parent::buildApplicationCrumbs() ->addTextCrumb(pht('Sync Logs'), $this->getApplicationURI('synclog/')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionPathValidateController.php
src/applications/diffusion/controller/DiffusionPathValidateController.php
<?php final class DiffusionPathValidateController extends DiffusionController { protected function getRepositoryIdentifierFromRequest( AphrontRequest $request) { return $request->getStr('repositoryPHID'); } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $path = $request->getStr('path'); $path = ltrim($path, '/'); $browse_results = DiffusionBrowseResultSet::newFromConduit( $this->callConduitWithDiffusionRequest( 'diffusion.browsequery', array( 'path' => $path, 'commit' => $drequest->getCommit(), 'needValidityOnly' => true, ))); $valid = $browse_results->isValidResults(); if (!$valid) { switch ($browse_results->getReasonForEmptyResultSet()) { case DiffusionBrowseResultSet::REASON_IS_FILE: $valid = true; break; case DiffusionBrowseResultSet::REASON_IS_EMPTY: $valid = true; break; } } $output = array( 'valid' => (bool)$valid, ); return id(new AphrontAjaxResponse())->setContent($output); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionRefTableController.php
src/applications/diffusion/controller/DiffusionRefTableController.php
<?php final class DiffusionRefTableController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); if (!$drequest->supportsBranches()) { return $this->newDialog() ->setTitle(pht('No Ref Support')) ->appendParagraph( pht( 'The version control system this repository uses does not '. 'support named references, so you can not resolve or list '. 'repository refs in this repository.')) ->addCancelButton($repository->getURI()); } $ref_name = $drequest->getBranch(); $cache_query = id(new DiffusionCachedResolveRefsQuery()) ->setRepository($repository); if ($ref_name !== null) { $cache_query->withRefs(array($ref_name)); } $cache_refs = $cache_query->execute(); $vcs_refs = DiffusionQuery::callConduitWithDiffusionRequest( $viewer, $drequest, 'diffusion.resolverefs', array( 'refs' => array($ref_name), )); $all = array(); foreach ($cache_refs as $ref => $results) { foreach ($results as $result) { $id = $result['type'].'/'.$result['identifier']; $all[$ref][$id]['cache'] = $result; } } foreach ($vcs_refs as $ref => $results) { foreach ($results as $result) { $id = $result['type'].'/'.$result['identifier']; $all[$ref][$id]['vcs'] = $result; } } $rows = array(); foreach ($all as $ref => $results) { foreach ($results as $info) { $cache = idx($info, 'cache', array()); $vcs = idx($info, 'vcs', array()); $type = idx($vcs, 'type'); if (!$type) { $type = idx($cache, 'type'); } $hash = idx($vcs, 'identifier'); if ($hash !== null) { $hash = DiffusionView::linkCommit( $repository, $hash); } $cached_hash = idx($cache, 'identifier'); if ($cached_hash !== null) { $cached_hash = DiffusionView::linkCommit( $repository, $cached_hash); } $closed = idx($vcs, 'closed', false); if (!$vcs) { $state = null; } else { $state = $closed ? pht('Closed') : pht('Open'); } $cached_closed = idx($cache, 'closed', false); if (!$cache) { $cached_state = null; } else { $cached_state = $cached_closed ? pht('Closed') : pht('Open'); } $alternate = idx($vcs, 'alternate'); if ($alternate !== null) { $alternate = DiffusionView::linkCommit( $repository, $alternate); } $rows[] = array( $ref, $type, $hash, $cached_hash, $state, $cached_state, $alternate, ); } } $table = id(new AphrontTableView($rows)) ->setHeaders( array( pht('Ref'), pht('Type'), pht('Hash'), pht('Cached Hash'), pht('State'), pht('Cached State'), pht('Alternate'), )); $content = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Ref "%s"', $ref_name)) ->setTable($table); $crumbs = $this->buildCrumbs(array()); $crumbs->addTextCrumb(pht('Refs')); return $this->newPage() ->setTitle( array( $ref_name, pht('Ref'), $repository->getDisplayName(), )) ->setCrumbs($crumbs) ->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/diffusion/controller/DiffusionDiffController.php
src/applications/diffusion/controller/DiffusionDiffController.php
<?php final class DiffusionDiffController extends DiffusionController { public function shouldAllowPublic() { return true; } protected function getDiffusionBlobFromRequest(AphrontRequest $request) { return $request->getStr('ref'); } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); if (!$request->isAjax()) { // This request came out of the dropdown menu, either "View Standalone" // or "View Raw File". $view = $request->getStr('view'); if ($view == 'r') { $uri = $drequest->generateURI( array( 'action' => 'browse', 'params' => array( 'view' => 'raw', ), )); } else { $uri = $drequest->generateURI( array( 'action' => 'change', )); } return id(new AphrontRedirectResponse())->setURI($uri); } $data = $this->callConduitWithDiffusionRequest( 'diffusion.diffquery', array( 'commit' => $drequest->getCommit(), 'path' => $drequest->getPath(), )); $drequest->updateSymbolicCommit($data['effectiveCommit']); $raw_changes = ArcanistDiffChange::newFromConduit($data['changes']); $diff = DifferentialDiff::newEphemeralFromRawChanges( $raw_changes); $changesets = $diff->getChangesets(); $changeset = reset($changesets); if (!$changeset) { return new Aphront404Response(); } $commit = $drequest->loadCommit(); $viewstate_engine = id(new PhabricatorChangesetViewStateEngine()) ->setViewer($viewer) ->setObjectPHID($commit->getPHID()) ->setChangeset($changeset); $viewstate = $viewstate_engine->newViewStateFromRequest($request); if ($viewstate->getDiscardResponse()) { return new AphrontAjaxResponse(); } $parser = id(new DifferentialChangesetParser()) ->setViewer($viewer) ->setChangeset($changeset) ->setViewState($viewstate); $parser->setRenderingReference($drequest->generateURI( array( 'action' => 'rendering-ref', ))); $coverage = $drequest->loadCoverage(); if ($coverage) { $parser->setCoverage($coverage); } $pquery = new DiffusionPathIDQuery(array($changeset->getFilename())); $ids = $pquery->loadPathIDs(); $path_id = $ids[$changeset->getFilename()]; $parser->setLeftSideCommentMapping($path_id, false); $parser->setRightSideCommentMapping($path_id, true); $parser->setCanMarkDone( ($commit->getAuthorPHID()) && ($viewer->getPHID() == $commit->getAuthorPHID())); $parser->setObjectOwnerPHID($commit->getAuthorPHID()); $inlines = id(new DiffusionDiffInlineCommentQuery()) ->setViewer($viewer) ->withCommitPHIDs(array($commit->getPHID())) ->withPathIDs(array($path_id)) ->withPublishedComments(true) ->withPublishableComments(true) ->execute(); $inlines = mpull($inlines, 'newInlineCommentObject'); if ($inlines) { foreach ($inlines as $inline) { $parser->parseInlineComment($inline); } $phids = mpull($inlines, 'getAuthorPHID'); $handles = $this->loadViewerHandles($phids); $parser->setHandles($handles); } $engine = new PhabricatorMarkupEngine(); $engine->setViewer($viewer); foreach ($inlines as $inline) { $engine->addObject( $inline, PhabricatorInlineComment::MARKUP_FIELD_BODY); } $engine->process(); $parser->setMarkupEngine($engine); $spec = $request->getStr('range'); list($range_s, $range_e, $mask) = DifferentialChangesetParser::parseRangeSpecification($spec); $parser->setRange($range_s, $range_e); $parser->setMask($mask); return $parser->newChangesetResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionLintController.php
src/applications/diffusion/controller/DiffusionLintController.php
<?php final class DiffusionLintController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); if ($this->getRepositoryIdentifierFromRequest($request)) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $drequest = $this->getDiffusionRequest(); } else { $drequest = null; } $code = $request->getStr('lint'); if (strlen($code)) { return $this->buildDetailsResponse(); } $owners = array(); if (!$drequest) { if (!$request->getArr('owner')) { $owners = array($viewer->getPHID()); } else { $owners = array(head($request->getArr('owner'))); } } $codes = $this->loadLintCodes($drequest, $owners); if ($codes) { $branches = id(new PhabricatorRepositoryBranch())->loadAllWhere( 'id IN (%Ld)', array_unique(ipull($codes, 'branchID'))); $branches = mpull($branches, null, 'getID'); } else { $branches = array(); } if ($branches) { $repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withIDs(mpull($branches, 'getRepositoryID')) ->execute(); $repositories = mpull($repositories, null, 'getID'); } else { $repositories = array(); } $rows = array(); $total = 0; foreach ($codes as $code) { $branch = idx($branches, $code['branchID']); if (!$branch) { continue; } $repository = idx($repositories, $branch->getRepositoryID()); if (!$repository) { continue; } $total += $code['n']; if ($drequest) { $href_lint = $drequest->generateURI( array( 'action' => 'lint', 'lint' => $code['code'], )); $href_browse = $drequest->generateURI( array( 'action' => 'browse', 'lint' => $code['code'], )); $href_repo = $drequest->generateURI( array( 'action' => 'lint', )); } else { $href_lint = $repository->generateURI( array( 'action' => 'lint', 'lint' => $code['code'], )); $href_browse = $repository->generateURI( array( 'action' => 'browse', 'lint' => $code['code'], )); $href_repo = $repository->generateURI( array( 'action' => 'lint', )); } $rows[] = array( phutil_tag('a', array('href' => $href_lint), $code['n']), phutil_tag('a', array('href' => $href_browse), $code['files']), phutil_tag( 'a', array( 'href' => $href_repo, ), $repository->getDisplayName()), ArcanistLintSeverity::getStringForSeverity($code['maxSeverity']), $code['code'], $code['maxName'], $code['maxDescription'], ); } $table = id(new AphrontTableView($rows)) ->setHeaders(array( pht('Problems'), pht('Files'), pht('Repository'), pht('Severity'), pht('Code'), pht('Name'), pht('Example'), )) ->setColumnVisibility(array(true, true, !$drequest)) ->setColumnClasses(array('n', 'n', '', '', 'pri', '', '')); $content = array(); if (!$drequest) { $form = id(new AphrontFormView()) ->setUser($viewer) ->setMethod('GET') ->appendControl( id(new AphrontFormTokenizerControl()) ->setDatasource(new PhabricatorPeopleDatasource()) ->setLimit(1) ->setName('owner') ->setLabel(pht('Owner')) ->setValue($owners)) ->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Filter'))); $content[] = id(new AphrontListFilterView())->appendChild($form); } $content[] = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Lint')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($table); $title = array('Lint'); $crumbs = $this->buildCrumbs( array( 'branch' => true, 'path' => true, 'view' => 'lint', )); $crumbs->setBorder(true); if ($drequest) { $title[] = $drequest->getRepository()->getDisplayName(); } else { $crumbs->addTextCrumb(pht('All Lint')); } if ($drequest) { $branch = $drequest->loadBranch(); $header = id(new PHUIHeaderView()) ->setHeader(pht('Lint: %s', $this->renderPathLinks($drequest, 'lint'))) ->setUser($viewer) ->setHeaderIcon('fa-code'); $actions = $this->buildActionView($drequest); $properties = $this->buildPropertyView( $drequest, $branch, $total, $actions); $object_box = id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addPropertyList($properties); } else { $object_box = null; $header = id(new PHUIHeaderView()) ->setHeader(pht('All Lint')) ->setHeaderIcon('fa-code'); } $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $object_box, $content, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild( array( $view, )); } private function loadLintCodes($drequest, array $owner_phids) { $conn = id(new PhabricatorRepository())->establishConnection('r'); $where = array('1 = 1'); if ($drequest) { $branch = $drequest->loadBranch(); if (!$branch) { return array(); } $where[] = qsprintf($conn, 'branchID = %d', $branch->getID()); if ($drequest->getPath() != '') { $path = '/'.$drequest->getPath(); $is_dir = (substr($path, -1) == '/'); $where[] = ($is_dir ? qsprintf($conn, 'path LIKE %>', $path) : qsprintf($conn, 'path = %s', $path)); } } if ($owner_phids) { $or = array(); $or[] = qsprintf($conn, 'authorPHID IN (%Ls)', $owner_phids); $paths = array(); $packages = id(new PhabricatorOwnersOwner()) ->loadAllWhere('userPHID IN (%Ls)', $owner_phids); if ($packages) { $paths = id(new PhabricatorOwnersPath())->loadAllWhere( 'packageID IN (%Ld)', mpull($packages, 'getPackageID')); } if ($paths) { $repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getRequest()->getUser()) ->withPHIDs(mpull($paths, 'getRepositoryPHID')) ->execute(); $repositories = mpull($repositories, 'getID', 'getPHID'); $branches = id(new PhabricatorRepositoryBranch())->loadAllWhere( 'repositoryID IN (%Ld)', $repositories); $branches = mgroup($branches, 'getRepositoryID'); } foreach ($paths as $path) { $branch = idx( $branches, idx( $repositories, $path->getRepositoryPHID())); if ($branch) { $condition = qsprintf( $conn, '(branchID IN (%Ld) AND path LIKE %>)', array_keys($branch), $path->getPath()); if ($path->getExcluded()) { $where[] = qsprintf($conn, 'NOT %Q', $condition); } else { $or[] = $condition; } } } $where[] = qsprintf($conn, '%LO', $or); } return queryfx_all( $conn, 'SELECT branchID, code, MAX(severity) AS maxSeverity, MAX(name) AS maxName, MAX(description) AS maxDescription, COUNT(DISTINCT path) AS files, COUNT(*) AS n FROM %T WHERE %LA GROUP BY branchID, code ORDER BY n DESC', PhabricatorRepository::TABLE_LINTMESSAGE, $where); } protected function buildActionView(DiffusionRequest $drequest) { $viewer = $this->getRequest()->getUser(); $view = id(new PhabricatorActionListView()) ->setUser($viewer); $list_uri = $drequest->generateURI( array( 'action' => 'lint', 'lint' => '', )); $view->addAction( id(new PhabricatorActionView()) ->setName(pht('View As List')) ->setHref($list_uri) ->setIcon('fa-list')); $history_uri = $drequest->generateURI( array( 'action' => 'history', )); $view->addAction( id(new PhabricatorActionView()) ->setName(pht('View History')) ->setHref($history_uri) ->setIcon('fa-clock-o')); $browse_uri = $drequest->generateURI( array( 'action' => 'browse', )); $view->addAction( id(new PhabricatorActionView()) ->setName(pht('Browse Content')) ->setHref($browse_uri) ->setIcon('fa-files-o')); return $view; } protected function buildPropertyView( DiffusionRequest $drequest, PhabricatorRepositoryBranch $branch, $total, PhabricatorActionListView $actions) { $viewer = $this->getRequest()->getUser(); $view = id(new PHUIPropertyListView()) ->setUser($viewer) ->setActionList($actions); $lint_commit = $branch->getLintCommit(); $view->addProperty( pht('Lint Commit'), phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => 'commit', 'commit' => $lint_commit, )), ), $drequest->getRepository()->formatCommitName($lint_commit))); $view->addProperty( pht('Total Messages'), pht('%s', new PhutilNumber($total))); return $view; } private function buildDetailsResponse() { $request = $this->getRequest(); $limit = 500; $pager = id(new PHUIPagerView()) ->readFromRequest($request) ->setPageSize($limit); $offset = $pager->getOffset(); $drequest = $this->getDiffusionRequest(); $branch = $drequest->loadBranch(); $messages = $this->loadLintMessages($branch, $limit, $offset); $is_dir = (substr('/'.$drequest->getPath(), -1) == '/'); $pager->setHasMorePages(count($messages) >= $limit); $authors = $this->loadViewerHandles(ipull($messages, 'authorPHID')); $rows = array(); foreach ($messages as $message) { $path = phutil_tag( 'a', array( 'href' => $drequest->generateURI(array( 'action' => 'lint', 'path' => $message['path'], )), ), substr($message['path'], strlen($drequest->getPath()) + 1)); $line = phutil_tag( 'a', array( 'href' => $drequest->generateURI(array( 'action' => 'browse', 'path' => $message['path'], 'line' => $message['line'], 'commit' => $branch->getLintCommit(), )), ), $message['line']); $author = $message['authorPHID']; if ($author && $authors[$author]) { $author = $authors[$author]->renderLink(); } $rows[] = array( $path, $line, $author, ArcanistLintSeverity::getStringForSeverity($message['severity']), $message['name'], $message['description'], ); } $table = id(new AphrontTableView($rows)) ->setHeaders(array( pht('Path'), pht('Line'), pht('Author'), pht('Severity'), pht('Name'), pht('Description'), )) ->setColumnClasses(array('', 'n')) ->setColumnVisibility(array($is_dir)); $content = array(); $content[] = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Lint Details')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($table) ->setPager($pager); $crumbs = $this->buildCrumbs( array( 'branch' => true, 'path' => true, 'view' => 'lint', )); $crumbs->setBorder(true); $header = id(new PHUIHeaderView()) ->setHeader(pht('Lint: %s', $drequest->getRepository()->getDisplayName())) ->setHeaderIcon('fa-code'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $content, )); return $this->newPage() ->setTitle( array( pht('Lint'), $drequest->getRepository()->getDisplayName(), )) ->setCrumbs($crumbs) ->appendChild( array( $view, )); } private function loadLintMessages( PhabricatorRepositoryBranch $branch, $limit, $offset) { $drequest = $this->getDiffusionRequest(); if (!$branch) { return array(); } $conn = $branch->establishConnection('r'); $where = array( qsprintf($conn, 'branchID = %d', $branch->getID()), ); if ($drequest->getPath() != '') { $path = '/'.$drequest->getPath(); $is_dir = (substr($path, -1) == '/'); $where[] = ($is_dir ? qsprintf($conn, 'path LIKE %>', $path) : qsprintf($conn, 'path = %s', $path)); } if ($drequest->getLint() != '') { $where[] = qsprintf( $conn, 'code = %s', $drequest->getLint()); } return queryfx_all( $conn, 'SELECT * FROM %T WHERE %LA ORDER BY path, code, line LIMIT %d OFFSET %d', PhabricatorRepository::TABLE_LINTMESSAGE, $where, $limit, $offset); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/controller/DiffusionChangeController.php
src/applications/diffusion/controller/DiffusionChangeController.php
<?php final class DiffusionChangeController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $data = $this->callConduitWithDiffusionRequest( 'diffusion.diffquery', array( 'commit' => $drequest->getCommit(), 'path' => $drequest->getPath(), )); $drequest->updateSymbolicCommit($data['effectiveCommit']); $raw_changes = ArcanistDiffChange::newFromConduit($data['changes']); $diff = DifferentialDiff::newEphemeralFromRawChanges( $raw_changes); $changesets = $diff->getChangesets(); $changeset = reset($changesets); if (!$changeset) { // TODO: Refine this. return new Aphront404Response(); } $repository = $drequest->getRepository(); $changesets = array( 0 => $changeset, ); $changeset_header = $this->buildChangesetHeader($drequest); $changeset_view = new DifferentialChangesetListView(); $changeset_view->setChangesets($changesets); $changeset_view->setBackground(PHUIObjectBoxView::BLUE_PROPERTY); $changeset_view->setVisibleChangesets($changesets); $changeset_view->setRenderingReferences( array( 0 => $drequest->generateURI(array('action' => 'rendering-ref')), )); $raw_params = array( 'action' => 'browse', 'params' => array( 'view' => 'raw', ), ); $right_uri = $drequest->generateURI($raw_params); $raw_params['params']['before'] = $drequest->getStableCommit(); $left_uri = $drequest->generateURI($raw_params); $changeset_view->setRawFileURIs($left_uri, $right_uri); $changeset_view->setRenderURI($repository->getPathURI('diff/')); $changeset_view->setUser($viewer); $changeset_view->setHeader($changeset_header); // TODO: This is pretty awkward, unify the CSS between Diffusion and // Differential better. require_celerity_resource('differential-core-view-css'); $crumbs = $this->buildCrumbs( array( 'branch' => true, 'path' => true, 'view' => 'change', )); $crumbs->setBorder(true); $links = $this->renderPathLinks($drequest, $mode = 'browse'); $header = $this->buildHeader($drequest, $links); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setMainColumn(array( )) ->setFooter(array( $changeset_view, )); return $this->newPage() ->setTitle( array( basename($drequest->getPath()), $repository->getDisplayName(), )) ->setCrumbs($crumbs) ->appendChild( array( $view, )); } private function buildHeader( DiffusionRequest $drequest, $links) { $viewer = $this->getViewer(); $tag = $this->renderCommitHashTag($drequest); $header = id(new PHUIHeaderView()) ->setHeader($links) ->setUser($viewer) ->setPolicyObject($drequest->getRepository()) ->addTag($tag); return $header; } private function buildChangesetHeader(DiffusionRequest $drequest) { $viewer = $this->getViewer(); $header = id(new PHUIHeaderView()) ->setHeader(pht('Changes')); $history_uri = $drequest->generateURI( array( 'action' => 'history', )); $header->addActionLink( id(new PHUIButtonView()) ->setTag('a') ->setText(pht('View History')) ->setHref($history_uri) ->setIcon('fa-clock-o')); $browse_uri = $drequest->generateURI( array( 'action' => 'browse', )); $header->addActionLink( id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Browse Content')) ->setHref($browse_uri) ->setIcon('fa-files-o')); return $header; } protected function buildPropertyView( DiffusionRequest $drequest, PhabricatorActionListView $actions) { $viewer = $this->getRequest()->getUser(); $view = id(new PHUIPropertyListView()) ->setUser($viewer) ->setActionList($actions); $stable_commit = $drequest->getStableCommit(); $view->addProperty( pht('Commit'), phutil_tag( 'a', array( 'href' => $drequest->generateURI( array( 'action' => 'commit', 'commit' => $stable_commit, )), ), $drequest->getRepository()->formatCommitName($stable_commit))); 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/diffusion/controller/DiffusionLastModifiedController.php
src/applications/diffusion/controller/DiffusionLastModifiedController.php
<?php final class DiffusionLastModifiedController extends DiffusionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $response = $this->loadDiffusionContext(); if ($response) { return $response; } $viewer = $this->getViewer(); $drequest = $this->getDiffusionRequest(); $paths = $request->getStr('paths'); try { $paths = phutil_json_decode($paths); } catch (PhutilJSONParserException $ex) { return new Aphront400Response(); } $modified_map = $this->callConduitWithDiffusionRequest( 'diffusion.lastmodifiedquery', array( 'paths' => array_fill_keys($paths, $drequest->getCommit()), )); if ($modified_map) { $commit_map = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($drequest->getRepository()) ->withIdentifiers(array_values($modified_map)) ->needCommitData(true) ->needIdentities(true) ->execute(); $commit_map = mpull($commit_map, null, 'getCommitIdentifier'); } else { $commit_map = array(); } $commits = array(); foreach ($paths as $path) { $modified_at = idx($modified_map, $path); if ($modified_at) { $commit = idx($commit_map, $modified_at); if ($commit) { $commits[$path] = $commit; } } } $branch = $drequest->loadBranch(); if ($branch && $commits) { $lint_query = id(new DiffusionLintCountQuery()) ->withBranchIDs(array($branch->getID())) ->withPaths(array_keys($commits)); if ($drequest->getLint()) { $lint_query->withCodes(array($drequest->getLint())); } $lint = $lint_query->execute(); } else { $lint = array(); } $output = array(); foreach ($commits as $path => $commit) { $prequest = clone $drequest; $prequest->setPath($path); $output[$path] = $this->renderColumns( $prequest, $commit, idx($lint, $path)); } return id(new AphrontAjaxResponse())->setContent($output); } private function renderColumns( DiffusionRequest $drequest, PhabricatorRepositoryCommit $commit = null, $lint = null) { $viewer = $this->getViewer(); if ($commit) { $epoch = $commit->getEpoch(); $modified = DiffusionView::linkCommit( $drequest->getRepository(), $commit->getCommitIdentifier()); $date = $viewer->formatShortDateTime($epoch); } else { $modified = ''; $date = ''; } $data = $commit->getCommitData(); $details = DiffusionView::linkDetail( $drequest->getRepository(), $commit->getCommitIdentifier(), $data->getSummary()); $details = AphrontTableView::renderSingleDisplayLine($details); $return = array( 'commit' => $modified, 'date' => $date, 'details' => $details, ); if ($lint !== null) { $return['lint'] = phutil_tag( 'a', array( 'href' => $drequest->generateURI(array( 'action' => 'lint', 'lint' => null, )), ), number_format($lint)); } // The client treats these results as markup, so make sure they have been // escaped correctly. foreach ($return as $key => $value) { $return[$key] = hsprintf('%s', $value); } return $return; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engineextension/DiffusionRepositoryURIsSearchEngineAttachment.php
src/applications/diffusion/engineextension/DiffusionRepositoryURIsSearchEngineAttachment.php
<?php final class DiffusionRepositoryURIsSearchEngineAttachment extends PhabricatorSearchEngineAttachment { public function getAttachmentName() { return pht('Repository URIs'); } public function getAttachmentDescription() { return pht('Get a list of associated URIs for each repository.'); } public function willLoadAttachmentData($query, $spec) { $query->needURIs(true); } public function getAttachmentForObject($object, $data, $spec) { $uris = array(); foreach ($object->getURIs() as $uri) { $uris[] = array( 'id' => $uri->getID(), 'type' => phid_get_type($uri->getPHID()), 'phid' => $uri->getPHID(), 'fields' => $uri->getFieldValuesForConduit(), ); } return array( 'uris' => $uris, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engineextension/DiffusionDatasourceEngineExtension.php
src/applications/diffusion/engineextension/DiffusionDatasourceEngineExtension.php
<?php final class DiffusionDatasourceEngineExtension extends PhabricatorDatasourceEngineExtension { public function newQuickSearchDatasources() { return array( new DiffusionRepositoryDatasource(), new DiffusionSymbolDatasource(), ); } public function newJumpURI($query) { $viewer = $this->getViewer(); // Send "r" to Diffusion. if (preg_match('/^r\z/i', $query)) { return '/diffusion/'; } // Send "a" to the commit list ("Audit"). if (preg_match('/^a\z/i', $query)) { return '/diffusion/commit/'; } // Send "r <string>" to a search for a matching repository. $matches = null; if (preg_match('/^r\s+(.+)\z/i', $query, $matches)) { $raw_query = $matches[1]; $engine = id(new PhabricatorRepository()) ->newFerretEngine(); $compiler = id(new PhutilSearchQueryCompiler()) ->setEnableFunctions(true); $raw_tokens = $compiler->newTokens($raw_query); $fulltext_tokens = array(); foreach ($raw_tokens as $raw_token) { $fulltext_token = id(new PhabricatorFulltextToken()) ->setToken($raw_token); $fulltext_tokens[] = $fulltext_token; } $repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withFerretConstraint($engine, $fulltext_tokens) ->execute(); if (count($repositories) == 1) { // Just one match, jump to repository. return head($repositories)->getURI(); } else { // More than one match, jump to search. return urisprintf( '/diffusion/?order=relevance&query=%s#R', $raw_query); } } // Send "s <string>" to a symbol search. $matches = null; if (preg_match('/^s\s+(.+)\z/i', $query, $matches)) { $symbol = $matches[1]; $parts = null; if (preg_match('/(.*)(?:\\.|::|->)(.*)/', $symbol, $parts)) { return urisprintf( '/diffusion/symbol/%p/?jump=true&context=%s', $parts[2], $parts[1]); } else { return urisprintf( '/diffusion/symbol/%p/?jump=true', $symbol); } } return null; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engineextension/DiffusionHovercardEngineExtension.php
src/applications/diffusion/engineextension/DiffusionHovercardEngineExtension.php
<?php final class DiffusionHovercardEngineExtension extends PhabricatorHovercardEngineExtension { const EXTENSIONKEY = 'diffusion'; public function isExtensionEnabled() { return PhabricatorApplication::isClassInstalled( 'PhabricatorDiffusionApplication'); } public function getExtensionName() { return pht('Diffusion Commits'); } public function canRenderObjectHovercard($object) { return ($object instanceof PhabricatorRepositoryCommit); } public function renderHovercard( PHUIHovercardView $hovercard, PhabricatorObjectHandle $handle, $commit, $data) { $viewer = $this->getViewer(); $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->needIdentities(true) ->needCommitData(true) ->withPHIDs(array($commit->getPHID())) ->executeOne(); if (!$commit) { return; } $author_phid = $commit->getAuthorDisplayPHID(); $committer_phid = $commit->getCommitterDisplayPHID(); $repository_phid = $commit->getRepository()->getPHID(); $phids = array(); $phids[] = $author_phid; $phids[] = $committer_phid; $phids[] = $repository_phid; $handles = $viewer->loadHandles($phids); $hovercard->setTitle($handle->getName()); // See T13620. Use a longer slice of the message than the "summary" here, // since we have at least a few lines of room in the UI. $commit_message = $commit->getCommitMessageForDisplay(); $message_limit = 512; $short_message = id(new PhutilUTF8StringTruncator()) ->setMaximumBytes($message_limit * 4) ->setMaximumGlyphs($message_limit) ->truncateString($commit_message); $short_message = phutil_escape_html_newlines($short_message); $hovercard->setDetail($short_message); $repository = $handles[$repository_phid]->renderLink(); $hovercard->addField(pht('Repository'), $repository); $author = $handles[$author_phid]->renderLink(); if ($author_phid) { $hovercard->addField(pht('Author'), $author); } if ($committer_phid && ($committer_phid !== $author_phid)) { $committer = $handles[$committer_phid]->renderLink(); $hovercard->addField(pht('Committer'), $committer); } $date = phabricator_date($commit->getEpoch(), $viewer); $hovercard->addField(pht('Commit Date'), $date); if (!$commit->isAuditStatusNoAudit()) { $status = $commit->getAuditStatusObject(); $hovercard->addField( pht('Audit Status'), $status->getName()); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engineextension/DiffusionCacheEngineExtension.php
src/applications/diffusion/engineextension/DiffusionCacheEngineExtension.php
<?php final class DiffusionCacheEngineExtension extends PhabricatorCacheEngineExtension { const EXTENSIONKEY = 'diffusion'; public function getExtensionName() { return pht('Diffusion Repositories'); } public function discoverLinkedObjects( PhabricatorCacheEngine $engine, array $objects) { $viewer = $engine->getViewer(); $results = array(); // When an Almanac Service changes, update linked repositories. $services = $this->selectObjects($objects, 'AlmanacService'); if ($services) { $repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withAlmanacServicePHIDs(mpull($services, 'getPHID')) ->execute(); foreach ($repositories as $repository) { $results[] = $repository; } } return $results; } public function deleteCaches( PhabricatorCacheEngine $engine, array $objects) { $keys = array(); $repositories = $this->selectObjects($objects, 'PhabricatorRepository'); foreach ($repositories as $repository) { $keys[] = $repository->getAlmanacServiceCacheKey(); } $keys = array_filter($keys); if ($keys) { $cache = PhabricatorCaches::getMutableStructureCache(); $cache->deleteKeys($keys); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engineextension/DiffusionAuditorsSearchEngineAttachment.php
src/applications/diffusion/engineextension/DiffusionAuditorsSearchEngineAttachment.php
<?php final class DiffusionAuditorsSearchEngineAttachment extends PhabricatorSearchEngineAttachment { public function getAttachmentName() { return pht('Diffusion Auditors'); } public function getAttachmentDescription() { return pht('Get the auditors for each commit.'); } public function willLoadAttachmentData($query, $spec) { $query->needAuditRequests(true); } public function getAttachmentForObject($object, $data, $spec) { $auditors = $object->getAudits(); $list = array(); foreach ($auditors as $auditor) { $status = $auditor->getAuditRequestStatusObject(); $list[] = array( 'auditorPHID' => $auditor->getAuditorPHID(), 'status' => $status->getStatusValueForConduit(), ); } return array( 'auditors' => $list, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engineextension/DiffusionRepositoryMetricsSearchEngineAttachment.php
src/applications/diffusion/engineextension/DiffusionRepositoryMetricsSearchEngineAttachment.php
<?php final class DiffusionRepositoryMetricsSearchEngineAttachment extends PhabricatorSearchEngineAttachment { public function getAttachmentName() { return pht('Repository Metrics'); } public function getAttachmentDescription() { return pht( 'Get metrics (like commit count and most recent commit) for each '. 'repository.'); } public function willLoadAttachmentData($query, $spec) { $query ->needCommitCounts(true) ->needMostRecentCommits(true); } public function getAttachmentForObject($object, $data, $spec) { $commit = $object->getMostRecentCommit(); if ($commit !== null) { $recent_commit = $commit->getFieldValuesForConduit(); } else { $recent_commit = null; } $commit_count = $object->getCommitCount(); if ($commit_count !== null) { $commit_count = (int)$commit_count; } return array( 'commitCount' => $commit_count, 'recentCommit' => $recent_commit, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engineextension/DiffusionSourceHyperlinkEngineExtension.php
src/applications/diffusion/engineextension/DiffusionSourceHyperlinkEngineExtension.php
<?php final class DiffusionSourceHyperlinkEngineExtension extends PhabricatorRemarkupHyperlinkEngineExtension { const LINKENGINEKEY = 'diffusion-src'; public function processHyperlinks(array $hyperlinks) { $engine = $this->getEngine(); $viewer = $engine->getConfig('viewer'); if (!$viewer) { return; } $hyperlinks = $this->getSelfLinks($hyperlinks); $links = array(); foreach ($hyperlinks as $link) { $uri = $link->getURI(); $uri = new PhutilURI($uri); $path = $uri->getPath(); $pattern = '(^'. '/(?:diffusion|source)'. '/(?P<identifier>[^/]+)'. '/browse'. '/(?P<blob>.*)'. '\z)'; $matches = null; if (!preg_match($pattern, $path, $matches)) { continue; } $links[] = array( 'ref' => $link, 'identifier' => $matches['identifier'], 'blob' => $matches['blob'], ); } if (!$links) { return; } $identifiers = ipull($links, 'identifier'); $query = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withIdentifiers($identifiers); $query->execute(); $repository_map = $query->getIdentifierMap(); foreach ($links as $link) { $identifier = $link['identifier']; $repository = idx($repository_map, $identifier); if (!$repository) { continue; } $ref = $link['ref']; $uri = $ref->getURI(); $tag = id(new DiffusionSourceLinkView()) ->setViewer($viewer) ->setRepository($repository) ->setURI($uri) ->setBlob($link['blob']); if (!$ref->isEmbed()) { $tag->setText($uri); } $ref->setResult($tag); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/engineextension/DiffusionRepositoryURIsIndexEngineExtension.php
src/applications/diffusion/engineextension/DiffusionRepositoryURIsIndexEngineExtension.php
<?php final class DiffusionRepositoryURIsIndexEngineExtension extends PhabricatorIndexEngineExtension { const EXTENSIONKEY = 'diffusion.repositories.uri'; public function getExtensionName() { return pht('Repository URIs'); } public function shouldIndexObject($object) { return ($object instanceof PhabricatorRepository); } public function indexObject( PhabricatorIndexEngine $engine, $object) { // Reload the repository to pick up URIs, which we need in order to update // the URI index. $object = id(new PhabricatorRepositoryQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($object->getPHID())) ->needURIs(true) ->executeOne(); if (!$object) { return; } $object->updateURIIndex(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryManagementOtherPanelGroup.php
src/applications/diffusion/management/DiffusionRepositoryManagementOtherPanelGroup.php
<?php final class DiffusionRepositoryManagementOtherPanelGroup extends DiffusionRepositoryManagementPanelGroup { const PANELGROUPKEY = 'other'; public function getManagementPanelGroupLabel() { return pht('Other'); } public function getManagementPanelGroupOrder() { return 9999; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryManagementIntegrationsPanelGroup.php
src/applications/diffusion/management/DiffusionRepositoryManagementIntegrationsPanelGroup.php
<?php final class DiffusionRepositoryManagementIntegrationsPanelGroup extends DiffusionRepositoryManagementPanelGroup { const PANELGROUPKEY = 'integrations'; public function getManagementPanelGroupLabel() { return pht('Integrations'); } public function getManagementPanelGroupOrder() { return 4000; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryManagementMainPanelGroup.php
src/applications/diffusion/management/DiffusionRepositoryManagementMainPanelGroup.php
<?php final class DiffusionRepositoryManagementMainPanelGroup extends DiffusionRepositoryManagementPanelGroup { const PANELGROUPKEY = 'main'; public function getManagementPanelGroupLabel() { return null; } public function getManagementPanelGroupOrder() { return 1000; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryStorageManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryStorageManagementPanel.php
<?php final class DiffusionRepositoryStorageManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'storage'; public function getManagementPanelLabel() { return pht('Storage'); } public function getManagementPanelOrder() { return 600; } public function getManagementPanelIcon() { $repository = $this->getRepository(); if ($repository->getAlmanacServicePHID()) { return 'fa-sitemap'; } else if ($repository->isHosted()) { return 'fa-database'; } else { return 'fa-download'; } } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $doc_href = PhabricatorEnv::getDoclink('Cluster: Repositories'); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-book') ->setHref($doc_href) ->setName(pht('Cluster Documentation'))); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { return array( $this->buildStorageStatusPanel(), $this->buildClusterStatusPanel(), $this->buildRefsStatusPanels(), ); } private function buildStorageStatusPanel() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); if ($repository->usesLocalWorkingCopy()) { $storage_path = $repository->getLocalPath(); } else { $storage_path = phutil_tag('em', array(), pht('No Local Working Copy')); } $service_phid = $repository->getAlmanacServicePHID(); if ($service_phid) { $storage_service = $viewer->renderHandle($service_phid); } else { $storage_service = phutil_tag('em', array(), pht('Local')); } $view->addProperty(pht('Storage Path'), $storage_path); $view->addProperty(pht('Storage Cluster'), $storage_service); return $this->newBox(pht('Storage'), $view); } private function buildClusterStatusPanel() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $service_phid = $repository->getAlmanacServicePHID(); if ($service_phid) { $service = id(new AlmanacServiceQuery()) ->setViewer($viewer) ->withServiceTypes( array( AlmanacClusterRepositoryServiceType::SERVICETYPE, )) ->withPHIDs(array($service_phid)) ->needActiveBindings(true) ->executeOne(); if (!$service) { // TODO: Viewer may not have permission to see the service, or it may // be invalid? Raise some more useful error here? throw new Exception(pht('Unable to load cluster service.')); } } else { $service = null; } Javelin::initBehavior('phabricator-tooltips'); $rows = array(); if ($service) { $bindings = $service->getActiveBindings(); $bindings = mgroup($bindings, 'getDevicePHID'); // This is an unusual read which always comes from the master. if (PhabricatorEnv::isReadOnly()) { $versions = array(); } else { $versions = PhabricatorRepositoryWorkingCopyVersion::loadVersions( $repository->getPHID()); } $versions = mpull($versions, null, 'getDevicePHID'); $sort = array(); foreach ($bindings as $key => $binding_group) { $sort[$key] = id(new PhutilSortVector()) ->addString(head($binding_group)->getDevice()->getName()); } $sort = msortv($sort, 'getSelf'); $bindings = array_select_keys($bindings, array_keys($sort)) + $bindings; foreach ($bindings as $binding_group) { $any_binding = head($binding_group); $binding_icon = 'fa-folder-open green'; $binding_tip = pht('Active'); $binding_icon = id(new PHUIIconView()) ->setIcon($binding_icon) ->addSigil('has-tooltip') ->setMetadata( array( 'tip' => $binding_tip, )); $device = $any_binding->getDevice(); $version = idx($versions, $device->getPHID()); if ($version) { $version_number = $version->getRepositoryVersion(); $href = null; if ($repository->isHosted()) { $href = "/diffusion/pushlog/view/{$version_number}/"; } else { $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withIDs(array($version_number)) ->executeOne(); if ($commit) { $href = $commit->getURI(); } } if ($href) { $version_number = phutil_tag( 'a', array( 'href' => $href, ), $version_number); } } else { $version_number = '-'; } if ($version && $version->getIsWriting()) { $is_writing = id(new PHUIIconView()) ->setIcon('fa-pencil green'); } else { $is_writing = id(new PHUIIconView()) ->setIcon('fa-pencil grey'); } $write_properties = null; if ($version) { $write_properties = $version->getWriteProperties(); if ($write_properties) { try { $write_properties = phutil_json_decode($write_properties); } catch (Exception $ex) { $write_properties = null; } } } $last_writer = null; $writer_epoch = null; if ($write_properties) { $writer_phid = idx($write_properties, 'userPHID'); if ($writer_phid) { $last_writer = $viewer->renderHandle($writer_phid); } $writer_epoch = idx($write_properties, 'epoch'); if ($writer_epoch) { $writer_epoch = phabricator_datetime($writer_epoch, $viewer); } } $rows[] = array( $binding_icon, phutil_tag( 'a', array( 'href' => $device->getURI(), ), $device->getName()), $version_number, $is_writing, $last_writer, $writer_epoch, ); } } $table = id(new AphrontTableView($rows)) ->setNoDataString(pht('This is not a cluster repository.')) ->setHeaders( array( null, pht('Device'), pht('Version'), pht('Writing'), pht('Last Writer'), pht('Last Write At'), )) ->setColumnClasses( array( null, null, null, 'right wide', null, 'date', )); return $this->newBox(pht('Cluster Status'), $table); } private function buildRefsStatusPanels() { $repository = $this->getRepository(); $service_phid = $repository->getAlmanacServicePHID(); if (!$service_phid) { // If this repository isn't clustered, don't bother rendering anything. // There are enough other context clues that another empty panel isn't // useful. return; } $all_protocols = array( 'http', 'https', 'ssh', ); $readable_panel = $this->buildRefsStatusPanel( pht('Readable Service Refs'), array( 'neverProxy' => false, 'protocols' => $all_protocols, 'writable' => false, )); $writable_panel = $this->buildRefsStatusPanel( pht('Writable Service Refs'), array( 'neverProxy' => false, 'protocols' => $all_protocols, 'writable' => true, )); return array( $readable_panel, $writable_panel, ); } private function buildRefsStatusPanel( $title, $options) { $repository = $this->getRepository(); $viewer = $this->getViewer(); $caught = null; try { $refs = $repository->getAlmanacServiceRefs($viewer, $options); } catch (Exception $ex) { $caught = $ex; } catch (Throwable $ex) { $caught = $ex; } $info_view = null; if ($caught) { $refs = array(); $info_view = id(new PHUIInfoView()) ->setErrors( array( phutil_escape_html_newlines($caught->getMessage()), )); } $phids = array(); foreach ($refs as $ref) { $phids[] = $ref->getDevicePHID(); } $handles = $viewer->loadHandles($phids); $icon_writable = id(new PHUIIconView()) ->setIcon('fa-pencil', 'green'); $icon_unwritable = id(new PHUIIconView()) ->setIcon('fa-times', 'grey'); $rows = array(); foreach ($refs as $ref) { $device_phid = $ref->getDevicePHID(); $device_handle = $handles[$device_phid]; if ($ref->isWritable()) { $writable_icon = $icon_writable; $writable_text = pht('Read/Write'); } else { $writable_icon = $icon_unwritable; $writable_text = pht('Read Only'); } $rows[] = array( $device_handle->renderLink(), $ref->getURI(), $writable_icon, $writable_text, ); } $table = id(new AphrontTableView($rows)) ->setNoDataString(pht('No repository service refs available.')) ->setHeaders( array( pht('Device'), pht('Internal Service URI'), null, pht('I/O'), )) ->setColumnClasses( array( null, 'wide', 'icon', null, )); $box_view = $this->newBox($title, $table); if ($info_view) { $box_view->setInfoView($info_view); } return $box_view; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryManagementPanel.php
<?php abstract class DiffusionRepositoryManagementPanel extends Phobject { private $viewer; private $repository; private $controller; final public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } final public function getViewer() { return $this->viewer; } final public function setRepository(PhabricatorRepository $repository) { $this->repository = $repository; return $this; } final public function getRepository() { return $this->repository; } final public function getRequest() { return $this->controller->getRequest(); } final public function setController(PhabricatorController $controller) { $this->controller = $controller; return $this; } final public function getManagementPanelKey() { return $this->getPhobjectClassConstant('PANELKEY'); } abstract public function getManagementPanelLabel(); abstract public function getManagementPanelOrder(); abstract public function buildManagementPanelContent(); public function buildManagementPanelCurtain() { return null; } public function getManagementPanelIcon() { return 'fa-pencil'; } public function getManagementPanelGroupKey() { return DiffusionRepositoryManagementMainPanelGroup::PANELGROUPKEY; } public function shouldEnableForRepository( PhabricatorRepository $repository) { return true; } public static function getAllPanels() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getManagementPanelKey') ->setSortMethod('getManagementPanelOrder') ->execute(); } final protected function newTimeline() { return $this->controller->newTimeline($this->getRepository()); } final public function getPanelURI() { $repository = $this->getRepository(); $key = $this->getManagementPanelKey(); return $repository->getPathURI("manage/{$key}/"); } final public function newEditEnginePage() { $field_keys = $this->getEditEngineFieldKeys(); if (!$field_keys) { return null; } $key = $this->getManagementPanelKey(); $label = $this->getManagementPanelLabel(); $panel_uri = $this->getPanelURI(); return id(new PhabricatorEditPage()) ->setKey($key) ->setLabel($label) ->setViewURI($panel_uri) ->setFieldKeys($field_keys); } protected function getEditEngineFieldKeys() { return array(); } protected function getEditPageURI($page = null) { if ($page === null) { $page = $this->getManagementPanelKey(); } $repository = $this->getRepository(); $id = $repository->getID(); return "/diffusion/edit/{$id}/page/{$page}/"; } public function getPanelNavigationURI() { return $this->getPanelURI(); } final protected function newActionList() { $viewer = $this->getViewer(); $action_id = celerity_generate_unique_node_id(); return id(new PhabricatorActionListView()) ->setViewer($viewer) ->setID($action_id); } final protected function newCurtainView() { $viewer = $this->getViewer(); return id(new PHUICurtainView()) ->setViewer($viewer); } final protected function newBox($header_text, $body) { $viewer = $this->getViewer(); $header = id(new PHUIHeaderView()) ->setViewer($viewer) ->setHeader($header_text); $view = id(new PHUIObjectBoxView()) ->setViewer($viewer) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild($body); 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/diffusion/management/DiffusionRepositoryManagementBuildsPanelGroup.php
src/applications/diffusion/management/DiffusionRepositoryManagementBuildsPanelGroup.php
<?php final class DiffusionRepositoryManagementBuildsPanelGroup extends DiffusionRepositoryManagementPanelGroup { const PANELGROUPKEY = 'builds'; public function getManagementPanelGroupLabel() { return pht('Builds'); } public function getManagementPanelGroupOrder() { return 2000; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryURIsManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryURIsManagementPanel.php
<?php final class DiffusionRepositoryURIsManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'uris'; public function getManagementPanelLabel() { return pht('URIs'); } public function getManagementPanelIcon() { return 'fa-globe'; } public function getManagementPanelOrder() { return 400; } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $doc_href = PhabricatorEnv::getDoclink('Diffusion User Guide: URIs'); $add_href = $repository->getPathURI('uri/edit/'); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-plus') ->setHref($add_href) ->setDisabled(!$can_edit) ->setName(pht('Add New URI'))); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-book') ->setHref($doc_href) ->setName(pht('URI Documentation'))); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $uris = $repository->getURIs(); Javelin::initBehavior('phabricator-tooltips'); $rows = array(); foreach ($uris as $uri) { $uri_name = $uri->getDisplayURI(); $uri_name = phutil_tag( 'a', array( 'href' => $uri->getViewURI(), ), $uri_name); if ($uri->getIsDisabled()) { $status_icon = 'fa-times grey'; } else { $status_icon = 'fa-check green'; } $uri_status = id(new PHUIIconView())->setIcon($status_icon); $io_type = $uri->getEffectiveIOType(); $io_map = PhabricatorRepositoryURI::getIOTypeMap(); $io_spec = idx($io_map, $io_type, array()); $io_icon = idx($io_spec, 'icon'); $io_color = idx($io_spec, 'color'); $io_label = idx($io_spec, 'label', $io_type); $uri_io = array( id(new PHUIIconView())->setIcon("{$io_icon} {$io_color}"), ' ', $io_label, ); $display_type = $uri->getEffectiveDisplayType(); $display_map = PhabricatorRepositoryURI::getDisplayTypeMap(); $display_spec = idx($display_map, $display_type, array()); $display_icon = idx($display_spec, 'icon'); $display_color = idx($display_spec, 'color'); $display_label = idx($display_spec, 'label', $display_type); $uri_display = array( id(new PHUIIconView())->setIcon("{$display_icon} {$display_color}"), ' ', $display_label, ); $rows[] = array( $uri_status, $uri_name, $uri_io, $uri_display, ); } $table = id(new AphrontTableView($rows)) ->setNoDataString(pht('This repository has no URIs.')) ->setHeaders( array( null, pht('URI'), pht('I/O'), pht('Display'), )) ->setColumnClasses( array( null, 'pri wide', null, null, )); $is_new = $repository->isNewlyInitialized(); $messages = array(); if ($repository->isHosted()) { if ($is_new) { $host_message = pht('This repository will be hosted.'); } else { $host_message = pht('This repository is observed.'); } $messages[] = $host_message; } else { if ($is_new) { $observe_message = pht( 'This repository will be observed.'); } else { $observe_message = pht( 'This remote repository is being observed.'); } $messages[] = $observe_message; } $info_view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->setErrors($messages); $box = $this->newBox(pht('Repository URIs'), $table); return array($info_view, $box); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryPoliciesManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryPoliciesManagementPanel.php
<?php final class DiffusionRepositoryPoliciesManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'policies'; public function getManagementPanelLabel() { return pht('Policies'); } public function getManagementPanelOrder() { return 300; } public function getManagementPanelIcon() { $viewer = $this->getViewer(); $repository = $this->getRepository(); $can_view = PhabricatorPolicyCapability::CAN_VIEW; $can_edit = PhabricatorPolicyCapability::CAN_EDIT; $can_push = DiffusionPushCapability::CAPABILITY; $actual_values = array( 'spacePHID' => $repository->getSpacePHID(), 'view' => $repository->getPolicy($can_view), 'edit' => $repository->getPolicy($can_edit), 'push' => $repository->getPolicy($can_push), ); $default = PhabricatorRepository::initializeNewRepository( $viewer); $default_values = array( 'spacePHID' => $default->getSpacePHID(), 'view' => $default->getPolicy($can_view), 'edit' => $default->getPolicy($can_edit), 'push' => $default->getPolicy($can_push), ); if ($actual_values === $default_values) { return 'fa-lock grey'; } else { return 'fa-lock'; } } protected function getEditEngineFieldKeys() { return array( 'policy.view', 'policy.edit', 'spacePHID', 'policy.push', ); } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $edit_uri = $this->getEditPageURI(); $action_list->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Policies')) ->setHref($edit_uri) ->setIcon('fa-pencil') ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $descriptions = PhabricatorPolicyQuery::renderPolicyDescriptions( $viewer, $repository); $view_parts = array(); if (PhabricatorSpacesNamespaceQuery::getViewerSpacesExist($viewer)) { $space_phid = PhabricatorSpacesNamespaceQuery::getObjectSpacePHID( $repository); $view_parts[] = $viewer->renderHandle($space_phid); } $view_parts[] = $descriptions[PhabricatorPolicyCapability::CAN_VIEW]; $view->addProperty( pht('Visible To'), phutil_implode_html(" \xC2\xB7 ", $view_parts)); $view->addProperty( pht('Editable By'), $descriptions[PhabricatorPolicyCapability::CAN_EDIT]); $pushable = $repository->isHosted() ? $descriptions[DiffusionPushCapability::CAPABILITY] : phutil_tag('em', array(), pht('Not a Hosted Repository')); $view->addProperty(pht('Pushable By'), $pushable); return $this->newBox(pht('Policies'), $view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryAutomationManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryAutomationManagementPanel.php
<?php final class DiffusionRepositoryAutomationManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'automation'; public function getManagementPanelLabel() { return pht('Automation'); } public function getManagementPanelOrder() { return 800; } public function getManagementPanelGroupKey() { return DiffusionRepositoryManagementBuildsPanelGroup::PANELGROUPKEY; } public function shouldEnableForRepository( PhabricatorRepository $repository) { return $repository->isGit(); } protected function getEditEngineFieldKeys() { return array( 'automationBlueprintPHIDs', ); } public function getManagementPanelIcon() { $repository = $this->getRepository(); if (!$repository->canPerformAutomation()) { return 'fa-truck grey'; } $blueprint_phids = $repository->getAutomationBlueprintPHIDs(); if (!$blueprint_phids) { return 'fa-truck grey'; } $is_authorized = DrydockAuthorizationQuery::isFullyAuthorized( $repository->getPHID(), $blueprint_phids); if (!$is_authorized) { return 'fa-exclamation-triangle yellow'; } return 'fa-truck'; } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $can_test = $can_edit && $repository->canPerformAutomation(); $automation_uri = $this->getEditPageURI(); $test_uri = $repository->getPathURI('edit/testautomation/'); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Automation')) ->setHref($automation_uri) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-gamepad') ->setName(pht('Test Configuration')) ->setWorkflow(true) ->setDisabled(!$can_test) ->setHref($test_uri)); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $blueprint_phids = $repository->getAutomationBlueprintPHIDs(); if (!$blueprint_phids) { $blueprint_view = phutil_tag('em', array(), pht('Not Configured')); } else { $blueprint_view = id(new DrydockObjectAuthorizationView()) ->setUser($viewer) ->setObjectPHID($repository->getPHID()) ->setBlueprintPHIDs($blueprint_phids); } $view->addProperty(pht('Automation'), $blueprint_view); return $this->newBox(pht('Automation'), $view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositorySubversionManagementPanel.php
src/applications/diffusion/management/DiffusionRepositorySubversionManagementPanel.php
<?php final class DiffusionRepositorySubversionManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'subversion'; public function getManagementPanelLabel() { return pht('Subversion'); } public function getManagementPanelOrder() { return 1000; } public function shouldEnableForRepository( PhabricatorRepository $repository) { return $repository->isSVN(); } public function getManagementPanelIcon() { $repository = $this->getRepository(); $has_any = (bool)$repository->getDetail('svn-subpath'); if ($has_any) { return 'fa-folder'; } else { return 'fa-folder grey'; } } protected function getEditEngineFieldKeys() { return array( 'importOnly', ); } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $subversion_uri = $this->getEditPageURI(); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Properties')) ->setHref($subversion_uri) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); return $this->newCurtainView($action_list) ->setActionList($action_list); } public function buildManagementPanelContent() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $default_branch = nonempty( $repository->getDetail('svn-subpath'), phutil_tag('em', array(), pht('Import Entire Repository'))); $view->addProperty(pht('Import Only'), $default_branch); return $this->newBox(pht('Subversion'), $view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryStagingManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryStagingManagementPanel.php
<?php final class DiffusionRepositoryStagingManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'staging'; public function getManagementPanelLabel() { return pht('Staging Area'); } public function getManagementPanelOrder() { return 700; } public function getManagementPanelGroupKey() { return DiffusionRepositoryManagementBuildsPanelGroup::PANELGROUPKEY; } public function shouldEnableForRepository( PhabricatorRepository $repository) { return $repository->isGit(); } public function getManagementPanelIcon() { $repository = $this->getRepository(); $staging_uri = $repository->getStagingURI(); if ($staging_uri) { return 'fa-upload'; } else { return 'fa-upload grey'; } } protected function getEditEngineFieldKeys() { return array( 'stagingAreaURI', ); } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $staging_uri = $this->getEditPageURI(); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Staging')) ->setHref($staging_uri) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $staging_uri = $repository->getStagingURI(); if (!$staging_uri) { $staging_uri = phutil_tag('em', array(), pht('No Staging Area')); } $view->addProperty(pht('Staging Area URI'), $staging_uri); return $this->newBox(pht('Staging Area'), $view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositorySymbolsManagementPanel.php
src/applications/diffusion/management/DiffusionRepositorySymbolsManagementPanel.php
<?php final class DiffusionRepositorySymbolsManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'symbols'; public function getManagementPanelLabel() { return pht('Symbols'); } public function getManagementPanelOrder() { return 900; } public function getManagementPanelGroupKey() { return DiffusionRepositoryManagementIntegrationsPanelGroup::PANELGROUPKEY; } public function getManagementPanelIcon() { $repository = $this->getRepository(); $has_any = $repository->getSymbolLanguages() || $repository->getSymbolSources(); if ($has_any) { return 'fa-link'; } else { return 'fa-link grey'; } } protected function getEditEngineFieldKeys() { return array( 'symbolLanguages', 'symbolRepositoryPHIDs', ); } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $symbols_uri = $this->getEditPageURI(); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Symbols')) ->setHref($symbols_uri) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $languages = $repository->getSymbolLanguages(); if ($languages) { $languages = implode(', ', $languages); } else { $languages = phutil_tag('em', array(), pht('Any')); } $view->addProperty(pht('Languages'), $languages); $sources = $repository->getSymbolSources(); if ($sources) { $sources = $viewer->renderHandleList($sources); } else { $sources = phutil_tag('em', array(), pht('This Repository Only')); } $view->addProperty(pht('Uses Symbols From'), $sources); return $this->newBox(pht('Symbols'), $view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryBasicsManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryBasicsManagementPanel.php
<?php final class DiffusionRepositoryBasicsManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'basics'; public function getManagementPanelLabel() { return pht('Basics'); } public function getManagementPanelOrder() { return 100; } public function getManagementPanelIcon() { return 'fa-code'; } protected function getEditEngineFieldKeys() { return array( 'name', 'callsign', 'shortName', 'description', 'projectPHIDs', ); } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = id(new PhabricatorActionListView()) ->setViewer($viewer); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $edit_uri = $this->getEditPageURI(); $activate_uri = $repository->getPathURI('edit/activate/'); $delete_uri = $repository->getPathURI('edit/delete/'); $encoding_uri = $this->getEditPageURI('encoding'); $dangerous_uri = $repository->getPathURI('edit/dangerous/'); $enormous_uri = $repository->getPathURI('edit/enormous/'); $update_uri = $repository->getPathURI('edit/update/'); $publish_uri = $repository->getPathURI('edit/publish/'); if ($repository->isTracked()) { $activate_icon = 'fa-ban'; $activate_label = pht('Deactivate Repository'); } else { $activate_icon = 'fa-check'; $activate_label = pht('Activate Repository'); } if (!$repository->isPublishingDisabled()) { $publish_icon = 'fa-ban'; $publish_label = pht('Disable Publishing'); } else { $publish_icon = 'fa-check'; $publish_label = pht('Enable Publishing'); } $should_dangerous = $repository->shouldAllowDangerousChanges(); if ($should_dangerous) { $dangerous_icon = 'fa-shield'; $dangerous_name = pht('Prevent Dangerous Changes'); $can_dangerous = $can_edit; } else { $dangerous_icon = 'fa-exclamation-triangle'; $dangerous_name = pht('Allow Dangerous Changes'); $can_dangerous = ($can_edit && $repository->canAllowDangerousChanges()); } $should_enormous = $repository->shouldAllowEnormousChanges(); if ($should_enormous) { $enormous_icon = 'fa-shield'; $enormous_name = pht('Prevent Enormous Changes'); $can_enormous = $can_edit; } else { $enormous_icon = 'fa-exclamation-triangle'; $enormous_name = pht('Allow Enormous Changes'); $can_enormous = ($can_edit && $repository->canAllowEnormousChanges()); } $action_list->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Basic Information')) ->setHref($edit_uri) ->setIcon('fa-pencil') ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); $action_list->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Text Encoding')) ->setIcon('fa-text-width') ->setHref($encoding_uri) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); $action_list->addAction( id(new PhabricatorActionView()) ->setName($dangerous_name) ->setHref($dangerous_uri) ->setIcon($dangerous_icon) ->setDisabled(!$can_dangerous) ->setWorkflow(true)); $action_list->addAction( id(new PhabricatorActionView()) ->setName($enormous_name) ->setHref($enormous_uri) ->setIcon($enormous_icon) ->setDisabled(!$can_enormous) ->setWorkflow(true)); $action_list->addAction( id(new PhabricatorActionView()) ->setType(PhabricatorActionView::TYPE_DIVIDER)); $action_list->addAction( id(new PhabricatorActionView()) ->setName($activate_label) ->setHref($activate_uri) ->setIcon($activate_icon) ->setDisabled(!$can_edit) ->setWorkflow(true)); $action_list->addAction( id(new PhabricatorActionView()) ->setName($publish_label) ->setHref($publish_uri) ->setIcon($publish_icon) ->setDisabled(!$can_edit) ->setWorkflow(true)); $action_list->addAction( id(new PhabricatorActionView()) ->setName(pht('Update Now')) ->setHref($update_uri) ->setIcon('fa-refresh') ->setWorkflow(true) ->setDisabled(!$can_edit)); $action_list->addAction( id(new PhabricatorActionView()) ->setType(PhabricatorActionView::TYPE_DIVIDER)); $action_list->addAction( id(new PhabricatorActionView()) ->setName(pht('Delete Repository')) ->setHref($delete_uri) ->setIcon('fa-times') ->setWorkflow(true)); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { $basics = $this->buildBasics(); $basics = $this->newBox(pht('Properties'), $basics); $repository = $this->getRepository(); $state = $this->buildStateView($repository); $is_new = $repository->isNewlyInitialized(); $info_view = null; if ($is_new) { $messages = array(); $messages[] = pht( 'This newly created repository is not active yet. Configure policies, '. 'options, and URIs. When ready, %s the repository.', phutil_tag('strong', array(), pht('Activate'))); if ($repository->isHosted()) { $messages[] = pht( 'If activated now, this repository will become a new hosted '. 'repository. To observe an existing repository instead, configure '. 'it in the %s panel.', phutil_tag('strong', array(), pht('URIs'))); } else { $messages[] = pht( 'If activated now, this repository will observe an existing remote '. 'repository and begin importing changes.'); } $info_view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->setErrors($messages); } $description = $this->buildDescription(); if ($description) { $description = $this->newBox(pht('Description'), $description); } $status = $this->buildStatus(); return array($info_view, $state, $basics, $description, $status); } private function buildBasics() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $name = $repository->getName(); $view->addProperty(pht('Name'), $name); $type = PhabricatorRepositoryType::getNameForRepositoryType( $repository->getVersionControlSystem()); $view->addProperty(pht('Type'), $type); $callsign = $repository->getCallsign(); if (!strlen($callsign)) { $callsign = phutil_tag('em', array(), pht('No Callsign')); } $view->addProperty(pht('Callsign'), $callsign); $short_name = $repository->getRepositorySlug(); if ($short_name === null) { $short_name = phutil_tag('em', array(), pht('No Short Name')); } $view->addProperty(pht('Short Name'), $short_name); $encoding = $repository->getDetail('encoding'); if (!$encoding) { $encoding = phutil_tag('em', array(), pht('Use Default (UTF-8)')); } $view->addProperty(pht('Encoding'), $encoding); $can_dangerous = $repository->canAllowDangerousChanges(); if (!$can_dangerous) { $dangerous = phutil_tag('em', array(), pht('Not Preventable')); } else { $should_dangerous = $repository->shouldAllowDangerousChanges(); if ($should_dangerous) { $dangerous = pht('Allowed'); } else { $dangerous = pht('Not Allowed'); } } $view->addProperty(pht('Dangerous Changes'), $dangerous); $can_enormous = $repository->canAllowEnormousChanges(); if (!$can_enormous) { $enormous = phutil_tag('em', array(), pht('Not Preventable')); } else { $should_enormous = $repository->shouldAllowEnormousChanges(); if ($should_enormous) { $enormous = pht('Allowed'); } else { $enormous = pht('Not Allowed'); } } $view->addProperty(pht('Enormous Changes'), $enormous); return $view; } private function buildDescription() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $description = $repository->getDetail('description'); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); if (!strlen($description)) { return null; } else { $description = new PHUIRemarkupView($viewer, $description); } $view->addTextContent($description); return $view; } private function buildStatus() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $view->addProperty( pht('Update Frequency'), $this->buildRepositoryUpdateInterval($repository)); $messages = $this->loadStatusMessages($repository); $status = $this->buildRepositoryStatus($repository, $messages); $raw_error = $this->buildRepositoryRawError($repository, $messages); $view->addProperty(pht('Status'), $status); if ($raw_error) { $view->addSectionHeader(pht('Raw Error')); $view->addTextContent($raw_error); } return $this->newBox(pht('Working Copy Status'), $view); } private function buildRepositoryUpdateInterval( PhabricatorRepository $repository) { $smart_wait = $repository->loadUpdateInterval(); $doc_href = PhabricatorEnv::getDoclink( 'Diffusion User Guide: Repository Updates'); return array( phutil_format_relative_time_detailed($smart_wait), " \xC2\xB7 ", phutil_tag( 'a', array( 'href' => $doc_href, 'target' => '_blank', ), pht('Learn More')), ); } private function buildRepositoryStatus( PhabricatorRepository $repository, array $messages) { $viewer = $this->getViewer(); $is_cluster = $repository->getAlmanacServicePHID(); $view = new PHUIStatusListView(); if ($repository->isTracked()) { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_ACCEPT, 'green') ->setTarget(pht('Repository Active'))); } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'bluegrey') ->setTarget(pht('Repository Inactive')) ->setNote( pht('Activate this repository to begin or resume import.'))); return $view; } $binaries = array(); $svnlook_check = false; switch ($repository->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $binaries[] = 'git'; break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $binaries[] = 'svn'; break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $binaries[] = 'hg'; break; } if ($repository->isHosted()) { $proto_https = PhabricatorRepositoryURI::BUILTIN_PROTOCOL_HTTPS; $proto_http = PhabricatorRepositoryURI::BUILTIN_PROTOCOL_HTTP; $can_http = $repository->canServeProtocol($proto_http, false) || $repository->canServeProtocol($proto_https, false); if ($can_http) { switch ($repository->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $binaries[] = 'git-http-backend'; break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $binaries[] = 'svnserve'; $binaries[] = 'svnadmin'; $binaries[] = 'svnlook'; $svnlook_check = true; break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $binaries[] = 'hg'; break; } } $proto_ssh = PhabricatorRepositoryURI::BUILTIN_PROTOCOL_SSH; $can_ssh = $repository->canServeProtocol($proto_ssh, false); if ($can_ssh) { switch ($repository->getVersionControlSystem()) { case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT: $binaries[] = 'git-receive-pack'; $binaries[] = 'git-upload-pack'; break; case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN: $binaries[] = 'svnserve'; $binaries[] = 'svnadmin'; $binaries[] = 'svnlook'; $svnlook_check = true; break; case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL: $binaries[] = 'hg'; break; } } } $binaries = array_unique($binaries); if (!$is_cluster) { // We're only checking for binaries if we aren't running with a cluster // configuration. In theory, we could check for binaries on the // repository host machine, but we'd need to make this more complicated // to do that. foreach ($binaries as $binary) { $where = Filesystem::resolveBinary($binary); if (!$where) { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'red') ->setTarget( pht('Missing Binary %s', phutil_tag('tt', array(), $binary))) ->setNote(pht( "Unable to find this binary in the webserver's PATH. You may ". "need to configure %s.", $this->getEnvConfigLink()))); } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_ACCEPT, 'green') ->setTarget( pht('Found Binary %s', phutil_tag('tt', array(), $binary))) ->setNote(phutil_tag('tt', array(), $where))); } } // This gets checked generically above. However, for svn commit hooks, we // need this to be in environment.append-paths because subversion strips // PATH. if ($svnlook_check) { $where = Filesystem::resolveBinary('svnlook'); if ($where) { $path = substr($where, 0, strlen($where) - strlen('svnlook')); $dirs = PhabricatorEnv::getEnvConfig('environment.append-paths'); $in_path = false; foreach ($dirs as $dir) { if (Filesystem::isDescendant($path, $dir)) { $in_path = true; break; } } if (!$in_path) { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'red') ->setTarget( pht('Commit Hooks: %s', phutil_tag('tt', array(), $binary))) ->setNote( pht( 'The directory containing the "svnlook" binary is not '. 'listed in "environment.append-paths", so commit hooks '. '(which execute with an empty "PATH") will not be able to '. 'find "svnlook". Add `%s` to %s.', $path, $this->getEnvConfigLink()))); } } } } $doc_href = PhabricatorEnv::getDoclink('Managing Daemons with phd'); $daemon_instructions = pht( 'Use %s to start daemons. See %s.', phutil_tag('tt', array(), 'bin/phd start'), phutil_tag( 'a', array( 'href' => $doc_href, ), pht('Managing Daemons with phd'))); $pull_daemon = id(new PhabricatorDaemonLogQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withStatus(PhabricatorDaemonLogQuery::STATUS_ALIVE) ->withDaemonClasses(array('PhabricatorRepositoryPullLocalDaemon')) ->setLimit(1) ->execute(); if ($pull_daemon) { // TODO: In a cluster environment, we need a daemon on this repository's // host, specifically, and we aren't checking for that right now. This // is a reasonable proxy for things being more-or-less correctly set up, // though. $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_ACCEPT, 'green') ->setTarget(pht('Pull Daemon Running'))); } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'red') ->setTarget(pht('Pull Daemon Not Running')) ->setNote($daemon_instructions)); } $task_daemon = id(new PhabricatorDaemonLogQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withStatus(PhabricatorDaemonLogQuery::STATUS_ALIVE) ->withDaemonClasses(array('PhabricatorTaskmasterDaemon')) ->setLimit(1) ->execute(); if ($task_daemon) { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_ACCEPT, 'green') ->setTarget(pht('Task Daemon Running'))); } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'red') ->setTarget(pht('Task Daemon Not Running')) ->setNote($daemon_instructions)); } if ($is_cluster) { // Just omit this status check for now in cluster environments. We // could make a service call and pull it from the repository host // eventually. } else if ($repository->usesLocalWorkingCopy()) { $local_parent = dirname($repository->getLocalPath()); if (Filesystem::pathExists($local_parent)) { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_ACCEPT, 'green') ->setTarget(pht('Storage Directory OK')) ->setNote(phutil_tag('tt', array(), $local_parent))); } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'red') ->setTarget(pht('No Storage Directory')) ->setNote( pht( 'Storage directory %s does not exist, or is not readable by '. 'the webserver. Create this directory or make it readable.', phutil_tag('tt', array(), $local_parent)))); return $view; } $local_path = $repository->getLocalPath(); $message = idx($messages, PhabricatorRepositoryStatusMessage::TYPE_INIT); if ($message) { switch ($message->getStatusCode()) { case PhabricatorRepositoryStatusMessage::CODE_ERROR: $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'red') ->setTarget(pht('Initialization Error')) ->setNote($message->getParameter('message'))); return $view; case PhabricatorRepositoryStatusMessage::CODE_OKAY: if (Filesystem::pathExists($local_path)) { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_ACCEPT, 'green') ->setTarget(pht('Working Copy OK')) ->setNote(phutil_tag('tt', array(), $local_path))); } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'red') ->setTarget(pht('Working Copy Error')) ->setNote( pht( 'Working copy %s has been deleted, or is not '. 'readable by the webserver. Make this directory '. 'readable. If it has been deleted, the daemons should '. 'restore it automatically.', phutil_tag('tt', array(), $local_path)))); return $view; } break; default: $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_CLOCK, 'green') ->setTarget(pht('Initializing Working Copy')) ->setNote(pht('Daemons are initializing the working copy.'))); return $view; } } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_CLOCK, 'orange') ->setTarget(pht('No Working Copy Yet')) ->setNote( pht('Waiting for daemons to build a working copy.'))); return $view; } } $message = idx($messages, PhabricatorRepositoryStatusMessage::TYPE_FETCH); if ($message) { switch ($message->getStatusCode()) { case PhabricatorRepositoryStatusMessage::CODE_ERROR: $message = $message->getParameter('message'); $suggestion = null; if (preg_match('/Permission denied \(publickey\)./', $message)) { $suggestion = pht( 'Public Key Error: This error usually indicates that the '. 'keypair you have configured does not have permission to '. 'access the repository.'); } $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_WARNING, 'red') ->setTarget(pht('Update Error')) ->setNote($suggestion)); return $view; case PhabricatorRepositoryStatusMessage::CODE_OKAY: $ago = (PhabricatorTime::getNow() - $message->getEpoch()); $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_ACCEPT, 'green') ->setTarget(pht('Updates OK')) ->setNote( pht( 'Last updated %s (%s ago).', phabricator_datetime($message->getEpoch(), $viewer), phutil_format_relative_time_detailed($ago)))); break; } } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_CLOCK, 'orange') ->setTarget(pht('Waiting For Update')) ->setNote( pht('Waiting for daemons to read updates.'))); } if ($repository->isImporting()) { $ratio = $repository->loadImportProgress(); $percentage = sprintf('%.2f%%', 100 * $ratio); $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_CLOCK, 'green') ->setTarget(pht('Importing')) ->setNote( pht('%s Complete', $percentage))); } else { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_ACCEPT, 'green') ->setTarget(pht('Fully Imported'))); } if (idx($messages, PhabricatorRepositoryStatusMessage::TYPE_NEEDS_UPDATE)) { $view->addItem( id(new PHUIStatusItemView()) ->setIcon(PHUIStatusItemView::ICON_UP, 'indigo') ->setTarget(pht('Prioritized')) ->setNote(pht('This repository will be updated soon!'))); } return $view; } private function buildRepositoryRawError( PhabricatorRepository $repository, array $messages) { $viewer = $this->getViewer(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $raw_error = null; $message = idx($messages, PhabricatorRepositoryStatusMessage::TYPE_FETCH); if ($message) { switch ($message->getStatusCode()) { case PhabricatorRepositoryStatusMessage::CODE_ERROR: $raw_error = $message->getParameter('message'); break; } } if ($raw_error !== null) { if (!$can_edit) { $raw_message = pht( 'You must be able to edit a repository to see raw error messages '. 'because they sometimes disclose sensitive information.'); $raw_message = phutil_tag('em', array(), $raw_message); } else { $raw_message = phutil_escape_html_newlines($raw_error); } } else { $raw_message = null; } return $raw_message; } private function loadStatusMessages(PhabricatorRepository $repository) { $messages = id(new PhabricatorRepositoryStatusMessage()) ->loadAllWhere('repositoryID = %d', $repository->getID()); $messages = mpull($messages, null, 'getStatusType'); return $messages; } private function getEnvConfigLink() { $config_href = '/config/edit/environment.append-paths/'; return phutil_tag( 'a', array( 'href' => $config_href, ), 'environment.append-paths'); } private function buildStateView(PhabricatorRepository $repository) { $viewer = $this->getViewer(); $is_new = $repository->isNewlyInitialized(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); if (!$repository->isTracked()) { if ($is_new) { $active_icon = 'fa-ban'; $active_color = 'yellow'; $active_label = pht('Not Activated Yet'); $active_note = pht('Complete Setup and Activate Repository'); } else { $active_icon = 'fa-times'; $active_color = 'red'; $active_label = pht('Not Active'); $active_note = pht('Repository Disabled'); } } else if ($repository->isImporting()) { $active_icon = 'fa-hourglass'; $active_color = 'yellow'; $active_label = pht('Importing...'); $active_note = null; } else { $active_icon = 'fa-check'; $active_color = 'green'; $active_label = pht('Repository Active'); $active_note = null; } $active_view = id(new PHUIStatusListView()) ->addItem( id(new PHUIStatusItemView()) ->setIcon($active_icon, $active_color) ->setTarget($active_label) ->setNote($active_note)); if ($repository->isPublishingDisabled()) { $publishing_icon = 'fa-times'; $publishing_color = 'red'; $publishing_label = pht('Not Publishing'); $publishing_note = pht('Publishing Disabled'); } else if (!$repository->isTracked()) { $publishing_icon = 'fa-ban'; $publishing_color = 'yellow'; $publishing_label = pht('Not Publishing'); if ($is_new) { $publishing_note = pht('Repository Not Active Yet'); } else { $publishing_note = pht('Repository Inactive'); } } else if ($repository->isImporting()) { $publishing_icon = 'fa-ban'; $publishing_color = 'yellow'; $publishing_label = pht('Not Publishing'); $publishing_note = pht('Repository Importing'); } else { $publishing_icon = 'fa-check'; $publishing_color = 'green'; $publishing_label = pht('Publishing Active'); $publishing_note = null; } $publishing_view = id(new PHUIStatusListView()) ->addItem( id(new PHUIStatusItemView()) ->setIcon($publishing_icon, $publishing_color) ->setTarget($publishing_label) ->setNote($publishing_note)); $view->addProperty(pht('Active'), $active_view); $view->addProperty(pht('Publishing'), $publishing_view); return $this->newBox(pht('State'), $view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryHistoryManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryHistoryManagementPanel.php
<?php final class DiffusionRepositoryHistoryManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'history'; public function getManagementPanelLabel() { return pht('History'); } public function getManagementPanelOrder() { return 2000; } public function getManagementPanelIcon() { return 'fa-list-ul'; } public function buildManagementPanelContent() { return $this->newTimeline(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryLimitsManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryLimitsManagementPanel.php
<?php final class DiffusionRepositoryLimitsManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'limits'; public function getManagementPanelLabel() { return pht('Limits'); } public function getManagementPanelOrder() { return 700; } public function shouldEnableForRepository( PhabricatorRepository $repository) { return $repository->isGit(); } public function getManagementPanelIcon() { $repository = $this->getRepository(); $any_limit = false; if ($repository->getFilesizeLimit()) { $any_limit = true; } if ($any_limit) { return 'fa-signal'; } else { return 'fa-signal grey'; } } protected function getEditEngineFieldKeys() { return array( 'filesizeLimit', 'copyTimeLimit', 'touchLimit', ); } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $limits_uri = $this->getEditPageURI(); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Limits')) ->setHref($limits_uri) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $byte_limit = $repository->getFilesizeLimit(); if ($byte_limit) { $filesize_display = pht('%s Bytes', new PhutilNumber($byte_limit)); } else { $filesize_display = pht('Unlimited'); $filesize_display = phutil_tag('em', array(), $filesize_display); } $view->addProperty(pht('Filesize Limit'), $filesize_display); $copy_limit = $repository->getCopyTimeLimit(); if ($copy_limit) { $copy_display = pht('%s Seconds', new PhutilNumber($copy_limit)); } else { $copy_default = $repository->getDefaultCopyTimeLimit(); $copy_display = pht( 'Default (%s Seconds)', new PhutilNumber($copy_default)); $copy_display = phutil_tag('em', array(), $copy_display); } $view->addProperty(pht('Clone/Fetch Timeout'), $copy_display); $touch_limit = $repository->getTouchLimit(); if ($touch_limit) { $touch_display = pht('%s Paths', new PhutilNumber($touch_limit)); } else { $touch_display = pht('Unlimited'); $touch_display = phutil_tag('em', array(), $touch_display); } $view->addProperty(pht('Touched Paths Limit'), $touch_display); return $this->newBox(pht('Limits'), $view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryBranchesManagementPanel.php
src/applications/diffusion/management/DiffusionRepositoryBranchesManagementPanel.php
<?php final class DiffusionRepositoryBranchesManagementPanel extends DiffusionRepositoryManagementPanel { const PANELKEY = 'branches'; public function getManagementPanelLabel() { return pht('Branches'); } public function getManagementPanelOrder() { return 1000; } public function shouldEnableForRepository( PhabricatorRepository $repository) { return ($repository->isGit() || $repository->isHg()); } public function getManagementPanelIcon() { $repository = $this->getRepository(); $has_any = $repository->getDetail('default-branch') || $repository->getFetchRules() || $repository->getTrackOnlyRules() || $repository->getPermanentRefRules(); if ($has_any) { return 'fa-code-fork'; } else { return 'fa-code-fork grey'; } } protected function getEditEngineFieldKeys() { return array( 'defaultBranch', 'fetchRefs', 'permanentRefs', 'trackOnly', ); } public function buildManagementPanelCurtain() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $action_list = $this->newActionList(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $repository, PhabricatorPolicyCapability::CAN_EDIT); $branches_uri = $this->getEditPageURI(); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Branches')) ->setHref($branches_uri) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); $drequest = DiffusionRequest::newFromDictionary( array( 'user' => $viewer, 'repository' => $repository, )); $view_uri = $drequest->generateURI( array( 'action' => 'branches', )); $action_list->addAction( id(new PhabricatorActionView()) ->setIcon('fa-code-fork') ->setName(pht('View Branches')) ->setHref($view_uri)); return $this->newCurtainView() ->setActionList($action_list); } public function buildManagementPanelContent() { $repository = $this->getRepository(); $viewer = $this->getViewer(); $content = array(); $view = id(new PHUIPropertyListView()) ->setViewer($viewer); $default_branch = nonempty( $repository->getDetail('default-branch'), phutil_tag('em', array(), $repository->getDefaultBranch())); $view->addProperty(pht('Default Branch'), $default_branch); if ($repository->supportsFetchRules()) { $fetch_only = $repository->getFetchRules(); if ($fetch_only) { $fetch_display = implode(', ', $fetch_only); } else { $fetch_display = phutil_tag('em', array(), pht('Fetch All Refs')); } $view->addProperty(pht('Fetch Refs'), $fetch_display); } $track_only_rules = $repository->getTrackOnlyRules(); if ($track_only_rules) { $track_only_rules = implode(', ', $track_only_rules); $view->addProperty(pht('Track Only'), $track_only_rules); } $publishing_disabled = $repository->isPublishingDisabled(); if ($publishing_disabled) { $permanent_display = phutil_tag('em', array(), pht('Publishing Disabled')); } else { $permanent_rules = $repository->getPermanentRefRules(); if ($permanent_rules) { $permanent_display = implode(', ', $permanent_rules); } else { $permanent_display = phutil_tag('em', array(), pht('All Branches')); } } $view->addProperty(pht('Permanent Refs'), $permanent_display); $content[] = $this->newBox(pht('Branches'), $view); return $content; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/management/DiffusionRepositoryManagementPanelGroup.php
src/applications/diffusion/management/DiffusionRepositoryManagementPanelGroup.php
<?php abstract class DiffusionRepositoryManagementPanelGroup extends Phobject { final public function getManagementPanelGroupKey() { return $this->getPhobjectClassConstant('PANELGROUPKEY'); } abstract public function getManagementPanelGroupOrder(); abstract public function getManagementPanelGroupLabel(); public static function getAllPanelGroups() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getManagementPanelGroupKey') ->setSortMethod('getManagementPanelGroupOrder') ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/worker/DiffusionUpdateObjectAfterCommitWorker.php
src/applications/diffusion/worker/DiffusionUpdateObjectAfterCommitWorker.php
<?php final class DiffusionUpdateObjectAfterCommitWorker extends PhabricatorWorker { private $properties; protected function getViewer() { return PhabricatorUser::getOmnipotentUser(); } protected function doWork() { $viewer = $this->getViewer(); $data = $this->getTaskData(); $commit_phid = idx($data, 'commitPHID'); if (!$commit_phid) { throw new PhabricatorWorkerPermanentFailureException( pht('No "commitPHID" in task data.')); } $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withPHIDs(array($commit_phid)) ->needIdentities(true) ->executeOne(); if (!$commit) { throw new PhabricatorWorkerPermanentFailureException( pht( 'Unable to load commit "%s".', $commit_phid)); } $object_phid = idx($data, 'objectPHID'); if (!$object_phid) { throw new PhabricatorWorkerPermanentFailureException( pht('No "objectPHID" in task data.')); } $object = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withPHIDs(array($object_phid)) ->executeOne(); if (!$object) { throw new PhabricatorWorkerPermanentFailureException( pht( 'Unable to load object "%s".', $object_phid)); } $properties = idx($data, 'properties', array()); $this->properties = $properties; if ($object instanceof ManiphestTask) { $this->updateTask($commit, $object); } else if ($object instanceof DifferentialRevision) { $this->updateRevision($commit, $object); } } protected function getUpdateProperty($key, $default = null) { return idx($this->properties, $key, $default); } protected function getActingPHID(PhabricatorRepositoryCommit $commit) { if ($commit->hasCommitterIdentity()) { return $commit->getCommitterIdentity()->getIdentityDisplayPHID(); } if ($commit->hasAuthorIdentity()) { return $commit->getAuthorIdentity()->getIdentityDisplayPHID(); } return id(new PhabricatorDiffusionApplication())->getPHID(); } protected function loadActingUser($acting_phid) { // If we we were able to identify an author or committer for the commit, we // try to act as that user when affecting other objects, like tasks marked // with "Fixes Txxx". // This helps to prevent mistakes where a user accidentally writes the // wrong task IDs and affects tasks they can't see (and thus can't undo the // status changes for). // This is just a guard rail, not a security measure. An attacker can still // forge another user's identity trivially by forging author or committer // email addresses. // We also let commits with unrecognized authors act on any task to make // behavior less confusing for new installs, and any user can craft a // commit with an unrecognized author and committer. $viewer = $this->getViewer(); $user_type = PhabricatorPeopleUserPHIDType::TYPECONST; if (phid_get_type($acting_phid) === $user_type) { $acting_user = id(new PhabricatorPeopleQuery()) ->setViewer($viewer) ->withPHIDs(array($acting_phid)) ->executeOne(); if ($acting_user) { return $acting_user; } } return $viewer; } private function updateTask( PhabricatorRepositoryCommit $commit, ManiphestTask $task) { $acting_phid = $this->getActingPHID($commit); $acting_user = $this->loadActingUser($acting_phid); $commit_phid = $commit->getPHID(); $xactions = array(); $xactions[] = $this->newEdgeTransaction( $task, $commit, ManiphestTaskHasCommitEdgeType::EDGECONST); $status = $this->getUpdateProperty('status'); if ($status) { $xactions[] = $task->getApplicationTransactionTemplate() ->setTransactionType(ManiphestTaskStatusTransaction::TRANSACTIONTYPE) ->setMetadataValue('commitPHID', $commit_phid) ->setNewValue($status); } $content_source = $this->newContentSource(); $editor = $task->getApplicationTransactionEditor() ->setActor($acting_user) ->setActingAsPHID($acting_phid) ->setContentSource($content_source) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->addUnmentionablePHIDs(array($commit_phid)); $editor->applyTransactions($task, $xactions); } private function updateRevision( PhabricatorRepositoryCommit $commit, DifferentialRevision $revision) { $acting_phid = $this->getActingPHID($commit); $acting_user = $this->loadActingUser($acting_phid); // See T13625. The "Acting User" is the author of the commit based on the // author string, or the Diffusion application PHID if we could not // identify an author. // This user may not be able to view the commit or the revision, and may // also be unable to make API calls. Here, we execute queries and apply // transactions as the omnipotent user. // It would probably be better to use the acting user everywhere here, and // exit gracefully if they can't see the revision (this is how the flow // on tasks works). However, without a positive indicator in the UI // explaining "no revision was updated because the author of this commit // can't see anything", this might be fairly confusing, and break workflows // which have worked historically. // This isn't, per se, a policy violation (you can't get access to anything // you don't already have access to by making commits that reference // revisions, even if you can't see the commits or revisions), so just // leave it for now. $viewer = $this->getViewer(); // Reload the revision to get the active diff, which is currently required // by "updateRevisionWithCommit()". $revision = id(new DifferentialRevisionQuery()) ->setViewer($viewer) ->withIDs(array($revision->getID())) ->needActiveDiffs(true) ->executeOne(); $xactions = array(); $xactions[] = $this->newEdgeTransaction( $revision, $commit, DifferentialRevisionHasCommitEdgeType::EDGECONST); $match_data = $this->getUpdateProperty('revisionMatchData'); $type_close = DifferentialRevisionCloseTransaction::TRANSACTIONTYPE; $xactions[] = $revision->getApplicationTransactionTemplate() ->setTransactionType($type_close) ->setNewValue(true) ->setMetadataValue('isCommitClose', true) ->setMetadataValue('revisionMatchData', $match_data) ->setMetadataValue('commitPHID', $commit->getPHID()); $extraction_engine = id(new DifferentialDiffExtractionEngine()) ->setViewer($viewer) ->setAuthorPHID($acting_phid); $content_source = $this->newContentSource(); $extraction_engine->updateRevisionWithCommit( $revision, $commit, $xactions, $content_source); } private function newEdgeTransaction( $object, PhabricatorRepositoryCommit $commit, $edge_type) { $commit_phid = $commit->getPHID(); return $object->getApplicationTransactionTemplate() ->setTransactionType(PhabricatorTransactions::TYPE_EDGE) ->setMetadataValue('edge:type', $edge_type) ->setNewValue( array( '+' => array( $commit_phid => $commit_phid, ), )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionCommitRequiredActionResultBucket.php
src/applications/diffusion/query/DiffusionCommitRequiredActionResultBucket.php
<?php final class DiffusionCommitRequiredActionResultBucket extends DiffusionCommitResultBucket { const BUCKETKEY = 'action'; private $objects; public function getResultBucketName() { return pht('Bucket by Required Action'); } protected function buildResultGroups( PhabricatorSavedQuery $query, array $objects) { $this->objects = $objects; $phids = $query->getEvaluatedParameter('responsiblePHIDs'); if (!$phids) { throw new Exception( pht( 'You can not bucket results by required action without '. 'specifying "Responsible Users".')); } $phids = array_fuse($phids); $groups = array(); $groups[] = $this->newGroup() ->setName(pht('Needs Attention')) ->setNoDataString(pht('None of your commits have active concerns.')) ->setObjects($this->filterConcernRaised($phids)); $groups[] = $this->newGroup() ->setName(pht('Needs Verification')) ->setNoDataString(pht('No commits are awaiting your verification.')) ->setObjects($this->filterNeedsVerification($phids)); $groups[] = $this->newGroup() ->setName(pht('Ready to Audit')) ->setNoDataString(pht('No commits are waiting for you to audit them.')) ->setObjects($this->filterShouldAudit($phids)); $groups[] = $this->newGroup() ->setName(pht('Waiting on Authors')) ->setNoDataString(pht('None of your audits are waiting on authors.')) ->setObjects($this->filterWaitingOnAuthors($phids)); $groups[] = $this->newGroup() ->setName(pht('Waiting on Auditors')) ->setNoDataString(pht('None of your commits are waiting on audit.')) ->setObjects($this->filterWaitingOnAuditors($phids)); // Because you can apply these buckets to queries which include revisions // that have been closed, add an "Other" bucket if we still have stuff // that didn't get filtered into any of the previous buckets. if ($this->objects) { $groups[] = $this->newGroup() ->setName(pht('Other Commits')) ->setObjects($this->objects); } return $groups; } private function filterConcernRaised(array $phids) { $results = array(); $objects = $this->objects; foreach ($objects as $key => $object) { if (empty($phids[$object->getAuthorPHID()])) { continue; } if (!$object->isAuditStatusConcernRaised()) { continue; } $results[$key] = $object; unset($this->objects[$key]); } return $results; } private function filterNeedsVerification(array $phids) { $results = array(); $objects = $this->objects; $has_concern = array( PhabricatorAuditRequestStatus::CONCERNED, ); $has_concern = array_fuse($has_concern); foreach ($objects as $key => $object) { if (isset($phids[$object->getAuthorPHID()])) { continue; } if (!$object->isAuditStatusNeedsVerification()) { continue; } if (!$this->hasAuditorsWithStatus($object, $phids, $has_concern)) { continue; } $results[$key] = $object; unset($this->objects[$key]); } return $results; } private function filterShouldAudit(array $phids) { $results = array(); $objects = $this->objects; $should_audit = array( PhabricatorAuditRequestStatus::AUDIT_REQUIRED, PhabricatorAuditRequestStatus::AUDIT_REQUESTED, ); $should_audit = array_fuse($should_audit); foreach ($objects as $key => $object) { if (isset($phids[$object->getAuthorPHID()])) { continue; } if (!$this->hasAuditorsWithStatus($object, $phids, $should_audit)) { continue; } $results[$key] = $object; unset($this->objects[$key]); } return $results; } private function filterWaitingOnAuthors(array $phids) { $results = array(); $objects = $this->objects; foreach ($objects as $key => $object) { if (!$object->isAuditStatusConcernRaised()) { continue; } if (isset($phids[$object->getAuthorPHID()])) { continue; } $results[$key] = $object; unset($this->objects[$key]); } return $results; } private function filterWaitingOnAuditors(array $phids) { $results = array(); $objects = $this->objects; foreach ($objects as $key => $object) { $any_waiting = $object->isAuditStatusNeedsAudit() || $object->isAuditStatusNeedsVerification() || $object->isAuditStatusPartiallyAudited(); if (!$any_waiting) { continue; } $results[$key] = $object; unset($this->objects[$key]); } return $results; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionResolveUserQuery.php
src/applications/diffusion/query/DiffusionResolveUserQuery.php
<?php /** * Resolve an author or committer name, like * `"Abraham Lincoln <alincoln@logcab.in>"`, into a valid Phabricator user * account, like `@alincoln`. */ final class DiffusionResolveUserQuery extends Phobject { private $name; public function withName($name) { $this->name = $name; return $this; } public function execute() { return $this->findUserPHID($this->name); } private function findUserPHID($user_name) { if (!strlen($user_name)) { return null; } $phid = $this->findUserByUserName($user_name); if ($phid) { return $phid; } $phid = $this->findUserByEmailAddress($user_name); if ($phid) { return $phid; } $phid = $this->findUserByRealName($user_name); if ($phid) { return $phid; } // No hits yet, try to parse it as an email address. $email = new PhutilEmailAddress($user_name); $phid = $this->findUserByEmailAddress($email->getAddress()); if ($phid) { return $phid; } $display_name = $email->getDisplayName(); if ($display_name) { $phid = $this->findUserByUserName($display_name); if ($phid) { return $phid; } $phid = $this->findUserByRealName($display_name); if ($phid) { return $phid; } } return null; } private function findUserByUserName($user_name) { $by_username = id(new PhabricatorUser())->loadOneWhere( 'userName = %s', $user_name); if ($by_username) { return $by_username->getPHID(); } return null; } private function findUserByRealName($real_name) { // Note, real names are not guaranteed unique, which is why we do it this // way. $by_realname = id(new PhabricatorUser())->loadAllWhere( 'realName = %s', $real_name); if (count($by_realname) == 1) { return head($by_realname)->getPHID(); } return null; } private function findUserByEmailAddress($email_address) { $by_email = PhabricatorUser::loadOneWithEmailAddress($email_address); if ($by_email) { return $by_email->getPHID(); } return null; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionFileFutureQuery.php
src/applications/diffusion/query/DiffusionFileFutureQuery.php
<?php abstract class DiffusionFileFutureQuery extends DiffusionQuery { private $timeout; private $byteLimit; private $didHitByteLimit = false; private $didHitTimeLimit = false; public static function getConduitParameters() { return array( 'timeout' => 'optional int', 'byteLimit' => 'optional int', ); } public function setTimeout($timeout) { $this->timeout = $timeout; return $this; } public function getTimeout() { return $this->timeout; } public function setByteLimit($byte_limit) { $this->byteLimit = $byte_limit; return $this; } public function getByteLimit() { return $this->byteLimit; } final public function getExceededByteLimit() { return $this->didHitByteLimit; } final public function getExceededTimeLimit() { return $this->didHitTimeLimit; } abstract protected function newQueryFuture(); final public function respondToConduitRequest(ConduitAPIRequest $request) { $drequest = $this->getRequest(); $timeout = $request->getValue('timeout'); if ($timeout) { $this->setTimeout($timeout); } $byte_limit = $request->getValue('byteLimit'); if ($byte_limit) { $this->setByteLimit($byte_limit); } $file = $this->execute(); $too_slow = (bool)$this->getExceededTimeLimit(); $too_huge = (bool)$this->getExceededByteLimit(); $file_phid = null; if (!$too_slow && !$too_huge) { $repository = $drequest->getRepository(); $repository_phid = $repository->getPHID(); $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $file->attachToObject($repository_phid); unset($unguarded); $file_phid = $file->getPHID(); } return array( 'tooSlow' => $too_slow, 'tooHuge' => $too_huge, 'filePHID' => $file_phid, ); } final public function executeInline() { $future = $this->newConfiguredQueryFuture(); list($stdout) = $future->resolvex(); return $stdout; } final protected function executeQuery() { $future = $this->newConfiguredQueryFuture(); $drequest = $this->getRequest(); $name = ''; if ($drequest->getPath() !== null) { $name = basename($drequest->getPath()); } $relative_ttl = phutil_units('48 hours in seconds'); try { $threshold = PhabricatorFileStorageEngine::getChunkThreshold(); $future->setReadBufferSize($threshold); $source = id(new PhabricatorExecFutureFileUploadSource()) ->setName($name) ->setRelativeTTL($relative_ttl) ->setViewPolicy(PhabricatorPolicies::POLICY_NOONE) ->setExecFuture($future); $byte_limit = $this->getByteLimit(); if ($byte_limit) { $source->setByteLimit($byte_limit); } $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $file = $source->uploadFile(); unset($unguarded); } catch (CommandException $ex) { if (!$future->getWasKilledByTimeout()) { throw $ex; } $this->didHitTimeLimit = true; $file = null; } catch (PhabricatorFileUploadSourceByteLimitException $ex) { $this->didHitByteLimit = true; $file = null; } return $file; } private function newConfiguredQueryFuture() { $future = $this->newQueryFuture(); if ($this->getTimeout()) { $future->setTimeout($this->getTimeout()); } return $future; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionCommitQuery.php
src/applications/diffusion/query/DiffusionCommitQuery.php
<?php final class DiffusionCommitQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $authorPHIDs; private $defaultRepository; private $identifiers; private $repositoryIDs; private $repositoryPHIDs; private $identifierMap; private $responsiblePHIDs; private $statuses; private $packagePHIDs; private $unreachable; private $permanent; private $needAuditRequests; private $needAuditAuthority; private $auditIDs; private $auditorPHIDs; private $epochMin; private $epochMax; private $importing; private $ancestorsOf; private $needCommitData; private $needDrafts; private $needIdentities; private $mustFilterRefs = false; private $refRepository; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withAuthorPHIDs(array $phids) { $this->authorPHIDs = $phids; return $this; } /** * Load commits by partial or full identifiers, e.g. "rXab82393", "rX1234", * or "a9caf12". When an identifier matches multiple commits, they will all * be returned; callers should be prepared to deal with more results than * they queried for. */ public function withIdentifiers(array $identifiers) { // Some workflows (like blame lookups) can pass in large numbers of // duplicate identifiers. We only care about unique identifiers, so // get rid of duplicates immediately. $identifiers = array_fuse($identifiers); $this->identifiers = $identifiers; return $this; } /** * Look up commits in a specific repository. This is a shorthand for calling * @{method:withDefaultRepository} and @{method:withRepositoryIDs}. */ public function withRepository(PhabricatorRepository $repository) { $this->withDefaultRepository($repository); $this->withRepositoryIDs(array($repository->getID())); return $this; } /** * Look up commits in a specific repository. Prefer * @{method:withRepositoryIDs}; the underlying table is keyed by ID such * that this method requires a separate initial query to map PHID to ID. */ public function withRepositoryPHIDs(array $phids) { $this->repositoryPHIDs = $phids; return $this; } /** * If a default repository is provided, ambiguous commit identifiers will * be assumed to belong to the default repository. * * For example, "r123" appearing in a commit message in repository X is * likely to be unambiguously "rX123". Normally the reference would be * considered ambiguous, but if you provide a default repository it will * be correctly resolved. */ public function withDefaultRepository(PhabricatorRepository $repository) { $this->defaultRepository = $repository; return $this; } public function withRepositoryIDs(array $repository_ids) { $this->repositoryIDs = array_unique($repository_ids); return $this; } public function needCommitData($need) { $this->needCommitData = $need; return $this; } public function needDrafts($need) { $this->needDrafts = $need; return $this; } public function needIdentities($need) { $this->needIdentities = $need; return $this; } public function needAuditRequests($need) { $this->needAuditRequests = $need; return $this; } public function needAuditAuthority(array $users) { assert_instances_of($users, 'PhabricatorUser'); $this->needAuditAuthority = $users; return $this; } public function withAuditIDs(array $ids) { $this->auditIDs = $ids; return $this; } public function withAuditorPHIDs(array $auditor_phids) { $this->auditorPHIDs = $auditor_phids; return $this; } public function withResponsiblePHIDs(array $responsible_phids) { $this->responsiblePHIDs = $responsible_phids; return $this; } public function withPackagePHIDs(array $package_phids) { $this->packagePHIDs = $package_phids; return $this; } public function withUnreachable($unreachable) { $this->unreachable = $unreachable; return $this; } public function withPermanent($permanent) { $this->permanent = $permanent; return $this; } public function withStatuses(array $statuses) { $this->statuses = $statuses; return $this; } public function withEpochRange($min, $max) { $this->epochMin = $min; $this->epochMax = $max; return $this; } public function withImporting($importing) { $this->importing = $importing; return $this; } public function withAncestorsOf(array $refs) { $this->ancestorsOf = $refs; return $this; } public function getIdentifierMap() { if ($this->identifierMap === null) { throw new Exception( pht( 'You must %s the query before accessing the identifier map.', 'execute()')); } return $this->identifierMap; } protected function getPrimaryTableAlias() { return 'commit'; } protected function willExecute() { if ($this->identifierMap === null) { $this->identifierMap = array(); } } public function newResultObject() { return new PhabricatorRepositoryCommit(); } protected function loadPage() { $table = $this->newResultObject(); $conn = $table->establishConnection('r'); $empty_exception = null; $subqueries = array(); if ($this->responsiblePHIDs) { $base_authors = $this->authorPHIDs; $base_auditors = $this->auditorPHIDs; $responsible_phids = $this->responsiblePHIDs; if ($base_authors) { $all_authors = array_merge($base_authors, $responsible_phids); } else { $all_authors = $responsible_phids; } if ($base_auditors) { $all_auditors = array_merge($base_auditors, $responsible_phids); } else { $all_auditors = $responsible_phids; } $this->authorPHIDs = $all_authors; $this->auditorPHIDs = $base_auditors; try { $subqueries[] = $this->buildStandardPageQuery( $conn, $table->getTableName()); } catch (PhabricatorEmptyQueryException $ex) { $empty_exception = $ex; } $this->authorPHIDs = $base_authors; $this->auditorPHIDs = $all_auditors; try { $subqueries[] = $this->buildStandardPageQuery( $conn, $table->getTableName()); } catch (PhabricatorEmptyQueryException $ex) { $empty_exception = $ex; } } else { $subqueries[] = $this->buildStandardPageQuery( $conn, $table->getTableName()); } if (!$subqueries) { throw $empty_exception; } if (count($subqueries) > 1) { $unions = null; foreach ($subqueries as $subquery) { if (!$unions) { $unions = qsprintf( $conn, '(%Q)', $subquery); continue; } $unions = qsprintf( $conn, '%Q UNION DISTINCT (%Q)', $unions, $subquery); } $query = qsprintf( $conn, '%Q %Q %Q', $unions, $this->buildOrderClause($conn, true), $this->buildLimitClause($conn)); } else { $query = head($subqueries); } $rows = queryfx_all($conn, '%Q', $query); $rows = $this->didLoadRawRows($rows); return $table->loadAllFromArray($rows); } protected function willFilterPage(array $commits) { $repository_ids = mpull($commits, 'getRepositoryID', 'getRepositoryID'); $repos = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getViewer()) ->withIDs($repository_ids) ->execute(); $min_qualified = PhabricatorRepository::MINIMUM_QUALIFIED_HASH; $result = array(); foreach ($commits as $key => $commit) { $repo = idx($repos, $commit->getRepositoryID()); if ($repo) { $commit->attachRepository($repo); } else { $this->didRejectResult($commit); unset($commits[$key]); continue; } // Build the identifierMap if ($this->identifiers !== null) { $ids = $this->identifiers; $prefixes = array( 'r'.$commit->getRepository()->getCallsign(), 'r'.$commit->getRepository()->getCallsign().':', 'R'.$commit->getRepository()->getID().':', '', // No prefix is valid too and will only match the commitIdentifier ); $suffix = $commit->getCommitIdentifier(); if ($commit->getRepository()->isSVN()) { foreach ($prefixes as $prefix) { if (isset($ids[$prefix.$suffix])) { $result[$prefix.$suffix][] = $commit; } } } else { // This awkward construction is so we can link the commits up in O(N) // time instead of O(N^2). for ($ii = $min_qualified; $ii <= strlen($suffix); $ii++) { $part = substr($suffix, 0, $ii); foreach ($prefixes as $prefix) { if (isset($ids[$prefix.$part])) { $result[$prefix.$part][] = $commit; } } } } } } if ($result) { foreach ($result as $identifier => $matching_commits) { if (count($matching_commits) == 1) { $result[$identifier] = head($matching_commits); } else { // This reference is ambiguous (it matches more than one commit) so // don't link it. unset($result[$identifier]); } } $this->identifierMap += $result; } return $commits; } protected function didFilterPage(array $commits) { $viewer = $this->getViewer(); if ($this->mustFilterRefs) { // If this flag is set, the query has an "Ancestors Of" constraint and // at least one of the constraining refs had too many ancestors for us // to apply the constraint with a big "commitIdentifier IN (%Ls)" clause. // We're going to filter each page and hope we get a full result set // before the query overheats. $ancestor_list = mpull($commits, 'getCommitIdentifier'); $ancestor_list = array_values($ancestor_list); foreach ($this->ancestorsOf as $ref) { try { $ancestor_list = DiffusionQuery::callConduitWithDiffusionRequest( $viewer, DiffusionRequest::newFromDictionary( array( 'repository' => $this->refRepository, 'user' => $viewer, )), 'diffusion.internal.ancestors', array( 'ref' => $ref, 'commits' => $ancestor_list, )); } catch (ConduitClientException $ex) { throw new PhabricatorSearchConstraintException( $ex->getMessage()); } if (!$ancestor_list) { break; } } $ancestor_list = array_fuse($ancestor_list); foreach ($commits as $key => $commit) { $identifier = $commit->getCommitIdentifier(); if (!isset($ancestor_list[$identifier])) { $this->didRejectResult($commit); unset($commits[$key]); } } if (!$commits) { return $commits; } } if ($this->needCommitData) { $data = id(new PhabricatorRepositoryCommitData())->loadAllWhere( 'commitID in (%Ld)', mpull($commits, 'getID')); $data = mpull($data, null, 'getCommitID'); foreach ($commits as $commit) { $commit_data = idx($data, $commit->getID()); if (!$commit_data) { $commit_data = new PhabricatorRepositoryCommitData(); } $commit->attachCommitData($commit_data); } } if ($this->needAuditRequests) { $requests = id(new PhabricatorRepositoryAuditRequest())->loadAllWhere( 'commitPHID IN (%Ls)', mpull($commits, 'getPHID')); $requests = mgroup($requests, 'getCommitPHID'); foreach ($commits as $commit) { $audit_requests = idx($requests, $commit->getPHID(), array()); $commit->attachAudits($audit_requests); foreach ($audit_requests as $audit_request) { $audit_request->attachCommit($commit); } } } if ($this->needIdentities) { $identity_phids = array_merge( mpull($commits, 'getAuthorIdentityPHID'), mpull($commits, 'getCommitterIdentityPHID')); $data = id(new PhabricatorRepositoryIdentityQuery()) ->withPHIDs($identity_phids) ->setViewer($this->getViewer()) ->execute(); $data = mpull($data, null, 'getPHID'); foreach ($commits as $commit) { $author_identity = idx($data, $commit->getAuthorIdentityPHID()); $committer_identity = idx($data, $commit->getCommitterIdentityPHID()); $commit->attachIdentities($author_identity, $committer_identity); } } if ($this->needDrafts) { PhabricatorDraftEngine::attachDrafts( $viewer, $commits); } if ($this->needAuditAuthority) { $authority_users = $this->needAuditAuthority; // NOTE: This isn't very efficient since we're running two queries per // user, but there's currently no way to figure out authority for // multiple users in one query. Today, we only ever request authority for // a single user and single commit, so this has no practical impact. // NOTE: We're querying with the viewership of query viewer, not the // actual users. If the viewer can't see a project or package, they // won't be able to see who has authority on it. This is safer than // showing them true authority, and should never matter today, but it // also doesn't seem like a significant disclosure and might be // reasonable to adjust later if it causes something weird or confusing // to happen. $authority_map = array(); foreach ($authority_users as $authority_user) { $authority_phid = $authority_user->getPHID(); if (!$authority_phid) { continue; } $result_phids = array(); // Users have authority over themselves. $result_phids[] = $authority_phid; // Users have authority over packages they own. $owned_packages = id(new PhabricatorOwnersPackageQuery()) ->setViewer($viewer) ->withAuthorityPHIDs(array($authority_phid)) ->execute(); foreach ($owned_packages as $package) { $result_phids[] = $package->getPHID(); } // Users have authority over projects they're members of. $projects = id(new PhabricatorProjectQuery()) ->setViewer($viewer) ->withMemberPHIDs(array($authority_phid)) ->execute(); foreach ($projects as $project) { $result_phids[] = $project->getPHID(); } $result_phids = array_fuse($result_phids); foreach ($commits as $commit) { $attach_phids = $result_phids; // NOTE: When modifying your own commits, you act only on behalf of // yourself, not your packages or projects. The idea here is that you // can't accept your own commits. In the future, this might change or // depend on configuration. $author_phid = $commit->getAuthorPHID(); if ($author_phid == $authority_phid) { $attach_phids = array($author_phid); $attach_phids = array_fuse($attach_phids); } $commit->attachAuditAuthority($authority_user, $attach_phids); } } } return $commits; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->repositoryPHIDs !== null) { $map_repositories = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getViewer()) ->withPHIDs($this->repositoryPHIDs) ->execute(); if (!$map_repositories) { throw new PhabricatorEmptyQueryException(); } $repository_ids = mpull($map_repositories, 'getID'); if ($this->repositoryIDs !== null) { $repository_ids = array_merge($repository_ids, $this->repositoryIDs); } $this->withRepositoryIDs($repository_ids); } if ($this->ancestorsOf !== null) { if (count($this->repositoryIDs) !== 1) { throw new PhabricatorSearchConstraintException( pht( 'To search for commits which are ancestors of particular refs, '. 'you must constrain the search to exactly one repository.')); } $repository_id = head($this->repositoryIDs); $history_limit = $this->getRawResultLimit() * 32; $viewer = $this->getViewer(); $repository = id(new PhabricatorRepositoryQuery()) ->setViewer($viewer) ->withIDs(array($repository_id)) ->executeOne(); if (!$repository) { throw new PhabricatorEmptyQueryException(); } if ($repository->isSVN()) { throw new PhabricatorSearchConstraintException( pht( 'Subversion does not support searching for ancestors of '. 'a particular ref. This operation is not meaningful in '. 'Subversion.')); } if ($repository->isHg()) { throw new PhabricatorSearchConstraintException( pht( 'Mercurial does not currently support searching for ancestors of '. 'a particular ref.')); } $can_constrain = true; $history_identifiers = array(); foreach ($this->ancestorsOf as $key => $ref) { try { $raw_history = DiffusionQuery::callConduitWithDiffusionRequest( $viewer, DiffusionRequest::newFromDictionary( array( 'repository' => $repository, 'user' => $viewer, )), 'diffusion.historyquery', array( 'commit' => $ref, 'limit' => $history_limit, )); } catch (ConduitClientException $ex) { throw new PhabricatorSearchConstraintException( $ex->getMessage()); } $ref_identifiers = array(); foreach ($raw_history['pathChanges'] as $change) { $ref_identifiers[] = $change['commitIdentifier']; } // If this ref had fewer total commits than the limit, we're safe to // apply the constraint as a large `IN (...)` query for a list of // commit identifiers. This is efficient. if ($history_limit) { if (count($ref_identifiers) >= $history_limit) { $can_constrain = false; break; } } $history_identifiers += array_fuse($ref_identifiers); } // If all refs had a small number of ancestors, we can just put the // constraint into the query here and we're done. Otherwise, we need // to filter each page after it comes out of the MySQL layer. if ($can_constrain) { $where[] = qsprintf( $conn, 'commit.commitIdentifier IN (%Ls)', $history_identifiers); } else { $this->mustFilterRefs = true; $this->refRepository = $repository; } } if ($this->ids !== null) { $where[] = qsprintf( $conn, 'commit.id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'commit.phid IN (%Ls)', $this->phids); } if ($this->repositoryIDs !== null) { $where[] = qsprintf( $conn, 'commit.repositoryID IN (%Ld)', $this->repositoryIDs); } if ($this->authorPHIDs !== null) { $author_phids = $this->authorPHIDs; if ($author_phids) { $author_phids = $this->selectPossibleAuthors($author_phids); if (!$author_phids) { throw new PhabricatorEmptyQueryException( pht('Author PHIDs contain no possible authors.')); } } $where[] = qsprintf( $conn, 'commit.authorPHID IN (%Ls)', $author_phids); } if ($this->epochMin !== null) { $where[] = qsprintf( $conn, 'commit.epoch >= %d', $this->epochMin); } if ($this->epochMax !== null) { $where[] = qsprintf( $conn, 'commit.epoch <= %d', $this->epochMax); } if ($this->importing !== null) { if ($this->importing) { $where[] = qsprintf( $conn, '(commit.importStatus & %d) != %d', PhabricatorRepositoryCommit::IMPORTED_ALL, PhabricatorRepositoryCommit::IMPORTED_ALL); } else { $where[] = qsprintf( $conn, '(commit.importStatus & %d) = %d', PhabricatorRepositoryCommit::IMPORTED_ALL, PhabricatorRepositoryCommit::IMPORTED_ALL); } } if ($this->identifiers !== null) { $min_unqualified = PhabricatorRepository::MINIMUM_UNQUALIFIED_HASH; $min_qualified = PhabricatorRepository::MINIMUM_QUALIFIED_HASH; $refs = array(); $bare = array(); foreach ($this->identifiers as $identifier) { $matches = null; preg_match('/^(?:[rR]([A-Z]+:?|[0-9]+:))?(.*)$/', $identifier, $matches); $repo = nonempty(rtrim($matches[1], ':'), null); $commit_identifier = nonempty($matches[2], null); if ($repo === null) { if ($this->defaultRepository) { $repo = $this->defaultRepository->getPHID(); } } if ($repo === null) { if (strlen($commit_identifier) < $min_unqualified) { continue; } $bare[] = $commit_identifier; } else { $refs[] = array( 'repository' => $repo, 'identifier' => $commit_identifier, ); } } $sql = array(); foreach ($bare as $identifier) { $sql[] = qsprintf( $conn, '(commit.commitIdentifier LIKE %> AND '. 'LENGTH(commit.commitIdentifier) = 40)', $identifier); } if ($refs) { $repositories = ipull($refs, 'repository'); $repos = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getViewer()) ->withIdentifiers($repositories); $repos->execute(); $repos = $repos->getIdentifierMap(); foreach ($refs as $key => $ref) { $repo = idx($repos, $ref['repository']); if (!$repo) { continue; } if ($repo->isSVN()) { if (!ctype_digit((string)$ref['identifier'])) { continue; } $sql[] = qsprintf( $conn, '(commit.repositoryID = %d AND commit.commitIdentifier = %s)', $repo->getID(), // NOTE: Because the 'commitIdentifier' column is a string, MySQL // ignores the index if we hand it an integer. Hand it a string. // See T3377. (int)$ref['identifier']); } else { if (strlen($ref['identifier']) < $min_qualified) { continue; } $identifier = $ref['identifier']; if (strlen($identifier) == 40) { // MySQL seems to do slightly better with this version if the // clause, so issue it if we have a full commit hash. $sql[] = qsprintf( $conn, '(commit.repositoryID = %d AND commit.commitIdentifier = %s)', $repo->getID(), $identifier); } else { $sql[] = qsprintf( $conn, '(commit.repositoryID = %d AND commit.commitIdentifier LIKE %>)', $repo->getID(), $identifier); } } } } if (!$sql) { // If we discarded all possible identifiers (e.g., they all referenced // bogus repositories or were all too short), make sure the query finds // nothing. throw new PhabricatorEmptyQueryException( pht('No commit identifiers.')); } $where[] = qsprintf($conn, '%LO', $sql); } if ($this->auditIDs !== null) { $where[] = qsprintf( $conn, 'auditor.id IN (%Ld)', $this->auditIDs); } if ($this->auditorPHIDs !== null) { $where[] = qsprintf( $conn, 'auditor.auditorPHID IN (%Ls)', $this->auditorPHIDs); } if ($this->statuses !== null) { $statuses = DiffusionCommitAuditStatus::newModernKeys( $this->statuses); $where[] = qsprintf( $conn, 'commit.auditStatus IN (%Ls)', $statuses); } if ($this->packagePHIDs !== null) { $where[] = qsprintf( $conn, 'package.dst IN (%Ls)', $this->packagePHIDs); } if ($this->unreachable !== null) { if ($this->unreachable) { $where[] = qsprintf( $conn, '(commit.importStatus & %d) = %d', PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE, PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE); } else { $where[] = qsprintf( $conn, '(commit.importStatus & %d) = 0', PhabricatorRepositoryCommit::IMPORTED_UNREACHABLE); } } if ($this->permanent !== null) { if ($this->permanent) { $where[] = qsprintf( $conn, '(commit.importStatus & %d) = %d', PhabricatorRepositoryCommit::IMPORTED_PERMANENT, PhabricatorRepositoryCommit::IMPORTED_PERMANENT); } else { $where[] = qsprintf( $conn, '(commit.importStatus & %d) = 0', PhabricatorRepositoryCommit::IMPORTED_PERMANENT); } } return $where; } protected function didFilterResults(array $filtered) { if ($this->identifierMap) { foreach ($this->identifierMap as $name => $commit) { if (isset($filtered[$commit->getPHID()])) { unset($this->identifierMap[$name]); } } } } private function shouldJoinAuditor() { return ($this->auditIDs || $this->auditorPHIDs); } private function shouldJoinOwners() { return (bool)$this->packagePHIDs; } protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) { $join = parent::buildJoinClauseParts($conn); $audit_request = new PhabricatorRepositoryAuditRequest(); if ($this->shouldJoinAuditor()) { $join[] = qsprintf( $conn, 'JOIN %T auditor ON commit.phid = auditor.commitPHID', $audit_request->getTableName()); } if ($this->shouldJoinOwners()) { $join[] = qsprintf( $conn, 'JOIN %T package ON commit.phid = package.src AND package.type = %s', PhabricatorEdgeConfig::TABLE_NAME_EDGE, DiffusionCommitHasPackageEdgeType::EDGECONST); } return $join; } protected function shouldGroupQueryResultRows() { if ($this->shouldJoinAuditor()) { return true; } if ($this->shouldJoinOwners()) { return true; } return parent::shouldGroupQueryResultRows(); } public function getQueryApplicationClass() { return 'PhabricatorDiffusionApplication'; } public function getOrderableColumns() { return parent::getOrderableColumns() + array( 'epoch' => array( 'table' => $this->getPrimaryTableAlias(), 'column' => 'epoch', 'type' => 'int', 'reverse' => false, ), ); } protected function newPagingMapFromPartialObject($object) { return array( 'id' => (int)$object->getID(), 'epoch' => (int)$object->getEpoch(), ); } public function getBuiltinOrders() { $parent = parent::getBuiltinOrders(); // Rename the default ID-based orders. $parent['importnew'] = array( 'name' => pht('Import Date (Newest First)'), ) + $parent['newest']; $parent['importold'] = array( 'name' => pht('Import Date (Oldest First)'), ) + $parent['oldest']; return array( 'newest' => array( 'vector' => array('epoch', 'id'), 'name' => pht('Commit Date (Newest First)'), ), 'oldest' => array( 'vector' => array('-epoch', '-id'), 'name' => pht('Commit Date (Oldest First)'), ), ) + $parent; } private function selectPossibleAuthors(array $phids) { // See PHI1057. Select PHIDs which might possibly be commit authors from // a larger list of PHIDs. This primarily filters out packages and projects // from "Responsible Users: ..." queries. Our goal in performing this // filtering is to improve the performance of the final query. foreach ($phids as $key => $phid) { if (phid_get_type($phid) !== PhabricatorPeopleUserPHIDType::TYPECONST) { unset($phids[$key]); } } return $phids; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/diffusion/query/DiffusionRenameHistoryQuery.php
src/applications/diffusion/query/DiffusionRenameHistoryQuery.php
<?php final class DiffusionRenameHistoryQuery extends Phobject { private $oldCommit; private $wasCreated; private $request; private $viewer; public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } public function getWasCreated() { return $this->wasCreated; } public function setRequest(DiffusionRequest $request) { $this->request = $request; return $this; } public function setOldCommit($old_commit) { $this->oldCommit = $old_commit; return $this; } public function getOldCommit() { return $this->oldCommit; } public function loadOldFilename() { $drequest = $this->request; $repository_id = $drequest->getRepository()->getID(); $conn_r = id(new PhabricatorRepository())->establishConnection('r'); $commit_id = $this->loadCommitId($this->oldCommit); $old_commit_sequence = $this->loadCommitSequence($commit_id); $path = '/'.$drequest->getPath(); $commit_id = $this->loadCommitId($drequest->getCommit()); do { $commit_sequence = $this->loadCommitSequence($commit_id); $change = queryfx_one( $conn_r, 'SELECT pc.changeType, pc.targetCommitID, tp.path FROM %T p JOIN %T pc ON p.id = pc.pathID LEFT JOIN %T tp ON pc.targetPathID = tp.id WHERE p.pathHash = %s AND pc.repositoryID = %d AND pc.changeType IN (%d, %d) AND pc.commitSequence BETWEEN %d AND %d ORDER BY pc.commitSequence DESC LIMIT 1', PhabricatorRepository::TABLE_PATH, PhabricatorRepository::TABLE_PATHCHANGE, PhabricatorRepository::TABLE_PATH, md5($path), $repository_id, ArcanistDiffChangeType::TYPE_MOVE_HERE, ArcanistDiffChangeType::TYPE_ADD, $old_commit_sequence, $commit_sequence); if ($change) { if ($change['changeType'] == ArcanistDiffChangeType::TYPE_ADD) { $this->wasCreated = true; return $path; } $commit_id = $change['targetCommitID']; $path = $change['path']; } } while ($change && $path); return $path; } private function loadCommitId($commit_identifier) { $commit = id(new DiffusionCommitQuery()) ->setViewer($this->viewer) ->withIdentifiers(array($commit_identifier)) ->withRepository($this->request->getRepository()) ->executeOne(); return $commit->getID(); } private function loadCommitSequence($commit_id) { $conn_r = id(new PhabricatorRepository())->establishConnection('r'); $path_change = queryfx_one( $conn_r, 'SELECT commitSequence FROM %T WHERE repositoryID = %d AND commitID = %d LIMIT 1', PhabricatorRepository::TABLE_PATHCHANGE, $this->request->getRepository()->getID(), $commit_id); return reset($path_change); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false