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/harbormaster/capability/HarbormasterBuildPlanDefaultViewCapability.php
src/applications/harbormaster/capability/HarbormasterBuildPlanDefaultViewCapability.php
<?php final class HarbormasterBuildPlanDefaultViewCapability extends PhabricatorPolicyCapability { // TODO: This is misspelled! See T13005. const CAPABILITY = 'harbomaster.plan.default.view'; public function getCapabilityName() { return pht('Default Build Plan View Policy'); } public function shouldAllowPublicPolicySetting() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/capability/HarbormasterBuildPlanDefaultEditCapability.php
src/applications/harbormaster/capability/HarbormasterBuildPlanDefaultEditCapability.php
<?php final class HarbormasterBuildPlanDefaultEditCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'harbormaster.plan.default.edit'; public function getCapabilityName() { return pht('Default Build Plan Edit Policy'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/capability/HarbormasterCreatePlansCapability.php
src/applications/harbormaster/capability/HarbormasterCreatePlansCapability.php
<?php final class HarbormasterCreatePlansCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'harbormaster.plans'; public function getCapabilityName() { return pht('Can Create Build Plans'); } public function describeCapabilityRejection() { return pht( 'You do not have permission to create Harbormaster build plans.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/future/HarbormasterExecFuture.php
src/applications/harbormaster/future/HarbormasterExecFuture.php
<?php final class HarbormasterExecFuture extends Future { private $future; private $stdout; private $stderr; public function setFuture(ExecFuture $future) { $this->future = $future; return $this; } public function getFuture() { return $this->future; } public function setLogs( HarbormasterBuildLog $stdout, HarbormasterBuildLog $stderr) { $this->stdout = $stdout; $this->stderr = $stderr; return $this; } public function isReady() { if ($this->hasResult()) { return true; } $future = $this->getFuture(); $is_ready = $future->isReady(); list($stdout, $stderr) = $future->read(); $future->discardBuffers(); if ($this->stdout) { $this->stdout->append($stdout); } if ($this->stderr) { $this->stderr->append($stderr); } if ($future->hasResult()) { $this->setResult($future->getResult()); } // TODO: This should probably be implemented as a FutureProxy; it will // not currently propagate exceptions or sockets properly. return $is_ready; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/remarkup/HarbormasterRemarkupRule.php
src/applications/harbormaster/remarkup/HarbormasterRemarkupRule.php
<?php final class HarbormasterRemarkupRule extends PhabricatorObjectRemarkupRule { protected function getObjectNamePrefix() { return 'B'; } protected function loadObjects(array $ids) { $viewer = $this->getEngine()->getConfig('viewer'); return id(new HarbormasterBuildableQuery()) ->setViewer($viewer) ->withIDs($ids) ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/constants/HarbormasterBuildableStatus.php
src/applications/harbormaster/constants/HarbormasterBuildableStatus.php
<?php final class HarbormasterBuildableStatus extends Phobject { const STATUS_PREPARING = 'preparing'; const STATUS_BUILDING = 'building'; const STATUS_PASSED = 'passed'; const STATUS_FAILED = 'failed'; private $key; private $properties; public function __construct($key, array $properties) { $this->key = $key; $this->properties = $properties; } public static function newBuildableStatusObject($status) { $spec = self::getSpecification($status); return new self($status, $spec); } private function getProperty($key) { if (!array_key_exists($key, $this->properties)) { throw new Exception( pht( 'Attempting to access unknown buildable status property ("%s").', $key)); } return $this->properties[$key]; } public function getIcon() { return $this->getProperty('icon'); } public function getDisplayName() { return $this->getProperty('name'); } public function getActionName() { return $this->getProperty('name.action'); } public function getColor() { return $this->getProperty('color'); } public function isPreparing() { return ($this->key === self::STATUS_PREPARING); } public function isBuilding() { return ($this->key === self::STATUS_BUILDING); } public function isFailed() { return ($this->key === self::STATUS_FAILED); } public static function getOptionMap() { return ipull(self::getSpecifications(), 'name'); } private static function getSpecifications() { return array( self::STATUS_PREPARING => array( 'name' => pht('Preparing'), 'color' => 'blue', 'icon' => 'fa-hourglass-o', 'name.action' => pht('Build Preparing'), ), self::STATUS_BUILDING => array( 'name' => pht('Building'), 'color' => 'blue', 'icon' => 'fa-chevron-circle-right', 'name.action' => pht('Build Started'), ), self::STATUS_PASSED => array( 'name' => pht('Passed'), 'color' => 'green', 'icon' => 'fa-check-circle', 'name.action' => pht('Build Passed'), ), self::STATUS_FAILED => array( 'name' => pht('Failed'), 'color' => 'red', 'icon' => 'fa-times-circle', 'name.action' => pht('Build Failed'), ), ); } private static function getSpecification($status) { $map = self::getSpecifications(); if (isset($map[$status])) { return $map[$status]; } return array( 'name' => pht('Unknown ("%s")', $status), 'icon' => 'fa-question-circle', 'color' => 'bluegrey', 'name.action' => pht('Build Status'), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/constants/HarbormasterUnitStatus.php
src/applications/harbormaster/constants/HarbormasterUnitStatus.php
<?php final class HarbormasterUnitStatus extends Phobject { public static function getUnitStatusIcon($status) { $map = self::getUnitStatusDictionary($status); $default = 'fa-question-circle'; return idx($map, 'icon', $default); } public static function getUnitStatusColor($status) { $map = self::getUnitStatusDictionary($status); $default = 'violet'; return idx($map, 'color', $default); } public static function getUnitStatusLabel($status) { $map = self::getUnitStatusDictionary($status); $default = pht('Unknown Status ("%s")', $status); return idx($map, 'label', $default); } public static function getUnitStatusSort($status) { $map = self::getUnitStatusDictionary($status); $default = 'N'; return idx($map, 'sort', $default); } private static function getUnitStatusDictionary($status) { $map = self::getUnitStatusMap(); $default = array(); return idx($map, $status, $default); } public static function getUnitStatusCountLabel($status, $count) { $count = new PhutilNumber($count); switch ($status) { case ArcanistUnitTestResult::RESULT_FAIL: return pht('%s Failed Test(s)', $count); case ArcanistUnitTestResult::RESULT_BROKEN: return pht('%s Broken Test(s)', $count); case ArcanistUnitTestResult::RESULT_UNSOUND: return pht('%s Unsound Test(s)', $count); case ArcanistUnitTestResult::RESULT_PASS: return pht('%s Passed Test(s)', $count); case ArcanistUnitTestResult::RESULT_SKIP: return pht('%s Skipped Test(s)', $count); } return pht('%s Other Test(s)', $count); } private static function getUnitStatusMap() { return array( ArcanistUnitTestResult::RESULT_FAIL => array( 'label' => pht('Failed'), 'icon' => 'fa-times', 'color' => 'red', 'sort' => 'A', ), ArcanistUnitTestResult::RESULT_BROKEN => array( 'label' => pht('Broken'), 'icon' => 'fa-bomb', 'color' => 'indigo', 'sort' => 'B', ), ArcanistUnitTestResult::RESULT_UNSOUND => array( 'label' => pht('Unsound'), 'icon' => 'fa-exclamation-triangle', 'color' => 'yellow', 'sort' => 'C', ), ArcanistUnitTestResult::RESULT_PASS => array( 'label' => pht('Passed'), 'icon' => 'fa-check', 'color' => 'green', 'sort' => 'D', ), ArcanistUnitTestResult::RESULT_SKIP => array( 'label' => pht('Skipped'), 'icon' => 'fa-fast-forward', 'color' => 'blue', 'sort' => 'E', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/harbormaster/constants/HarbormasterBuildStatus.php
src/applications/harbormaster/constants/HarbormasterBuildStatus.php
<?php final class HarbormasterBuildStatus extends Phobject { const STATUS_INACTIVE = 'inactive'; const STATUS_PENDING = 'pending'; const STATUS_BUILDING = 'building'; const STATUS_PASSED = 'passed'; const STATUS_FAILED = 'failed'; const STATUS_ABORTED = 'aborted'; const STATUS_ERROR = 'error'; const STATUS_PAUSED = 'paused'; const STATUS_DEADLOCKED = 'deadlocked'; const PENDING_PAUSING = 'x-pausing'; const PENDING_RESUMING = 'x-resuming'; const PENDING_RESTARTING = 'x-restarting'; const PENDING_ABORTING = 'x-aborting'; private $key; private $properties; public function __construct($key, array $properties) { $this->key = $key; $this->properties = $properties; } public static function newBuildStatusObject($status) { $spec = self::getBuildStatusSpec($status); return new self($status, $spec); } private function getProperty($key) { if (!array_key_exists($key, $this->properties)) { throw new Exception( pht( 'Attempting to access unknown build status property ("%s").', $key)); } return $this->properties[$key]; } public function isBuilding() { return $this->getProperty('isBuilding'); } public function isPaused() { return ($this->key === self::STATUS_PAUSED); } public function isComplete() { return $this->getProperty('isComplete'); } public function isPassed() { return ($this->key === self::STATUS_PASSED); } public function isFailed() { return ($this->key === self::STATUS_FAILED); } public function isAborting() { return ($this->key === self::PENDING_ABORTING); } public function isRestarting() { return ($this->key === self::PENDING_RESTARTING); } public function isResuming() { return ($this->key === self::PENDING_RESUMING); } public function isPausing() { return ($this->key === self::PENDING_PAUSING); } public function isPending() { return ($this->key === self::STATUS_PENDING); } public function getIconIcon() { return $this->getProperty('icon'); } public function getIconColor() { return $this->getProperty('color'); } public function getName() { return $this->getProperty('name'); } /** * Get a human readable name for a build status constant. * * @param const Build status constant. * @return string Human-readable name. */ public static function getBuildStatusName($status) { $spec = self::getBuildStatusSpec($status); return $spec['name']; } public static function getBuildStatusMap() { $specs = self::getBuildStatusSpecMap(); return ipull($specs, 'name'); } public static function getBuildStatusIcon($status) { $spec = self::getBuildStatusSpec($status); return $spec['icon']; } public static function getBuildStatusColor($status) { $spec = self::getBuildStatusSpec($status); return $spec['color']; } public static function getBuildStatusANSIColor($status) { $spec = self::getBuildStatusSpec($status); return $spec['color.ansi']; } public static function getWaitingStatusConstants() { return array( self::STATUS_INACTIVE, self::STATUS_PENDING, ); } public static function getActiveStatusConstants() { return array( self::STATUS_BUILDING, self::STATUS_PAUSED, ); } public static function getIncompleteStatusConstants() { $map = self::getBuildStatusSpecMap(); $constants = array(); foreach ($map as $constant => $spec) { if (!$spec['isComplete']) { $constants[] = $constant; } } return $constants; } public static function getCompletedStatusConstants() { return array( self::STATUS_PASSED, self::STATUS_FAILED, self::STATUS_ABORTED, self::STATUS_ERROR, self::STATUS_DEADLOCKED, ); } private static function getBuildStatusSpecMap() { return array( self::STATUS_INACTIVE => array( 'name' => pht('Inactive'), 'icon' => 'fa-circle-o', 'color' => 'dark', 'color.ansi' => 'yellow', 'isBuilding' => false, 'isComplete' => false, ), self::STATUS_PENDING => array( 'name' => pht('Pending'), 'icon' => 'fa-circle-o', 'color' => 'blue', 'color.ansi' => 'yellow', 'isBuilding' => true, 'isComplete' => false, ), self::STATUS_BUILDING => array( 'name' => pht('Building'), 'icon' => 'fa-chevron-circle-right', 'color' => 'blue', 'color.ansi' => 'yellow', 'isBuilding' => true, 'isComplete' => false, ), self::STATUS_PASSED => array( 'name' => pht('Passed'), 'icon' => 'fa-check-circle', 'color' => 'green', 'color.ansi' => 'green', 'isBuilding' => false, 'isComplete' => true, ), self::STATUS_FAILED => array( 'name' => pht('Failed'), 'icon' => 'fa-times-circle', 'color' => 'red', 'color.ansi' => 'red', 'isBuilding' => false, 'isComplete' => true, ), self::STATUS_ABORTED => array( 'name' => pht('Aborted'), 'icon' => 'fa-minus-circle', 'color' => 'red', 'color.ansi' => 'red', 'isBuilding' => false, 'isComplete' => true, ), self::STATUS_ERROR => array( 'name' => pht('Unexpected Error'), 'icon' => 'fa-minus-circle', 'color' => 'red', 'color.ansi' => 'red', 'isBuilding' => false, 'isComplete' => true, ), self::STATUS_PAUSED => array( 'name' => pht('Paused'), 'icon' => 'fa-pause', 'color' => 'yellow', 'color.ansi' => 'yellow', 'isBuilding' => false, 'isComplete' => false, ), self::STATUS_DEADLOCKED => array( 'name' => pht('Deadlocked'), 'icon' => 'fa-exclamation-circle', 'color' => 'red', 'color.ansi' => 'red', 'isBuilding' => false, 'isComplete' => true, ), self::PENDING_PAUSING => array( 'name' => pht('Pausing'), 'icon' => 'fa-exclamation-triangle', 'color' => 'red', 'color.ansi' => 'red', 'isBuilding' => false, 'isComplete' => false, ), self::PENDING_RESUMING => array( 'name' => pht('Resuming'), 'icon' => 'fa-exclamation-triangle', 'color' => 'red', 'color.ansi' => 'red', 'isBuilding' => false, 'isComplete' => false, ), self::PENDING_RESTARTING => array( 'name' => pht('Restarting'), 'icon' => 'fa-exclamation-triangle', 'color' => 'red', 'color.ansi' => 'red', 'isBuilding' => false, 'isComplete' => false, ), self::PENDING_ABORTING => array( 'name' => pht('Aborting'), 'icon' => 'fa-exclamation-triangle', 'color' => 'red', 'color.ansi' => 'red', 'isBuilding' => false, 'isComplete' => false, ), ); } private static function getBuildStatusSpec($status) { $map = self::getBuildStatusSpecMap(); if (isset($map[$status])) { return $map[$status]; } return array( 'name' => pht('Unknown ("%s")', $status), 'icon' => 'fa-question-circle', 'color' => 'bluegrey', 'color.ansi' => 'magenta', 'isBuilding' => false, 'isComplete' => false, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/PhabricatorApplication.php
src/applications/base/PhabricatorApplication.php
<?php /** * @task info Application Information * @task ui UI Integration * @task uri URI Routing * @task mail Email integration * @task fact Fact Integration * @task meta Application Management */ abstract class PhabricatorApplication extends PhabricatorLiskDAO implements PhabricatorPolicyInterface, PhabricatorApplicationTransactionInterface { const GROUP_CORE = 'core'; const GROUP_UTILITIES = 'util'; const GROUP_ADMIN = 'admin'; const GROUP_DEVELOPER = 'developer'; final public static function getApplicationGroups() { return array( self::GROUP_CORE => pht('Core Applications'), self::GROUP_UTILITIES => pht('Utilities'), self::GROUP_ADMIN => pht('Administration'), self::GROUP_DEVELOPER => pht('Developer Tools'), ); } final public function getApplicationName() { return 'application'; } final public function getTableName() { return 'application_application'; } final protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, ) + parent::getConfiguration(); } final public function generatePHID() { return $this->getPHID(); } final public function save() { // When "save()" is called on applications, we just return without // actually writing anything to the database. return $this; } /* -( Application Information )-------------------------------------------- */ abstract public function getName(); public function getShortDescription() { return pht('%s Application', $this->getName()); } final public function isInstalled() { if (!$this->canUninstall()) { return true; } $prototypes = PhabricatorEnv::getEnvConfig('phabricator.show-prototypes'); if (!$prototypes && $this->isPrototype()) { return false; } $uninstalled = PhabricatorEnv::getEnvConfig( 'phabricator.uninstalled-applications'); return empty($uninstalled[get_class($this)]); } public function isPrototype() { return false; } /** * Return `true` if this application should never appear in application lists * in the UI. Primarily intended for unit test applications or other * pseudo-applications. * * Few applications should be unlisted. For most applications, use * @{method:isLaunchable} to hide them from main launch views instead. * * @return bool True to remove application from UI lists. */ public function isUnlisted() { return false; } /** * Return `true` if this application is a normal application with a base * URI and a web interface. * * Launchable applications can be pinned to the home page, and show up in the * "Launcher" view of the Applications application. Making an application * unlaunchable prevents pinning and hides it from this view. * * Usually, an application should be marked unlaunchable if: * * - it is available on every page anyway (like search); or * - it does not have a web interface (like subscriptions); or * - it is still pre-release and being intentionally buried. * * To hide applications more completely, use @{method:isUnlisted}. * * @return bool True if the application is launchable. */ public function isLaunchable() { return true; } /** * Return `true` if this application should be pinned by default. * * Users who have not yet set preferences see a default list of applications. * * @param PhabricatorUser User viewing the pinned application list. * @return bool True if this application should be pinned by default. */ public function isPinnedByDefault(PhabricatorUser $viewer) { return false; } /** * Returns true if an application is first-party and false otherwise. * * @return bool True if this application is first-party. */ final public function isFirstParty() { $where = id(new ReflectionClass($this))->getFileName(); $root = phutil_get_library_root('phabricator'); if (!Filesystem::isDescendant($where, $root)) { return false; } if (Filesystem::isDescendant($where, $root.'/extensions')) { return false; } return true; } public function canUninstall() { return true; } final public function getPHID() { return 'PHID-APPS-'.get_class($this); } public function getTypeaheadURI() { return $this->isLaunchable() ? $this->getBaseURI() : null; } public function getBaseURI() { return null; } final public function getApplicationURI($path = '') { return $this->getBaseURI().ltrim($path, '/'); } public function getIcon() { return 'fa-puzzle-piece'; } public function getApplicationOrder() { return PHP_INT_MAX; } public function getApplicationGroup() { return self::GROUP_CORE; } public function getTitleGlyph() { return null; } final public function getHelpMenuItems(PhabricatorUser $viewer) { $items = array(); $articles = $this->getHelpDocumentationArticles($viewer); if ($articles) { foreach ($articles as $article) { $item = id(new PhabricatorActionView()) ->setName($article['name']) ->setHref($article['href']) ->addSigil('help-item') ->setOpenInNewWindow(true); $items[] = $item; } } $command_specs = $this->getMailCommandObjects(); if ($command_specs) { foreach ($command_specs as $key => $spec) { $object = $spec['object']; $class = get_class($this); $href = '/applications/mailcommands/'.$class.'/'.$key.'/'; $item = id(new PhabricatorActionView()) ->setName($spec['name']) ->setHref($href) ->addSigil('help-item') ->setOpenInNewWindow(true); $items[] = $item; } } if ($items) { $divider = id(new PhabricatorActionView()) ->addSigil('help-item') ->setType(PhabricatorActionView::TYPE_DIVIDER); array_unshift($items, $divider); } return array_values($items); } public function getHelpDocumentationArticles(PhabricatorUser $viewer) { return array(); } public function getOverview() { return null; } public function getEventListeners() { return array(); } public function getRemarkupRules() { return array(); } public function getQuicksandURIPatternBlacklist() { return array(); } public function getMailCommandObjects() { return array(); } /* -( URI Routing )-------------------------------------------------------- */ public function getRoutes() { return array(); } public function getResourceRoutes() { return array(); } /* -( Email Integration )-------------------------------------------------- */ public function supportsEmailIntegration() { return false; } final protected function getInboundEmailSupportLink() { return PhabricatorEnv::getDoclink('Configuring Inbound Email'); } public function getAppEmailBlurb() { throw new PhutilMethodNotImplementedException(); } /* -( Fact Integration )--------------------------------------------------- */ public function getFactObjectsForAnalysis() { return array(); } /* -( UI Integration )----------------------------------------------------- */ /** * You can provide an optional piece of flavor text for the application. This * is currently rendered in application launch views if the application has no * status elements. * * @return string|null Flavor text. * @task ui */ public function getFlavorText() { return null; } /** * Build items for the main menu. * * @param PhabricatorUser The viewing user. * @param AphrontController The current controller. May be null for special * pages like 404, exception handlers, etc. * @return list<PHUIListItemView> List of menu items. * @task ui */ public function buildMainMenuItems( PhabricatorUser $user, PhabricatorController $controller = null) { return array(); } /* -( Application Management )--------------------------------------------- */ final public static function getByClass($class_name) { $selected = null; $applications = self::getAllApplications(); foreach ($applications as $application) { if (get_class($application) == $class_name) { $selected = $application; break; } } if (!$selected) { throw new Exception(pht("No application '%s'!", $class_name)); } return $selected; } final public static function getAllApplications() { static $applications; if ($applications === null) { $apps = id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setSortMethod('getApplicationOrder') ->execute(); // Reorder the applications into "application order". Notably, this // ensures their event handlers register in application order. $apps = mgroup($apps, 'getApplicationGroup'); $group_order = array_keys(self::getApplicationGroups()); $apps = array_select_keys($apps, $group_order) + $apps; $apps = array_mergev($apps); $applications = $apps; } return $applications; } final public static function getAllInstalledApplications() { $all_applications = self::getAllApplications(); $apps = array(); foreach ($all_applications as $app) { if (!$app->isInstalled()) { continue; } $apps[] = $app; } return $apps; } /** * Determine if an application is installed, by application class name. * * To check if an application is installed //and// available to a particular * viewer, user @{method:isClassInstalledForViewer}. * * @param string Application class name. * @return bool True if the class is installed. * @task meta */ final public static function isClassInstalled($class) { return self::getByClass($class)->isInstalled(); } /** * Determine if an application is installed and available to a viewer, by * application class name. * * To check if an application is installed at all, use * @{method:isClassInstalled}. * * @param string Application class name. * @param PhabricatorUser Viewing user. * @return bool True if the class is installed for the viewer. * @task meta */ final public static function isClassInstalledForViewer( $class, PhabricatorUser $viewer) { if ($viewer->isOmnipotent()) { return true; } $cache = PhabricatorCaches::getRequestCache(); $viewer_fragment = $viewer->getCacheFragment(); $key = 'app.'.$class.'.installed.'.$viewer_fragment; $result = $cache->getKey($key); if ($result === null) { if (!self::isClassInstalled($class)) { $result = false; } else { $application = self::getByClass($class); if (!$application->canUninstall()) { // If the application can not be uninstalled, always allow viewers // to see it. In particular, this allows logged-out viewers to see // Settings and load global default settings even if the install // does not allow public viewers. $result = true; } else { $result = PhabricatorPolicyFilter::hasCapability( $viewer, self::getByClass($class), PhabricatorPolicyCapability::CAN_VIEW); } } $cache->setKey($key, $result); } return $result; } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array_merge( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ), array_keys($this->getCustomCapabilities())); } public function getPolicy($capability) { $default = $this->getCustomPolicySetting($capability); if ($default) { return $default; } switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return PhabricatorPolicies::getMostOpenPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return PhabricatorPolicies::POLICY_ADMIN; default: $spec = $this->getCustomCapabilitySpecification($capability); return idx($spec, 'default', PhabricatorPolicies::POLICY_USER); } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return false; } /* -( Policies )----------------------------------------------------------- */ protected function getCustomCapabilities() { return array(); } private function getCustomPolicySetting($capability) { if (!$this->isCapabilityEditable($capability)) { return null; } $policy_locked = PhabricatorEnv::getEnvConfig('policy.locked'); if (isset($policy_locked[$capability])) { return $policy_locked[$capability]; } $config = PhabricatorEnv::getEnvConfig('phabricator.application-settings'); $app = idx($config, $this->getPHID()); if (!$app) { return null; } $policy = idx($app, 'policy'); if (!$policy) { return null; } return idx($policy, $capability); } private function getCustomCapabilitySpecification($capability) { $custom = $this->getCustomCapabilities(); if (!isset($custom[$capability])) { throw new Exception(pht("Unknown capability '%s'!", $capability)); } return $custom[$capability]; } final public function getCapabilityLabel($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return pht('Can Use Application'); case PhabricatorPolicyCapability::CAN_EDIT: return pht('Can Configure Application'); } $capobj = PhabricatorPolicyCapability::getCapabilityByKey($capability); if ($capobj) { return $capobj->getCapabilityName(); } return null; } final public function isCapabilityEditable($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->canUninstall(); case PhabricatorPolicyCapability::CAN_EDIT: return true; default: $spec = $this->getCustomCapabilitySpecification($capability); return idx($spec, 'edit', true); } } final public function getCapabilityCaption($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: if (!$this->canUninstall()) { return pht( 'This application is required, so all '. 'users must have access to it.'); } else { return null; } case PhabricatorPolicyCapability::CAN_EDIT: return null; default: $spec = $this->getCustomCapabilitySpecification($capability); return idx($spec, 'caption'); } } final public function getCapabilityTemplatePHIDType($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: case PhabricatorPolicyCapability::CAN_EDIT: return null; } $spec = $this->getCustomCapabilitySpecification($capability); return idx($spec, 'template'); } final public function getDefaultObjectTypePolicyMap() { $map = array(); foreach ($this->getCustomCapabilities() as $capability => $spec) { if (empty($spec['template'])) { continue; } if (empty($spec['capability'])) { continue; } $default = $this->getPolicy($capability); $map[$spec['template']][$spec['capability']] = $default; } return $map; } public function getApplicationSearchDocumentTypes() { return array(); } protected function getEditRoutePattern($base = null) { return $base.'(?:'. '(?P<id>[0-9]\d*)/)?'. '(?:'. '(?:'. '(?P<editAction>parameters|nodefault|nocreate|nomanage|comment)/'. '|'. '(?:form/(?P<formKey>[^/]+)/)?(?:page/(?P<pageKey>[^/]+)/)?'. ')'. ')?'; } protected function getBulkRoutePattern($base = null) { return $base.'(?:query/(?P<queryKey>[^/]+)/)?'; } protected function getQueryRoutePattern($base = null) { return $base.'(?:query/(?P<queryKey>[^/]+)/(?:(?P<queryAction>[^/]+)/)?)?'; } protected function getProfileMenuRouting($controller) { $edit_route = $this->getEditRoutePattern(); $mode_route = '(?P<itemEditMode>global|custom)/'; return array( '(?P<itemAction>view)/(?P<itemID>[^/]+)/' => $controller, '(?P<itemAction>hide)/(?P<itemID>[^/]+)/' => $controller, '(?P<itemAction>default)/(?P<itemID>[^/]+)/' => $controller, '(?P<itemAction>configure)/' => $controller, '(?P<itemAction>configure)/'.$mode_route => $controller, '(?P<itemAction>reorder)/'.$mode_route => $controller, '(?P<itemAction>edit)/'.$edit_route => $controller, '(?P<itemAction>new)/'.$mode_route.'(?<itemKey>[^/]+)/'.$edit_route => $controller, '(?P<itemAction>builtin)/(?<itemID>[^/]+)/'.$edit_route => $controller, ); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhabricatorApplicationEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorApplicationApplicationTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/controller/PhabricatorRedirectController.php
src/applications/base/controller/PhabricatorRedirectController.php
<?php final class PhabricatorRedirectController extends PhabricatorController { public function shouldRequireLogin() { return false; } public function shouldRequireEnabledUser() { return false; } public function handleRequest(AphrontRequest $request) { $uri = $request->getURIData('uri'); $external = $request->getURIData('external', false); return id(new AphrontRedirectResponse()) ->setURI($uri) ->setIsExternal($external); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/controller/PhabricatorController.php
src/applications/base/controller/PhabricatorController.php
<?php abstract class PhabricatorController extends AphrontController { private $handles; public function shouldRequireLogin() { return true; } public function shouldRequireAdmin() { return false; } public function shouldRequireEnabledUser() { return true; } public function shouldAllowPublic() { return false; } public function shouldAllowPartialSessions() { return false; } public function shouldRequireEmailVerification() { return PhabricatorUserEmail::isEmailVerificationRequired(); } public function shouldAllowRestrictedParameter($parameter_name) { return false; } public function shouldRequireMultiFactorEnrollment() { if (!$this->shouldRequireLogin()) { return false; } if (!$this->shouldRequireEnabledUser()) { return false; } if ($this->shouldAllowPartialSessions()) { return false; } $user = $this->getRequest()->getUser(); if (!$user->getIsStandardUser()) { return false; } return PhabricatorEnv::getEnvConfig('security.require-multi-factor-auth'); } public function shouldAllowLegallyNonCompliantUsers() { return false; } public function isGlobalDragAndDropUploadEnabled() { return false; } public function willBeginExecution() { $request = $this->getRequest(); if ($request->getUser()) { // NOTE: Unit tests can set a user explicitly. Normal requests are not // permitted to do this. PhabricatorTestCase::assertExecutingUnitTests(); $user = $request->getUser(); } else { $user = new PhabricatorUser(); $session_engine = new PhabricatorAuthSessionEngine(); $phsid = $request->getCookie(PhabricatorCookies::COOKIE_SESSION); if ($phsid !== null && strlen($phsid)) { $session_user = $session_engine->loadUserForSession( PhabricatorAuthSession::TYPE_WEB, $phsid); if ($session_user) { $user = $session_user; } } else { // If the client doesn't have a session token, generate an anonymous // session. This is used to provide CSRF protection to logged-out users. $phsid = $session_engine->establishSession( PhabricatorAuthSession::TYPE_WEB, null, $partial = false); // This may be a resource request, in which case we just don't set // the cookie. if ($request->canSetCookies()) { $request->setCookie(PhabricatorCookies::COOKIE_SESSION, $phsid); } } if (!$user->isLoggedIn()) { $csrf = PhabricatorHash::digestWithNamedKey($phsid, 'csrf.alternate'); $user->attachAlternateCSRFString($csrf); } $request->setUser($user); } id(new PhabricatorAuthSessionEngine()) ->willServeRequestForUser($user); if (PhabricatorEnv::getEnvConfig('darkconsole.enabled')) { $dark_console = PhabricatorDarkConsoleSetting::SETTINGKEY; if ($user->getUserSetting($dark_console) || PhabricatorEnv::getEnvConfig('darkconsole.always-on')) { $console = new DarkConsoleCore(); $request->getApplicationConfiguration()->setConsole($console); } } // NOTE: We want to set up the user first so we can render a real page // here, but fire this before any real logic. $restricted = array( 'code', ); foreach ($restricted as $parameter) { if ($request->getExists($parameter)) { if (!$this->shouldAllowRestrictedParameter($parameter)) { throw new Exception( pht( 'Request includes restricted parameter "%s", but this '. 'controller ("%s") does not whitelist it. Refusing to '. 'serve this request because it might be part of a redirection '. 'attack.', $parameter, get_class($this))); } } } if ($this->shouldRequireEnabledUser()) { if ($user->getIsDisabled()) { $controller = new PhabricatorDisabledUserController(); return $this->delegateToController($controller); } } $auth_class = 'PhabricatorAuthApplication'; $auth_application = PhabricatorApplication::getByClass($auth_class); // Require partial sessions to finish login before doing anything. if (!$this->shouldAllowPartialSessions()) { if ($user->hasSession() && $user->getSession()->getIsPartial()) { $login_controller = new PhabricatorAuthFinishController(); $this->setCurrentApplication($auth_application); return $this->delegateToController($login_controller); } } // Require users sign Legalpad documents before we check if they have // MFA. If we don't do this, they can get stuck in a state where they // can't add MFA until they sign, and can't sign until they add MFA. // See T13024 and PHI223. $result = $this->requireLegalpadSignatures(); if ($result !== null) { return $result; } // Check if the user needs to configure MFA. $need_mfa = $this->shouldRequireMultiFactorEnrollment(); $have_mfa = $user->getIsEnrolledInMultiFactor(); if ($need_mfa && !$have_mfa) { // Check if the cache is just out of date. Otherwise, roadblock the user // and require MFA enrollment. $user->updateMultiFactorEnrollment(); if (!$user->getIsEnrolledInMultiFactor()) { $mfa_controller = new PhabricatorAuthNeedsMultiFactorController(); $this->setCurrentApplication($auth_application); return $this->delegateToController($mfa_controller); } } if ($this->shouldRequireLogin()) { // This actually means we need either: // - a valid user, or a public controller; and // - permission to see the application; and // - permission to see at least one Space if spaces are configured. $allow_public = $this->shouldAllowPublic() && PhabricatorEnv::getEnvConfig('policy.allow-public'); // If this controller isn't public, and the user isn't logged in, require // login. if (!$allow_public && !$user->isLoggedIn()) { $login_controller = new PhabricatorAuthStartController(); $this->setCurrentApplication($auth_application); return $this->delegateToController($login_controller); } if ($user->isLoggedIn()) { if ($this->shouldRequireEmailVerification()) { if (!$user->getIsEmailVerified()) { $controller = new PhabricatorMustVerifyEmailController(); $this->setCurrentApplication($auth_application); return $this->delegateToController($controller); } } } // If Spaces are configured, require that the user have access to at // least one. If we don't do this, they'll get confusing error messages // later on. $spaces = PhabricatorSpacesNamespaceQuery::getSpacesExist(); if ($spaces) { $viewer_spaces = PhabricatorSpacesNamespaceQuery::getViewerSpaces( $user); if (!$viewer_spaces) { $controller = new PhabricatorSpacesNoAccessController(); return $this->delegateToController($controller); } } // If the user doesn't have access to the application, don't let them use // any of its controllers. We query the application in order to generate // a policy exception if the viewer doesn't have permission. $application = $this->getCurrentApplication(); if ($application) { id(new PhabricatorApplicationQuery()) ->setViewer($user) ->withPHIDs(array($application->getPHID())) ->executeOne(); } // If users need approval, require they wait here. We do this near the // end so they can take other actions (like verifying email, signing // documents, and enrolling in MFA) while waiting for an admin to take a // look at things. See T13024 for more discussion. if ($this->shouldRequireEnabledUser()) { if ($user->isLoggedIn() && !$user->getIsApproved()) { $controller = new PhabricatorAuthNeedsApprovalController(); return $this->delegateToController($controller); } } } // NOTE: We do this last so that users get a login page instead of a 403 // if they need to login. if ($this->shouldRequireAdmin() && !$user->getIsAdmin()) { return new Aphront403Response(); } } public function getApplicationURI($path = '') { if (!$this->getCurrentApplication()) { throw new Exception(pht('No application!')); } return $this->getCurrentApplication()->getApplicationURI($path); } public function willSendResponse(AphrontResponse $response) { $request = $this->getRequest(); if ($response instanceof AphrontDialogResponse) { if (!$request->isAjax() && !$request->isQuicksand()) { $dialog = $response->getDialog(); $title = $dialog->getTitle(); $short = $dialog->getShortTitle(); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb(coalesce($short, $title)); $page_content = array( $crumbs, $response->buildResponseString(), ); $view = id(new PhabricatorStandardPageView()) ->setRequest($request) ->setController($this) ->setDeviceReady(true) ->setTitle($title) ->appendChild($page_content); $response = id(new AphrontWebpageResponse()) ->setContent($view->render()) ->setHTTPResponseCode($response->getHTTPResponseCode()); } else { $response->getDialog()->setIsStandalone(true); return id(new AphrontAjaxResponse()) ->setContent(array( 'dialog' => $response->buildResponseString(), )); } } else if ($response instanceof AphrontRedirectResponse) { if ($request->isAjax() || $request->isQuicksand()) { return id(new AphrontAjaxResponse()) ->setContent( array( 'redirect' => $response->getURI(), 'close' => $response->getCloseDialogBeforeRedirect(), )); } } return $response; } /** * WARNING: Do not call this in new code. * * @deprecated See "Handles Technical Documentation". */ protected function loadViewerHandles(array $phids) { return id(new PhabricatorHandleQuery()) ->setViewer($this->getRequest()->getUser()) ->withPHIDs($phids) ->execute(); } public function buildApplicationMenu() { return null; } protected function buildApplicationCrumbs() { $crumbs = array(); $application = $this->getCurrentApplication(); if ($application) { $icon = $application->getIcon(); if (!$icon) { $icon = 'fa-puzzle'; } $crumbs[] = id(new PHUICrumbView()) ->setHref($this->getApplicationURI()) ->setName($application->getName()) ->setIcon($icon); } $view = new PHUICrumbsView(); foreach ($crumbs as $crumb) { $view->addCrumb($crumb); } return $view; } protected function hasApplicationCapability($capability) { return PhabricatorPolicyFilter::hasCapability( $this->getRequest()->getUser(), $this->getCurrentApplication(), $capability); } protected function requireApplicationCapability($capability) { PhabricatorPolicyFilter::requireCapability( $this->getRequest()->getUser(), $this->getCurrentApplication(), $capability); } protected function explainApplicationCapability( $capability, $positive_message, $negative_message) { $can_act = $this->hasApplicationCapability($capability); if ($can_act) { $message = $positive_message; $icon_name = 'fa-play-circle-o lightgreytext'; } else { $message = $negative_message; $icon_name = 'fa-lock'; } $icon = id(new PHUIIconView()) ->setIcon($icon_name); require_celerity_resource('policy-css'); $phid = $this->getCurrentApplication()->getPHID(); $explain_uri = "/policy/explain/{$phid}/{$capability}/"; $message = phutil_tag( 'div', array( 'class' => 'policy-capability-explanation', ), array( $icon, javelin_tag( 'a', array( 'href' => $explain_uri, 'sigil' => 'workflow', ), $message), )); return array($can_act, $message); } public function getDefaultResourceSource() { return 'phabricator'; } /** * Create a new @{class:AphrontDialogView} with defaults filled in. * * @return AphrontDialogView New dialog. */ public function newDialog() { $submit_uri = new PhutilURI($this->getRequest()->getRequestURI()); $submit_uri = $submit_uri->getPath(); return id(new AphrontDialogView()) ->setUser($this->getRequest()->getUser()) ->setSubmitURI($submit_uri); } public function newRedirect() { return id(new AphrontRedirectResponse()); } public function newPage() { $page = id(new PhabricatorStandardPageView()) ->setRequest($this->getRequest()) ->setController($this) ->setDeviceReady(true); $application = $this->getCurrentApplication(); if ($application) { $page->setApplicationName($application->getName()); if ($application->getTitleGlyph()) { $page->setGlyph($application->getTitleGlyph()); } } $viewer = $this->getRequest()->getUser(); if ($viewer) { $page->setUser($viewer); } return $page; } public function newApplicationMenu() { return id(new PHUIApplicationMenuView()) ->setViewer($this->getViewer()); } public function newCurtainView($object = null) { $viewer = $this->getViewer(); $action_id = celerity_generate_unique_node_id(); $action_list = id(new PhabricatorActionListView()) ->setViewer($viewer) ->setID($action_id); // NOTE: Applications (objects of class PhabricatorApplication) can't // currently be set here, although they don't need any of the extensions // anyway. This should probably work differently than it does, though. if ($object) { if ($object instanceof PhabricatorLiskDAO) { $action_list->setObject($object); } } $curtain = id(new PHUICurtainView()) ->setViewer($viewer) ->setActionList($action_list); if ($object) { $panels = PHUICurtainExtension::buildExtensionPanels($viewer, $object); foreach ($panels as $panel) { $curtain->addPanel($panel); } } return $curtain; } protected function buildTransactionTimeline( PhabricatorApplicationTransactionInterface $object, PhabricatorApplicationTransactionQuery $query = null, PhabricatorMarkupEngine $engine = null, $view_data = array()) { $request = $this->getRequest(); $viewer = $this->getViewer(); $xaction = $object->getApplicationTransactionTemplate(); if (!$query) { $query = PhabricatorApplicationTransactionQuery::newQueryForObject( $object); if (!$query) { throw new Exception( pht( 'Unable to find transaction query for object of class "%s".', get_class($object))); } } $pager = id(new AphrontCursorPagerView()) ->readFromRequest($request) ->setURI(new PhutilURI( '/transactions/showolder/'.$object->getPHID().'/')); $xactions = $query ->setViewer($viewer) ->withObjectPHIDs(array($object->getPHID())) ->needComments(true) ->executeWithCursorPager($pager); $xactions = array_reverse($xactions); $timeline_engine = PhabricatorTimelineEngine::newForObject($object) ->setViewer($viewer) ->setTransactions($xactions) ->setViewData($view_data); $view = $timeline_engine->buildTimelineView(); if ($engine) { foreach ($xactions as $xaction) { if ($xaction->getComment()) { $engine->addObject( $xaction->getComment(), PhabricatorApplicationTransactionComment::MARKUP_FIELD_COMMENT); } } $engine->process(); $view->setMarkupEngine($engine); } $timeline = $view ->setPager($pager) ->setQuoteTargetID($this->getRequest()->getStr('quoteTargetID')) ->setQuoteRef($this->getRequest()->getStr('quoteRef')); return $timeline; } public function buildApplicationCrumbsForEditEngine() { // TODO: This is kind of gross, I'm basically just making this public so // I can use it in EditEngine. We could do this without making it public // by using controller delegation, or make it properly public. return $this->buildApplicationCrumbs(); } private function requireLegalpadSignatures() { if (!$this->shouldRequireLogin()) { return null; } if ($this->shouldAllowLegallyNonCompliantUsers()) { return null; } $viewer = $this->getViewer(); if (!$viewer->hasSession()) { return null; } $session = $viewer->getSession(); if ($session->getIsPartial()) { // If the user hasn't made it through MFA yet, require they survive // MFA first. return null; } if ($session->getSignedLegalpadDocuments()) { return null; } if (!$viewer->isLoggedIn()) { return null; } $must_sign_docs = array(); $sign_docs = array(); $legalpad_class = 'PhabricatorLegalpadApplication'; $legalpad_installed = PhabricatorApplication::isClassInstalledForViewer( $legalpad_class, $viewer); if ($legalpad_installed) { $sign_docs = id(new LegalpadDocumentQuery()) ->setViewer($viewer) ->withSignatureRequired(1) ->needViewerSignatures(true) ->setOrder('oldest') ->execute(); foreach ($sign_docs as $sign_doc) { if (!$sign_doc->getUserSignature($viewer->getPHID())) { $must_sign_docs[] = $sign_doc; } } } if (!$must_sign_docs) { // If nothing needs to be signed (either because there are no documents // which require a signature, or because the user has already signed // all of them) mark the session as good and continue. $engine = id(new PhabricatorAuthSessionEngine()) ->signLegalpadDocuments($viewer, $sign_docs); return null; } $request = $this->getRequest(); $request->setURIMap( array( 'id' => head($must_sign_docs)->getID(), )); $application = PhabricatorApplication::getByClass($legalpad_class); $this->setCurrentApplication($application); $controller = new LegalpadDocumentSignController(); $controller->setIsSessionGate(true); return $this->delegateToController($controller); } /* -( Deprecated )--------------------------------------------------------- */ /** * DEPRECATED. Use @{method:newPage}. */ public function buildStandardPageView() { return $this->newPage(); } /** * DEPRECATED. Use @{method:newPage}. */ public function buildStandardPageResponse($view, array $data) { $page = $this->buildStandardPageView(); $page->appendChild($view); return $page->produceAphrontResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/controller/Phabricator404Controller.php
src/applications/base/controller/Phabricator404Controller.php
<?php final class Phabricator404Controller extends PhabricatorController { public function shouldRequireLogin() { return false; } public function processRequest() { return new Aphront404Response(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/controller/PhabricatorPlatform404Controller.php
src/applications/base/controller/PhabricatorPlatform404Controller.php
<?php final class PhabricatorPlatform404Controller extends PhabricatorController { public function processRequest() { return new Aphront404Response(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/controller/__tests__/PhabricatorTestController.php
src/applications/base/controller/__tests__/PhabricatorTestController.php
<?php final class PhabricatorTestController extends PhabricatorController { private $config = array(); public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getConfig($key, $default) { return idx($this->config, $key, $default); } public function shouldRequireLogin() { return $this->getConfig('login', parent::shouldRequireLogin()); } public function shouldRequireAdmin() { return $this->getConfig('admin', parent::shouldRequireAdmin()); } public function shouldAllowPublic() { return $this->getConfig('public', parent::shouldAllowPublic()); } public function shouldRequireEmailVerification() { return $this->getConfig('email', parent::shouldRequireEmailVerification()); } public function shouldRequireEnabledUser() { return $this->getConfig('enabled', parent::shouldRequireEnabledUser()); } public function processRequest() {} }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/controller/__tests__/PhabricatorTestApplication.php
src/applications/base/controller/__tests__/PhabricatorTestApplication.php
<?php final class PhabricatorTestApplication extends PhabricatorApplication { private $policies = array(); public function getName() { return pht('Test'); } public function isUnlisted() { return true; } public function isLaunchable() { return false; } public function reset() { $this->policies = array(); } public function setPolicy($capability, $value) { $this->policies[$capability] = $value; return $this; } public function getPolicy($capability) { return idx($this->policies, $capability, parent::getPolicy($capability)); } public function canUninstall() { return false; } public function getRoutes() { return array(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/controller/__tests__/PhabricatorAccessControlTestCase.php
src/applications/base/controller/__tests__/PhabricatorAccessControlTestCase.php
<?php final class PhabricatorAccessControlTestCase extends PhabricatorTestCase { protected function getPhabricatorTestCaseConfiguration() { return array( self::PHABRICATOR_TESTCONFIG_BUILD_STORAGE_FIXTURES => true, ); } public function testControllerAccessControls() { $root = dirname(phutil_get_library_root('phabricator')); require_once $root.'/support/startup/PhabricatorStartup.php'; $application_configuration = new AphrontApplicationConfiguration(); $host = 'meow.example.com'; $_SERVER['REQUEST_METHOD'] = 'GET'; $request = id(new AphrontRequest($host, '/')) ->setApplicationConfiguration($application_configuration) ->setRequestData(array()); $controller = new PhabricatorTestController(); $controller->setRequest($request); $u_public = id(new PhabricatorUser()) ->setUsername('public'); $u_unverified = $this->generateNewTestUser() ->setUsername('unverified') ->save(); $u_unverified->setIsEmailVerified(0)->save(); $u_normal = $this->generateNewTestUser() ->setUsername('normal') ->save(); $u_disabled = $this->generateNewTestUser() ->setIsDisabled(true) ->setUsername('disabled') ->save(); $u_admin = $this->generateNewTestUser() ->setIsAdmin(true) ->setUsername('admin') ->save(); $u_notapproved = $this->generateNewTestUser() ->setIsApproved(0) ->setUsername('notapproved') ->save(); $env = PhabricatorEnv::beginScopedEnv(); $env->overrideEnvConfig('phabricator.base-uri', 'http://'.$host); $env->overrideEnvConfig('policy.allow-public', false); $env->overrideEnvConfig('auth.require-email-verification', false); $env->overrideEnvConfig('security.require-multi-factor-auth', false); // Test standard defaults. $this->checkAccess( pht('Default'), id(clone $controller), $request, array( $u_normal, $u_admin, $u_unverified, ), array( $u_public, $u_disabled, $u_notapproved, )); // Test email verification. $env->overrideEnvConfig('auth.require-email-verification', true); $this->checkAccess( pht('Email Verification Required'), id(clone $controller), $request, array( $u_normal, $u_admin, ), array( $u_unverified, $u_public, $u_disabled, $u_notapproved, )); $this->checkAccess( pht('Email Verification Required, With Exception'), id(clone $controller)->setConfig('email', false), $request, array( $u_normal, $u_admin, $u_unverified, ), array( $u_public, $u_disabled, $u_notapproved, )); $env->overrideEnvConfig('auth.require-email-verification', false); // Test admin access. $this->checkAccess( pht('Admin Required'), id(clone $controller)->setConfig('admin', true), $request, array( $u_admin, ), array( $u_normal, $u_unverified, $u_public, $u_disabled, $u_notapproved, )); // Test disabled access. $this->checkAccess( pht('Allow Disabled'), id(clone $controller)->setConfig('enabled', false), $request, array( $u_normal, $u_unverified, $u_admin, $u_disabled, $u_notapproved, ), array( $u_public, )); // Test no login required. $this->checkAccess( pht('No Login Required'), id(clone $controller)->setConfig('login', false), $request, array( $u_normal, $u_unverified, $u_admin, $u_public, $u_notapproved, ), array( $u_disabled, )); // Test public access. $this->checkAccess( pht('Public Access'), id(clone $controller)->setConfig('public', true), $request, array( $u_normal, $u_unverified, $u_admin, ), array( $u_disabled, $u_public, )); $env->overrideEnvConfig('policy.allow-public', true); $this->checkAccess( pht('Public + configured'), id(clone $controller)->setConfig('public', true), $request, array( $u_normal, $u_unverified, $u_admin, $u_public, ), array( $u_disabled, $u_notapproved, )); $env->overrideEnvConfig('policy.allow-public', false); $app = PhabricatorApplication::getByClass('PhabricatorTestApplication'); $app->reset(); $app->setPolicy( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicies::POLICY_NOONE); $app_controller = id(clone $controller)->setCurrentApplication($app); $this->checkAccess( pht('Application Controller'), $app_controller, $request, array( ), array( $u_normal, $u_unverified, $u_admin, $u_public, $u_disabled, $u_notapproved, )); $this->checkAccess( pht('Application Controller, No Login Required'), id(clone $app_controller)->setConfig('login', false), $request, array( $u_normal, $u_unverified, $u_admin, $u_public, $u_notapproved, ), array( $u_disabled, )); } private function checkAccess( $label, $controller, $request, array $yes, array $no) { foreach ($yes as $user) { $request->setUser($user); $uname = $user->getUsername(); try { $result = id(clone $controller)->willBeginExecution(); } catch (Exception $ex) { $result = $ex; } $this->assertTrue( ($result === null), pht("Expect user '%s' to be allowed access to '%s'.", $uname, $label)); } foreach ($no as $user) { $request->setUser($user); $uname = $user->getUsername(); try { $result = id(clone $controller)->willBeginExecution(); } catch (Exception $ex) { $result = $ex; } $this->assertFalse( ($result === null), pht("Expect user '%s' to be denied access to '%s'.", $uname, $label)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/base/__tests__/PhabricatorApplicationTestCase.php
src/applications/base/__tests__/PhabricatorApplicationTestCase.php
<?php final class PhabricatorApplicationTestCase extends PhabricatorTestCase { public function testGetAllApplications() { PhabricatorApplication::getAllApplications(); $this->assertTrue(true); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/help/controller/PhabricatorHelpKeyboardShortcutController.php
src/applications/help/controller/PhabricatorHelpKeyboardShortcutController.php
<?php final class PhabricatorHelpKeyboardShortcutController extends PhabricatorHelpController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $keys = $request->getStr('keys'); try { $keys = phutil_json_decode($keys); } catch (PhutilJSONParserException $ex) { return new Aphront400Response(); } // There have been at least two users asking for a keyboard shortcut to // close the dialog, so be explicit that escape works since it isn't // terribly discoverable. $keys[] = array( 'keys' => array('Esc'), 'description' => pht('Close any dialog, including this one.'), 'group' => 'global', ); $groups = array( 'default' => array( 'name' => pht('Page Shortcuts'), 'icon' => 'fa-keyboard-o', ), 'diff-nav' => array( 'name' => pht('Diff Navigation'), 'icon' => 'fa-arrows', ), 'diff-vis' => array( 'name' => pht('Hiding Content'), 'icon' => 'fa-eye-slash', ), 'inline' => array( 'name' => pht('Editing Inline Comments'), 'icon' => 'fa-pencil', ), 'xactions' => array( 'name' => pht('Comments'), 'icon' => 'fa-comments-o', ), 'global' => array( 'name' => pht('Global Shortcuts'), 'icon' => 'fa-globe', ), ); $stroke_map = array( 'left' => "\xE2\x86\x90", 'right' => "\xE2\x86\x92", 'up' => "\xE2\x86\x91", 'down' => "\xE2\x86\x93", 'return' => "\xE2\x8F\x8E", 'tab' => "\xE2\x87\xA5", 'delete' => "\xE2\x8C\xAB", ); $row_maps = array(); foreach ($keys as $shortcut) { $keystrokes = array(); foreach ($shortcut['keys'] as $stroke) { $stroke = idx($stroke_map, $stroke, $stroke); $keystrokes[] = phutil_tag( 'span', array( 'class' => 'keyboard-shortcut-key', ), $stroke); } $keystrokes = phutil_implode_html(' or ', $keystrokes); $group_key = idx($shortcut, 'group'); if (!isset($groups[$group_key])) { $group_key = 'default'; } $row = phutil_tag( 'tr', array(), array( phutil_tag('th', array(), $keystrokes), phutil_tag('td', array(), $shortcut['description']), )); $row_maps[$group_key][] = $row; } $tab_group = id(new PHUITabGroupView()) ->setVertical(true); foreach ($groups as $key => $group) { $rows = idx($row_maps, $key); if (!$rows) { continue; } $icon = id(new PHUIIconView()) ->setIcon($group['icon']); $tab = id(new PHUITabView()) ->setKey($key) ->setName($group['name']) ->setIcon($icon); $table = phutil_tag( 'table', array('class' => 'keyboard-shortcut-help'), $rows); $tab->appendChild($table); $tab_group->addTab($tab); } return $this->newDialog() ->setTitle(pht('Keyboard Shortcuts')) ->setWidth(AphrontDialogView::WIDTH_FULL) ->setFlush(true) ->appendChild($tab_group) ->addCancelButton('#', 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/help/controller/PhabricatorHelpController.php
src/applications/help/controller/PhabricatorHelpController.php
<?php abstract class PhabricatorHelpController 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/help/controller/PhabricatorHelpDocumentationController.php
src/applications/help/controller/PhabricatorHelpDocumentationController.php
<?php final class PhabricatorHelpDocumentationController extends PhabricatorHelpController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $application_class = $request->getURIData('application'); $application = id(new PhabricatorApplicationQuery()) ->setViewer($viewer) ->withClasses(array($application_class)) ->executeOne(); if (!$application) { return new Aphront404Response(); } $items = $application->getHelpMenuItems($viewer); $title = pht('%s Help', $application->getName()); $list = id(new PHUIObjectItemListView()) ->setUser($viewer); foreach ($items as $item) { if ($item->getType() == PHUIListItemView::TYPE_LABEL) { continue; } $list->addItem( id(new PHUIObjectItemView()) ->setHeader($item->getName()) ->setHref($item->getHref())); } $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($title); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($list); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/help/application/PhabricatorHelpApplication.php
src/applications/help/application/PhabricatorHelpApplication.php
<?php final class PhabricatorHelpApplication extends PhabricatorApplication { public function getName() { return pht('Help'); } public function canUninstall() { return false; } public function isUnlisted() { return true; } public function getRoutes() { return array( '/help/' => array( 'keyboardshortcut/' => 'PhabricatorHelpKeyboardShortcutController', 'documentation/(?P<application>\w+)/' => 'PhabricatorHelpDocumentationController', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/PhabricatorKeyValueDatabaseCache.php
src/applications/cache/PhabricatorKeyValueDatabaseCache.php
<?php final class PhabricatorKeyValueDatabaseCache extends PhutilKeyValueCache { const CACHE_FORMAT_RAW = 'raw'; const CACHE_FORMAT_DEFLATE = 'deflate'; public function setKeys(array $keys, $ttl = null) { if (PhabricatorEnv::isReadOnly()) { return; } if ($keys) { $map = $this->digestKeys(array_keys($keys)); $conn_w = $this->establishConnection('w'); $sql = array(); foreach ($map as $key => $hash) { $value = $keys[$key]; list($format, $storage_value) = $this->willWriteValue($key, $value); $sql[] = qsprintf( $conn_w, '(%s, %s, %s, %B, %d, %nd)', $hash, $key, $format, $storage_value, time(), $ttl ? (time() + $ttl) : null); } $guard = AphrontWriteGuard::beginScopedUnguardedWrites(); foreach (PhabricatorLiskDAO::chunkSQL($sql) as $chunk) { queryfx( $conn_w, 'INSERT INTO %T (cacheKeyHash, cacheKey, cacheFormat, cacheData, cacheCreated, cacheExpires) VALUES %LQ ON DUPLICATE KEY UPDATE cacheKey = VALUES(cacheKey), cacheFormat = VALUES(cacheFormat), cacheData = VALUES(cacheData), cacheCreated = VALUES(cacheCreated), cacheExpires = VALUES(cacheExpires)', $this->getTableName(), $chunk); } unset($guard); } return $this; } public function getKeys(array $keys) { $results = array(); if ($keys) { $map = $this->digestKeys($keys); $rows = queryfx_all( $this->establishConnection('r'), 'SELECT * FROM %T WHERE cacheKeyHash IN (%Ls)', $this->getTableName(), $map); $rows = ipull($rows, null, 'cacheKey'); foreach ($keys as $key) { if (empty($rows[$key])) { continue; } $row = $rows[$key]; if ($row['cacheExpires'] && ($row['cacheExpires'] < time())) { continue; } try { $results[$key] = $this->didReadValue( $row['cacheFormat'], $row['cacheData']); } catch (Exception $ex) { // Treat this as a cache miss. phlog($ex); } } } return $results; } public function deleteKeys(array $keys) { if ($keys) { $map = $this->digestKeys($keys); queryfx( $this->establishConnection('w'), 'DELETE FROM %T WHERE cacheKeyHash IN (%Ls)', $this->getTableName(), $map); } return $this; } public function destroyCache() { queryfx( $this->establishConnection('w'), 'DELETE FROM %T', $this->getTableName()); return $this; } /* -( Raw Cache Access )--------------------------------------------------- */ public function establishConnection($mode) { // TODO: This is the only concrete table we have on the database right // now. return id(new PhabricatorMarkupCache())->establishConnection($mode); } public function getTableName() { return 'cache_general'; } /* -( Implementation )----------------------------------------------------- */ private function digestKeys(array $keys) { $map = array(); foreach ($keys as $key) { $map[$key] = PhabricatorHash::digestForIndex($key); } return $map; } private function willWriteValue($key, $value) { if (!is_string($value)) { throw new Exception(pht('Only strings may be written to the DB cache!')); } static $can_deflate; if ($can_deflate === null) { $can_deflate = function_exists('gzdeflate'); } if ($can_deflate) { $deflated = PhabricatorCaches::maybeDeflateData($value); if ($deflated !== null) { return array(self::CACHE_FORMAT_DEFLATE, $deflated); } } return array(self::CACHE_FORMAT_RAW, $value); } private function didReadValue($format, $value) { switch ($format) { case self::CACHE_FORMAT_RAW: return $value; case self::CACHE_FORMAT_DEFLATE: return PhabricatorCaches::inflateData($value); default: throw new Exception(pht('Unknown cache format.')); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/PhabricatorCaches.php
src/applications/cache/PhabricatorCaches.php
<?php /** * * @task request Request Cache * @task immutable Immutable Cache * @task setup Setup Cache * @task compress Compression */ final class PhabricatorCaches extends Phobject { private static $requestCache; public static function getNamespace() { return PhabricatorEnv::getEnvConfig('phabricator.cache-namespace'); } private static function newStackFromCaches(array $caches) { $caches = self::addNamespaceToCaches($caches); $caches = self::addProfilerToCaches($caches); return id(new PhutilKeyValueCacheStack()) ->setCaches($caches); } /* -( Request Cache )------------------------------------------------------ */ /** * Get a request cache stack. * * This cache stack is destroyed after each logical request. In particular, * it is destroyed periodically by the daemons, while `static` caches are * not. * * @return PhutilKeyValueCacheStack Request cache stack. */ public static function getRequestCache() { if (!self::$requestCache) { self::$requestCache = new PhutilInRequestKeyValueCache(); } return self::$requestCache; } /** * Destroy the request cache. * * This is called at the beginning of each logical request. * * @return void */ public static function destroyRequestCache() { self::$requestCache = null; // See T12997. Force the GC to run when the request cache is destroyed to // clean up any cycles which may still be hanging around. if (function_exists('gc_collect_cycles')) { gc_collect_cycles(); } } /* -( Immutable Cache )---------------------------------------------------- */ /** * Gets an immutable cache stack. * * This stack trades mutability away for improved performance. Normally, it is * APC + DB. * * In the general case with multiple web frontends, this stack can not be * cleared, so it is only appropriate for use if the value of a given key is * permanent and immutable. * * @return PhutilKeyValueCacheStack Best immutable stack available. * @task immutable */ public static function getImmutableCache() { static $cache; if (!$cache) { $caches = self::buildImmutableCaches(); $cache = self::newStackFromCaches($caches); } return $cache; } /** * Build the immutable cache stack. * * @return list<PhutilKeyValueCache> List of caches. * @task immutable */ private static function buildImmutableCaches() { $caches = array(); $apc = new PhutilAPCKeyValueCache(); if ($apc->isAvailable()) { $caches[] = $apc; } $caches[] = new PhabricatorKeyValueDatabaseCache(); return $caches; } public static function getMutableCache() { static $cache; if (!$cache) { $caches = self::buildMutableCaches(); $cache = self::newStackFromCaches($caches); } return $cache; } private static function buildMutableCaches() { $caches = array(); $caches[] = new PhabricatorKeyValueDatabaseCache(); return $caches; } public static function getMutableStructureCache() { static $cache; if (!$cache) { $caches = self::buildMutableStructureCaches(); $cache = self::newStackFromCaches($caches); } return $cache; } private static function buildMutableStructureCaches() { $caches = array(); $cache = new PhabricatorKeyValueDatabaseCache(); $cache = new PhabricatorKeyValueSerializingCacheProxy($cache); $caches[] = $cache; return $caches; } /* -( Runtime Cache )------------------------------------------------------ */ /** * Get a runtime cache stack. * * This stack is just APC. It's fast, it's effectively immutable, and it * gets thrown away when the webserver restarts. * * This cache is suitable for deriving runtime caches, like a map of Conduit * method names to provider classes. * * @return PhutilKeyValueCacheStack Best runtime stack available. */ public static function getRuntimeCache() { static $cache; if (!$cache) { $caches = self::buildRuntimeCaches(); $cache = self::newStackFromCaches($caches); } return $cache; } private static function buildRuntimeCaches() { $caches = array(); $apc = new PhutilAPCKeyValueCache(); if ($apc->isAvailable()) { $caches[] = $apc; } return $caches; } /* -( Repository Graph Cache )--------------------------------------------- */ public static function getRepositoryGraphL1Cache() { static $cache; if (!$cache) { $caches = self::buildRepositoryGraphL1Caches(); $cache = self::newStackFromCaches($caches); } return $cache; } private static function buildRepositoryGraphL1Caches() { $caches = array(); $request = new PhutilInRequestKeyValueCache(); $request->setLimit(32); $caches[] = $request; $apc = new PhutilAPCKeyValueCache(); if ($apc->isAvailable()) { $caches[] = $apc; } return $caches; } public static function getRepositoryGraphL2Cache() { static $cache; if (!$cache) { $caches = self::buildRepositoryGraphL2Caches(); $cache = self::newStackFromCaches($caches); } return $cache; } private static function buildRepositoryGraphL2Caches() { $caches = array(); $caches[] = new PhabricatorKeyValueDatabaseCache(); return $caches; } /* -( Server State Cache )------------------------------------------------- */ /** * Highly specialized cache for storing server process state. * * We use this cache to track initial steps in the setup phase, before * configuration is loaded. * * This cache does NOT use the cache namespace (it must be accessed before * we build configuration), and is global across all instances on the host. * * @return PhutilKeyValueCacheStack Best available server state cache stack. * @task setup */ public static function getServerStateCache() { static $cache; if (!$cache) { $caches = self::buildSetupCaches('phabricator-server'); // NOTE: We are NOT adding a cache namespace here! This cache is shared // across all instances on the host. $caches = self::addProfilerToCaches($caches); $cache = id(new PhutilKeyValueCacheStack()) ->setCaches($caches); } return $cache; } /* -( Setup Cache )-------------------------------------------------------- */ /** * Highly specialized cache for performing setup checks. We use this cache * to determine if we need to run expensive setup checks when the page * loads. Without it, we would need to run these checks every time. * * Normally, this cache is just APC. In the absence of APC, this cache * degrades into a slow, quirky on-disk cache. * * NOTE: Do not use this cache for anything else! It is not a general-purpose * cache! * * @return PhutilKeyValueCacheStack Most qualified available cache stack. * @task setup */ public static function getSetupCache() { static $cache; if (!$cache) { $caches = self::buildSetupCaches('phabricator-setup'); $cache = self::newStackFromCaches($caches); } return $cache; } /** * @task setup */ private static function buildSetupCaches($cache_name) { // If this is the CLI, just build a setup cache. if (php_sapi_name() == 'cli') { return array(); } // In most cases, we should have APC. This is an ideal cache for our // purposes -- it's fast and empties on server restart. $apc = new PhutilAPCKeyValueCache(); if ($apc->isAvailable()) { return array($apc); } // If we don't have APC, build a poor approximation on disk. This is still // much better than nothing; some setup steps are quite slow. $disk_path = self::getSetupCacheDiskCachePath($cache_name); if ($disk_path) { $disk = new PhutilOnDiskKeyValueCache(); $disk->setCacheFile($disk_path); $disk->setWait(0.1); if ($disk->isAvailable()) { return array($disk); } } return array(); } /** * @task setup */ private static function getSetupCacheDiskCachePath($name) { // The difficulty here is in choosing a path which will change on server // restart (we MUST have this property), but as rarely as possible // otherwise (we desire this property to give the cache the best hit rate // we can). // Unfortunately, we don't have a very good strategy for minimizing the // churn rate of the cache. We previously tried to use the parent process // PID in some cases, but this was not reliable. See T9599 for one case of // this. $pid_basis = getmypid(); // If possible, we also want to know when the process launched, so we can // drop the cache if a process restarts but gets the same PID an earlier // process had. "/proc" is not available everywhere (e.g., not on OSX), but // check if we have it. $epoch_basis = null; $stat = @stat("/proc/{$pid_basis}"); if ($stat !== false) { $epoch_basis = $stat['ctime']; } $tmp_dir = sys_get_temp_dir(); $tmp_path = $tmp_dir.DIRECTORY_SEPARATOR.$name; if (!file_exists($tmp_path)) { @mkdir($tmp_path); } $is_ok = self::testTemporaryDirectory($tmp_path); if (!$is_ok) { $tmp_path = $tmp_dir; $is_ok = self::testTemporaryDirectory($tmp_path); if (!$is_ok) { // We can't find anywhere to write the cache, so just bail. return null; } } $tmp_name = 'setup-'.$pid_basis; if ($epoch_basis) { $tmp_name .= '.'.$epoch_basis; } $tmp_name .= '.cache'; return $tmp_path.DIRECTORY_SEPARATOR.$tmp_name; } /** * @task setup */ private static function testTemporaryDirectory($dir) { if (!@file_exists($dir)) { return false; } if (!@is_dir($dir)) { return false; } if (!@is_writable($dir)) { return false; } return true; } private static function addProfilerToCaches(array $caches) { foreach ($caches as $key => $cache) { $pcache = new PhutilKeyValueCacheProfiler($cache); $pcache->setProfiler(PhutilServiceProfiler::getInstance()); $caches[$key] = $pcache; } return $caches; } private static function addNamespaceToCaches(array $caches) { $namespace = self::getNamespace(); if (!$namespace) { return $caches; } foreach ($caches as $key => $cache) { $ncache = new PhutilKeyValueCacheNamespace($cache); $ncache->setNamespace($namespace); $caches[$key] = $ncache; } return $caches; } /** * Deflate a value, if deflation is available and has an impact. * * If the value is larger than 1KB, we have `gzdeflate()`, we successfully * can deflate it, and it benefits from deflation, we deflate it. Otherwise * we leave it as-is. * * Data can later be inflated with @{method:inflateData}. * * @param string String to attempt to deflate. * @return string|null Deflated string, or null if it was not deflated. * @task compress */ public static function maybeDeflateData($value) { $len = strlen($value); if ($len <= 1024) { return null; } if (!function_exists('gzdeflate')) { return null; } $deflated = gzdeflate($value); if ($deflated === false) { return null; } $deflated_len = strlen($deflated); if ($deflated_len >= ($len / 2)) { return null; } return $deflated; } /** * Inflate data previously deflated by @{method:maybeDeflateData}. * * @param string Deflated data, from @{method:maybeDeflateData}. * @return string Original, uncompressed data. * @task compress */ public static function inflateData($value) { if (!function_exists('gzinflate')) { throw new Exception( pht( '%s is not available; unable to read deflated data!', 'gzinflate()')); } $value = gzinflate($value); if ($value === false) { throw new Exception(pht('Failed to inflate data!')); } return $value; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/PhabricatorCachedClassMapQuery.php
src/applications/cache/PhabricatorCachedClassMapQuery.php
<?php /** * Cached @{class:PhutilClassMapQuery} which can perform lookups for single * classes efficiently. * * Some class trees (like Conduit methods and PHID types) contain a huge number * of classes but are frequently accessed by looking for a specific class by * a known identifier (like a Conduit method name or a PHID type constant). * * Loading the entire class map for these cases has a small but measurable * performance cost. Instead, we can build a cache from each Conduit method * name to just the class required to serve that request. This means that we * load fewer classes and have less overhead to execute API calls. */ final class PhabricatorCachedClassMapQuery extends Phobject { private $query; private $queryCacheKey; private $mapKeyMethod; private $objectMap; public function setClassMapQuery(PhutilClassMapQuery $query) { $this->query = $query; return $this; } public function setMapKeyMethod($method) { $this->mapKeyMethod = $method; return $this; } public function loadClasses(array $values) { $cache = PhabricatorCaches::getRuntimeCache(); $cache_keys = $this->getCacheKeys($values); $cache_map = $cache->getKeys($cache_keys); $results = array(); $writes = array(); foreach ($cache_keys as $value => $cache_key) { if (isset($cache_map[$cache_key])) { $class_name = $cache_map[$cache_key]; try { $result = $this->newObject($class_name); if ($this->getObjectMapKey($result) === $value) { $results[$value] = $result; continue; } } catch (Exception $ex) { // Keep going, we'll handle this immediately below. } // If we didn't "continue;" above, there was either a direct issue with // the cache or the cached class did not generate the correct map key. // Wipe the cache and pretend we missed. $cache->deleteKey($cache_key); } if ($this->objectMap === null) { $this->objectMap = $this->newObjectMap(); } if (isset($this->objectMap[$value])) { $results[$value] = $this->objectMap[$value]; $writes[$cache_key] = get_class($results[$value]); } } if ($writes) { $cache->setKeys($writes); } return $results; } public function loadClass($value) { $result = $this->loadClasses(array($value)); return idx($result, $value); } private function getCacheKeys(array $values) { if ($this->queryCacheKey === null) { $this->queryCacheKey = $this->query->getCacheKey(); } $key = $this->queryCacheKey; $method = $this->mapKeyMethod; $keys = array(); foreach ($values as $value) { $keys[$value] = "classmap({$key}).{$method}({$value})"; } return $keys; } private function newObject($class_name) { return newv($class_name, array()); } private function newObjectMap() { $map = $this->query->execute(); $result = array(); foreach ($map as $object) { $value = $this->getObjectMapKey($object); if (isset($result[$value])) { $other = $result[$value]; throw new Exception( pht( 'Two objects (of classes "%s" and "%s") generate the same map '. 'value ("%s"). Each object must generate a unique map value.', get_class($object), get_class($other), $value)); } $result[$value] = $object; } return $result; } private function getObjectMapKey($object) { return call_user_func(array($object, $this->mapKeyMethod)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/PhabricatorKeyValueSerializingCacheProxy.php
src/applications/cache/PhabricatorKeyValueSerializingCacheProxy.php
<?php /** * Proxies another cache and serializes values. * * This allows more complex data to be stored in a cache which can only store * strings. */ final class PhabricatorKeyValueSerializingCacheProxy extends PhutilKeyValueCacheProxy { public function getKeys(array $keys) { $results = parent::getKeys($keys); $reads = array(); foreach ($results as $key => $result) { $structure = @unserialize($result); // The unserialize() function returns false when unserializing a // literal `false`, and also when it fails. If we get a literal // `false`, test if the serialized form is the same as the // serialization of `false` and miss the cache otherwise. if ($structure === false) { static $serialized_false; if ($serialized_false === null) { $serialized_false = serialize(false); } if ($result !== $serialized_false) { continue; } } $reads[$key] = $structure; } return $reads; } public function setKeys(array $keys, $ttl = null) { $writes = array(); foreach ($keys as $key => $value) { if (is_object($value)) { throw new Exception( pht( 'Serializing cache can not write objects (for key "%s")!', $key)); } $writes[$key] = serialize($value); } return parent::setKeys($writes, $ttl); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/storage/PhabricatorCacheSchemaSpec.php
src/applications/cache/storage/PhabricatorCacheSchemaSpec.php
<?php final class PhabricatorCacheSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildRawSchema( 'cache', id(new PhabricatorKeyValueDatabaseCache())->getTableName(), array( 'id' => 'auto64', 'cacheKeyHash' => 'bytes12', 'cacheKey' => 'text128', 'cacheFormat' => 'text16', 'cacheData' => 'bytes', 'cacheCreated' => 'epoch', 'cacheExpires' => 'epoch?', ), array( 'PRIMARY' => array( 'columns' => array('id'), 'unique' => true, ), 'key_cacheKeyHash' => array( 'columns' => array('cacheKeyHash'), 'unique' => true, ), 'key_cacheCreated' => array( 'columns' => array('cacheCreated'), ), 'key_ttl' => array( 'columns' => array('cacheExpires'), ), ), array( 'persistence' => PhabricatorConfigTableSchema::PERSISTENCE_CACHE, )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/storage/PhabricatorCacheDAO.php
src/applications/cache/storage/PhabricatorCacheDAO.php
<?php abstract class PhabricatorCacheDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'cache'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/storage/PhabricatorMarkupCache.php
src/applications/cache/storage/PhabricatorMarkupCache.php
<?php final class PhabricatorMarkupCache extends PhabricatorCacheDAO { protected $cacheKey; protected $cacheData; protected $metadata; protected function getConfiguration() { return array( self::CONFIG_SERIALIZATION => array( 'cacheData' => self::SERIALIZATION_PHP, 'metadata' => self::SERIALIZATION_JSON, ), self::CONFIG_BINARY => array( 'cacheData' => true, ), self::CONFIG_COLUMN_SCHEMA => array( 'cacheKey' => 'text128', ), self::CONFIG_KEY_SCHEMA => array( 'cacheKey' => array( 'columns' => array('cacheKey'), 'unique' => true, ), 'dateCreated' => array( 'columns' => array('dateCreated'), ), ), ) + parent::getConfiguration(); } public function getSchemaPersistence() { return PhabricatorConfigTableSchema::PERSISTENCE_CACHE; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/management/PhabricatorCacheManagementWorkflow.php
src/applications/cache/management/PhabricatorCacheManagementWorkflow.php
<?php abstract class PhabricatorCacheManagementWorkflow extends PhabricatorManagementWorkflow {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/management/PhabricatorCacheManagementPurgeWorkflow.php
src/applications/cache/management/PhabricatorCacheManagementPurgeWorkflow.php
<?php final class PhabricatorCacheManagementPurgeWorkflow extends PhabricatorCacheManagementWorkflow { protected function didConstruct() { $this ->setName('purge') ->setSynopsis(pht('Drop data from readthrough caches.')) ->setArguments( array( array( 'name' => 'all', 'help' => pht('Purge all caches.'), ), array( 'name' => 'caches', 'param' => 'keys', 'help' => pht('Purge a specific set of caches.'), ), )); } public function execute(PhutilArgumentParser $args) { $all_purgers = PhabricatorCachePurger::getAllPurgers(); $is_all = $args->getArg('all'); $key_list = $args->getArg('caches'); if ($is_all && phutil_nonempty_string($key_list)) { throw new PhutilArgumentUsageException( pht( 'Specify either "--all" or "--caches", not both.')); } else if (!$is_all && !phutil_nonempty_string($key_list)) { throw new PhutilArgumentUsageException( pht( 'Select caches to purge with "--all" or "--caches". Available '. 'caches are: %s.', implode(', ', array_keys($all_purgers)))); } if ($is_all) { $purgers = $all_purgers; } else { $key_list = preg_split('/[\s,]+/', $key_list); $purgers = array(); foreach ($key_list as $key) { if (isset($all_purgers[$key])) { $purgers[$key] = $all_purgers[$key]; } else { throw new PhutilArgumentUsageException( pht( 'Cache purger "%s" is not recognized. Available caches '. 'are: %s.', $key, implode(', ', array_keys($all_purgers)))); } } if (!$purgers) { throw new PhutilArgumentUsageException( pht( 'When using "--caches", you must select at least one valid '. 'cache to purge.')); } } $viewer = $this->getViewer(); foreach ($purgers as $key => $purger) { $purger->setViewer($viewer); echo tsprintf( "%s\n", pht( 'Purging "%s" cache...', $key)); $purger->purgeCache(); } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/purger/PhabricatorBuiltinFileCachePurger.php
src/applications/cache/purger/PhabricatorBuiltinFileCachePurger.php
<?php final class PhabricatorBuiltinFileCachePurger extends PhabricatorCachePurger { const PURGERKEY = 'builtin-file'; public function purgeCache() { $viewer = $this->getViewer(); $files = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withIsBuiltin(true) ->execute(); $engine = new PhabricatorDestructionEngine(); foreach ($files as $file) { $engine->destroyObject($file); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/purger/PhabricatorUserCachePurger.php
src/applications/cache/purger/PhabricatorUserCachePurger.php
<?php final class PhabricatorUserCachePurger extends PhabricatorCachePurger { const PURGERKEY = 'user'; public function purgeCache() { $table = new PhabricatorUserCache(); $conn = $table->establishConnection('w'); queryfx( $conn, 'TRUNCATE TABLE %T', $table->getTableName()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/purger/PhabricatorRemarkupCachePurger.php
src/applications/cache/purger/PhabricatorRemarkupCachePurger.php
<?php final class PhabricatorRemarkupCachePurger extends PhabricatorCachePurger { const PURGERKEY = 'remarkup'; public function purgeCache() { $table = new PhabricatorMarkupCache(); $conn = $table->establishConnection('w'); queryfx( $conn, 'TRUNCATE TABLE %T', $table->getTableName()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/purger/PhabricatorGeneralCachePurger.php
src/applications/cache/purger/PhabricatorGeneralCachePurger.php
<?php final class PhabricatorGeneralCachePurger extends PhabricatorCachePurger { const PURGERKEY = 'general'; public function purgeCache() { $table = new PhabricatorMarkupCache(); $conn = $table->establishConnection('w'); queryfx( $conn, 'TRUNCATE TABLE %T', 'cache_general'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/purger/PhabricatorChangesetCachePurger.php
src/applications/cache/purger/PhabricatorChangesetCachePurger.php
<?php final class PhabricatorChangesetCachePurger extends PhabricatorCachePurger { const PURGERKEY = 'changeset'; public function purgeCache() { $table = new DifferentialChangeset(); $conn = $table->establishConnection('w'); queryfx( $conn, 'TRUNCATE TABLE %T', DifferentialChangeset::TABLE_CACHE); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/purger/PhabricatorCachePurger.php
src/applications/cache/purger/PhabricatorCachePurger.php
<?php abstract class PhabricatorCachePurger extends Phobject { private $viewer; abstract public function purgeCache(); final public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } final public function getViewer() { return $this->viewer; } final public function getPurgerKey() { return $this->getPhobjectClassConstant('PURGERKEY'); } final public static function getAllPurgers() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getPurgerKey') ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/__tests__/PhabricatorCachesTestCase.php
src/applications/cache/__tests__/PhabricatorCachesTestCase.php
<?php final class PhabricatorCachesTestCase extends PhabricatorTestCase { public function testRequestCache() { $cache = PhabricatorCaches::getRequestCache(); $test_key = 'unit.'.Filesystem::readRandomCharacters(8); $default_value = pht('Default'); $new_value = pht('New Value'); $this->assertEqual( $default_value, $cache->getKey($test_key, $default_value)); // Set a key, verify it persists. $cache = PhabricatorCaches::getRequestCache(); $cache->setKey($test_key, $new_value); $this->assertEqual( $new_value, $cache->getKey($test_key, $default_value)); // Refetch the cache, verify it's really a cache. $cache = PhabricatorCaches::getRequestCache(); $this->assertEqual( $new_value, $cache->getKey($test_key, $default_value)); // Destroy the cache. PhabricatorCaches::destroyRequestCache(); // Now, the value should be missing again. $cache = PhabricatorCaches::getRequestCache(); $this->assertEqual( $default_value, $cache->getKey($test_key, $default_value)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/garbagecollector/PhabricatorCacheMarkupGarbageCollector.php
src/applications/cache/garbagecollector/PhabricatorCacheMarkupGarbageCollector.php
<?php final class PhabricatorCacheMarkupGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'cache.markup'; public function getCollectorName() { return pht('Markup Cache'); } public function getDefaultRetentionPolicy() { return phutil_units('30 days in seconds'); } protected function collectGarbage() { $table = new PhabricatorMarkupCache(); $conn_w = $table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE dateCreated < %d LIMIT 100', $table->getTableName(), $this->getGarbageEpoch()); return ($conn_w->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/garbagecollector/PhabricatorCacheGeneralGarbageCollector.php
src/applications/cache/garbagecollector/PhabricatorCacheGeneralGarbageCollector.php
<?php final class PhabricatorCacheGeneralGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'cache.general'; public function getCollectorName() { return pht('General Cache'); } public function getDefaultRetentionPolicy() { return phutil_units('30 days in seconds'); } protected function collectGarbage() { $cache = new PhabricatorKeyValueDatabaseCache(); $conn_w = $cache->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE cacheCreated < %d ORDER BY cacheCreated ASC LIMIT 100', $cache->getTableName(), $this->getGarbageEpoch()); return ($conn_w->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/garbagecollector/PhabricatorCacheTTLGarbageCollector.php
src/applications/cache/garbagecollector/PhabricatorCacheTTLGarbageCollector.php
<?php final class PhabricatorCacheTTLGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'cache.general.ttl'; public function getCollectorName() { return pht('General Cache (TTL)'); } public function hasAutomaticPolicy() { return true; } protected function collectGarbage() { $cache = new PhabricatorKeyValueDatabaseCache(); $conn_w = $cache->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE cacheExpires < %d ORDER BY cacheExpires ASC LIMIT 100', $cache->getTableName(), PhabricatorTime::getNow()); return ($conn_w->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/spec/PhabricatorDataCacheSpec.php
src/applications/cache/spec/PhabricatorDataCacheSpec.php
<?php final class PhabricatorDataCacheSpec extends PhabricatorCacheSpec { private $cacheSummary; public function setCacheSummary(array $cache_summary) { $this->cacheSummary = $cache_summary; return $this; } public function getCacheSummary() { return $this->cacheSummary; } public static function getActiveCacheSpec() { $spec = new PhabricatorDataCacheSpec(); // NOTE: If APCu is installed, it reports that APC is installed. if (extension_loaded('apc') && !extension_loaded('apcu')) { $spec->initAPCSpec(); } else if (extension_loaded('apcu')) { $spec->initAPCuSpec(); } else { $spec->initNoneSpec(); } return $spec; } private function initAPCSpec() { $this ->setName(pht('APC User Cache')) ->setVersion(phpversion('apc')); if (ini_get('apc.enabled')) { $this ->setIsEnabled(true) ->setClearCacheCallback('apc_clear_cache'); $this->initAPCCommonSpec(); } else { $this->setIsEnabled(false); $this->raiseEnableAPCIssue(); } } private function initAPCuSpec() { $this ->setName(pht('APCu')) ->setVersion(phpversion('apcu')); if (ini_get('apc.enabled')) { if (function_exists('apcu_clear_cache')) { $clear_callback = 'apcu_clear_cache'; } else { $clear_callback = 'apc_clear_cache'; } $this ->setIsEnabled(true) ->setClearCacheCallback($clear_callback); $this->initAPCCommonSpec(); } else { $this->setIsEnabled(false); $this->raiseEnableAPCIssue(); } } private function initNoneSpec() { if (version_compare(phpversion(), '5.5', '>=')) { $message = pht( 'Installing the "APCu" PHP extension will improve performance. '. 'This extension is strongly recommended. Without it, this software '. 'must rely on a very inefficient disk-based cache.'); $this ->newIssue('extension.apcu') ->setShortName(pht('APCu')) ->setName(pht('PHP Extension "APCu" Not Installed')) ->setMessage($message) ->addPHPExtension('apcu'); } else { $this->raiseInstallAPCIssue(); } } private function initAPCCommonSpec() { $state = array(); if (function_exists('apcu_sma_info')) { $mem = apcu_sma_info(); $info = apcu_cache_info(); } else if (function_exists('apc_sma_info')) { $mem = apc_sma_info(); $info = apc_cache_info('user'); } else { $mem = null; } if ($mem) { $this->setTotalMemory($mem['num_seg'] * $mem['seg_size']); $this->setUsedMemory($info['mem_size']); $this->setEntryCount(count($info['cache_list'])); $cache = $info['cache_list']; $state = array(); foreach ($cache as $item) { // Some older versions of APCu report the cachekey as "key", while // newer APCu and APC report it as "info". Just check both indexes // for commpatibility. See T13164 for details. $info = idx($item, 'info'); if ($info === null) { $info = idx($item, 'key'); } if ($info === null) { $key = '<unknown-key>'; } else { $key = self::getKeyPattern($info); } if (empty($state[$key])) { $state[$key] = array( 'max' => 0, 'total' => 0, 'count' => 0, ); } $state[$key]['max'] = max($state[$key]['max'], $item['mem_size']); $state[$key]['total'] += $item['mem_size']; $state[$key]['count']++; } } $this->setCacheSummary($state); } private static function getKeyPattern($key) { // If this key isn't in the current cache namespace, don't reveal any // information about it. $namespace = PhabricatorEnv::getEnvConfig('phabricator.cache-namespace'); if (strncmp($key, $namespace.':', strlen($namespace) + 1)) { return '<other-namespace>'; } $key = preg_replace('/(?<![a-zA-Z])\d+(?![a-zA-Z])/', 'N', $key); $key = preg_replace('/PHID-[A-Z]{4}-[a-z0-9]{20}/', 'PHID', $key); // TODO: We should probably standardize how digests get embedded into cache // keys to make this rule more generic. $key = preg_replace('/:celerity:.*$/', ':celerity:X', $key); $key = preg_replace('/:pkcs8:.*$/', ':pkcs8:X', $key); return $key; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/spec/PhabricatorOpcodeCacheSpec.php
src/applications/cache/spec/PhabricatorOpcodeCacheSpec.php
<?php final class PhabricatorOpcodeCacheSpec extends PhabricatorCacheSpec { public static function getActiveCacheSpec() { $spec = new PhabricatorOpcodeCacheSpec(); // NOTE: If APCu is installed, it reports that APC is installed. if (extension_loaded('apc') && !extension_loaded('apcu')) { $spec->initAPCSpec(); } else if (extension_loaded('Zend OPcache')) { $spec->initOpcacheSpec(); } else { $spec->initNoneSpec(); } return $spec; } private function initAPCSpec() { $this ->setName(pht('APC')) ->setVersion(phpversion('apc')); if (ini_get('apc.enabled')) { $this ->setIsEnabled(true) ->setClearCacheCallback('apc_clear_cache'); $mem = apc_sma_info(); $this->setTotalMemory($mem['num_seg'] * $mem['seg_size']); $info = apc_cache_info(); $this->setUsedMemory($info['mem_size']); $write_lock = ini_get('apc.write_lock'); $slam_defense = ini_get('apc.slam_defense'); if (!$write_lock || $slam_defense) { $summary = pht('Adjust APC settings to quiet unnecessary errors.'); $message = pht( 'Some versions of APC may emit unnecessary errors into the '. 'error log under the current APC settings. To resolve this, '. 'enable "%s" and disable "%s" in your PHP configuration.', 'apc.write_lock', 'apc.slam_defense'); $this ->newIssue('extension.apc.write-lock') ->setShortName(pht('Noisy APC')) ->setName(pht('APC Has Noisy Configuration')) ->setSummary($summary) ->setMessage($message) ->addPHPConfig('apc.write_lock') ->addPHPConfig('apc.slam_defense'); } $is_dev = PhabricatorEnv::getEnvConfig('phabricator.developer-mode'); $is_stat_enabled = ini_get('apc.stat'); if ($is_stat_enabled && !$is_dev) { $summary = pht( '"%s" is currently enabled, but should probably be disabled.', 'apc.stat'); $message = pht( 'The "%s" setting is currently enabled in your PHP configuration. '. 'In production mode, "%s" should be disabled. '. 'This will improve performance slightly.', 'apc.stat', 'apc.stat'); $this ->newIssue('extension.apc.stat-enabled') ->setShortName(pht('"%s" Enabled', 'apc.stat')) ->setName(pht('"%s" Enabled in Production', 'apc.stat')) ->setSummary($summary) ->setMessage($message) ->addPHPConfig('apc.stat') ->addPhabricatorConfig('phabricator.developer-mode'); } else if (!$is_stat_enabled && $is_dev) { $summary = pht( '"%s" is currently disabled, but should probably be enabled.', 'apc.stat'); $message = pht( 'The "%s" setting is currently disabled in your PHP configuration, '. 'but this software is running in development mode. This option '. 'should normally be enabled in development so you do not need to '. 'restart anything after making changes to the code.', 'apc.stat'); $this ->newIssue('extension.apc.stat-disabled') ->setShortName(pht('"%s" Disabled', 'apc.stat')) ->setName(pht('"%s" Disabled in Development', 'apc.stat')) ->setSummary($summary) ->setMessage($message) ->addPHPConfig('apc.stat') ->addPhabricatorConfig('phabricator.developer-mode'); } } else { $this->setIsEnabled(false); $this->raiseEnableAPCIssue(); } } private function initOpcacheSpec() { $this ->setName(pht('Zend OPcache')) ->setVersion(phpversion('Zend OPcache')); if (ini_get('opcache.enable')) { $this ->setIsEnabled(true) ->setClearCacheCallback('opcache_reset'); $status = opcache_get_status(); $memory = $status['memory_usage']; $mem_used = $memory['used_memory']; $mem_free = $memory['free_memory']; $mem_junk = $memory['wasted_memory']; $this->setUsedMemory($mem_used + $mem_junk); $this->setTotalMemory($mem_used + $mem_junk + $mem_free); $this->setEntryCount($status['opcache_statistics']['num_cached_keys']); $is_dev = PhabricatorEnv::getEnvConfig('phabricator.developer-mode'); $validate = ini_get('opcache.validate_timestamps'); $freq = ini_get('opcache.revalidate_freq'); if ($is_dev && (!$validate || $freq)) { $summary = pht( 'OPcache is not configured properly for development.'); $message = pht( 'In development, OPcache should be configured to always reload '. 'code so nothing needs to be restarted after making changes. To do '. 'this, enable "%s" and set "%s" to 0.', 'opcache.validate_timestamps', 'opcache.revalidate_freq'); $this ->newIssue('extension.opcache.devmode') ->setShortName(pht('OPcache Config')) ->setName(pht('OPcache Not Configured for Development')) ->setSummary($summary) ->setMessage($message) ->addPHPConfig('opcache.validate_timestamps') ->addPHPConfig('opcache.revalidate_freq') ->addPhabricatorConfig('phabricator.developer-mode'); } else if (!$is_dev && $validate) { $summary = pht('OPcache is not configured ideally for production.'); $message = pht( 'In production, OPcache should be configured to never '. 'revalidate code. This will slightly improve performance. '. 'To do this, disable "%s" in your PHP configuration.', 'opcache.validate_timestamps'); $this ->newIssue('extension.opcache.production') ->setShortName(pht('OPcache Config')) ->setName(pht('OPcache Not Configured for Production')) ->setSummary($summary) ->setMessage($message) ->addPHPConfig('opcache.validate_timestamps') ->addPhabricatorConfig('phabricator.developer-mode'); } } else { $this->setIsEnabled(false); $summary = pht('Enabling OPcache will dramatically improve performance.'); $message = pht( 'The PHP "Zend OPcache" extension is installed, but not enabled in '. 'your PHP configuration. Enabling it will dramatically improve '. 'performance. Edit the "%s" setting to enable the extension.', 'opcache.enable'); $this->newIssue('extension.opcache.enable') ->setShortName(pht('OPcache Disabled')) ->setName(pht('Zend OPcache Not Enabled')) ->setSummary($summary) ->setMessage($message) ->addPHPConfig('opcache.enable'); } } private function initNoneSpec() { if (version_compare(phpversion(), '5.5', '>=')) { $message = pht( 'Installing the "Zend OPcache" extension will dramatically improve '. 'performance.'); $this ->newIssue('extension.opcache') ->setShortName(pht('OPcache')) ->setName(pht('Zend OPcache Not Installed')) ->setMessage($message) ->addPHPExtension('Zend OPcache'); } else { $this->raiseInstallAPCIssue(); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/cache/spec/PhabricatorCacheSpec.php
src/applications/cache/spec/PhabricatorCacheSpec.php
<?php abstract class PhabricatorCacheSpec extends Phobject { private $name; private $isEnabled = false; private $version; private $clearCacheCallback = null; private $issues = array(); private $usedMemory = 0; private $totalMemory = 0; private $entryCount = null; public function setName($name) { $this->name = $name; return $this; } public function getName() { return $this->name; } public function setIsEnabled($is_enabled) { $this->isEnabled = $is_enabled; return $this; } public function getIsEnabled() { return $this->isEnabled; } public function setVersion($version) { $this->version = $version; return $this; } public function getVersion() { return $this->version; } protected function newIssue($key) { $issue = id(new PhabricatorSetupIssue()) ->setIssueKey($key); $this->issues[$key] = $issue; return $issue; } public function getIssues() { return $this->issues; } public function setUsedMemory($used_memory) { $this->usedMemory = $used_memory; return $this; } public function getUsedMemory() { return $this->usedMemory; } public function setTotalMemory($total_memory) { $this->totalMemory = $total_memory; return $this; } public function getTotalMemory() { return $this->totalMemory; } public function setEntryCount($entry_count) { $this->entryCount = $entry_count; return $this; } public function getEntryCount() { return $this->entryCount; } protected function raiseInstallAPCIssue() { $message = pht( "Installing the PHP extension 'APC' (Alternative PHP Cache) will ". "dramatically improve performance. Note that APC versions 3.1.14 and ". "3.1.15 are broken; 3.1.13 is recommended instead."); return $this ->newIssue('extension.apc') ->setShortName(pht('APC')) ->setName(pht("PHP Extension 'APC' Not Installed")) ->setMessage($message) ->addPHPExtension('apc'); } protected function raiseEnableAPCIssue() { $summary = pht('Enabling APC/APCu will improve performance.'); $message = pht( 'The APC or APCu PHP extensions are installed, but not enabled in your '. 'PHP configuration. Enabling these extensions will improve performance. '. 'Edit the "%s" setting to enable these extensions.', 'apc.enabled'); return $this ->newIssue('extension.apc.enabled') ->setShortName(pht('APC/APCu Disabled')) ->setName(pht('APC/APCu Extensions Not Enabled')) ->setSummary($summary) ->setMessage($message) ->addPHPConfig('apc.enabled'); } public function setClearCacheCallback($callback) { $this->clearCacheCallback = $callback; return $this; } public function getClearCacheCallback() { return $this->clearCacheCallback; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/controller/PhabricatorSettingsIssueController.php
src/applications/settings/controller/PhabricatorSettingsIssueController.php
<?php final class PhabricatorSettingsIssueController extends PhabricatorController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $setup_uri = id(new PhabricatorEmailAddressesSettingsPanel()) ->setViewer($viewer) ->setUser($viewer) ->getPanelURI(); $issues = array(); if (!$viewer->getIsEmailVerified()) { // We could specifically detect that the user has missed email because // their address is unverified here and point them at Mail so they can // look at messages they missed. // We could also detect that an administrator unverified their address // and let that come with a message. // For now, just make sure the unverified address does not escape notice. $issues[] = array( 'title' => pht('Primary Email Unverified'), 'summary' => pht( 'Your primary email address is unverified. You will not be able '. 'to receive email until you verify it.'), 'uri' => $setup_uri, ); } if ($issues) { require_celerity_resource('phabricator-notification-menu-css'); $items = array(); foreach ($issues as $issue) { $classes = array(); $classes[] = 'phabricator-notification'; $classes[] = 'phabricator-notification-unread'; $uri = $issue['uri']; $title = $issue['title']; $summary = $issue['summary']; $items[] = javelin_tag( 'div', array( 'class' => 'phabricator-notification phabricator-notification-unread', 'sigil' => 'notification', 'meta' => array( 'href' => $uri, ), ), array( phutil_tag('strong', array(), pht('%s:', $title)), ' ', $summary, )); } $content = phutil_tag( 'div', array( 'class' => 'setup-issue-menu', ), $items); } else { $content = phutil_tag( 'div', array( 'class' => 'phabricator-notification no-notifications', ), pht('You have no account setup issues.')); } $header = phutil_tag( 'div', array( 'class' => 'phabricator-notification-header', ), phutil_tag( 'a', array( 'href' => $setup_uri, ), pht('Account Setup Issues'))); $content = array( $header, $content, ); $json = array( 'content' => hsprintf('%s', $content), 'number' => count($issues), ); return id(new AphrontAjaxResponse())->setContent($json); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/controller/PhabricatorSettingsAdjustController.php
src/applications/settings/controller/PhabricatorSettingsAdjustController.php
<?php final class PhabricatorSettingsAdjustController extends PhabricatorController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $preferences = PhabricatorUserPreferences::loadUserPreferences($viewer); $editor = id(new PhabricatorUserPreferencesEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true); $key = $request->getStr('key'); $value = $request->getStr('value'); $xactions = array(); $xactions[] = $preferences->newTransaction($key, $value); $editor->applyTransactions($preferences, $xactions); return id(new AphrontAjaxResponse())->setContent(array()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/controller/PhabricatorSettingsListController.php
src/applications/settings/controller/PhabricatorSettingsListController.php
<?php final class PhabricatorSettingsListController extends PhabricatorController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); // If the viewer isn't an administrator, just redirect them to their own // settings panel. if (!$viewer->getIsAdmin()) { $settings_uri = '/user/'.$viewer->getUsername().'/'; $settings_uri = $this->getApplicationURI($settings_uri); return id(new AphrontRedirectResponse()) ->setURI($settings_uri); } return id(new PhabricatorUserPreferencesSearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); $viewer = $this->getViewer(); if ($viewer->getIsAdmin()) { $builtin_global = PhabricatorUserPreferences::BUILTIN_GLOBAL_DEFAULT; $global_settings = id(new PhabricatorUserPreferencesQuery()) ->setViewer($viewer) ->withBuiltinKeys( array( $builtin_global, )) ->execute(); if (!$global_settings) { $action = id(new PHUIListItemView()) ->setName(pht('Create Global Defaults')) ->setHref('/settings/builtin/'.$builtin_global.'/') ->setIcon('fa-plus'); $crumbs->addAction($action); } } 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/settings/controller/PhabricatorSettingsTimezoneController.php
src/applications/settings/controller/PhabricatorSettingsTimezoneController.php
<?php final class PhabricatorSettingsTimezoneController extends PhabricatorController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $client_offset = $request->getURIData('offset'); $client_offset = (int)$client_offset; $timezones = DateTimeZone::listIdentifiers(); $now = new DateTime('@'.PhabricatorTime::getNow()); $options = array( 'ignore' => pht('Ignore Conflict'), ); foreach ($timezones as $identifier) { $zone = new DateTimeZone($identifier); $offset = -($zone->getOffset($now) / 60); if ($offset == $client_offset) { $name = PhabricatorTime::getTimezoneDisplayName($identifier); $options[$identifier] = $name; } } $settings_help = pht( 'You can change your date and time preferences in Settings.'); $did_calibrate = false; if ($request->isFormPost()) { $timezone = $request->getStr('timezone'); $pref_ignore = PhabricatorTimezoneIgnoreOffsetSetting::SETTINGKEY; $pref_timezone = PhabricatorTimezoneSetting::SETTINGKEY; if ($timezone == 'ignore') { $this->writeSettings( array( $pref_ignore => $client_offset, )); return $this->newDialog() ->setTitle(pht('Conflict Ignored')) ->appendParagraph( pht( 'The conflict between your browser and profile timezone '. 'settings will be ignored.')) ->appendParagraph($settings_help) ->addCancelButton('/', pht('Done')); } if (isset($options[$timezone])) { $this->writeSettings( array( $pref_ignore => null, $pref_timezone => $timezone, )); $did_calibrate = true; } } $server_offset = $viewer->getTimeZoneOffset(); if (($client_offset == $server_offset) || $did_calibrate) { return $this->newDialog() ->setTitle(pht('Timezone Calibrated')) ->appendParagraph( pht( 'Your browser timezone and profile timezone are now '. 'in agreement (%s).', $this->formatOffset($client_offset))) ->appendParagraph($settings_help) ->addCancelButton('/', pht('Done')); } // If we have a guess at the timezone from the client, select it as the // default. $guess = $request->getStr('guess'); if (empty($options[$guess])) { $guess = 'ignore'; } $current_zone = $viewer->getTimezoneIdentifier(); $current_zone = phutil_tag('strong', array(), $current_zone); $form = id(new AphrontFormView()) ->appendChild( id(new AphrontFormMarkupControl()) ->setLabel(pht('Current Setting')) ->setValue($current_zone)) ->appendChild( id(new AphrontFormSelectControl()) ->setName('timezone') ->setLabel(pht('New Setting')) ->setOptions($options) ->setValue($guess)); return $this->newDialog() ->setTitle(pht('Adjust Timezone')) ->setWidth(AphrontDialogView::WIDTH_FORM) ->appendParagraph( pht( 'Your browser timezone (%s) differs from your profile timezone '. '(%s). You can ignore this conflict or adjust your profile setting '. 'to match your client.', $this->formatOffset($client_offset), $this->formatOffset($server_offset))) ->appendForm($form) ->addCancelButton(pht('Cancel')) ->addSubmitButton(pht('Change Timezone')); } private function formatOffset($offset) { // This controller works with client-side (Javascript) offsets, which have // the opposite sign we might expect -- for example "UTC-3" is a positive // offset. Invert the sign before rendering the offset. $offset = -1 * $offset; $hours = $offset / 60; // Non-integer number of hours off UTC? if ($offset % 60) { $minutes = abs($offset % 60); return pht('UTC%+d:%02d', $hours, $minutes); } else { return pht('UTC%+d', $hours); } } private function writeSettings(array $map) { $request = $this->getRequest(); $viewer = $this->getViewer(); $preferences = PhabricatorUserPreferences::loadUserPreferences($viewer); $editor = id(new PhabricatorUserPreferencesEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true); $xactions = array(); foreach ($map as $key => $value) { $xactions[] = $preferences->newTransaction($key, $value); } $editor->applyTransactions($preferences, $xactions); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/controller/PhabricatorSettingsMainController.php
src/applications/settings/controller/PhabricatorSettingsMainController.php
<?php final class PhabricatorSettingsMainController extends PhabricatorController { private $user; private $builtinKey; private $preferences; private function getUser() { return $this->user; } private function isSelf() { $user = $this->getUser(); if (!$user) { return false; } $user_phid = $user->getPHID(); $viewer_phid = $this->getViewer()->getPHID(); return ($viewer_phid == $user_phid); } private function isTemplate() { return ($this->builtinKey !== null); } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); // Redirect "/panel/XYZ/" to the viewer's personal settings panel. This // was the primary URI before global settings were introduced and allows // generation of viewer-agnostic URIs for email and logged-out users. $panel = $request->getURIData('panel'); if ($panel) { $panel = phutil_escape_uri($panel); $username = $viewer->getUsername(); $panel_uri = "/user/{$username}/page/{$panel}/"; $panel_uri = $this->getApplicationURI($panel_uri); return id(new AphrontRedirectResponse())->setURI($panel_uri); } $username = $request->getURIData('username'); $builtin = $request->getURIData('builtin'); $key = $request->getURIData('pageKey'); if ($builtin) { $this->builtinKey = $builtin; $preferences = id(new PhabricatorUserPreferencesQuery()) ->setViewer($viewer) ->withBuiltinKeys(array($builtin)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$preferences) { $preferences = id(new PhabricatorUserPreferences()) ->attachUser(null) ->setBuiltinKey($builtin); } } else { $user = id(new PhabricatorPeopleQuery()) ->setViewer($viewer) ->withUsernames(array($username)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$user) { return new Aphront404Response(); } $preferences = PhabricatorUserPreferences::loadUserPreferences($user); $this->user = $user; } if (!$preferences) { return new Aphront404Response(); } PhabricatorPolicyFilter::requireCapability( $viewer, $preferences, PhabricatorPolicyCapability::CAN_EDIT); $this->preferences = $preferences; $panels = $this->buildPanels($preferences); $nav = $this->renderSideNav($panels); $key = $nav->selectFilter($key, head($panels)->getPanelKey()); $panel = $panels[$key] ->setController($this) ->setNavigation($nav); $response = $panel->processRequest($request); if (($response instanceof AphrontResponse) || ($response instanceof AphrontResponseProducerInterface)) { return $response; } $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($panel->getPanelName()); $crumbs->setBorder(true); if ($this->user) { $header_text = pht('Edit Settings: %s', $user->getUserName()); } else { $header_text = pht('Edit Global Settings'); } $header = id(new PHUIHeaderView()) ->setHeader($header_text); $title = $panel->getPanelName(); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter($response); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->setNavigation($nav) ->appendChild($view); } private function buildPanels(PhabricatorUserPreferences $preferences) { $viewer = $this->getViewer(); $panels = PhabricatorSettingsPanel::getAllDisplayPanels(); $result = array(); foreach ($panels as $key => $panel) { $panel ->setPreferences($preferences) ->setViewer($viewer); if ($this->user) { $panel->setUser($this->user); } if (!$panel->isEnabled()) { continue; } if ($this->isTemplate()) { if (!$panel->isTemplatePanel()) { continue; } } else { if (!$this->isSelf() && !$panel->isManagementPanel()) { continue; } if ($this->isSelf() && !$panel->isUserPanel()) { continue; } } if (!empty($result[$key])) { throw new Exception(pht( "Two settings panels share the same panel key ('%s'): %s, %s.", $key, get_class($panel), get_class($result[$key]))); } $result[$key] = $panel; } if (!$result) { throw new Exception(pht('No settings panels are available.')); } return $result; } private function renderSideNav(array $panels) { $nav = new AphrontSideNavFilterView(); if ($this->isTemplate()) { $base_uri = 'builtin/'.$this->builtinKey.'/page/'; } else { $user = $this->getUser(); $base_uri = 'user/'.$user->getUsername().'/page/'; } $nav->setBaseURI(new PhutilURI($this->getApplicationURI($base_uri))); $group_key = null; foreach ($panels as $panel) { if ($panel->getPanelGroupKey() != $group_key) { $group_key = $panel->getPanelGroupKey(); $group = $panel->getPanelGroup(); $panel_name = $group->getPanelGroupName(); if ($panel_name) { $nav->addLabel($panel_name); } } $nav->addFilter( $panel->getPanelKey(), $panel->getPanelName(), null, $panel->getPanelMenuIcon()); } return $nav; } public function buildApplicationMenu() { if ($this->preferences) { $panels = $this->buildPanels($this->preferences); return $this->renderSideNav($panels)->getMenu(); } return parent::buildApplicationMenu(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); $user = $this->getUser(); if (!$this->isSelf() && $user) { $username = $user->getUsername(); $crumbs->addTextCrumb($username, "/p/{$username}/"); } 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/settings/storage/PhabricatorUserPreferencesTransaction.php
src/applications/settings/storage/PhabricatorUserPreferencesTransaction.php
<?php final class PhabricatorUserPreferencesTransaction extends PhabricatorApplicationTransaction { const TYPE_SETTING = 'setting'; const PROPERTY_SETTING = 'setting.key'; public function getApplicationName() { return 'user'; } public function getApplicationTransactionType() { return PhabricatorUserPreferencesPHIDType::TYPECONST; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/storage/PhabricatorUserPreferences.php
src/applications/settings/storage/PhabricatorUserPreferences.php
<?php final class PhabricatorUserPreferences extends PhabricatorUserDAO implements PhabricatorPolicyInterface, PhabricatorDestructibleInterface, PhabricatorApplicationTransactionInterface { const BUILTIN_GLOBAL_DEFAULT = 'global'; protected $userPHID; protected $preferences = array(); protected $builtinKey; private $user = self::ATTACHABLE; private $defaultSettings; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'preferences' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'userPHID' => 'phid?', 'builtinKey' => 'text32?', ), self::CONFIG_KEY_SCHEMA => array( 'key_user' => array( 'columns' => array('userPHID'), 'unique' => true, ), 'key_builtin' => array( 'columns' => array('builtinKey'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorUserPreferencesPHIDType::TYPECONST); } public function getPreference($key, $default = null) { return idx($this->preferences, $key, $default); } public function setPreference($key, $value) { $this->preferences[$key] = $value; return $this; } public function unsetPreference($key) { unset($this->preferences[$key]); return $this; } public function getDefaultValue($key) { if ($this->defaultSettings) { return $this->defaultSettings->getSettingValue($key); } $setting = self::getSettingObject($key); if (!$setting) { return null; } $setting = id(clone $setting) ->setViewer($this->getUser()); return $setting->getSettingDefaultValue(); } public function getSettingValue($key) { if (array_key_exists($key, $this->preferences)) { return $this->preferences[$key]; } return $this->getDefaultValue($key); } private static function getSettingObject($key) { $settings = PhabricatorSetting::getAllSettings(); return idx($settings, $key); } public function attachDefaultSettings(PhabricatorUserPreferences $settings) { $this->defaultSettings = $settings; return $this; } public function attachUser(PhabricatorUser $user = null) { $this->user = $user; return $this; } public function getUser() { return $this->assertAttached($this->user); } public function hasManagedUser() { $user_phid = $this->getUserPHID(); if (!$user_phid) { return false; } $user = $this->getUser(); if ($user->getIsSystemAgent() || $user->getIsMailingList()) { return true; } return false; } /** * Load or create a preferences object for the given user. * * @param PhabricatorUser User to load or create preferences for. */ public static function loadUserPreferences(PhabricatorUser $user) { return id(new PhabricatorUserPreferencesQuery()) ->setViewer($user) ->withUsers(array($user)) ->needSyntheticPreferences(true) ->executeOne(); } /** * Load or create a global preferences object. * * If no global preferences exist, an empty preferences object is returned. * * @param PhabricatorUser Viewing user. */ public static function loadGlobalPreferences(PhabricatorUser $viewer) { $global = id(new PhabricatorUserPreferencesQuery()) ->setViewer($viewer) ->withBuiltinKeys( array( self::BUILTIN_GLOBAL_DEFAULT, )) ->executeOne(); if (!$global) { $global = id(new self()) ->attachUser(new PhabricatorUser()); } return $global; } public function newTransaction($key, $value) { $setting_property = PhabricatorUserPreferencesTransaction::PROPERTY_SETTING; $xaction_type = PhabricatorUserPreferencesTransaction::TYPE_SETTING; return id(clone $this->getApplicationTransactionTemplate()) ->setTransactionType($xaction_type) ->setMetadataValue($setting_property, $key) ->setNewValue($value); } public function getEditURI() { if ($this->getUser()) { return '/settings/user/'.$this->getUser()->getUsername().'/'; } else { return '/settings/builtin/'.$this->getBuiltinKey().'/'; } } public function getDisplayName() { if ($this->getBuiltinKey()) { return pht('Global Default Settings'); } return pht('Personal Settings'); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: $user_phid = $this->getUserPHID(); if ($user_phid) { return $user_phid; } return PhabricatorPolicies::getMostOpenPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: if ($this->hasManagedUser()) { return PhabricatorPolicies::POLICY_ADMIN; } $user_phid = $this->getUserPHID(); if ($user_phid) { return $user_phid; } return PhabricatorPolicies::POLICY_ADMIN; } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { if ($this->hasManagedUser()) { if ($viewer->getIsAdmin()) { return true; } } $builtin_key = $this->getBuiltinKey(); $is_global = ($builtin_key === self::BUILTIN_GLOBAL_DEFAULT); $is_view = ($capability === PhabricatorPolicyCapability::CAN_VIEW); if ($is_global && $is_view) { // NOTE: Without this policy exception, the logged-out viewer can not // see global preferences. return true; } return false; } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->delete(); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhabricatorUserPreferencesEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorUserPreferencesTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/query/PhabricatorUserPreferencesQuery.php
src/applications/settings/query/PhabricatorUserPreferencesQuery.php
<?php final class PhabricatorUserPreferencesQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $userPHIDs; private $builtinKeys; private $hasUserPHID; private $users = array(); private $synthetic; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withHasUserPHID($is_user) { $this->hasUserPHID = $is_user; return $this; } public function withUserPHIDs(array $phids) { $this->userPHIDs = $phids; return $this; } public function withUsers(array $users) { assert_instances_of($users, 'PhabricatorUser'); $this->users = mpull($users, null, 'getPHID'); $this->withUserPHIDs(array_keys($this->users)); return $this; } public function withBuiltinKeys(array $keys) { $this->builtinKeys = $keys; return $this; } /** * Always return preferences for every queried user. * * If no settings exist for a user, a new empty settings object with * appropriate defaults is returned. * * @param bool True to generate synthetic preferences for missing users. */ public function needSyntheticPreferences($synthetic) { $this->synthetic = $synthetic; return $this; } public function newResultObject() { return new PhabricatorUserPreferences(); } protected function loadPage() { $preferences = $this->loadStandardPage($this->newResultObject()); if ($this->synthetic) { $user_map = mpull($preferences, null, 'getUserPHID'); foreach ($this->userPHIDs as $user_phid) { if (isset($user_map[$user_phid])) { continue; } $preferences[] = $this->newResultObject() ->setUserPHID($user_phid); } } return $preferences; } protected function willFilterPage(array $prefs) { $user_phids = mpull($prefs, 'getUserPHID'); $user_phids = array_filter($user_phids); // If some of the preferences are attached to users, try to use any objects // we were handed first. If we're missing some, load them. if ($user_phids) { $users = $this->users; $user_phids = array_fuse($user_phids); $load_phids = array_diff_key($user_phids, $users); $load_phids = array_keys($load_phids); if ($load_phids) { $load_users = id(new PhabricatorPeopleQuery()) ->setViewer($this->getViewer()) ->withPHIDs($load_phids) ->execute(); $load_users = mpull($load_users, null, 'getPHID'); $users += $load_users; } } else { $users = array(); } $need_global = array(); foreach ($prefs as $key => $pref) { $user_phid = $pref->getUserPHID(); if (!$user_phid) { $pref->attachUser(null); continue; } $need_global[] = $pref; $user = idx($users, $user_phid); if (!$user) { $this->didRejectResult($pref); unset($prefs[$key]); continue; } $pref->attachUser($user); } // If we loaded any user preferences, load the global defaults and attach // them if they exist. if ($need_global) { $global = id(new self()) ->setViewer($this->getViewer()) ->withBuiltinKeys( array( PhabricatorUserPreferences::BUILTIN_GLOBAL_DEFAULT, )) ->executeOne(); if ($global) { foreach ($need_global as $pref) { $pref->attachDefaultSettings($global); } } } return $prefs; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'phid IN (%Ls)', $this->phids); } if ($this->userPHIDs !== null) { $where[] = qsprintf( $conn, 'userPHID IN (%Ls)', $this->userPHIDs); } if ($this->builtinKeys !== null) { $where[] = qsprintf( $conn, 'builtinKey IN (%Ls)', $this->builtinKeys); } if ($this->hasUserPHID !== null) { if ($this->hasUserPHID) { $where[] = qsprintf( $conn, 'userPHID IS NOT NULL'); } else { $where[] = qsprintf( $conn, 'userPHID IS NULL'); } } return $where; } public function getQueryApplicationClass() { return 'PhabricatorSettingsApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/query/PhabricatorUserPreferencesTransactionQuery.php
src/applications/settings/query/PhabricatorUserPreferencesTransactionQuery.php
<?php final class PhabricatorUserPreferencesTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhabricatorUserPreferencesTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/query/PhabricatorUserPreferencesSearchEngine.php
src/applications/settings/query/PhabricatorUserPreferencesSearchEngine.php
<?php final class PhabricatorUserPreferencesSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('User Preferences'); } public function getApplicationClassName() { return 'PhabricatorSettingApplication'; } public function newQuery() { return id(new PhabricatorUserPreferencesQuery()) ->withHasUserPHID(false); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); return $query; } protected function buildCustomSearchFields() { return array(); } protected function getURI($path) { return '/settings/'.$path; } protected function getBuiltinQueryNames() { $names = array( 'all' => pht('All Settings'), ); return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $settings, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($settings, 'PhabricatorUserPreferences'); $viewer = $this->requireViewer(); $list = id(new PHUIObjectItemListView()) ->setViewer($viewer); foreach ($settings as $setting) { $icon = id(new PHUIIconView()) ->setIcon('fa-globe') ->setBackground('bg-sky'); $item = id(new PHUIObjectItemView()) ->setHeader($setting->getDisplayName()) ->setHref($setting->getEditURI()) ->setImageIcon($icon) ->addAttribute(pht('Edit global default settings for all users.')); $list->addItem($item); } $list->addItem( id(new PHUIObjectItemView()) ->setHeader(pht('Personal Account Settings')) ->addAttribute(pht('Edit settings for your personal account.')) ->setImageURI($viewer->getProfileImageURI()) ->setHref('/settings/user/'.$viewer->getUsername().'/')); return id(new PhabricatorApplicationSearchResultView()) ->setObjectList($list); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/action/PhabricatorSettingsAddEmailAction.php
src/applications/settings/action/PhabricatorSettingsAddEmailAction.php
<?php final class PhabricatorSettingsAddEmailAction extends PhabricatorSystemAction { const TYPECONST = 'email.add'; public function getScoreThreshold() { return 6 / phutil_units('1 hour in seconds'); } public function getLimitExplanation() { return pht( 'You are adding too many email addresses to your account too quickly.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/editor/PhabricatorUserPreferencesEditor.php
src/applications/settings/editor/PhabricatorUserPreferencesEditor.php
<?php final class PhabricatorUserPreferencesEditor extends PhabricatorApplicationTransactionEditor { public function getEditorApplicationClass() { return 'PhabricatorSettingsApplication'; } public function getEditorObjectsDescription() { return pht('Settings'); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorUserPreferencesTransaction::TYPE_SETTING; return $types; } protected function expandTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { $setting_key = $xaction->getMetadataValue( PhabricatorUserPreferencesTransaction::PROPERTY_SETTING); $settings = $this->getSettings(); $setting = idx($settings, $setting_key); if ($setting) { return $setting->expandSettingTransaction($object, $xaction); } return parent::expandTransaction($object, $xaction); } protected function getCustomTransactionOldValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { $setting_key = $xaction->getMetadataValue( PhabricatorUserPreferencesTransaction::PROPERTY_SETTING); switch ($xaction->getTransactionType()) { case PhabricatorUserPreferencesTransaction::TYPE_SETTING: return $object->getPreference($setting_key); } return parent::getCustomTransactionOldValue($object, $xaction); } protected function getCustomTransactionNewValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { $actor = $this->getActor(); $setting_key = $xaction->getMetadataValue( PhabricatorUserPreferencesTransaction::PROPERTY_SETTING); $settings = PhabricatorSetting::getAllEnabledSettings($actor); $setting = $settings[$setting_key]; switch ($xaction->getTransactionType()) { case PhabricatorUserPreferencesTransaction::TYPE_SETTING: $value = $xaction->getNewValue(); $value = $setting->getTransactionNewValue($value); return $value; } return parent::getCustomTransactionNewValue($object, $xaction); } protected function applyCustomInternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { $setting_key = $xaction->getMetadataValue( PhabricatorUserPreferencesTransaction::PROPERTY_SETTING); switch ($xaction->getTransactionType()) { case PhabricatorUserPreferencesTransaction::TYPE_SETTING: $new_value = $xaction->getNewValue(); if ($new_value === null) { $object->unsetPreference($setting_key); } else { $object->setPreference($setting_key, $new_value); } return; } return parent::applyCustomInternalTransaction($object, $xaction); } protected function applyCustomExternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorUserPreferencesTransaction::TYPE_SETTING: return; } return parent::applyCustomExternalTransaction($object, $xaction); } protected function validateTransaction( PhabricatorLiskDAO $object, $type, array $xactions) { $errors = parent::validateTransaction($object, $type, $xactions); $settings = $this->getSettings(); switch ($type) { case PhabricatorUserPreferencesTransaction::TYPE_SETTING: foreach ($xactions as $xaction) { $setting_key = $xaction->getMetadataValue( PhabricatorUserPreferencesTransaction::PROPERTY_SETTING); $setting = idx($settings, $setting_key); if (!$setting) { $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), pht( 'There is no known application setting with key "%s".', $setting_key), $xaction); continue; } try { $setting->validateTransactionValue($xaction->getNewValue()); } catch (Exception $ex) { $errors[] = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), $ex->getMessage(), $xaction); } } break; } return $errors; } protected function applyFinalEffects( PhabricatorLiskDAO $object, array $xactions) { $user_phid = $object->getUserPHID(); if ($user_phid) { PhabricatorUserCache::clearCache( PhabricatorUserPreferencesCacheType::KEY_PREFERENCES, $user_phid); } else { $cache = PhabricatorCaches::getMutableStructureCache(); $cache->deleteKey(PhabricatorUser::getGlobalSettingsCacheKey()); PhabricatorUserCache::clearCacheForAllUsers( PhabricatorUserPreferencesCacheType::KEY_PREFERENCES); } return $xactions; } private function getSettings() { $actor = $this->getActor(); $settings = PhabricatorSetting::getAllEnabledSettings($actor); foreach ($settings as $key => $setting) { $setting = clone $setting; $setting->setViewer($actor); $settings[$key] = $setting; } return $settings; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/editor/PhabricatorSettingsEditEngine.php
src/applications/settings/editor/PhabricatorSettingsEditEngine.php
<?php final class PhabricatorSettingsEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'settings.settings'; private $isSelfEdit; private $profileURI; private $settingsPanel; public function setIsSelfEdit($is_self_edit) { $this->isSelfEdit = $is_self_edit; return $this; } public function getIsSelfEdit() { return $this->isSelfEdit; } public function setProfileURI($profile_uri) { $this->profileURI = $profile_uri; return $this; } public function getProfileURI() { return $this->profileURI; } public function setSettingsPanel($settings_panel) { $this->settingsPanel = $settings_panel; return $this; } public function getSettingsPanel() { return $this->settingsPanel; } public function isEngineConfigurable() { return false; } public function getEngineName() { return pht('Settings'); } public function getSummaryHeader() { return pht('Edit Settings Configurations'); } public function getSummaryText() { return pht('This engine is used to edit settings.'); } public function getEngineApplicationClass() { return 'PhabricatorSettingsApplication'; } protected function newEditableObject() { return new PhabricatorUserPreferences(); } protected function newObjectQuery() { return new PhabricatorUserPreferencesQuery(); } protected function getObjectCreateTitleText($object) { return pht('Create Settings'); } protected function getObjectCreateButtonText($object) { return pht('Create Settings'); } protected function getObjectEditTitleText($object) { $page = $this->getSelectedPage(); if ($page) { return $page->getLabel(); } return pht('Settings'); } protected function getObjectEditShortText($object) { if (!$object->getUser()) { return pht('Global Defaults'); } else { if ($this->getIsSelfEdit()) { return pht('Personal Settings'); } else { return pht('Account Settings'); } } } protected function getObjectCreateShortText() { return pht('Create Settings'); } protected function getObjectName() { $page = $this->getSelectedPage(); if ($page) { return $page->getLabel(); } return pht('Settings'); } protected function getPageHeader($object) { $user = $object->getUser(); if ($user) { $text = pht('Edit Settings: %s', $user->getUserName()); } else { $text = pht('Edit Global Settings'); } $header = id(new PHUIHeaderView()) ->setHeader($text); return $header; } protected function getEditorURI() { throw new PhutilMethodNotImplementedException(); } protected function getObjectCreateCancelURI($object) { return '/settings/'; } protected function getObjectViewURI($object) { return $object->getEditURI(); } protected function getCreateNewObjectPolicy() { return PhabricatorPolicies::POLICY_ADMIN; } public function getEffectiveObjectEditCancelURI($object) { if (!$object->getUser()) { return '/settings/'; } if ($this->getIsSelfEdit()) { return null; } if ($this->getProfileURI()) { return $this->getProfileURI(); } return parent::getEffectiveObjectEditCancelURI($object); } protected function newPages($object) { $viewer = $this->getViewer(); $user = $object->getUser(); $panels = PhabricatorSettingsPanel::getAllDisplayPanels(); foreach ($panels as $key => $panel) { if (!($panel instanceof PhabricatorEditEngineSettingsPanel)) { unset($panels[$key]); continue; } $panel->setViewer($viewer); if ($user) { $panel->setUser($user); } } $pages = array(); $uris = array(); foreach ($panels as $key => $panel) { $uris[$key] = $panel->getPanelURI(); $page = $panel->newEditEnginePage(); if (!$page) { continue; } $pages[] = $page; } $more_pages = array( id(new PhabricatorEditPage()) ->setKey('extra') ->setLabel(pht('Extra Settings')) ->setIsDefault(true), ); foreach ($more_pages as $page) { $pages[] = $page; } return $pages; } protected function buildCustomEditFields($object) { $viewer = $this->getViewer(); $settings = PhabricatorSetting::getAllEnabledSettings($viewer); foreach ($settings as $key => $setting) { $setting = clone $setting; $setting->setViewer($viewer); $settings[$key] = $setting; } $settings = msortv($settings, 'getSettingOrderVector'); $fields = array(); foreach ($settings as $setting) { foreach ($setting->newCustomEditFields($object) as $field) { $fields[] = $field; } } return $fields; } protected function getValidationExceptionShortMessage( PhabricatorApplicationTransactionValidationException $ex, PhabricatorEditField $field) { // Settings fields all have the same transaction type so we need to make // sure the transaction is changing the same setting before matching an // error to a given field. $xaction_type = $field->getTransactionType(); if ($xaction_type == PhabricatorUserPreferencesTransaction::TYPE_SETTING) { $property = PhabricatorUserPreferencesTransaction::PROPERTY_SETTING; $field_setting = idx($field->getMetadata(), $property); foreach ($ex->getErrors() as $error) { if ($error->getType() !== $xaction_type) { continue; } $xaction = $error->getTransaction(); if (!$xaction) { continue; } $xaction_setting = $xaction->getMetadataValue($property); if ($xaction_setting != $field_setting) { continue; } $short_message = $error->getShortMessage(); if ($short_message !== null) { return $short_message; } } return null; } return parent::getValidationExceptionShortMessage($ex, $field); } protected function newEditFormHeadContent( PhabricatorEditEnginePageState $state) { $content = array(); if ($state->getIsSave()) { $content[] = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->appendChild(pht('Changes saved.')); } $panel = $this->getSettingsPanel(); $content[] = $panel->newSettingsPanelEditFormHeadContent($state); return $content; } protected function newEditFormTailContent( PhabricatorEditEnginePageState $state) { $content = array(); $panel = $this->getSettingsPanel(); $content[] = $panel->newSettingsPanelEditFormTailContent($state); 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/settings/panel/PhabricatorDiffPreferencesSettingsPanel.php
src/applications/settings/panel/PhabricatorDiffPreferencesSettingsPanel.php
<?php final class PhabricatorDiffPreferencesSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'diff'; public function getPanelName() { return pht('Diff Preferences'); } public function getPanelMenuIcon() { return 'fa-cog'; } public function getPanelGroupKey() { return PhabricatorSettingsApplicationsPanelGroup::PANELGROUPKEY; } public function isTemplatePanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorNotificationsSettingsPanel.php
src/applications/settings/panel/PhabricatorNotificationsSettingsPanel.php
<?php final class PhabricatorNotificationsSettingsPanel extends PhabricatorSettingsPanel { public function isEnabled() { $servers = PhabricatorNotificationServerRef::getEnabledAdminServers(); if (!$servers) { return false; } return PhabricatorApplication::isClassInstalled( 'PhabricatorNotificationsApplication'); } public function getPanelKey() { return 'notifications'; } public function getPanelName() { return pht('Notifications'); } public function getPanelMenuIcon() { return 'fa-bell-o'; } public function getPanelGroupKey() { return PhabricatorSettingsApplicationsPanelGroup::PANELGROUPKEY; } public function processRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $preferences = $this->getPreferences(); $notifications_key = PhabricatorNotificationsSetting::SETTINGKEY; $notifications_value = $preferences->getSettingValue($notifications_key); if ($request->isFormPost()) { $this->writeSetting( $preferences, $notifications_key, $request->getInt($notifications_key)); return id(new AphrontRedirectResponse()) ->setURI($this->getPanelURI('?saved=true')); } $title = pht('Notifications'); $control_id = celerity_generate_unique_node_id(); $status_id = celerity_generate_unique_node_id(); $browser_status_id = celerity_generate_unique_node_id(); $cancel_ask = pht( 'The dialog asking for permission to send desktop notifications was '. 'closed without granting permission. Only application notifications '. 'will be sent.'); $accept_ask = pht( 'Click "Save Preference" to persist these changes.'); $reject_ask = pht( 'Permission for desktop notifications was denied. Only application '. 'notifications will be sent.'); $no_support = pht( 'This web browser does not support desktop notifications. Only '. 'application notifications will be sent for this browser regardless of '. 'this preference.'); $default_status = phutil_tag( 'span', array(), array( pht( 'Your browser has not yet granted this server permission to send '. 'desktop notifications.'), phutil_tag('br'), phutil_tag('br'), javelin_tag( 'button', array( 'sigil' => 'desktop-notifications-permission-button', 'class' => 'green', ), pht('Grant Permission')), )); $granted_status = phutil_tag( 'span', array(), pht('Your browser has granted this server permission to send desktop '. 'notifications.')); $denied_status = phutil_tag( 'span', array(), pht('This browser has denied permission to send desktop notifications '. 'to this server. Consult your browser settings / '. 'documentation to figure out how to clear this setting, do so, '. 'and then re-visit this page to grant permission.')); $message_id = celerity_generate_unique_node_id(); $message_container = phutil_tag( 'span', array( 'id' => $message_id, )); $saved_box = null; if ($request->getBool('saved')) { $saved_box = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->appendChild(pht('Changes saved.')); } $status_box = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->setID($status_id) ->setIsHidden(true) ->appendChild($message_container); $status_box = id(new PHUIBoxView()) ->addClass('mll mlr') ->appendChild($status_box); $control_config = array( 'controlID' => $control_id, 'statusID' => $status_id, 'messageID' => $message_id, 'browserStatusID' => $browser_status_id, 'defaultMode' => 0, 'desktop' => 1, 'desktopOnly' => 2, 'cancelAsk' => $cancel_ask, 'grantedAsk' => $accept_ask, 'deniedAsk' => $reject_ask, 'defaultStatus' => $default_status, 'deniedStatus' => $denied_status, 'grantedStatus' => $granted_status, 'noSupport' => $no_support, ); $form = id(new AphrontFormView()) ->setUser($viewer) ->appendChild( id(new AphrontFormSelectControl()) ->setLabel($title) ->setControlID($control_id) ->setName($notifications_key) ->setValue($notifications_value) ->setOptions(PhabricatorNotificationsSetting::getOptionsMap()) ->setCaption( pht( 'This server can send real-time notifications to your web browser '. 'or to your desktop. Select where you want to receive these '. 'real-time updates.')) ->initBehavior( 'desktop-notifications-control', $control_config)) ->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Save Preference'))); $button = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-send-o') ->setWorkflow(true) ->setText(pht('Send Test Notification')) ->setHref('/notification/test/') ->setColor(PHUIButtonView::GREY); $form_content = array($saved_box, $status_box, $form); $form_box = $this->newBox( pht('Notifications'), $form_content, array($button)); $browser_status_box = id(new PHUIInfoView()) ->setID($browser_status_id) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->setIsHidden(true) ->appendChild($default_status); return array( $form_box, $browser_status_box, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorDateTimeSettingsPanel.php
src/applications/settings/panel/PhabricatorDateTimeSettingsPanel.php
<?php final class PhabricatorDateTimeSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'datetime'; public function getPanelName() { return pht('Date and Time'); } public function getPanelMenuIcon() { return 'fa-calendar'; } public function getPanelGroupKey() { return PhabricatorSettingsAccountPanelGroup::PANELGROUPKEY; } public function isManagementPanel() { return true; } public function isTemplatePanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorActivitySettingsPanel.php
src/applications/settings/panel/PhabricatorActivitySettingsPanel.php
<?php final class PhabricatorActivitySettingsPanel extends PhabricatorSettingsPanel { public function getPanelKey() { return 'activity'; } public function getPanelName() { return pht('Activity Logs'); } public function getPanelMenuIcon() { return 'fa-list'; } public function getPanelGroupKey() { return PhabricatorSettingsLogsPanelGroup::PANELGROUPKEY; } public function processRequest(AphrontRequest $request) { $viewer = $request->getUser(); $user = $this->getUser(); $pager = id(new AphrontCursorPagerView()) ->readFromRequest($request); $logs = id(new PhabricatorPeopleLogQuery()) ->setViewer($viewer) ->withRelatedPHIDs(array($user->getPHID())) ->executeWithCursorPager($pager); $table = id(new PhabricatorUserLogView()) ->setUser($viewer) ->setLogs($logs); $panel = $this->newBox(pht('Account Activity Logs'), $table); $pager_box = id(new PHUIBoxView()) ->addMargin(PHUI::MARGIN_LARGE) ->appendChild($pager); return array($panel, $pager_box); } public function isManagementPanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorDisplayPreferencesSettingsPanel.php
src/applications/settings/panel/PhabricatorDisplayPreferencesSettingsPanel.php
<?php final class PhabricatorDisplayPreferencesSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'display'; public function getPanelName() { return pht('Display Preferences'); } public function getPanelMenuIcon() { return 'fa-desktop'; } public function getPanelGroupKey() { return PhabricatorSettingsApplicationsPanelGroup::PANELGROUPKEY; } public function isTemplatePanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorSessionsSettingsPanel.php
src/applications/settings/panel/PhabricatorSessionsSettingsPanel.php
<?php final class PhabricatorSessionsSettingsPanel extends PhabricatorSettingsPanel { public function getPanelKey() { return 'sessions'; } public function getPanelName() { return pht('Sessions'); } public function getPanelMenuIcon() { return 'fa-user'; } public function getPanelGroupKey() { return PhabricatorSettingsLogsPanelGroup::PANELGROUPKEY; } public function isEnabled() { return true; } public function processRequest(AphrontRequest $request) { $viewer = $request->getUser(); $accounts = id(new PhabricatorExternalAccountQuery()) ->setViewer($viewer) ->withUserPHIDs(array($viewer->getPHID())) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->execute(); $identity_phids = mpull($accounts, 'getPHID'); $identity_phids[] = $viewer->getPHID(); $sessions = id(new PhabricatorAuthSessionQuery()) ->setViewer($viewer) ->withIdentityPHIDs($identity_phids) ->execute(); $handles = id(new PhabricatorHandleQuery()) ->setViewer($viewer) ->withPHIDs($identity_phids) ->execute(); $current_key = PhabricatorAuthSession::newSessionDigest( new PhutilOpaqueEnvelope( $request->getCookie(PhabricatorCookies::COOKIE_SESSION))); $rows = array(); $rowc = array(); foreach ($sessions as $session) { $is_current = phutil_hashes_are_identical( $session->getSessionKey(), $current_key); if ($is_current) { $rowc[] = 'highlighted'; $button = phutil_tag( 'a', array( 'class' => 'small button button-grey disabled', ), pht('Current')); } else { $rowc[] = null; $button = javelin_tag( 'a', array( 'href' => '/auth/session/terminate/'.$session->getID().'/', 'class' => 'small button button-grey', 'sigil' => 'workflow', ), pht('Terminate')); } $hisec = ($session->getHighSecurityUntil() - time()); $rows[] = array( $handles[$session->getUserPHID()]->renderLink(), substr($session->getSessionKey(), 0, 6), $session->getType(), ($hisec > 0) ? phutil_format_relative_time($hisec) : null, phabricator_datetime($session->getSessionStart(), $viewer), phabricator_date($session->getSessionExpires(), $viewer), $button, ); } $table = new AphrontTableView($rows); $table->setNoDataString(pht("You don't have any active sessions.")); $table->setRowClasses($rowc); $table->setHeaders( array( pht('Identity'), pht('Session'), pht('Type'), pht('HiSec'), pht('Created'), pht('Expires'), pht(''), )); $table->setColumnClasses( array( 'wide', 'n', '', 'right', 'right', 'right', 'action', )); $buttons = array(); $buttons[] = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-warning') ->setText(pht('Terminate All Sessions')) ->setHref('/auth/session/terminate/all/') ->setWorkflow(true) ->setColor(PHUIButtonView::RED); $hisec = ($viewer->getSession()->getHighSecurityUntil() - time()); if ($hisec > 0) { $buttons[] = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-lock') ->setText(pht('Leave High Security')) ->setHref('/auth/session/downgrade/') ->setWorkflow(true) ->setColor(PHUIButtonView::RED); } return $this->newBox(pht('Active Login Sessions'), $table, $buttons); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorLanguageSettingsPanel.php
src/applications/settings/panel/PhabricatorLanguageSettingsPanel.php
<?php final class PhabricatorLanguageSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'language'; public function getPanelName() { return pht('Language'); } public function getPanelMenuIcon() { return 'fa-globe'; } public function getPanelGroupKey() { return PhabricatorSettingsAccountPanelGroup::PANELGROUPKEY; } public function isManagementPanel() { return true; } public function isTemplatePanel() { return true; } public function isMultiFactorEnrollmentPanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorEmailAddressesSettingsPanel.php
src/applications/settings/panel/PhabricatorEmailAddressesSettingsPanel.php
<?php final class PhabricatorEmailAddressesSettingsPanel extends PhabricatorSettingsPanel { public function getPanelKey() { return 'email'; } public function getPanelName() { return pht('Email Addresses'); } public function getPanelMenuIcon() { return 'fa-at'; } public function getPanelGroupKey() { return PhabricatorSettingsEmailPanelGroup::PANELGROUPKEY; } public function isEditableByAdministrators() { if ($this->getUser()->getIsMailingList()) { return true; } return false; } public function processRequest(AphrontRequest $request) { $user = $this->getUser(); $editable = PhabricatorEnv::getEnvConfig('account.editable'); $uri = new PhutilURI($request->getPath()); if ($editable) { $new = $request->getStr('new'); if ($new) { return $this->returnNewAddressResponse($request, $uri, $new); } $delete = $request->getInt('delete'); if ($delete) { return $this->returnDeleteAddressResponse($request, $uri, $delete); } } $verify = $request->getInt('verify'); if ($verify) { return $this->returnVerifyAddressResponse($request, $uri, $verify); } $primary = $request->getInt('primary'); if ($primary) { return $this->returnPrimaryAddressResponse($request, $uri, $primary); } $emails = id(new PhabricatorUserEmail())->loadAllWhere( 'userPHID = %s ORDER BY address', $user->getPHID()); $rowc = array(); $rows = array(); foreach ($emails as $email) { $button_verify = javelin_tag( 'a', array( 'class' => 'button small button-grey', 'href' => $uri->alter('verify', $email->getID()), 'sigil' => 'workflow', ), pht('Verify')); $button_make_primary = javelin_tag( 'a', array( 'class' => 'button small button-grey', 'href' => $uri->alter('primary', $email->getID()), 'sigil' => 'workflow', ), pht('Make Primary')); $button_remove = javelin_tag( 'a', array( 'class' => 'button small button-grey', 'href' => $uri->alter('delete', $email->getID()), 'sigil' => 'workflow', ), pht('Remove')); $button_primary = phutil_tag( 'a', array( 'class' => 'button small disabled', ), pht('Primary')); if (!$email->getIsVerified()) { $action = $button_verify; } else if ($email->getIsPrimary()) { $action = $button_primary; } else { $action = $button_make_primary; } if ($email->getIsPrimary()) { $remove = $button_primary; $rowc[] = 'highlighted'; } else { $remove = $button_remove; $rowc[] = null; } $rows[] = array( $email->getAddress(), $action, $remove, ); } $table = new AphrontTableView($rows); $table->setHeaders( array( pht('Email'), pht('Status'), pht('Remove'), )); $table->setColumnClasses( array( 'wide', 'action', 'action', )); $table->setRowClasses($rowc); $table->setColumnVisibility( array( true, true, $editable, )); $buttons = array(); if ($editable) { $buttons[] = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-plus') ->setText(pht('Add New Address')) ->setHref($uri->alter('new', 'true')) ->addSigil('workflow') ->setColor(PHUIButtonView::GREY); } return $this->newBox(pht('Email Addresses'), $table, $buttons); } private function returnNewAddressResponse( AphrontRequest $request, PhutilURI $uri, $new) { $user = $this->getUser(); $viewer = $this->getViewer(); $token = id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession( $viewer, $request, $this->getPanelURI()); $e_email = true; $email = null; $errors = array(); if ($request->isDialogFormPost()) { $email = $request->getStr('email'); if (phutil_nonempty_string($email)) { $email = trim($email); } if ($new == 'verify') { // The user clicked "Done" from the "an email has been sent" dialog. return id(new AphrontReloadResponse())->setURI($uri); } PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorSettingsAddEmailAction(), 1); if ($email === null || !strlen($email)) { $e_email = pht('Required'); $errors[] = pht('Email is required.'); } else if (!PhabricatorUserEmail::isValidAddress($email)) { $e_email = pht('Invalid'); $errors[] = PhabricatorUserEmail::describeValidAddresses(); } else if (!PhabricatorUserEmail::isAllowedAddress($email)) { $e_email = pht('Disallowed'); $errors[] = PhabricatorUserEmail::describeAllowedAddresses(); } if ($e_email === true) { $application_email = id(new PhabricatorMetaMTAApplicationEmailQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withAddresses(array($email)) ->executeOne(); if ($application_email) { $e_email = pht('In Use'); $errors[] = $application_email->getInUseMessage(); } } if (!$errors) { $object = id(new PhabricatorUserEmail()) ->setAddress($email) ->setIsVerified(0); // If an administrator is editing a mailing list, automatically verify // the address. if ($viewer->getPHID() != $user->getPHID()) { if ($viewer->getIsAdmin()) { $object->setIsVerified(1); } } try { id(new PhabricatorUserEditor()) ->setActor($viewer) ->addEmail($user, $object); if ($object->getIsVerified()) { // If we autoverified the address, just reload the page. return id(new AphrontReloadResponse())->setURI($uri); } $object->sendVerificationEmail($user); $dialog = $this->newDialog() ->addHiddenInput('new', 'verify') ->setTitle(pht('Verification Email Sent')) ->appendChild(phutil_tag('p', array(), pht( 'A verification email has been sent. Click the link in the '. 'email to verify your address.'))) ->setSubmitURI($uri) ->addSubmitButton(pht('Done')); return id(new AphrontDialogResponse())->setDialog($dialog); } catch (AphrontDuplicateKeyQueryException $ex) { $e_email = pht('Duplicate'); $errors[] = pht('Another user already has this email.'); } } } if ($errors) { $errors = id(new PHUIInfoView()) ->setErrors($errors); } $form = id(new PHUIFormLayoutView()) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Email')) ->setName('email') ->setValue($email) ->setCaption(PhabricatorUserEmail::describeAllowedAddresses()) ->setError($e_email)); $dialog = $this->newDialog() ->addHiddenInput('new', 'true') ->setTitle(pht('New Address')) ->appendChild($errors) ->appendChild($form) ->addSubmitButton(pht('Save')) ->addCancelButton($uri); return id(new AphrontDialogResponse())->setDialog($dialog); } private function returnDeleteAddressResponse( AphrontRequest $request, PhutilURI $uri, $email_id) { $user = $this->getUser(); $viewer = $this->getViewer(); $token = id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession( $viewer, $request, $this->getPanelURI()); // NOTE: You can only delete your own email addresses, and you can not // delete your primary address. $email = id(new PhabricatorUserEmail())->loadOneWhere( 'id = %d AND userPHID = %s AND isPrimary = 0', $email_id, $user->getPHID()); if (!$email) { return new Aphront404Response(); } if ($request->isFormPost()) { id(new PhabricatorUserEditor()) ->setActor($viewer) ->removeEmail($user, $email); return id(new AphrontRedirectResponse())->setURI($uri); } $address = $email->getAddress(); $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->addHiddenInput('delete', $email_id) ->setTitle(pht("Really delete address '%s'?", $address)) ->appendParagraph( pht( 'Are you sure you want to delete this address? You will no '. 'longer be able to use it to login.')) ->appendParagraph( pht( 'Note: Removing an email address from your account will invalidate '. 'any outstanding password reset links.')) ->addSubmitButton(pht('Delete')) ->addCancelButton($uri); return id(new AphrontDialogResponse())->setDialog($dialog); } private function returnVerifyAddressResponse( AphrontRequest $request, PhutilURI $uri, $email_id) { $user = $this->getUser(); $viewer = $this->getViewer(); // NOTE: You can only send more email for your unverified addresses. $email = id(new PhabricatorUserEmail())->loadOneWhere( 'id = %d AND userPHID = %s AND isVerified = 0', $email_id, $user->getPHID()); if (!$email) { return new Aphront404Response(); } if ($request->isFormPost()) { $email->sendVerificationEmail($user); return id(new AphrontRedirectResponse())->setURI($uri); } $address = $email->getAddress(); $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->addHiddenInput('verify', $email_id) ->setTitle(pht('Send Another Verification Email?')) ->appendChild(phutil_tag('p', array(), pht( 'Send another copy of the verification email to %s?', $address))) ->addSubmitButton(pht('Send Email')) ->addCancelButton($uri); return id(new AphrontDialogResponse())->setDialog($dialog); } private function returnPrimaryAddressResponse( AphrontRequest $request, PhutilURI $uri, $email_id) { $user = $this->getUser(); $viewer = $this->getViewer(); $token = id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession( $viewer, $request, $this->getPanelURI()); // NOTE: You can only make your own verified addresses primary. $email = id(new PhabricatorUserEmail())->loadOneWhere( 'id = %d AND userPHID = %s AND isVerified = 1 AND isPrimary = 0', $email_id, $user->getPHID()); if (!$email) { return new Aphront404Response(); } if ($request->isFormPost()) { id(new PhabricatorUserEditor()) ->setActor($viewer) ->changePrimaryEmail($user, $email); return id(new AphrontRedirectResponse())->setURI($uri); } $address = $email->getAddress(); $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->addHiddenInput('primary', $email_id) ->setTitle(pht('Change primary email address?')) ->appendParagraph( pht( 'If you change your primary address, %s will send all '. 'email to %s.', PlatformSymbols::getPlatformServerName(), $address)) ->appendParagraph( pht( 'Note: Changing your primary email address will invalidate any '. 'outstanding password reset links.')) ->addSubmitButton(pht('Change Primary Address')) ->addCancelButton($uri); return id(new AphrontDialogResponse())->setDialog($dialog); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorEmailDeliverySettingsPanel.php
src/applications/settings/panel/PhabricatorEmailDeliverySettingsPanel.php
<?php final class PhabricatorEmailDeliverySettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'emaildelivery'; public function getPanelName() { return pht('Email Delivery'); } public function getPanelMenuIcon() { return 'fa-envelope-o'; } public function getPanelGroupKey() { return PhabricatorSettingsEmailPanelGroup::PANELGROUPKEY; } public function isManagementPanel() { if ($this->getUser()->getIsMailingList()) { return true; } return false; } public function isTemplatePanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorDeveloperPreferencesSettingsPanel.php
src/applications/settings/panel/PhabricatorDeveloperPreferencesSettingsPanel.php
<?php final class PhabricatorDeveloperPreferencesSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'developer'; public function getPanelName() { return pht('Developer Settings'); } public function getPanelMenuIcon() { return 'fa-magic'; } public function getPanelGroupKey() { return PhabricatorSettingsDeveloperPanelGroup::PANELGROUPKEY; } public function isTemplatePanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorExternalEditorSettingsPanel.php
src/applications/settings/panel/PhabricatorExternalEditorSettingsPanel.php
<?php final class PhabricatorExternalEditorSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'editor'; public function getPanelName() { return pht('External Editor'); } public function getPanelMenuIcon() { return 'fa-i-cursor'; } public function getPanelGroupKey() { return PhabricatorSettingsApplicationsPanelGroup::PANELGROUPKEY; } public function isTemplatePanel() { return true; } public function newSettingsPanelEditFormHeadContent( PhabricatorEditEnginePageState $state) { // The "Editor" setting stored in the database may be invalidated by // configuration or software changes. If a saved URI becomes invalid // (for example, its protocol is removed from the list of allowed // protocols), it will stop working. // If the stored value has a problem like this, show a static error // message without requiring the user to save changes. if ($state->getIsSubmit()) { return null; } $viewer = $this->getViewer(); $pattern = $viewer->getUserSetting(PhabricatorEditorSetting::SETTINGKEY); if ($pattern === null || !strlen($pattern)) { return null; } $caught = null; try { id(new PhabricatorEditorURIEngine()) ->setPattern($pattern) ->validatePattern(); } catch (PhabricatorEditorURIParserException $ex) { $caught = $ex; } if (!$caught) { return null; } return id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->appendChild($caught->getMessage()); } public function newSettingsPanelEditFormTailContent( PhabricatorEditEnginePageState $state) { $viewer = $this->getViewer(); $variables = PhabricatorEditorURIEngine::getVariableDefinitions(); $rows = array(); foreach ($variables as $key => $variable) { $rows[] = array( phutil_tag('tt', array(), '%'.$key), $variable['name'], $variable['example'], ); } $table = id(new AphrontTableView($rows)) ->setHeaders( array( pht('Variable'), pht('Replaced With'), pht('Example'), )) ->setColumnClasses( array( 'center', 'pri', 'wide', )); $variables_box = id(new PHUIObjectBoxView()) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setHeaderText(pht('External Editor URI Variables')) ->setTable($table); $label_map = array( 'http' => pht('Hypertext Transfer Protocol'), 'https' => pht('Hypertext Transfer Protocol over SSL'), 'txmt' => pht('TextMate'), 'mvim' => pht('MacVim'), 'subl' => pht('Sublime Text'), 'vim' => pht('Vim'), 'emacs' => pht('Emacs'), 'vscode' => pht('Visual Studio Code'), 'editor' => pht('Generic Editor'), 'idea' => pht('IntelliJ IDEA'), ); $default_label = phutil_tag('em', array(), pht('Supported Protocol')); $config_key = 'uri.allowed-editor-protocols'; $protocols = PhabricatorEnv::getEnvConfig($config_key); $protocols = array_keys($protocols); sort($protocols); $protocol_rows = array(); foreach ($protocols as $protocol) { $label = idx($label_map, $protocol, $default_label); $protocol_rows[] = array( $protocol.'://', $label, ); } $protocol_table = id(new AphrontTableView($protocol_rows)) ->setNoDataString( pht( 'No allowed editor protocols are configured.')) ->setHeaders( array( pht('Protocol'), pht('Description'), )) ->setColumnClasses( array( 'pri', 'wide', )); $is_admin = $viewer->getIsAdmin(); $configure_button = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('View Configuration')) ->setIcon('fa-sliders') ->setHref( urisprintf( '/config/edit/%s/', $config_key)) ->setDisabled(!$is_admin); $protocol_header = id(new PHUIHeaderView()) ->setHeader(pht('Supported Editor Protocols')) ->addActionLink($configure_button); $protocols_box = id(new PHUIObjectBoxView()) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setHeader($protocol_header) ->setTable($protocol_table); return array( $variables_box, $protocols_box, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorTokensSettingsPanel.php
src/applications/settings/panel/PhabricatorTokensSettingsPanel.php
<?php final class PhabricatorTokensSettingsPanel extends PhabricatorSettingsPanel { public function getPanelKey() { return 'tokens'; } public function getPanelName() { return pht('Temporary Tokens'); } public function getPanelMenuIcon() { return 'fa-ticket'; } public function getPanelGroupKey() { return PhabricatorSettingsLogsPanelGroup::PANELGROUPKEY; } public function processRequest(AphrontRequest $request) { $viewer = $request->getUser(); $tokens = id(new PhabricatorAuthTemporaryTokenQuery()) ->setViewer($viewer) ->withTokenResources(array($viewer->getPHID())) ->execute(); $rows = array(); foreach ($tokens as $token) { if ($token->isRevocable()) { $button = javelin_tag( 'a', array( 'href' => '/auth/token/revoke/'.$token->getID().'/', 'class' => 'small button button-grey', 'sigil' => 'workflow', ), pht('Revoke')); } else { $button = javelin_tag( 'a', array( 'class' => 'small button button-grey disabled', ), pht('Revoke')); } if ($token->getTokenExpires() >= time()) { $expiry = phabricator_datetime($token->getTokenExpires(), $viewer); } else { $expiry = pht('Expired'); } $rows[] = array( $token->getTokenReadableTypeName(), $expiry, $button, ); } $table = new AphrontTableView($rows); $table->setNoDataString(pht("You don't have any active tokens.")); $table->setHeaders( array( pht('Type'), pht('Expires'), pht(''), )); $table->setColumnClasses( array( 'wide', 'right', 'action', )); $button = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-warning') ->setText(pht('Revoke All')) ->setHref('/auth/token/revoke/all/') ->setWorkflow(true) ->setColor(PHUIButtonView::RED); return $this->newBox(pht('Temporary Tokens'), $table, array($button)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorEmailFormatSettingsPanel.php
src/applications/settings/panel/PhabricatorEmailFormatSettingsPanel.php
<?php final class PhabricatorEmailFormatSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'emailformat'; public function getPanelName() { return pht('Email Format'); } public function getPanelMenuIcon() { return 'fa-font'; } public function getPanelGroupKey() { return PhabricatorSettingsEmailPanelGroup::PANELGROUPKEY; } public function isUserPanel() { return PhabricatorMetaMTAMail::shouldMailEachRecipient(); } public function isManagementPanel() { return false; } public function isTemplatePanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorEmailPreferencesSettingsPanel.php
src/applications/settings/panel/PhabricatorEmailPreferencesSettingsPanel.php
<?php final class PhabricatorEmailPreferencesSettingsPanel extends PhabricatorSettingsPanel { public function getPanelKey() { return 'emailpreferences'; } public function getPanelName() { return pht('Email Preferences'); } public function getPanelMenuIcon() { return 'fa-envelope-open-o'; } public function getPanelGroupKey() { return PhabricatorSettingsEmailPanelGroup::PANELGROUPKEY; } public function isManagementPanel() { if ($this->getUser()->getIsMailingList()) { return true; } return false; } public function isTemplatePanel() { return true; } public function processRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $user = $this->getUser(); $preferences = $this->getPreferences(); $value_email = PhabricatorEmailTagsSetting::VALUE_EMAIL; $errors = array(); if ($request->isFormPost()) { $new_tags = $request->getArr('mailtags'); $mailtags = $preferences->getPreference('mailtags', array()); $all_tags = $this->getAllTags($user); foreach ($all_tags as $key => $label) { $mailtags[$key] = (int)idx($new_tags, $key, $value_email); } $this->writeSetting( $preferences, PhabricatorEmailTagsSetting::SETTINGKEY, $mailtags); return id(new AphrontRedirectResponse()) ->setURI($this->getPanelURI('?saved=true')); } $mailtags = $preferences->getSettingValue( PhabricatorEmailTagsSetting::SETTINGKEY); $form = id(new AphrontFormView()) ->setUser($viewer); $form->appendRemarkupInstructions( pht( 'You can adjust **Application Settings** here to customize when '. 'you are emailed and notified.'. "\n\n". "| Setting | Effect\n". "| ------- | -------\n". "| Email | You will receive an email and a notification, but the ". "notification will be marked \"read\".\n". "| Notify | You will receive an unread notification only.\n". "| Ignore | You will receive nothing.\n". "\n\n". 'If an update makes several changes (like adding CCs to a task, '. 'closing it, and adding a comment) you will receive the strongest '. 'notification any of the changes is configured to deliver.'. "\n\n". 'These preferences **only** apply to objects you are connected to '. '(for example, Revisions where you are a reviewer or tasks you are '. 'CC\'d on). To receive email alerts when other objects are created, '. 'configure [[ /herald/ | Herald Rules ]].')); $editors = $this->getAllEditorsWithTags($user); // Find all the tags shared by more than one application, and put them // in a "common" group. $all_tags = array(); foreach ($editors as $editor) { foreach ($editor->getMailTagsMap() as $tag => $name) { if (empty($all_tags[$tag])) { $all_tags[$tag] = array( 'count' => 0, 'name' => $name, ); } $all_tags[$tag]['count']; } } $common_tags = array(); foreach ($all_tags as $tag => $info) { if ($info['count'] > 1) { $common_tags[$tag] = $info['name']; } } // Build up the groups of application-specific options. $tag_groups = array(); foreach ($editors as $editor) { $tag_groups[] = array( $editor->getEditorObjectsDescription(), array_diff_key($editor->getMailTagsMap(), $common_tags), ); } // Sort them, then put "Common" at the top. $tag_groups = isort($tag_groups, 0); if ($common_tags) { array_unshift($tag_groups, array(pht('Common'), $common_tags)); } // Finally, build the controls. foreach ($tag_groups as $spec) { list($label, $map) = $spec; $control = $this->buildMailTagControl($label, $map, $mailtags); $form->appendChild($control); } $form ->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Save Preferences'))); $form_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Email Preferences')) ->setFormErrors($errors) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setForm($form); return $form_box; } private function getAllEditorsWithTags(PhabricatorUser $user = null) { $editors = id(new PhutilClassMapQuery()) ->setAncestorClass('PhabricatorApplicationTransactionEditor') ->setFilterMethod('getMailTagsMap') ->execute(); foreach ($editors as $key => $editor) { // Remove editors for applications which are not installed. $app = $editor->getEditorApplicationClass(); if ($app !== null && $user !== null) { if (!PhabricatorApplication::isClassInstalledForViewer($app, $user)) { unset($editors[$key]); } } } return $editors; } private function getAllTags(PhabricatorUser $user = null) { $tags = array(); foreach ($this->getAllEditorsWithTags($user) as $editor) { $tags += $editor->getMailTagsMap(); } return $tags; } private function buildMailTagControl( $control_label, array $tags, array $prefs) { $value_email = PhabricatorEmailTagsSetting::VALUE_EMAIL; $value_notify = PhabricatorEmailTagsSetting::VALUE_NOTIFY; $value_ignore = PhabricatorEmailTagsSetting::VALUE_IGNORE; $content = array(); foreach ($tags as $key => $label) { $select = AphrontFormSelectControl::renderSelectTag( (int)idx($prefs, $key, $value_email), array( $value_email => pht("\xE2\x9A\xAB Email"), $value_notify => pht("\xE2\x97\x90 Notify"), $value_ignore => pht("\xE2\x9A\xAA Ignore"), ), array( 'name' => 'mailtags['.$key.']', )); $content[] = phutil_tag( 'div', array( 'class' => 'psb', ), array( $select, ' ', $label, )); } $control = new AphrontFormStaticControl(); $control->setLabel($control_label); $control->setValue($content); return $control; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorSettingsPanel.php
src/applications/settings/panel/PhabricatorSettingsPanel.php
<?php /** * Defines a settings panel. Settings panels appear in the Settings application, * and behave like lightweight controllers -- generally, they render some sort * of form with options in it, and then update preferences when the user * submits the form. By extending this class, you can add new settings * panels. * * @task config Panel Configuration * @task panel Panel Implementation * @task internal Internals */ abstract class PhabricatorSettingsPanel extends Phobject { private $user; private $viewer; private $controller; private $navigation; private $overrideURI; private $preferences; public function setUser(PhabricatorUser $user) { $this->user = $user; return $this; } public function getUser() { return $this->user; } public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } public function getViewer() { return $this->viewer; } public function setOverrideURI($override_uri) { $this->overrideURI = $override_uri; return $this; } final public function setController(PhabricatorController $controller) { $this->controller = $controller; return $this; } final public function getController() { return $this->controller; } final public function setNavigation(AphrontSideNavFilterView $navigation) { $this->navigation = $navigation; return $this; } final public function getNavigation() { return $this->navigation; } public function setPreferences(PhabricatorUserPreferences $preferences) { $this->preferences = $preferences; return $this; } public function getPreferences() { return $this->preferences; } final public static function getAllPanels() { $panels = id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getPanelKey') ->execute(); return msortv($panels, 'getPanelOrderVector'); } final public static function getAllDisplayPanels() { $panels = array(); $groups = PhabricatorSettingsPanelGroup::getAllPanelGroupsWithPanels(); foreach ($groups as $group) { foreach ($group->getPanels() as $key => $panel) { $panels[$key] = $panel; } } return $panels; } final public function getPanelGroup() { $group_key = $this->getPanelGroupKey(); $groups = PhabricatorSettingsPanelGroup::getAllPanelGroupsWithPanels(); $group = idx($groups, $group_key); if (!$group) { throw new Exception( pht( 'No settings panel group with key "%s" exists!', $group_key)); } return $group; } /* -( Panel Configuration )------------------------------------------------ */ /** * Return a unique string used in the URI to identify this panel, like * "example". * * @return string Unique panel identifier (used in URIs). * @task config */ public function getPanelKey() { return $this->getPhobjectClassConstant('PANELKEY'); } /** * Return a human-readable description of the panel's contents, like * "Example Settings". * * @return string Human-readable panel name. * @task config */ abstract public function getPanelName(); /** * Return an icon for the panel in the menu. * * @return string Icon identifier. * @task config */ public function getPanelMenuIcon() { return 'fa-wrench'; } /** * Return a panel group key constant for this panel. * * @return const Panel group key. * @task config */ abstract public function getPanelGroupKey(); /** * Return false to prevent this panel from being displayed or used. You can * do, e.g., configuration checks here, to determine if the feature your * panel controls is unavailable in this install. By default, all panels are * enabled. * * @return bool True if the panel should be shown. * @task config */ public function isEnabled() { return true; } /** * Return true if this panel is available to users while editing their own * settings. * * @return bool True to enable management on behalf of a user. * @task config */ public function isUserPanel() { return true; } /** * Return true if this panel is available to administrators while managing * bot and mailing list accounts. * * @return bool True to enable management on behalf of accounts. * @task config */ public function isManagementPanel() { return false; } /** * Return true if this panel is available while editing settings templates. * * @return bool True to allow editing in templates. * @task config */ public function isTemplatePanel() { return false; } /** * Return true if this panel should be available when enrolling in MFA on * a new account with MFA requiredd. * * @return bool True to allow configuration during MFA enrollment. * @task config */ public function isMultiFactorEnrollmentPanel() { return false; } /* -( Panel Implementation )----------------------------------------------- */ /** * Process a user request for this settings panel. Implement this method like * a lightweight controller. If you return an @{class:AphrontResponse}, the * response will be used in whole. If you return anything else, it will be * treated as a view and composed into a normal settings page. * * Generally, render your settings panel by returning a form, then return * a redirect when the user saves settings. * * @param AphrontRequest Incoming request. * @return wild Response to request, either as an * @{class:AphrontResponse} or something which can * be composed into a @{class:AphrontView}. * @task panel */ abstract public function processRequest(AphrontRequest $request); /** * Get the URI for this panel. * * @param string? Optional path to append. * @return string Relative URI for the panel. * @task panel */ final public function getPanelURI($path = '') { $path = ltrim($path, '/'); if ($this->overrideURI) { return rtrim($this->overrideURI, '/').'/'.$path; } $key = $this->getPanelKey(); $key = phutil_escape_uri($key); $user = $this->getUser(); if ($user) { if ($user->isLoggedIn()) { $username = $user->getUsername(); return "/settings/user/{$username}/page/{$key}/{$path}"; } else { // For logged-out users, we can't put their username in the URI. This // page will prompt them to login, then redirect them to the correct // location. return "/settings/panel/{$key}/"; } } else { $builtin = $this->getPreferences()->getBuiltinKey(); return "/settings/builtin/{$builtin}/page/{$key}/{$path}"; } } /* -( Internals )---------------------------------------------------------- */ /** * Generates a key to sort the list of panels. * * @return string Sortable key. * @task internal */ final public function getPanelOrderVector() { return id(new PhutilSortVector()) ->addString($this->getPanelName()); } protected function newDialog() { return $this->getController()->newDialog(); } protected function writeSetting( PhabricatorUserPreferences $preferences, $key, $value) { $viewer = $this->getViewer(); $request = $this->getController()->getRequest(); $editor = id(new PhabricatorUserPreferencesEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true); $xactions = array(); $xactions[] = $preferences->newTransaction($key, $value); $editor->applyTransactions($preferences, $xactions); } public function newBox($title, $content, $actions = array()) { $header = id(new PHUIHeaderView()) ->setHeader($title); foreach ($actions as $action) { $header->addActionLink($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/settings/panel/PhabricatorSearchSettingsPanel.php
src/applications/settings/panel/PhabricatorSearchSettingsPanel.php
<?php final class PhabricatorSearchSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'search'; public function getPanelName() { return pht('Search'); } public function getPanelMenuIcon() { return 'fa-search'; } public function getPanelGroupKey() { return PhabricatorSettingsApplicationsPanelGroup::PANELGROUPKEY; } public function isTemplatePanel() { return true; } public function isUserPanel() { 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/settings/panel/PhabricatorExternalAccountsSettingsPanel.php
src/applications/settings/panel/PhabricatorExternalAccountsSettingsPanel.php
<?php final class PhabricatorExternalAccountsSettingsPanel extends PhabricatorSettingsPanel { public function getPanelKey() { return 'external'; } public function getPanelName() { return pht('External Accounts'); } public function getPanelMenuIcon() { return 'fa-users'; } public function getPanelGroupKey() { return PhabricatorSettingsAuthenticationPanelGroup::PANELGROUPKEY; } public function processRequest(AphrontRequest $request) { $viewer = $request->getUser(); $providers = PhabricatorAuthProvider::getAllProviders(); $accounts = id(new PhabricatorExternalAccountQuery()) ->setViewer($viewer) ->withUserPHIDs(array($viewer->getPHID())) ->needImages(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->execute(); $linked_head = pht('Linked Accounts and Authentication'); $linked = id(new PHUIObjectItemListView()) ->setUser($viewer) ->setNoDataString(pht('You have no linked accounts.')); foreach ($accounts as $account) { $item = new PHUIObjectItemView(); $config = $account->getProviderConfig(); $provider = $config->getProvider(); $item->setHeader($provider->getProviderName()); $can_unlink = $provider->shouldAllowAccountUnlink(); if (!$can_unlink) { $item->addAttribute(pht('Permanently Linked')); } $can_login = $account->isUsableForLogin(); if (!$can_login) { $item->addAttribute( pht( 'Disabled (an administrator has disabled login for this '. 'account provider).')); } $can_refresh = $provider->shouldAllowAccountRefresh(); if ($can_refresh) { $item->addAction( id(new PHUIListItemView()) ->setIcon('fa-refresh') ->setHref('/auth/refresh/'.$config->getID().'/')); } $item->addAction( id(new PHUIListItemView()) ->setIcon('fa-times') ->setWorkflow(true) ->setDisabled(!$can_unlink) ->setHref('/auth/unlink/'.$account->getID().'/')); if ($provider) { $provider->willRenderLinkedAccount($viewer, $item, $account); } $linked->addItem($item); } $linkable_head = pht('Add External Account'); $linkable = id(new PHUIObjectItemListView()) ->setUser($viewer) ->setNoDataString( pht('Your account is linked with all available providers.')); $configs = id(new PhabricatorAuthProviderConfigQuery()) ->setViewer($viewer) ->withIsEnabled(true) ->execute(); $configs = msortv($configs, 'getSortVector'); $account_map = mgroup($accounts, 'getProviderConfigPHID'); foreach ($configs as $config) { $provider = $config->getProvider(); if (!$provider->shouldAllowAccountLink()) { continue; } // Don't show the user providers they already have linked. if (isset($account_map[$config->getPHID()])) { continue; } $link_uri = '/auth/link/'.$config->getID().'/'; $link_button = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-link') ->setHref($link_uri) ->setColor(PHUIButtonView::GREY) ->setText(pht('Link External Account')); $item = id(new PHUIObjectItemView()) ->setHeader($config->getDisplayName()) ->setHref($link_uri) ->setImageIcon($config->newIconView()) ->setSideColumn($link_button); $linkable->addItem($item); } $linked_box = $this->newBox($linked_head, $linked); $linkable_box = $this->newBox($linkable_head, $linkable); return array( $linked_box, $linkable_box, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorEditEngineSettingsPanel.php
src/applications/settings/panel/PhabricatorEditEngineSettingsPanel.php
<?php abstract class PhabricatorEditEngineSettingsPanel extends PhabricatorSettingsPanel { final public function processRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $user = $this->getUser(); if ($user && ($user->getPHID() === $viewer->getPHID())) { $is_self = true; } else { $is_self = false; } if ($user && $user->getPHID()) { $profile_uri = '/people/manage/'.$user->getID().'/'; } else { $profile_uri = null; } $engine = id(new PhabricatorSettingsEditEngine()) ->setController($this->getController()) ->setNavigation($this->getNavigation()) ->setSettingsPanel($this) ->setIsSelfEdit($is_self) ->setProfileURI($profile_uri); $preferences = $this->getPreferences(); $engine->setTargetObject($preferences); return $engine->buildResponse(); } final public function isEnabled() { // Only enable the panel if it has any fields. $field_keys = $this->getPanelSettingsKeys(); return (bool)$field_keys; } final public function newEditEnginePage() { $field_keys = $this->getPanelSettingsKeys(); if (!$field_keys) { return null; } $key = $this->getPanelKey(); $label = $this->getPanelName(); $panel_uri = $this->getPanelURI(); return id(new PhabricatorEditPage()) ->setKey($key) ->setLabel($label) ->setViewURI($panel_uri) ->setFieldKeys($field_keys); } final public function getPanelSettingsKeys() { $viewer = $this->getViewer(); $settings = PhabricatorSetting::getAllEnabledSettings($viewer); $this_key = $this->getPanelKey(); $panel_settings = array(); foreach ($settings as $setting) { if ($setting->getSettingPanelKey() == $this_key) { $panel_settings[] = $setting; } } return mpull($panel_settings, 'getSettingKey'); } public function newSettingsPanelEditFormHeadContent( PhabricatorEditEnginePageState $state) { return null; } public function newSettingsPanelEditFormTailContent( PhabricatorEditEnginePageState $state) { 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/settings/panel/PhabricatorSSHKeysSettingsPanel.php
src/applications/settings/panel/PhabricatorSSHKeysSettingsPanel.php
<?php final class PhabricatorSSHKeysSettingsPanel extends PhabricatorSettingsPanel { public function isManagementPanel() { if ($this->getUser()->getIsMailingList()) { return false; } return true; } public function getPanelKey() { return 'ssh'; } public function getPanelName() { return pht('SSH Public Keys'); } public function getPanelMenuIcon() { return 'fa-file-text-o'; } public function getPanelGroupKey() { return PhabricatorSettingsAuthenticationPanelGroup::PANELGROUPKEY; } public function processRequest(AphrontRequest $request) { $user = $this->getUser(); $viewer = $request->getUser(); $keys = id(new PhabricatorAuthSSHKeyQuery()) ->setViewer($viewer) ->withObjectPHIDs(array($user->getPHID())) ->withIsActive(true) ->execute(); $table = id(new PhabricatorAuthSSHKeyTableView()) ->setUser($viewer) ->setKeys($keys) ->setCanEdit(true) ->setNoDataString(pht("You haven't added any SSH Public Keys.")); $panel = new PHUIObjectBoxView(); $header = new PHUIHeaderView(); $ssh_actions = PhabricatorAuthSSHKeyTableView::newKeyActionsMenu( $viewer, $user); return $this->newBox(pht('SSH Public Keys'), $table, array($ssh_actions)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorContactNumbersSettingsPanel.php
src/applications/settings/panel/PhabricatorContactNumbersSettingsPanel.php
<?php final class PhabricatorContactNumbersSettingsPanel extends PhabricatorSettingsPanel { public function getPanelKey() { return 'contact'; } public function getPanelName() { return pht('Contact Numbers'); } public function getPanelMenuIcon() { return 'fa-hashtag'; } public function getPanelGroupKey() { return PhabricatorSettingsAuthenticationPanelGroup::PANELGROUPKEY; } public function isMultiFactorEnrollmentPanel() { return true; } public function processRequest(AphrontRequest $request) { $user = $this->getUser(); $viewer = $request->getUser(); $numbers = id(new PhabricatorAuthContactNumberQuery()) ->setViewer($viewer) ->withObjectPHIDs(array($user->getPHID())) ->execute(); $numbers = msortv($numbers, 'getSortVector'); $rows = array(); $row_classes = array(); foreach ($numbers as $number) { if ($number->getIsPrimary()) { $primary_display = pht('Primary'); $row_classes[] = 'highlighted'; } else { $primary_display = null; $row_classes[] = null; } $rows[] = array( $number->newIconView(), phutil_tag( 'a', array( 'href' => $number->getURI(), ), $number->getDisplayName()), $primary_display, phabricator_datetime($number->getDateCreated(), $viewer), ); } $table = id(new AphrontTableView($rows)) ->setNoDataString( pht("You haven't added any contact numbers to your account.")) ->setRowClasses($row_classes) ->setHeaders( array( null, pht('Number'), pht('Status'), pht('Created'), )) ->setColumnClasses( array( null, 'wide pri', null, 'right', )); $buttons = array(); $buttons[] = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-plus') ->setText(pht('Add Contact Number')) ->setHref('/auth/contact/edit/') ->setColor(PHUIButtonView::GREY); return $this->newBox(pht('Contact Numbers'), $table, $buttons); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorPasswordSettingsPanel.php
src/applications/settings/panel/PhabricatorPasswordSettingsPanel.php
<?php final class PhabricatorPasswordSettingsPanel extends PhabricatorSettingsPanel { public function getPanelKey() { return 'password'; } public function getPanelName() { return pht('Password'); } public function getPanelMenuIcon() { return 'fa-key'; } public function getPanelGroupKey() { return PhabricatorSettingsAuthenticationPanelGroup::PANELGROUPKEY; } public function isEnabled() { // There's no sense in showing a change password panel if this install // doesn't support password authentication. if (!PhabricatorPasswordAuthProvider::getPasswordProvider()) { return false; } return true; } public function processRequest(AphrontRequest $request) { $viewer = $request->getUser(); $user = $this->getUser(); $content_source = PhabricatorContentSource::newFromRequest($request); $min_len = PhabricatorEnv::getEnvConfig('account.minimum-password-length'); $min_len = (int)$min_len; // NOTE: Users can also change passwords through the separate "set/reset" // interface which is reached by logging in with a one-time token after // registration or password reset. If this flow changes, that flow may // also need to change. $account_type = PhabricatorAuthPassword::PASSWORD_TYPE_ACCOUNT; $password_objects = id(new PhabricatorAuthPasswordQuery()) ->setViewer($viewer) ->withObjectPHIDs(array($user->getPHID())) ->withPasswordTypes(array($account_type)) ->withIsRevoked(false) ->execute(); if (!$password_objects) { return $this->newSetPasswordView($request); } $password_object = head($password_objects); $e_old = true; $e_new = true; $e_conf = true; $errors = array(); if ($request->isFormOrHisecPost()) { $workflow_key = sprintf( 'password.change(%s)', $user->getPHID()); $hisec_token = id(new PhabricatorAuthSessionEngine()) ->setWorkflowKey($workflow_key) ->requireHighSecurityToken($viewer, $request, '/settings/'); // Rate limit guesses about the old password. This page requires MFA and // session compromise already, so this is mostly just to stop researchers // from reporting this as a vulnerability. PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorAuthChangePasswordAction(), 1); $envelope = new PhutilOpaqueEnvelope($request->getStr('old_pw')); $engine = id(new PhabricatorAuthPasswordEngine()) ->setViewer($viewer) ->setContentSource($content_source) ->setPasswordType($account_type) ->setObject($user); if (!strlen($envelope->openEnvelope())) { $errors[] = pht('You must enter your current password.'); $e_old = pht('Required'); } else if (!$engine->isValidPassword($envelope)) { $errors[] = pht('The old password you entered is incorrect.'); $e_old = pht('Invalid'); } else { $e_old = null; // Refund the user an action credit for getting the password right. PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorAuthChangePasswordAction(), -1); } $pass = $request->getStr('new_pw'); $conf = $request->getStr('conf_pw'); $password_envelope = new PhutilOpaqueEnvelope($pass); $confirm_envelope = new PhutilOpaqueEnvelope($conf); try { $engine->checkNewPassword($password_envelope, $confirm_envelope); $e_new = null; $e_conf = null; } catch (PhabricatorAuthPasswordException $ex) { $errors[] = $ex->getMessage(); $e_new = $ex->getPasswordError(); $e_conf = $ex->getConfirmError(); } if (!$errors) { $password_object ->setPassword($password_envelope, $user) ->save(); $next = $this->getPanelURI('?saved=true'); id(new PhabricatorAuthSessionEngine())->terminateLoginSessions( $user, new PhutilOpaqueEnvelope( $request->getCookie(PhabricatorCookies::COOKIE_SESSION))); return id(new AphrontRedirectResponse())->setURI($next); } } if ($password_object->getID()) { try { $can_upgrade = $password_object->canUpgrade(); } catch (PhabricatorPasswordHasherUnavailableException $ex) { $can_upgrade = false; $errors[] = pht( 'Your password is currently hashed using an algorithm which is '. 'no longer available on this install.'); $errors[] = pht( 'Because the algorithm implementation is missing, your password '. 'can not be used or updated.'); $errors[] = pht( 'To set a new password, request a password reset link from the '. 'login screen and then follow the instructions.'); } if ($can_upgrade) { $errors[] = pht( 'The strength of your stored password hash can be upgraded. '. 'To upgrade, either: log out and log in using your password; or '. 'change your password.'); } } $len_caption = null; if ($min_len) { $len_caption = pht('Minimum password length: %d characters.', $min_len); } $form = id(new AphrontFormView()) ->setViewer($viewer) ->appendChild( id(new AphrontFormPasswordControl()) ->setLabel(pht('Old Password')) ->setError($e_old) ->setName('old_pw')) ->appendChild( id(new AphrontFormPasswordControl()) ->setDisableAutocomplete(true) ->setLabel(pht('New Password')) ->setError($e_new) ->setName('new_pw')) ->appendChild( id(new AphrontFormPasswordControl()) ->setDisableAutocomplete(true) ->setLabel(pht('Confirm Password')) ->setCaption($len_caption) ->setError($e_conf) ->setName('conf_pw')) ->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Change Password'))); $properties = id(new PHUIPropertyListView()); $properties->addProperty( pht('Current Algorithm'), PhabricatorPasswordHasher::getCurrentAlgorithmName( $password_object->newPasswordEnvelope())); $properties->addProperty( pht('Best Available Algorithm'), PhabricatorPasswordHasher::getBestAlgorithmName()); $info_view = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->appendChild( pht('Changing your password will terminate any other outstanding '. 'login sessions.')); $algo_box = $this->newBox(pht('Password Algorithms'), $properties); $form_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Change Password')) ->setFormErrors($errors) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setForm($form); return array( $form_box, $algo_box, $info_view, ); } private function newSetPasswordView(AphrontRequest $request) { $viewer = $request->getUser(); $user = $this->getUser(); $form = id(new AphrontFormView()) ->setViewer($viewer) ->appendRemarkupInstructions( pht( 'Your account does not currently have a password set. You can '. 'choose a password by performing a password reset.')) ->appendControl( id(new AphrontFormSubmitControl()) ->addCancelButton('/login/email/', pht('Reset Password'))); $form_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Set Password')) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setForm($form); return $form_box; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorConpherencePreferencesSettingsPanel.php
src/applications/settings/panel/PhabricatorConpherencePreferencesSettingsPanel.php
<?php final class PhabricatorConpherencePreferencesSettingsPanel extends PhabricatorEditEngineSettingsPanel { const PANELKEY = 'conpherence'; public function getPanelName() { return pht('Conpherence'); } public function getPanelMenuIcon() { return 'fa-comment-o'; } public function getPanelGroupKey() { return PhabricatorSettingsApplicationsPanelGroup::PANELGROUPKEY; } public function isTemplatePanel() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panel/PhabricatorMultiFactorSettingsPanel.php
src/applications/settings/panel/PhabricatorMultiFactorSettingsPanel.php
<?php final class PhabricatorMultiFactorSettingsPanel extends PhabricatorSettingsPanel { private $isEnrollment; public function getPanelKey() { return 'multifactor'; } public function getPanelName() { return pht('Multi-Factor Auth'); } public function getPanelMenuIcon() { return 'fa-lock'; } public function getPanelGroupKey() { return PhabricatorSettingsAuthenticationPanelGroup::PANELGROUPKEY; } public function isMultiFactorEnrollmentPanel() { return true; } public function setIsEnrollment($is_enrollment) { $this->isEnrollment = $is_enrollment; return $this; } public function getIsEnrollment() { return $this->isEnrollment; } public function processRequest(AphrontRequest $request) { if ($request->getExists('new') || $request->getExists('providerPHID')) { return $this->processNew($request); } if ($request->getExists('edit')) { return $this->processEdit($request); } if ($request->getExists('delete')) { return $this->processDelete($request); } $user = $this->getUser(); $viewer = $request->getUser(); $factors = id(new PhabricatorAuthFactorConfigQuery()) ->setViewer($viewer) ->withUserPHIDs(array($user->getPHID())) ->execute(); $factors = msortv($factors, 'newSortVector'); $rows = array(); $rowc = array(); $highlight_id = $request->getInt('id'); foreach ($factors as $factor) { $provider = $factor->getFactorProvider(); if ($factor->getID() == $highlight_id) { $rowc[] = 'highlighted'; } else { $rowc[] = null; } $status = $provider->newStatus(); $status_icon = $status->getFactorIcon(); $status_color = $status->getFactorColor(); $icon = id(new PHUIIconView()) ->setIcon("{$status_icon} {$status_color}") ->setTooltip(pht('Provider: %s', $status->getName())); $details = $provider->getConfigurationListDetails($factor, $viewer); $rows[] = array( $icon, javelin_tag( 'a', array( 'href' => $this->getPanelURI('?edit='.$factor->getID()), 'sigil' => 'workflow', ), $factor->getFactorName()), $provider->getFactor()->getFactorShortName(), $provider->getDisplayName(), $details, phabricator_datetime($factor->getDateCreated(), $viewer), javelin_tag( 'a', array( 'href' => $this->getPanelURI('?delete='.$factor->getID()), 'sigil' => 'workflow', 'class' => 'small button button-grey', ), pht('Remove')), ); } $table = new AphrontTableView($rows); $table->setNoDataString( pht("You haven't added any authentication factors to your account yet.")); $table->setHeaders( array( null, pht('Name'), pht('Type'), pht('Provider'), pht('Details'), pht('Created'), null, )); $table->setColumnClasses( array( null, 'wide pri', null, null, null, 'right', 'action', )); $table->setRowClasses($rowc); $table->setDeviceVisibility( array( true, true, false, false, false, false, true, )); $help_uri = PhabricatorEnv::getDoclink( 'User Guide: Multi-Factor Authentication'); $buttons = array(); // If we're enrolling a new account in MFA, provide a small visual hint // that this is the button they want to click. if ($this->getIsEnrollment()) { $add_color = PHUIButtonView::BLUE; } else { $add_color = PHUIButtonView::GREY; } $can_add = (bool)$this->loadActiveMFAProviders(); $buttons[] = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-plus') ->setText(pht('Add Auth Factor')) ->setHref($this->getPanelURI('?new=true')) ->setWorkflow(true) ->setDisabled(!$can_add) ->setColor($add_color); $buttons[] = id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-book') ->setText(pht('Help')) ->setHref($help_uri) ->setColor(PHUIButtonView::GREY); return $this->newBox(pht('Authentication Factors'), $table, $buttons); } private function processNew(AphrontRequest $request) { $viewer = $request->getUser(); $user = $this->getUser(); $cancel_uri = $this->getPanelURI(); // Check that we have providers before we send the user through the MFA // gate, so you don't authenticate and then immediately get roadblocked. $providers = $this->loadActiveMFAProviders(); if (!$providers) { return $this->newDialog() ->setTitle(pht('No MFA Providers')) ->appendParagraph( pht( 'This install does not have any active MFA providers configured. '. 'At least one provider must be configured and active before you '. 'can add new MFA factors.')) ->addCancelButton($cancel_uri); } $token = id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession( $viewer, $request, $cancel_uri); $selected_phid = $request->getStr('providerPHID'); if (empty($providers[$selected_phid])) { $selected_provider = null; } else { $selected_provider = $providers[$selected_phid]; // Only let the user continue creating a factor for a given provider if // they actually pass the provider's checks. if (!$selected_provider->canCreateNewConfiguration($viewer)) { $selected_provider = null; } } if (!$selected_provider) { $menu = id(new PHUIObjectItemListView()) ->setViewer($viewer) ->setBig(true) ->setFlush(true); foreach ($providers as $provider_phid => $provider) { $provider_uri = id(new PhutilURI($this->getPanelURI())) ->replaceQueryParam('providerPHID', $provider_phid); $is_enabled = $provider->canCreateNewConfiguration($viewer); $item = id(new PHUIObjectItemView()) ->setHeader($provider->getDisplayName()) ->setImageIcon($provider->newIconView()) ->addAttribute($provider->getDisplayDescription()); if ($is_enabled) { $item ->setHref($provider_uri) ->setClickable(true); } else { $item->setDisabled(true); } $create_description = $provider->getConfigurationCreateDescription( $viewer); if ($create_description) { $item->appendChild($create_description); } $menu->addItem($item); } return $this->newDialog() ->setTitle(pht('Choose Factor Type')) ->appendChild($menu) ->addCancelButton($cancel_uri); } // NOTE: Beyond providing guidance, this step is also providing a CSRF gate // on this endpoint, since prompting the user to respond to a challenge // sometimes requires us to push a challenge to them as a side effect (for // example, with SMS). if (!$request->isFormPost() || !$request->getBool('mfa.start')) { $enroll = $selected_provider->getEnrollMessage(); if (!strlen($enroll)) { $enroll = $selected_provider->getEnrollDescription($viewer); } return $this->newDialog() ->addHiddenInput('providerPHID', $selected_provider->getPHID()) ->addHiddenInput('mfa.start', 1) ->setTitle(pht('Add Authentication Factor')) ->appendChild(new PHUIRemarkupView($viewer, $enroll)) ->addCancelButton($cancel_uri) ->addSubmitButton($selected_provider->getEnrollButtonText($viewer)); } $form = id(new AphrontFormView()) ->setViewer($viewer); if ($request->getBool('mfa.enroll')) { // Subject users to rate limiting so that it's difficult to add factors // by pure brute force. This is normally not much of an attack, but push // factor types may have side effects. PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorAuthNewFactorAction(), 1); } else { // Test the limit before showing the user a form, so we don't give them // a form which can never possibly work because it will always hit rate // limiting. PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorAuthNewFactorAction(), 0); } $config = $selected_provider->processAddFactorForm( $form, $request, $user); if ($config) { // If the user added a factor, give them a rate limiting point back. PhabricatorSystemActionEngine::willTakeAction( array($viewer->getPHID()), new PhabricatorAuthNewFactorAction(), -1); $config->save(); // If we used a temporary token to handle synchronizing the factor, // revoke it now. $sync_token = $config->getMFASyncToken(); if ($sync_token) { $sync_token->revokeToken(); } $log = PhabricatorUserLog::initializeNewLog( $viewer, $user->getPHID(), PhabricatorAddMultifactorUserLogType::LOGTYPE); $log->save(); $user->updateMultiFactorEnrollment(); // Terminate other sessions so they must log in and survive the // multi-factor auth check. id(new PhabricatorAuthSessionEngine())->terminateLoginSessions( $user, new PhutilOpaqueEnvelope( $request->getCookie(PhabricatorCookies::COOKIE_SESSION))); return id(new AphrontRedirectResponse()) ->setURI($this->getPanelURI('?id='.$config->getID())); } return $this->newDialog() ->addHiddenInput('providerPHID', $selected_provider->getPHID()) ->addHiddenInput('mfa.start', 1) ->addHiddenInput('mfa.enroll', 1) ->setWidth(AphrontDialogView::WIDTH_FORM) ->setTitle(pht('Add Authentication Factor')) ->appendChild($form->buildLayoutView()) ->addSubmitButton(pht('Continue')) ->addCancelButton($cancel_uri); } private function processEdit(AphrontRequest $request) { $viewer = $request->getUser(); $user = $this->getUser(); $factor = id(new PhabricatorAuthFactorConfig())->loadOneWhere( 'id = %d AND userPHID = %s', $request->getInt('edit'), $user->getPHID()); if (!$factor) { return new Aphront404Response(); } $e_name = true; $errors = array(); if ($request->isFormPost()) { $name = $request->getStr('name'); if (!strlen($name)) { $e_name = pht('Required'); $errors[] = pht( 'Authentication factors must have a name to identify them.'); } if (!$errors) { $factor->setFactorName($name); $factor->save(); $user->updateMultiFactorEnrollment(); return id(new AphrontRedirectResponse()) ->setURI($this->getPanelURI('?id='.$factor->getID())); } } else { $name = $factor->getFactorName(); } $form = id(new AphrontFormView()) ->setUser($viewer) ->appendChild( id(new AphrontFormTextControl()) ->setName('name') ->setLabel(pht('Name')) ->setValue($name) ->setError($e_name)); $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->addHiddenInput('edit', $factor->getID()) ->setTitle(pht('Edit Authentication Factor')) ->setErrors($errors) ->appendChild($form->buildLayoutView()) ->addSubmitButton(pht('Save')) ->addCancelButton($this->getPanelURI()); return id(new AphrontDialogResponse()) ->setDialog($dialog); } private function processDelete(AphrontRequest $request) { $viewer = $request->getUser(); $user = $this->getUser(); $token = id(new PhabricatorAuthSessionEngine())->requireHighSecuritySession( $viewer, $request, $this->getPanelURI()); $factor = id(new PhabricatorAuthFactorConfig())->loadOneWhere( 'id = %d AND userPHID = %s', $request->getInt('delete'), $user->getPHID()); if (!$factor) { return new Aphront404Response(); } if ($request->isFormPost()) { $factor->delete(); $log = PhabricatorUserLog::initializeNewLog( $viewer, $user->getPHID(), PhabricatorRemoveMultifactorUserLogType::LOGTYPE); $log->save(); $user->updateMultiFactorEnrollment(); return id(new AphrontRedirectResponse()) ->setURI($this->getPanelURI()); } $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->addHiddenInput('delete', $factor->getID()) ->setTitle(pht('Delete Authentication Factor')) ->appendParagraph( pht( 'Really remove the authentication factor %s from your account?', phutil_tag('strong', array(), $factor->getFactorName()))) ->addSubmitButton(pht('Remove Factor')) ->addCancelButton($this->getPanelURI()); return id(new AphrontDialogResponse()) ->setDialog($dialog); } private function loadActiveMFAProviders() { $viewer = $this->getViewer(); $providers = id(new PhabricatorAuthFactorProviderQuery()) ->setViewer($viewer) ->withStatuses( array( PhabricatorAuthFactorProviderStatus::STATUS_ACTIVE, )) ->execute(); $providers = mpull($providers, null, 'getPHID'); $providers = msortv($providers, 'newSortVector'); return $providers; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/application/PhabricatorSettingsApplication.php
src/applications/settings/application/PhabricatorSettingsApplication.php
<?php final class PhabricatorSettingsApplication extends PhabricatorApplication { public function getBaseURI() { return '/settings/'; } public function getName() { return pht('Settings'); } public function getShortDescription() { return pht('User Preferences'); } public function getIcon() { return 'fa-wrench'; } public function canUninstall() { return false; } public function getRoutes() { $panel_pattern = '(?:page/(?P<pageKey>[^/]+)/)?'; return array( '/settings/' => array( $this->getQueryRoutePattern() => 'PhabricatorSettingsListController', 'user/(?P<username>[^/]+)/'.$panel_pattern => 'PhabricatorSettingsMainController', 'builtin/(?P<builtin>global)/'.$panel_pattern => 'PhabricatorSettingsMainController', 'panel/(?P<panel>[^/]+)/' => 'PhabricatorSettingsMainController', 'adjust/' => 'PhabricatorSettingsAdjustController', 'timezone/(?P<offset>[^/]+)/' => 'PhabricatorSettingsTimezoneController', 'issue/' => 'PhabricatorSettingsIssueController', ), ); } public function getApplicationGroup() { return self::GROUP_UTILITIES; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panelgroup/PhabricatorSettingsAuthenticationPanelGroup.php
src/applications/settings/panelgroup/PhabricatorSettingsAuthenticationPanelGroup.php
<?php final class PhabricatorSettingsAuthenticationPanelGroup extends PhabricatorSettingsPanelGroup { const PANELGROUPKEY = 'authentication'; public function getPanelGroupName() { return pht('Authentication'); } protected function getPanelGroupOrder() { return 300; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panelgroup/PhabricatorSettingsLogsPanelGroup.php
src/applications/settings/panelgroup/PhabricatorSettingsLogsPanelGroup.php
<?php final class PhabricatorSettingsLogsPanelGroup extends PhabricatorSettingsPanelGroup { const PANELGROUPKEY = 'logs'; public function getPanelGroupName() { return pht('Sessions and Logs'); } protected function getPanelGroupOrder() { return 600; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panelgroup/PhabricatorSettingsEmailPanelGroup.php
src/applications/settings/panelgroup/PhabricatorSettingsEmailPanelGroup.php
<?php final class PhabricatorSettingsEmailPanelGroup extends PhabricatorSettingsPanelGroup { const PANELGROUPKEY = 'email'; public function getPanelGroupName() { return pht('Email'); } protected function getPanelGroupOrder() { return 500; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panelgroup/PhabricatorSettingsApplicationsPanelGroup.php
src/applications/settings/panelgroup/PhabricatorSettingsApplicationsPanelGroup.php
<?php final class PhabricatorSettingsApplicationsPanelGroup extends PhabricatorSettingsPanelGroup { const PANELGROUPKEY = 'applications'; public function getPanelGroupName() { return pht('Applications'); } protected function getPanelGroupOrder() { return 200; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panelgroup/PhabricatorSettingsPanelGroup.php
src/applications/settings/panelgroup/PhabricatorSettingsPanelGroup.php
<?php abstract class PhabricatorSettingsPanelGroup extends Phobject { private $panels; abstract public function getPanelGroupName(); protected function getPanelGroupOrder() { return 1000; } final public function getPanelGroupOrderVector() { return id(new PhutilSortVector()) ->addInt($this->getPanelGroupOrder()) ->addString($this->getPanelGroupName()); } final public function getPanelGroupKey() { return $this->getPhobjectClassConstant('PANELGROUPKEY'); } final public static function getAllPanelGroups() { $groups = id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getPanelGroupKey') ->execute(); return msortv($groups, 'getPanelGroupOrderVector'); } final public static function getAllPanelGroupsWithPanels() { $groups = self::getAllPanelGroups(); $panels = PhabricatorSettingsPanel::getAllPanels(); $panels = mgroup($panels, 'getPanelGroupKey'); foreach ($groups as $key => $group) { $group->panels = idx($panels, $key, array()); } return $groups; } public function getPanels() { return $this->panels; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panelgroup/PhabricatorSettingsAccountPanelGroup.php
src/applications/settings/panelgroup/PhabricatorSettingsAccountPanelGroup.php
<?php final class PhabricatorSettingsAccountPanelGroup extends PhabricatorSettingsPanelGroup { const PANELGROUPKEY = 'account'; public function getPanelGroupName() { return pht('Account'); } protected function getPanelGroupOrder() { return 100; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/panelgroup/PhabricatorSettingsDeveloperPanelGroup.php
src/applications/settings/panelgroup/PhabricatorSettingsDeveloperPanelGroup.php
<?php final class PhabricatorSettingsDeveloperPanelGroup extends PhabricatorSettingsPanelGroup { const PANELGROUPKEY = 'developer'; public function getPanelGroupName() { return pht('Developer'); } protected function getPanelGroupOrder() { return 400; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/phid/PhabricatorUserPreferencesPHIDType.php
src/applications/settings/phid/PhabricatorUserPreferencesPHIDType.php
<?php final class PhabricatorUserPreferencesPHIDType extends PhabricatorPHIDType { const TYPECONST = 'PSET'; public function getTypeName() { return pht('Settings'); } public function newObject() { return new PhabricatorUserPreferences(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorSettingsApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorUserPreferencesQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { $viewer = $query->getViewer(); foreach ($handles as $phid => $handle) { $preferences = $objects[$phid]; $handle->setName(pht('Settings %d', $preferences->getID())); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorSearchScopeSetting.php
src/applications/settings/setting/PhabricatorSearchScopeSetting.php
<?php final class PhabricatorSearchScopeSetting extends PhabricatorSelectSetting { const SETTINGKEY = 'search-scope'; public function getSettingName() { return pht('Search Scope'); } public function getSettingPanelKey() { return PhabricatorSearchSettingsPanel::PANELKEY; } public function getSettingDefaultValue() { return 'all'; } protected function getControlInstructions() { return pht( 'Choose the default behavior of the global search in the main menu.'); } protected function getSelectOptions() { $scopes = PhabricatorMainMenuSearchView::getGlobalSearchScopeItems( $this->getViewer(), new PhabricatorSettingsApplication(), $only_global = true); $scope_map = array(); foreach ($scopes as $scope) { if (!isset($scope['value'])) { continue; } $scope_map[$scope['value']] = $scope['name']; } return $scope_map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorEmailTagsSetting.php
src/applications/settings/setting/PhabricatorEmailTagsSetting.php
<?php final class PhabricatorEmailTagsSetting extends PhabricatorInternalSetting { const SETTINGKEY = 'mailtags'; // These are in an unusual order for historic reasons. const VALUE_NOTIFY = 0; const VALUE_EMAIL = 1; const VALUE_IGNORE = 2; public function getSettingName() { return pht('Mail Tags'); } public function getSettingDefaultValue() { return array(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorDarkConsoleTabSetting.php
src/applications/settings/setting/PhabricatorDarkConsoleTabSetting.php
<?php final class PhabricatorDarkConsoleTabSetting extends PhabricatorInternalSetting { const SETTINGKEY = 'darkconsole.tab'; public function getSettingName() { return pht('DarkConsole Tab'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorEmailNotificationsSetting.php
src/applications/settings/setting/PhabricatorEmailNotificationsSetting.php
<?php final class PhabricatorEmailNotificationsSetting extends PhabricatorSelectSetting { const SETTINGKEY = 'no-mail'; const VALUE_SEND_MAIL = '0'; const VALUE_NO_MAIL = '1'; public function getSettingName() { return pht('Email Notifications'); } public function getSettingPanelKey() { return PhabricatorEmailDeliverySettingsPanel::PANELKEY; } protected function getSettingOrder() { return 100; } protected function getControlInstructions() { return pht( 'If you disable **Email Notifications**, this server will never '. 'send email to notify you about events. This preference overrides '. 'all your other settings.'. "\n\n". "//You will still receive some administrative email, like password ". "reset email.//"); } public function getSettingDefaultValue() { return self::VALUE_SEND_MAIL; } protected function getSelectOptions() { return array( self::VALUE_SEND_MAIL => pht('Enable Email Notifications'), self::VALUE_NO_MAIL => pht('Disable Email Notifications'), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorEmailRePrefixSetting.php
src/applications/settings/setting/PhabricatorEmailRePrefixSetting.php
<?php final class PhabricatorEmailRePrefixSetting extends PhabricatorSelectSetting { const SETTINGKEY = 're-prefix'; const VALUE_RE_PREFIX = 're'; const VALUE_NO_PREFIX = 'none'; public function getSettingName() { return pht('Add "Re:" Prefix'); } public function getSettingPanelKey() { return PhabricatorEmailFormatSettingsPanel::PANELKEY; } protected function getSettingOrder() { return 200; } protected function getControlInstructions() { return pht( 'The **Add "Re:" Prefix** setting adds "Re:" in front of all messages, '. 'even if they are not replies. If you use **Mail.app** on Mac OS X, '. 'this may improve mail threading.'. "\n\n". "| Setting | Example Mail Subject\n". "|------------------------|----------------\n". "| Enable \"Re:\" Prefix | ". "`Re: [Differential] [Accepted] D123: Example Revision`\n". "| Disable \"Re:\" Prefix | ". "`[Differential] [Accepted] D123: Example Revision`"); } public function getSettingDefaultValue() { return self::VALUE_NO_PREFIX; } protected function getSelectOptions() { return array( self::VALUE_RE_PREFIX => pht('Enable "Re:" Prefix'), self::VALUE_NO_PREFIX => pht('Disable "Re:" Prefix'), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorUnifiedDiffsSetting.php
src/applications/settings/setting/PhabricatorUnifiedDiffsSetting.php
<?php final class PhabricatorUnifiedDiffsSetting extends PhabricatorSelectSetting { const SETTINGKEY = 'diff-unified'; const VALUE_ON_SMALL_SCREENS = 'default'; const VALUE_ALWAYS_UNIFIED = 'unified'; public function getSettingName() { return pht('Show Unified Diffs'); } protected function getSettingOrder() { return 100; } public function getSettingPanelKey() { return PhabricatorDiffPreferencesSettingsPanel::PANELKEY; } protected function getControlInstructions() { return pht( 'Diffs are normally shown in a side-by-side layout on large '. 'screens and automatically switched to a unified view on small '. 'screens (like mobile phones). If you prefer unified diffs even on '. 'large screens, you can select them for use on all displays.'); } public function getSettingDefaultValue() { return self::VALUE_ON_SMALL_SCREENS; } protected function getSelectOptions() { return array( self::VALUE_ON_SMALL_SCREENS => pht('On Small Screens'), self::VALUE_ALWAYS_UNIFIED => pht('Always'), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorConpherenceSoundSetting.php
src/applications/settings/setting/PhabricatorConpherenceSoundSetting.php
<?php final class PhabricatorConpherenceSoundSetting extends PhabricatorSelectSetting { const SETTINGKEY = 'conpherence-sound'; const VALUE_CONPHERENCE_SILENT = '0'; const VALUE_CONPHERENCE_MENTION = '1'; const VALUE_CONPHERENCE_ALL = '2'; public function getSettingName() { return pht('Conpherence Sound'); } public function getSettingPanelKey() { return PhabricatorConpherencePreferencesSettingsPanel::PANELKEY; } protected function getControlInstructions() { return pht( 'Choose the default sound behavior for new Conpherence rooms.'); } protected function isEnabledForViewer(PhabricatorUser $viewer) { return PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorConpherenceApplication', $viewer); } public function getSettingDefaultValue() { return self::VALUE_CONPHERENCE_ALL; } protected function getSelectOptions() { return self::getOptionsMap(); } public static function getSettingLabel($key) { $labels = self::getOptionsMap(); return idx($labels, $key, pht('Unknown ("%s")', $key)); } public static function getDefaultSound($value) { switch ($value) { case self::VALUE_CONPHERENCE_ALL: return array( ConpherenceRoomSettings::SOUND_RECEIVE => ConpherenceRoomSettings::DEFAULT_RECEIVE_SOUND, ConpherenceRoomSettings::SOUND_MENTION => ConpherenceRoomSettings::DEFAULT_MENTION_SOUND, ); break; case self::VALUE_CONPHERENCE_MENTION: return array( ConpherenceRoomSettings::SOUND_RECEIVE => ConpherenceRoomSettings::DEFAULT_NO_SOUND, ConpherenceRoomSettings::SOUND_MENTION => ConpherenceRoomSettings::DEFAULT_MENTION_SOUND, ); break; case self::VALUE_CONPHERENCE_SILENT: return array( ConpherenceRoomSettings::SOUND_RECEIVE => ConpherenceRoomSettings::DEFAULT_NO_SOUND, ConpherenceRoomSettings::SOUND_MENTION => ConpherenceRoomSettings::DEFAULT_NO_SOUND, ); break; } } private static function getOptionsMap() { return array( self::VALUE_CONPHERENCE_SILENT => pht('No Sounds'), // self::VALUE_CONPHERENCE_MENTION => pht('Mentions Only'), self::VALUE_CONPHERENCE_ALL => pht('All Messages'), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorConpherenceColumnMinimizeSetting.php
src/applications/settings/setting/PhabricatorConpherenceColumnMinimizeSetting.php
<?php final class PhabricatorConpherenceColumnMinimizeSetting extends PhabricatorInternalSetting { const SETTINGKEY = 'conpherence-minimize-column'; public function getSettingName() { return pht('Conpherence Column Minimize'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorMonospacedFontSetting.php
src/applications/settings/setting/PhabricatorMonospacedFontSetting.php
<?php final class PhabricatorMonospacedFontSetting extends PhabricatorStringSetting { const SETTINGKEY = 'monospaced'; public function getSettingName() { return pht('Monospaced Font'); } public function getSettingPanelKey() { return PhabricatorDisplayPreferencesSettingsPanel::PANELKEY; } protected function getSettingOrder() { return 500; } protected function getControlInstructions() { return pht( 'You can customize the font used when showing monospaced text, '. 'including source code. You should enter a valid CSS font declaration '. 'like: `13px Consolas`'); } public function validateTransactionValue($value) { if (!strlen($value)) { return; } $filtered = self::filterMonospacedCSSRule($value); if ($filtered !== $value) { throw new Exception( pht( 'Monospaced font value "%s" is unsafe. You may only enter '. 'letters, numbers, spaces, commas, periods, hyphens, '. 'forward slashes, and double quotes', $value)); } } public static function filterMonospacedCSSRule($monospaced) { // Prevent the user from doing dangerous things. return preg_replace('([^a-z0-9 ,"./-]+)i', '', $monospaced); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorSetting.php
src/applications/settings/setting/PhabricatorSetting.php
<?php abstract class PhabricatorSetting extends Phobject { private $viewer = false; public function setViewer(PhabricatorUser $viewer = null) { $this->viewer = $viewer; return $this; } public function getViewer() { if ($this->viewer === false) { throw new PhutilInvalidStateException('setViewer'); } return $this->viewer; } abstract public function getSettingName(); public function getSettingPanelKey() { return null; } protected function getSettingOrder() { return 1000; } public function getSettingOrderVector() { return id(new PhutilSortVector()) ->addInt($this->getSettingOrder()) ->addString($this->getSettingName()); } protected function getControlInstructions() { return null; } protected function isEnabledForViewer(PhabricatorUser $viewer) { return true; } public function getSettingDefaultValue() { return null; } final public function getSettingKey() { return $this->getPhobjectClassConstant('SETTINGKEY'); } public static function getAllSettings() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getSettingKey') ->execute(); } public static function getAllEnabledSettings(PhabricatorUser $viewer) { $settings = self::getAllSettings(); foreach ($settings as $key => $setting) { if (!$setting->isEnabledForViewer($viewer)) { unset($settings[$key]); } } return $settings; } final public function newCustomEditFields($object) { $fields = array(); $field = $this->newCustomEditField($object); if ($field) { $fields[] = $field; } return $fields; } protected function newCustomEditField($object) { return null; } protected function newEditField($object, PhabricatorEditField $template) { $setting_property = PhabricatorUserPreferencesTransaction::PROPERTY_SETTING; $setting_key = $this->getSettingKey(); $value = $object->getPreference($setting_key); $xaction_type = PhabricatorUserPreferencesTransaction::TYPE_SETTING; $label = $this->getSettingName(); $template ->setKey($setting_key) ->setLabel($label) ->setValue($value) ->setTransactionType($xaction_type) ->setMetadataValue($setting_property, $setting_key); $instructions = $this->getControlInstructions(); if (strlen($instructions)) { $template->setControlInstructions($instructions); } return $template; } public function validateTransactionValue($value) { return; } public function assertValidValue($value) { $this->validateTransactionValue($value); } public function getTransactionNewValue($value) { return $value; } public function expandSettingTransaction($object, $xaction) { return array($xaction); } protected function newSettingTransaction($object, $key, $value) { $setting_property = PhabricatorUserPreferencesTransaction::PROPERTY_SETTING; $xaction_type = PhabricatorUserPreferencesTransaction::TYPE_SETTING; return id(clone $object->getApplicationTransactionTemplate()) ->setTransactionType($xaction_type) ->setMetadataValue($setting_property, $key) ->setNewValue($value); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorSelectSetting.php
src/applications/settings/setting/PhabricatorSelectSetting.php
<?php abstract class PhabricatorSelectSetting extends PhabricatorSetting { abstract protected function getSelectOptions(); final protected function newCustomEditField($object) { $setting_key = $this->getSettingKey(); $default_value = $object->getDefaultValue($setting_key); $options = $this->getSelectOptions(); if (isset($options[$default_value])) { $default_label = pht('Default (%s)', $options[$default_value]); } else { $default_label = pht('Default (Unknown, "%s")', $default_value); } if (empty($options[''])) { $options = array( '' => $default_label, ) + $options; } return $this->newEditField($object, new PhabricatorSelectEditField()) ->setOptions($options); } public function assertValidValue($value) { // This is a slightly stricter check than the transaction check. It's // OK for empty string to go through transactions because it gets converted // to null later, but we shouldn't be reading the empty string from // storage. if ($value === null) { return; } if (!strlen($value)) { throw new Exception( pht( 'Empty string is not a valid setting for "%s".', $this->getSettingName())); } $this->validateTransactionValue($value); } final public function validateTransactionValue($value) { $value = phutil_string_cast($value); if (!strlen($value)) { return; } $options = $this->getSelectOptions(); if (!isset($options[$value])) { throw new Exception( pht( 'Value "%s" is not valid for setting "%s": valid values are %s.', $value, $this->getSettingName(), implode(', ', array_keys($options)))); } return; } public function getTransactionNewValue($value) { $value = phutil_string_cast($value); if (!strlen($value)) { return null; } return $value; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/settings/setting/PhabricatorPronounSetting.php
src/applications/settings/setting/PhabricatorPronounSetting.php
<?php final class PhabricatorPronounSetting extends PhabricatorSelectSetting { const SETTINGKEY = 'pronoun'; public function getSettingName() { return pht('Pronoun'); } public function getSettingPanelKey() { return PhabricatorLanguageSettingsPanel::PANELKEY; } protected function getSettingOrder() { return 200; } protected function getControlInstructions() { return pht('Choose the pronoun you prefer.'); } public function getSettingDefaultValue() { return PhutilPerson::GENDER_UNKNOWN; } protected function getSelectOptions() { // TODO: When editing another user's settings as an administrator, this // is not the best username: the user's username would be better. $viewer = $this->getViewer(); $username = $viewer->getUsername(); $label_unknown = pht('%s updated their profile', $username); $label_her = pht('%s updated her profile', $username); $label_his = pht('%s updated his profile', $username); return array( PhutilPerson::GENDER_UNKNOWN => $label_unknown, PhutilPerson::GENDER_MASCULINE => $label_his, PhutilPerson::GENDER_FEMININE => $label_her, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false