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/passphrase/credentialtype/__tests__/PassphraseCredentialTypeTestCase.php
src/applications/passphrase/credentialtype/__tests__/PassphraseCredentialTypeTestCase.php
<?php final class PassphraseCredentialTypeTestCase extends PhabricatorTestCase { public function testGetAllTypes() { PassphraseCredentialType::getAllTypes(); $this->assertTrue(true); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/policyrule/PassphraseCredentialAuthorPolicyRule.php
src/applications/passphrase/policyrule/PassphraseCredentialAuthorPolicyRule.php
<?php final class PassphraseCredentialAuthorPolicyRule extends PhabricatorPolicyRule { public function getObjectPolicyKey() { return 'passphrase.author'; } public function getObjectPolicyName() { return pht('Credential Author'); } public function getPolicyExplanation() { return pht('The author of this credential can take this action.'); } public function getRuleDescription() { return pht('credential author'); } public function canApplyToObject(PhabricatorPolicyInterface $object) { return ($object instanceof PassphraseCredential); } public function applyRule( PhabricatorUser $viewer, $value, PhabricatorPolicyInterface $object) { $author_phid = $object->getAuthorPHID(); if (!$author_phid) { return false; } $viewer_phid = $viewer->getPHID(); if (!$viewer_phid) { return false; } return ($viewer_phid == $author_phid); } public function getValueControlType() { return self::CONTROL_TYPE_NONE; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/view/PassphraseCredentialControl.php
src/applications/passphrase/view/PassphraseCredentialControl.php
<?php final class PassphraseCredentialControl extends AphrontFormControl { private $options = array(); private $credentialType; private $defaultUsername; private $allowNull; public function setAllowNull($allow_null) { $this->allowNull = $allow_null; return $this; } public function setDefaultUsername($default_username) { $this->defaultUsername = $default_username; return $this; } public function setCredentialType($credential_type) { $this->credentialType = $credential_type; return $this; } public function getCredentialType() { return $this->credentialType; } public function setOptions(array $options) { assert_instances_of($options, 'PassphraseCredential'); $this->options = $options; return $this; } protected function getCustomControlClass() { return 'passphrase-credential-control'; } protected function renderInput() { $options_map = array(); foreach ($this->options as $option) { $options_map[$option->getPHID()] = pht( '%s %s', $option->getMonogram(), $option->getName()); } // The user editing the form may not have permission to see the current // credential. Populate it into the menu to allow them to save the form // without making any changes. $current_phid = $this->getValue(); if ($current_phid !== null && strlen($current_phid) && empty($options_map[$current_phid])) { $viewer = $this->getViewer(); $current_name = null; try { $user_credential = id(new PassphraseCredentialQuery()) ->setViewer($viewer) ->withPHIDs(array($current_phid)) ->executeOne(); if ($user_credential) { $current_name = pht( '%s %s', $user_credential->getMonogram(), $user_credential->getName()); } } catch (PhabricatorPolicyException $policy_exception) { // Pull the credential with the omnipotent viewer so we can look up // the ID and provide the monogram. $omnipotent_credential = id(new PassphraseCredentialQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs(array($current_phid)) ->executeOne(); if ($omnipotent_credential) { $current_name = pht( '%s (Restricted Credential)', $omnipotent_credential->getMonogram()); } } if ($current_name === null) { $current_name = pht( 'Invalid Credential ("%s")', $current_phid); } $options_map = array( $current_phid => $current_name, ) + $options_map; } $disabled = $this->getDisabled(); if ($this->allowNull) { $options_map = array('' => pht('(No Credentials)')) + $options_map; } else { if (!$options_map) { $options_map[''] = pht('(No Existing Credentials)'); $disabled = true; } } Javelin::initBehavior('passphrase-credential-control'); $options = AphrontFormSelectControl::renderSelectTag( $this->getValue(), $options_map, array( 'id' => $this->getControlID(), 'name' => $this->getName(), 'disabled' => $disabled ? 'disabled' : null, 'sigil' => 'passphrase-credential-select', )); if ($this->credentialType) { $button = javelin_tag( 'a', array( 'href' => '#', 'class' => 'button button-grey mll', 'sigil' => 'passphrase-credential-add', 'mustcapture' => true, 'style' => 'height: 20px;', // move aphront-form to tables ), pht('Add New Credential')); } else { $button = null; } return javelin_tag( 'div', array( 'sigil' => 'passphrase-credential-control', 'meta' => array( 'type' => $this->getCredentialType(), 'username' => $this->defaultUsername, 'allowNull' => $this->allowNull, ), ), array( $options, $button, )); } /** * Verify that a given actor has permission to use all of the credentials * in a list of credential transactions. * * In general, the rule here is: * * - If you're editing an object and it uses a credential you can't use, * that's fine as long as you don't change the credential. * - If you do change the credential, the new credential must be one you * can use. * * @param PhabricatorUser The acting user. * @param list<PhabricatorApplicationTransaction> List of credential altering * transactions. * @return bool True if the transactions are valid. */ public static function validateTransactions( PhabricatorUser $actor, array $xactions) { $new_phids = array(); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if (!$new) { // Removing a credential, so this is OK. continue; } $old = $xaction->getOldValue(); if ($old == $new) { // This is a no-op transaction, so this is also OK. continue; } // Otherwise, we need to check this credential. $new_phids[] = $new; } if (!$new_phids) { // No new credentials being set, so this is fine. return true; } $usable_credentials = id(new PassphraseCredentialQuery()) ->setViewer($actor) ->withPHIDs($new_phids) ->execute(); $usable_credentials = mpull($usable_credentials, null, 'getPHID'); foreach ($new_phids as $phid) { if (empty($usable_credentials[$phid])) { return false; } } 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/passphrase/phid/PassphraseCredentialPHIDType.php
src/applications/passphrase/phid/PassphraseCredentialPHIDType.php
<?php final class PassphraseCredentialPHIDType extends PhabricatorPHIDType { const TYPECONST = 'CDTL'; public function getTypeName() { return pht('Passphrase Credential'); } public function newObject() { return new PassphraseCredential(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorPassphraseApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PassphraseCredentialQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $credential = $objects[$phid]; $id = $credential->getID(); $name = $credential->getName(); $handle->setName("K{$id}"); $handle->setFullName("K{$id} {$name}"); $handle->setURI("/K{$id}"); if ($credential->getIsDestroyed()) { $handle->setStatus(PhabricatorObjectHandle::STATUS_CLOSED); } } } public function canLoadNamedObject($name) { return preg_match('/^K\d*[1-9]\d*$/i', $name); } public function loadNamedObjects( PhabricatorObjectQuery $query, array $names) { $id_map = array(); foreach ($names as $name) { $id = (int)substr($name, 1); $id_map[$id][] = $name; } $objects = id(new PassphraseCredentialQuery()) ->setViewer($query->getViewer()) ->withIDs(array_keys($id_map)) ->execute(); $results = array(); foreach ($objects as $id => $object) { foreach (idx($id_map, $id, array()) as $name) { $results[$name] = $object; } } return $results; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/conduit/PassphraseConduitAPIMethod.php
src/applications/passphrase/conduit/PassphraseConduitAPIMethod.php
<?php abstract class PassphraseConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass( 'PhabricatorPassphraseApplication'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/conduit/PassphraseQueryConduitAPIMethod.php
src/applications/passphrase/conduit/PassphraseQueryConduitAPIMethod.php
<?php final class PassphraseQueryConduitAPIMethod extends PassphraseConduitAPIMethod { public function getAPIMethodName() { return 'passphrase.query'; } public function getMethodDescription() { return pht('Query credentials.'); } public function newQueryObject() { return new PassphraseCredentialQuery(); } protected function defineParamTypes() { return array( 'ids' => 'optional list<int>', 'phids' => 'optional list<phid>', 'needSecrets' => 'optional bool', 'needPublicKeys' => 'optional bool', ); } protected function defineReturnType() { return 'list<dict>'; } protected function execute(ConduitAPIRequest $request) { $query = $this->newQueryForRequest($request); if ($request->getValue('ids')) { $query->withIDs($request->getValue('ids')); } if ($request->getValue('phids')) { $query->withPHIDs($request->getValue('phids')); } if ($request->getValue('needSecrets')) { $query->needSecrets(true); } $pager = $this->newPager($request); $credentials = $query->executeWithCursorPager($pager); $results = array(); foreach ($credentials as $credential) { $type = PassphraseCredentialType::getTypeByConstant( $credential->getCredentialType()); if (!$type) { continue; } $public_key = null; if ($request->getValue('needPublicKeys') && $type->hasPublicKey()) { $public_key = $type->getPublicKey( $request->getUser(), $credential); } $material = array(); $is_locked = $credential->getIsLocked(); $allow_api = ($credential->getAllowConduit() && !$is_locked); $secret = null; if ($request->getValue('needSecrets')) { if ($allow_api) { $secret = $credential->getSecret(); if ($secret) { $secret = $secret->openEnvelope(); } else { $material['destroyed'] = pht( 'The private material for this credential has been '. 'destroyed.'); } } } switch ($credential->getCredentialType()) { case PassphraseSSHPrivateKeyFileCredentialType::CREDENTIAL_TYPE: if ($secret !== null) { $material['file'] = $secret; } if ($public_key) { $material['publicKey'] = $public_key; } break; case PassphraseSSHGeneratedKeyCredentialType::CREDENTIAL_TYPE: case PassphraseSSHPrivateKeyTextCredentialType::CREDENTIAL_TYPE: if ($secret !== null) { $material['privateKey'] = $secret; } if ($public_key) { $material['publicKey'] = $public_key; } break; case PassphrasePasswordCredentialType::CREDENTIAL_TYPE: if ($secret !== null) { $material['password'] = $secret; } break; case PassphraseTokenCredentialType::CREDENTIAL_TYPE: if ($secret !== null) { $material['token'] = $secret; } break; } if (!$allow_api) { $material['noAPIAccess'] = pht( 'This private material for this credential is not accessible via '. 'API calls.'); } $results[$credential->getPHID()] = array( 'id' => $credential->getID(), 'phid' => $credential->getPHID(), 'type' => $credential->getCredentialType(), 'name' => $credential->getName(), 'description' => $credential->getDescription(), 'uri' => PhabricatorEnv::getProductionURI('/'.$credential->getMonogram()), 'monogram' => $credential->getMonogram(), 'username' => $credential->getUsername(), 'material' => $material, ); } $result = array( 'data' => $results, ); return $this->addPagerResults($result, $pager); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/search/PassphraseCredentialFerretEngine.php
src/applications/passphrase/search/PassphraseCredentialFerretEngine.php
<?php final class PassphraseCredentialFerretEngine extends PhabricatorFerretEngine { public function getApplicationName() { return 'passphrase'; } public function getScopeName() { return 'credential'; } public function newSearchEngine() { return new PassphraseCredentialSearchEngine(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/search/PassphraseCredentialFulltextEngine.php
src/applications/passphrase/search/PassphraseCredentialFulltextEngine.php
<?php final class PassphraseCredentialFulltextEngine extends PhabricatorFulltextEngine { protected function buildAbstractDocument( PhabricatorSearchAbstractDocument $document, $object) { $credential = $object; $document->setDocumentTitle($credential->getName()); $document->addField( PhabricatorSearchDocumentFieldType::FIELD_BODY, $credential->getDescription()); $document->addRelationship( $credential->getIsDestroyed() ? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED : PhabricatorSearchRelationship::RELATIONSHIP_OPEN, $credential->getPHID(), PassphraseCredentialPHIDType::TYPECONST, PhabricatorTime::getNow()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/capability/PassphraseDefaultViewCapability.php
src/applications/passphrase/capability/PassphraseDefaultViewCapability.php
<?php final class PassphraseDefaultViewCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'passphrase.default.view'; public function getCapabilityName() { return pht('Default View Policy'); } public function shouldAllowPublicPolicySetting() { return true; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/capability/PassphraseDefaultEditCapability.php
src/applications/passphrase/capability/PassphraseDefaultEditCapability.php
<?php final class PassphraseDefaultEditCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'passphrase.default.edit'; public function getCapabilityName() { return pht('Default Edit Policy'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/keys/PassphrasePasswordKey.php
src/applications/passphrase/keys/PassphrasePasswordKey.php
<?php final class PassphrasePasswordKey extends PassphraseAbstractKey { public static function loadFromPHID($phid, PhabricatorUser $viewer) { $key = new PassphrasePasswordKey(); return $key->loadAndValidateFromPHID( $phid, $viewer, PassphrasePasswordCredentialType::PROVIDES_TYPE); } public function getPasswordEnvelope() { return $this->requireCredential()->getSecret(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/keys/PassphraseSSHKey.php
src/applications/passphrase/keys/PassphraseSSHKey.php
<?php final class PassphraseSSHKey extends PassphraseAbstractKey { private $keyFile; public static function loadFromPHID($phid, PhabricatorUser $viewer) { $key = new PassphraseSSHKey(); return $key->loadAndValidateFromPHID( $phid, $viewer, PassphraseSSHPrivateKeyCredentialType::PROVIDES_TYPE); } public function getKeyfileEnvelope() { $credential = $this->requireCredential(); $file_type = PassphraseSSHPrivateKeyFileCredentialType::CREDENTIAL_TYPE; if ($credential->getCredentialType() != $file_type) { // If the credential does not store a file, write the key text out to a // temporary file so we can pass it to `ssh`. if (!$this->keyFile) { $secret = $credential->getSecret(); if (!$secret) { throw new Exception( pht( 'Attempting to use a credential ("%s") but the credential '. 'secret has been destroyed!', $credential->getMonogram())); } $temporary_file = new TempFile('passphrase-ssh-key'); Filesystem::changePermissions($temporary_file, 0600); Filesystem::writeFile($temporary_file, $secret->openEnvelope()); $this->keyFile = $temporary_file; } return new PhutilOpaqueEnvelope((string)$this->keyFile); } return $credential->getSecret(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/keys/PassphraseAbstractKey.php
src/applications/passphrase/keys/PassphraseAbstractKey.php
<?php abstract class PassphraseAbstractKey extends Phobject { private $credential; protected function requireCredential() { if (!$this->credential) { throw new Exception(pht('Credential is required!')); } return $this->credential; } private function loadCredential( $phid, PhabricatorUser $viewer) { $credential = id(new PassphraseCredentialQuery()) ->setViewer($viewer) ->withPHIDs(array($phid)) ->needSecrets(true) ->executeOne(); if (!$credential) { throw new Exception(pht('Failed to load credential "%s"!', $phid)); } return $credential; } private function validateCredential( PassphraseCredential $credential, $provides_type) { $type = $credential->getImplementation(); if (!$type) { throw new Exception( pht( 'Credential "%s" is of unknown type "%s"!', $credential->getMonogram(), $credential->getCredentialType())); } if ($type->getProvidesType() !== $provides_type) { throw new Exception( pht( 'Credential "%s" must provide "%s", but provides "%s"!', $credential->getMonogram(), $provides_type, $type->getProvidesType())); } } protected function loadAndValidateFromPHID( $phid, PhabricatorUser $viewer, $type) { $credential = $this->loadCredential($phid, $viewer); $this->validateCredential($credential, $type); $this->credential = $credential; return $this; } public function getUsernameEnvelope() { $credential = $this->requireCredential(); return new PhutilOpaqueEnvelope($credential->getUsername()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/passphrase/remarkup/PassphraseRemarkupRule.php
src/applications/passphrase/remarkup/PassphraseRemarkupRule.php
<?php final class PassphraseRemarkupRule extends PhabricatorObjectRemarkupRule { protected function getObjectNamePrefix() { return 'K'; } protected function loadObjects(array $ids) { $viewer = $this->getEngine()->getConfig('viewer'); return id(new PassphraseCredentialQuery()) ->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/lipsum/management/PhabricatorLipsumGenerateWorkflow.php
src/applications/lipsum/management/PhabricatorLipsumGenerateWorkflow.php
<?php final class PhabricatorLipsumGenerateWorkflow extends PhabricatorLipsumManagementWorkflow { protected function didConstruct() { $this ->setName('generate') ->setExamples('**generate**') ->setSynopsis(pht('Generate synthetic test objects.')) ->setArguments( array( array( 'name' => 'force', 'short' => 'f', 'help' => pht( 'Generate objects without prompting for confirmation.'), ), array( 'name' => 'quickly', 'help' => pht( 'Generate objects as quickly as possible.'), ), array( 'name' => 'args', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $config_key = 'phabricator.developer-mode'; if (!PhabricatorEnv::getEnvConfig($config_key)) { throw new PhutilArgumentUsageException( pht( 'lipsum is a development and testing tool and may only be run '. 'on installs in developer mode. Enable "%s" in your configuration '. 'to enable lipsum.', $config_key)); } $all_generators = id(new PhutilClassMapQuery()) ->setAncestorClass('PhabricatorTestDataGenerator') ->setUniqueMethod('getGeneratorKey') ->execute(); $argv = $args->getArg('args'); $is_force = $args->getArg('force'); $is_quickly = $args->getArg('quickly'); $all = 'all'; if (isset($all_generators[$all])) { throw new Exception( pht( 'A lipsum generator is registered with key "%s". This key is '. 'reserved.', $all)); } if (!$argv) { ksort($all_generators); $names = array(); foreach ($all_generators as $generator) { $names[] = tsprintf( '%s (%s)', $generator->getGeneratorKey(), $generator->getGeneratorName()); } $list = id(new PhutilConsoleList()) ->setWrap(false) ->addItems($names); id(new PhutilConsoleBlock()) ->addParagraph( pht( 'Choose which type or types of test data you want to generate, '. 'or select "%s".', $all)) ->addList($list) ->draw(); return 0; } $generators = array(); foreach ($argv as $arg_original) { $arg = phutil_utf8_strtolower($arg_original); if ($arg == 'all') { $matches = $all_generators; } else { $matches = array(); foreach ($all_generators as $generator) { $name = phutil_utf8_strtolower($generator->getGeneratorKey()); // If there's an exact match, select just that generator. if ($arg == $name) { $matches = array($generator); break; } // If there's a partial match, match that generator but continue. if (strpos($name, $arg) !== false) { $matches[] = $generator; } } if (!$matches) { throw new PhutilArgumentUsageException( pht( 'Argument "%s" does not match the name of any generators.', $arg_original)); } if (count($matches) > 1) { throw new PhutilArgumentUsageException( pht( 'Argument "%s" is ambiguous, and matches multiple '. 'generators: %s.', $arg_original, implode(', ', mpull($matches, 'getGeneratorName')))); } } foreach ($matches as $match) { $generators[] = $match; } } $generators = mpull($generators, null, 'getGeneratorKey'); echo tsprintf( "**<bg:blue> %s </bg>** %s\n", pht('GENERATORS'), pht( 'Selected generators: %s.', implode(', ', mpull($generators, 'getGeneratorName')))); if (!$is_force) { echo tsprintf( "**<bg:yellow> %s </bg>** %s\n", pht('WARNING'), pht( 'This command generates synthetic test data, including user '. 'accounts. It is intended for use in development environments so '. 'you can test features more easily. There is no easy way to delete '. 'this data or undo the effects of this command. If you run it in a '. 'production environment, it will pollute your data with large '. 'amounts of meaningless garbage that you can not get rid of.')); $prompt = pht('Are you sure you want to generate piles of garbage?'); if (!phutil_console_confirm($prompt, true)) { return; } } echo tsprintf( "**<bg:green> %s </bg>** %s\n", pht('LIPSUM'), pht( 'Generating synthetic test objects forever. '. 'Use ^C to stop when satisfied.')); $this->generate($generators, $is_quickly); } protected function generate(array $generators, $is_quickly) { $viewer = $this->getViewer(); foreach ($generators as $generator) { $generator->setViewer($this->getViewer()); } while (true) { $generator = $generators[array_rand($generators)]; try { $object = $generator->generateObject(); } catch (Exception $ex) { echo tsprintf( "**<bg:yellow> %s </bg>** %s\n", pht('OOPS'), pht( 'Generator ("%s") was unable to generate an object.', $generator->getGeneratorName())); echo tsprintf( "%B\n", $ex->getMessage()); continue; } if (is_string($object)) { $object_phid = $object; } else { $object_phid = $object->getPHID(); } $handles = $viewer->loadHandles(array($object_phid)); echo tsprintf( "%s\n", pht( 'Generated "%s": %s', $handles[$object_phid]->getTypeName(), $handles[$object_phid]->getFullName())); if (!$is_quickly) { sleep(1); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/lipsum/management/PhabricatorLipsumManagementWorkflow.php
src/applications/lipsum/management/PhabricatorLipsumManagementWorkflow.php
<?php abstract class PhabricatorLipsumManagementWorkflow 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/lipsum/image/PhabricatorLipsumArtist.php
src/applications/lipsum/image/PhabricatorLipsumArtist.php
<?php abstract class PhabricatorLipsumArtist extends Phobject { protected function getHSBColor($h, $s, $b) { if ($s == 0) { $cr = $b; $cg = $b; $cb = $b; } else { $h /= 60; $i = (int)$h; $f = $h - $i; $p = $b * (1 - $s); $q = $b * (1 - $s * $f); $t = $b * (1 - $s * (1 - $f)); switch ($i) { case 0: $cr = $b; $cg = $t; $cb = $p; break; case 1: $cr = $q; $cg = $b; $cb = $p; break; case 2: $cr = $p; $cg = $b; $cb = $t; break; case 3: $cr = $p; $cg = $q; $cb = $b; break; case 4: $cr = $t; $cg = $p; $cb = $b; break; default: $cr = $b; $cg = $p; $cb = $q; break; } } $cr = (int)round($cr * 255); $cg = (int)round($cg * 255); $cb = (int)round($cb * 255); return ($cr << 16) + ($cg << 8) + $cb; } public function generate($x, $y) { $image = imagecreatetruecolor($x, $y); $this->draw($image, $x, $y); return PhabricatorImageTransformer::saveImageDataInAnyFormat( $image, 'image/jpeg'); } abstract protected function draw($image, $x, $y); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/lipsum/image/PhabricatorLipsumMondrianArtist.php
src/applications/lipsum/image/PhabricatorLipsumMondrianArtist.php
<?php final class PhabricatorLipsumMondrianArtist extends PhabricatorLipsumArtist { protected function draw($image, $x, $y) { $c_white = 0xFFFFFF; $c_black = 0x000000; imagefill($image, 0, 0, $c_white); $lines_h = mt_rand(2, 5); $lines_v = mt_rand(2, 5); for ($ii = 0; $ii < $lines_h; $ii++) { $yp = mt_rand(0, $y); $thickness = mt_rand(2, 3); for ($jj = 0; $jj < $thickness; $jj++) { imageline($image, 0, $yp + $jj, $x, $yp + $jj, $c_black); } } for ($ii = 0; $ii < $lines_v; $ii++) { $xp = mt_rand(0, $x); $thickness = mt_rand(2, 3); for ($jj = 0; $jj < $thickness; $jj++) { imageline($image, $xp + $jj, 0, $xp + $jj, $y, $c_black); } } $fills = mt_rand(3, 8); for ($ii = 0; $ii < $fills; $ii++) { $xp = mt_rand(0, $x - 1); $yp = mt_rand(0, $y - 1); if (imagecolorat($image, $xp, $yp) != $c_white) { continue; } $c_fill = $this->getHSBColor( mt_rand(0, 359), mt_rand(80, 100) / 100, mt_rand(90, 100) / 100); imagefill($image, $xp, $yp, $c_fill); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/lipsum/generator/PhabricatorTestDataGenerator.php
src/applications/lipsum/generator/PhabricatorTestDataGenerator.php
<?php abstract class PhabricatorTestDataGenerator extends Phobject { private $viewer; abstract public function getGeneratorName(); abstract public function generateObject(); final public function setViewer(PhabricatorUser $viewer) { $this->viewer = $viewer; return $this; } final public function getViewer() { return $this->viewer; } final public function getGeneratorKey() { return $this->getPhobjectClassConstant('GENERATORKEY', 64); } protected function loadRandomPHID($table) { $conn_r = $table->establishConnection('r'); $row = queryfx_one( $conn_r, 'SELECT phid FROM %T ORDER BY RAND() LIMIT 1', $table->getTableName()); if (!$row) { return null; } return $row['phid']; } protected function loadRandomUser() { $viewer = $this->getViewer(); $user_phid = $this->loadRandomPHID(new PhabricatorUser()); $user = null; if ($user_phid) { $user = id(new PhabricatorPeopleQuery()) ->setViewer($viewer) ->withPHIDs(array($user_phid)) ->needUserSettings(true) ->executeOne(); } if (!$user) { throw new Exception( pht( 'Failed to load a random user. You may need to generate more '. 'test users first.')); } return $user; } protected function getLipsumContentSource() { return PhabricatorContentSource::newForSource( PhabricatorLipsumContentSource::SOURCECONST); } /** * Roll `n` dice with `d` sides each, then add `bonus` and return the sum. */ protected function roll($n, $d, $bonus = 0) { $sum = 0; for ($ii = 0; $ii < $n; $ii++) { $sum += mt_rand(1, $d); } $sum += $bonus; return $sum; } protected function newEmptyTransaction() { throw new PhutilMethodNotImplementedException(); } protected function newTransaction($type, $value, $metadata = array()) { $xaction = $this->newEmptyTransaction() ->setTransactionType($type) ->setNewValue($value); foreach ($metadata as $key => $value) { $xaction->setMetadataValue($key, $value); } return $xaction; } public function loadOneRandom($classname) { try { return newv($classname, array()) ->loadOneWhere('1 = 1 ORDER BY RAND() LIMIT 1'); } catch (PhutilMissingSymbolException $ex) { throw new PhutilMissingSymbolException( $classname, pht('class'), pht( 'Unable to load symbol %s: this class does not exist.', $classname)); } } public function loadPhabricatorUserPHID() { return $this->loadOneRandom('PhabricatorUser')->getPHID(); } public function loadPhabricatorUser() { return $this->loadOneRandom('PhabricatorUser'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/controller/PhluxListController.php
src/applications/phlux/controller/PhluxListController.php
<?php final class PhluxListController extends PhluxController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $pager = new AphrontCursorPagerView(); $pager->readFromRequest($request); $query = id(new PhluxVariableQuery()) ->setViewer($viewer); $vars = $query->executeWithCursorPager($pager); $view = new PHUIObjectItemListView(); $view->setFlush(true); foreach ($vars as $var) { $key = $var->getVariableKey(); $item = new PHUIObjectItemView(); $item->setHeader($key); $item->setHref($this->getApplicationURI('/view/'.$key.'/')); $item->addIcon( 'none', phabricator_datetime($var->getDateModified(), $viewer)); $view->addItem($item); } $crumbs = $this->buildApplicationCrumbs(); $box = id(new PHUIObjectBoxView()) ->setHeaderText('Variables') ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild($view); $title = pht('Variable List'); $header = id(new PHUIHeaderView()) ->setHeader($title) ->setHeaderIcon('fa-copy'); $crumbs->addTextCrumb($title, $this->getApplicationURI()); $crumbs->setBorder(true); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $box, $pager, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/controller/PhluxEditController.php
src/applications/phlux/controller/PhluxEditController.php
<?php final class PhluxEditController extends PhluxController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $key = $request->getURIData('key'); $is_new = ($key === null); if ($is_new) { $var = new PhluxVariable(); $var->setViewPolicy(PhabricatorPolicies::POLICY_USER); $var->setEditPolicy(PhabricatorPolicies::POLICY_USER); } else { $var = id(new PhluxVariableQuery()) ->setViewer($viewer) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->withKeys(array($key)) ->executeOne(); if (!$var) { return new Aphront404Response(); } $view_uri = $this->getApplicationURI('/view/'.$key.'/'); } $e_key = ($is_new ? true : null); $e_value = true; $errors = array(); $key = $var->getVariableKey(); $display_value = null; $value = $var->getVariableValue(); if ($request->isFormPost()) { if ($is_new) { $key = $request->getStr('key'); if (!strlen($key)) { $errors[] = pht('Variable key is required.'); $e_key = pht('Required'); } else if (!preg_match('/^[a-z0-9.-]+\z/', $key)) { $errors[] = pht( 'Variable key "%s" must contain only lowercase letters, digits, '. 'period, and hyphen.', $key); $e_key = pht('Invalid'); } } $raw_value = $request->getStr('value'); $value = json_decode($raw_value, true); if ($value === null && strtolower($raw_value) !== 'null') { $e_value = pht('Invalid'); $errors[] = pht('Variable value must be valid JSON.'); $display_value = $raw_value; } if (!$errors) { $editor = id(new PhluxVariableEditor()) ->setActor($viewer) ->setContinueOnNoEffect(true) ->setContentSourceFromRequest($request); $xactions = array(); $xactions[] = id(new PhluxTransaction()) ->setTransactionType(PhluxTransaction::TYPE_EDIT_KEY) ->setNewValue($key); $xactions[] = id(new PhluxTransaction()) ->setTransactionType(PhluxTransaction::TYPE_EDIT_VALUE) ->setNewValue($value); $xactions[] = id(new PhluxTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY) ->setNewValue($request->getStr('viewPolicy')); $xactions[] = id(new PhluxTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDIT_POLICY) ->setNewValue($request->getStr('editPolicy')); try { $editor->applyTransactions($var, $xactions); $view_uri = $this->getApplicationURI('/view/'.$key.'/'); return id(new AphrontRedirectResponse())->setURI($view_uri); } catch (AphrontDuplicateKeyQueryException $ex) { $e_key = pht('Not Unique'); $errors[] = pht('Variable key must be unique.'); } } } if ($display_value === null) { if (is_array($value) && (array_keys($value) !== array_keys(array_values($value)))) { $json = new PhutilJSON(); $display_value = $json->encodeFormatted($value); } else { $display_value = json_encode($value); } } $policies = id(new PhabricatorPolicyQuery()) ->setViewer($viewer) ->setObject($var) ->execute(); $form = id(new AphrontFormView()) ->setUser($viewer) ->appendChild( id(new AphrontFormTextControl()) ->setValue($var->getVariableKey()) ->setLabel(pht('Key')) ->setName('key') ->setError($e_key) ->setCaption(pht('Lowercase letters, digits, dot and hyphen only.')) ->setDisabled(!$is_new)) ->appendChild( id(new AphrontFormTextAreaControl()) ->setValue($display_value) ->setLabel(pht('Value')) ->setName('value') ->setCaption(pht('Enter value as JSON.')) ->setError($e_value)) ->appendChild( id(new AphrontFormPolicyControl()) ->setName('viewPolicy') ->setPolicyObject($var) ->setCapability(PhabricatorPolicyCapability::CAN_VIEW) ->setPolicies($policies)) ->appendChild( id(new AphrontFormPolicyControl()) ->setName('editPolicy') ->setPolicyObject($var) ->setCapability(PhabricatorPolicyCapability::CAN_EDIT) ->setPolicies($policies)); if ($is_new) { $form->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Create Variable'))); } else { $form->appendChild( id(new AphrontFormSubmitControl()) ->setValue(pht('Update Variable')) ->addCancelButton($view_uri)); } $crumbs = $this->buildApplicationCrumbs(); if ($is_new) { $title = pht('Create Variable'); $crumbs->addTextCrumb($title, $request->getRequestURI()); } else { $title = pht('Edit Variable: %s', $key); $crumbs->addTextCrumb($title, $request->getRequestURI()); } $crumbs->setBorder(true); $box = id(new PHUIObjectBoxView()) ->setHeaderText($title) ->setFormErrors($errors) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setForm($form); $view = id(new PHUITwoColumnView()) ->setFooter(array( $box, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/controller/PhluxController.php
src/applications/phlux/controller/PhluxController.php
<?php abstract class PhluxController extends PhabricatorController { protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); $crumbs->addAction( id(new PHUIListItemView()) ->setName(pht('Create Variable')) ->setHref($this->getApplicationURI('/edit/')) ->setIcon('fa-plus-square')); 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/phlux/controller/PhluxViewController.php
src/applications/phlux/controller/PhluxViewController.php
<?php final class PhluxViewController extends PhluxController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $key = $request->getURIData('key'); $var = id(new PhluxVariableQuery()) ->setViewer($viewer) ->withKeys(array($key)) ->executeOne(); if (!$var) { return new Aphront404Response(); } $title = $var->getVariableKey(); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($title, $request->getRequestURI()); $crumbs->setBorder(true); $curtain = $this->buildCurtainView($var); $header = id(new PHUIHeaderView()) ->setHeader($title) ->setUser($viewer) ->setPolicyObject($var) ->setHeaderIcon('fa-copy'); $display_value = json_encode($var->getVariableValue()); $properties = id(new PHUIPropertyListView()) ->setUser($viewer) ->addProperty(pht('Value'), $display_value); $timeline = $this->buildTransactionTimeline( $var, new PhluxTransactionQuery()); $timeline->setShouldTerminate(true); $object_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Details')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addPropertyList($properties); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setCurtain($curtain) ->setMainColumn(array( $object_box, $timeline, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } private function buildCurtainView(PhluxVariable $var) { $viewer = $this->getViewer(); $curtain = $this->newCurtainView($var); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $var, PhabricatorPolicyCapability::CAN_EDIT); $curtain->addAction( id(new PhabricatorActionView()) ->setIcon('fa-pencil') ->setName(pht('Edit Variable')) ->setHref($this->getApplicationURI('/edit/'.$var->getVariableKey().'/')) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); return $curtain; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/storage/PhluxSchemaSpec.php
src/applications/phlux/storage/PhluxSchemaSpec.php
<?php final class PhluxSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new PhluxVariable()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/storage/PhluxTransaction.php
src/applications/phlux/storage/PhluxTransaction.php
<?php final class PhluxTransaction extends PhabricatorApplicationTransaction { const TYPE_EDIT_KEY = 'phlux:key'; const TYPE_EDIT_VALUE = 'phlux:value'; public function getApplicationName() { return 'phlux'; } public function getApplicationTransactionType() { return PhluxVariablePHIDType::TYPECONST; } public function getTitle() { $author_phid = $this->getAuthorPHID(); switch ($this->getTransactionType()) { case self::TYPE_EDIT_KEY: return pht( '%s created this variable.', $this->renderHandleLink($author_phid)); case self::TYPE_EDIT_VALUE: return pht( '%s updated this variable.', $this->renderHandleLink($author_phid)); } return parent::getTitle(); } public function hasChangeDetails() { switch ($this->getTransactionType()) { case self::TYPE_EDIT_VALUE: return true; } return parent::hasChangeDetails(); } public function renderChangeDetails(PhabricatorUser $viewer) { return $this->renderTextCorpusChangeDetails( $viewer, json_encode($this->getOldValue()), json_encode($this->getNewValue())); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/storage/PhluxDAO.php
src/applications/phlux/storage/PhluxDAO.php
<?php abstract class PhluxDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'phlux'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/storage/PhluxVariable.php
src/applications/phlux/storage/PhluxVariable.php
<?php final class PhluxVariable extends PhluxDAO implements PhabricatorApplicationTransactionInterface, PhabricatorFlaggableInterface, PhabricatorPolicyInterface { protected $variableKey; protected $variableValue; protected $viewPolicy; protected $editPolicy; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_SERIALIZATION => array( 'variableValue' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'variableKey' => 'text64', ), self::CONFIG_KEY_SCHEMA => array( 'key_key' => array( 'columns' => array('variableKey'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID(PhluxVariablePHIDType::TYPECONST); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhluxVariableEditor(); } public function getApplicationTransactionTemplate() { return new PhluxTransaction(); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->viewPolicy; case PhabricatorPolicyCapability::CAN_EDIT: return $this->editPolicy; } } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return false; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/query/PhluxTransactionQuery.php
src/applications/phlux/query/PhluxTransactionQuery.php
<?php final class PhluxTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhluxTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/query/PhluxVariableQuery.php
src/applications/phlux/query/PhluxVariableQuery.php
<?php final class PhluxVariableQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $keys; private $phids; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withKeys(array $keys) { $this->keys = $keys; return $this; } protected function loadPage() { $table = new PhluxVariable(); $conn_r = $table->establishConnection('r'); $rows = queryfx_all( $conn_r, 'SELECT * FROM %T %Q %Q %Q', $table->getTableName(), $this->buildWhereClause($conn_r), $this->buildOrderClause($conn_r), $this->buildLimitClause($conn_r)); return $table->loadAllFromArray($rows); } protected function buildWhereClause(AphrontDatabaseConnection $conn) { $where = array(); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'id IN (%Ld)', $this->ids); } if ($this->keys !== null) { $where[] = qsprintf( $conn, 'variableKey IN (%Ls)', $this->keys); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'phid IN (%Ls)', $this->phids); } $where[] = $this->buildPagingClause($conn); return $this->formatWhereClause($conn, $where); } protected function getDefaultOrderVector() { return array('key'); } public function getOrderableColumns() { return array( 'key' => array( 'column' => 'variableKey', 'type' => 'string', 'reverse' => true, 'unique' => true, ), ); } protected function newPagingMapFromPartialObject($object) { return array( 'id' => (int)$object->getID(), 'key' => $object->getVariableKey(), ); } public function getQueryApplicationClass() { return 'PhabricatorPhluxApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/editor/PhluxVariableEditor.php
src/applications/phlux/editor/PhluxVariableEditor.php
<?php final class PhluxVariableEditor extends PhabricatorApplicationTransactionEditor { public function getEditorApplicationClass() { return 'PhabricatorPhluxApplication'; } public function getEditorObjectsDescription() { return pht('Phlux Variables'); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhluxTransaction::TYPE_EDIT_KEY; $types[] = PhluxTransaction::TYPE_EDIT_VALUE; $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY; $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY; return $types; } protected function getCustomTransactionOldValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhluxTransaction::TYPE_EDIT_KEY: return $object->getVariableKey(); case PhluxTransaction::TYPE_EDIT_VALUE: return $object->getVariableValue(); } return parent::getCustomTransactionOldValue($object, $xaction); } protected function getCustomTransactionNewValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhluxTransaction::TYPE_EDIT_KEY: case PhluxTransaction::TYPE_EDIT_VALUE: return $xaction->getNewValue(); } return parent::getCustomTransactionNewValue($object, $xaction); } protected function applyCustomInternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhluxTransaction::TYPE_EDIT_KEY: $object->setVariableKey($xaction->getNewValue()); return; case PhluxTransaction::TYPE_EDIT_VALUE: $object->setVariableValue($xaction->getNewValue()); return; } return parent::applyCustomInternalTransaction($object, $xaction); } protected function applyCustomExternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhluxTransaction::TYPE_EDIT_KEY: case PhluxTransaction::TYPE_EDIT_VALUE: return; } return parent::applyCustomExternalTransaction($object, $xaction); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/application/PhabricatorPhluxApplication.php
src/applications/phlux/application/PhabricatorPhluxApplication.php
<?php final class PhabricatorPhluxApplication extends PhabricatorApplication { public function getName() { return pht('Phlux'); } public function getBaseURI() { return '/phlux/'; } public function getShortDescription() { return pht('Key/Value Configuration Store'); } public function getIcon() { return 'fa-copy'; } public function getTitleGlyph() { return "\xE2\x98\xBD"; } public function getApplicationGroup() { return self::GROUP_UTILITIES; } public function isPrototype() { return true; } public function getRoutes() { return array( '/phlux/' => array( '' => 'PhluxListController', 'view/(?P<key>[^/]+)/' => 'PhluxViewController', 'edit/(?:(?P<key>[^/]+)/)?' => 'PhluxEditController', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phlux/phid/PhluxVariablePHIDType.php
src/applications/phlux/phid/PhluxVariablePHIDType.php
<?php final class PhluxVariablePHIDType extends PhabricatorPHIDType { const TYPECONST = 'PVAR'; public function getTypeName() { return pht('Variable'); } public function newObject() { return new PhluxVariable(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorPhluxApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhluxVariableQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $variable = $objects[$phid]; $key = $variable->getVariableKey(); $handle->setName($key); $handle->setFullName(pht('Variable "%s"', $key)); $handle->setURI("/phlux/view/{$key}/"); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/controller/PhabricatorAuditController.php
src/applications/audit/controller/PhabricatorAuditController.php
<?php abstract class PhabricatorAuditController extends PhabricatorController { public function buildSideNavView() { $user = $this->getRequest()->getUser(); $nav = new AphrontSideNavFilterView(); $nav->setBaseURI(new PhutilURI($this->getApplicationURI())); id(new PhabricatorCommitSearchEngine()) ->setViewer($user) ->addNavigationItems($nav->getMenu()); $nav->selectFilter(null); return $nav; } public function buildApplicationMenu() { return $this->buildSideNavView()->getMenu(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/storage/PhabricatorAuditTransaction.php
src/applications/audit/storage/PhabricatorAuditTransaction.php
<?php final class PhabricatorAuditTransaction extends PhabricatorModularTransaction { const TYPE_COMMIT = 'audit:commit'; const MAILTAG_ACTION_CONCERN = 'audit-action-concern'; const MAILTAG_ACTION_ACCEPT = 'audit-action-accept'; const MAILTAG_ACTION_RESIGN = 'audit-action-resign'; const MAILTAG_ACTION_CLOSE = 'audit-action-close'; const MAILTAG_ADD_AUDITORS = 'audit-add-auditors'; const MAILTAG_ADD_CCS = 'audit-add-ccs'; const MAILTAG_COMMENT = 'audit-comment'; const MAILTAG_COMMIT = 'audit-commit'; const MAILTAG_PROJECTS = 'audit-projects'; const MAILTAG_OTHER = 'audit-other'; public function getApplicationName() { return 'audit'; } public function getBaseTransactionClass() { return 'DiffusionCommitTransactionType'; } public function getApplicationTransactionType() { return PhabricatorRepositoryCommitPHIDType::TYPECONST; } public function getApplicationTransactionCommentObject() { return new PhabricatorAuditTransactionComment(); } public function getRemarkupBlocks() { $blocks = parent::getRemarkupBlocks(); switch ($this->getTransactionType()) { case self::TYPE_COMMIT: $data = $this->getNewValue(); $blocks[] = $data['description']; break; } return $blocks; } public function getActionStrength() { $type = $this->getTransactionType(); switch ($type) { case self::TYPE_COMMIT: return 300; } return parent::getActionStrength(); } public function getRequiredHandlePHIDs() { $phids = parent::getRequiredHandlePHIDs(); $type = $this->getTransactionType(); switch ($type) { case self::TYPE_COMMIT: $phids[] = $this->getObjectPHID(); $data = $this->getNewValue(); if ($data['authorPHID']) { $phids[] = $data['authorPHID']; } if ($data['committerPHID']) { $phids[] = $data['committerPHID']; } break; case PhabricatorAuditActionConstants::ADD_CCS: case PhabricatorAuditActionConstants::ADD_AUDITORS: $old = $this->getOldValue(); $new = $this->getNewValue(); if (!is_array($old)) { $old = array(); } if (!is_array($new)) { $new = array(); } foreach (array_keys($old + $new) as $phid) { $phids[] = $phid; } break; } return $phids; } public function getActionName() { switch ($this->getTransactionType()) { case PhabricatorAuditActionConstants::ACTION: switch ($this->getNewValue()) { case PhabricatorAuditActionConstants::CONCERN: return pht('Raised Concern'); case PhabricatorAuditActionConstants::ACCEPT: return pht('Accepted'); case PhabricatorAuditActionConstants::RESIGN: return pht('Resigned'); case PhabricatorAuditActionConstants::CLOSE: return pht('Closed'); } break; case PhabricatorAuditActionConstants::ADD_AUDITORS: return pht('Added Auditors'); case self::TYPE_COMMIT: return pht('Committed'); } return parent::getActionName(); } public function getColor() { $type = $this->getTransactionType(); switch ($type) { case PhabricatorAuditActionConstants::ACTION: switch ($this->getNewValue()) { case PhabricatorAuditActionConstants::CONCERN: return 'red'; case PhabricatorAuditActionConstants::ACCEPT: return 'green'; case PhabricatorAuditActionConstants::RESIGN: return 'black'; case PhabricatorAuditActionConstants::CLOSE: return 'indigo'; } } return parent::getColor(); } public function getIcon() { $type = $this->getTransactionType(); switch ($type) { case PhabricatorAuditActionConstants::ACTION: switch ($this->getNewValue()) { case PhabricatorAuditActionConstants::CONCERN: return 'fa-exclamation-circle'; case PhabricatorAuditActionConstants::ACCEPT: return 'fa-check'; case PhabricatorAuditActionConstants::RESIGN: return 'fa-plane'; case PhabricatorAuditActionConstants::CLOSE: return 'fa-check'; } } return parent::getIcon(); } public function getTitle() { $old = $this->getOldValue(); $new = $this->getNewValue(); $author_handle = $this->renderHandleLink($this->getAuthorPHID()); $type = $this->getTransactionType(); switch ($type) { case PhabricatorAuditActionConstants::ADD_CCS: case PhabricatorAuditActionConstants::ADD_AUDITORS: if (!is_array($old)) { $old = array(); } if (!is_array($new)) { $new = array(); } $add = array_keys(array_diff_key($new, $old)); $rem = array_keys(array_diff_key($old, $new)); break; } switch ($type) { case self::TYPE_COMMIT: $author = null; if ($new['authorPHID']) { $author = $this->renderHandleLink($new['authorPHID']); } else { $author = $new['authorName']; } $committer = null; if ($new['committerPHID']) { $committer = $this->renderHandleLink($new['committerPHID']); } else if ($new['committerName']) { $committer = $new['committerName']; } $commit = $this->renderHandleLink($this->getObjectPHID()); if (!$committer) { $committer = $author; $author = null; } if ($author) { $title = pht( '%s committed %s (authored by %s).', $committer, $commit, $author); } else { $title = pht( '%s committed %s.', $committer, $commit); } return $title; case PhabricatorAuditActionConstants::INLINE: return pht( '%s added inline comments.', $author_handle); case PhabricatorAuditActionConstants::ADD_CCS: if ($add && $rem) { return pht( '%s edited subscribers; added: %s, removed: %s.', $author_handle, $this->renderHandleList($add), $this->renderHandleList($rem)); } else if ($add) { return pht( '%s added subscribers: %s.', $author_handle, $this->renderHandleList($add)); } else if ($rem) { return pht( '%s removed subscribers: %s.', $author_handle, $this->renderHandleList($rem)); } else { return pht( '%s added subscribers...', $author_handle); } case PhabricatorAuditActionConstants::ADD_AUDITORS: if ($add && $rem) { return pht( '%s edited auditors; added: %s, removed: %s.', $author_handle, $this->renderHandleList($add), $this->renderHandleList($rem)); } else if ($add) { return pht( '%s added auditors: %s.', $author_handle, $this->renderHandleList($add)); } else if ($rem) { return pht( '%s removed auditors: %s.', $author_handle, $this->renderHandleList($rem)); } else { return pht( '%s added auditors...', $author_handle); } case PhabricatorAuditActionConstants::ACTION: switch ($new) { case PhabricatorAuditActionConstants::ACCEPT: return pht( '%s accepted this commit.', $author_handle); case PhabricatorAuditActionConstants::CONCERN: return pht( '%s raised a concern with this commit.', $author_handle); case PhabricatorAuditActionConstants::RESIGN: return pht( '%s resigned from this audit.', $author_handle); case PhabricatorAuditActionConstants::CLOSE: return pht( '%s closed this audit.', $author_handle); } } return parent::getTitle(); } public function getTitleForFeed() { $old = $this->getOldValue(); $new = $this->getNewValue(); $author_handle = $this->renderHandleLink($this->getAuthorPHID()); $object_handle = $this->renderHandleLink($this->getObjectPHID()); $type = $this->getTransactionType(); switch ($type) { case PhabricatorAuditActionConstants::ADD_CCS: case PhabricatorAuditActionConstants::ADD_AUDITORS: if (!is_array($old)) { $old = array(); } if (!is_array($new)) { $new = array(); } $add = array_keys(array_diff_key($new, $old)); $rem = array_keys(array_diff_key($old, $new)); break; } switch ($type) { case self::TYPE_COMMIT: $author = null; if ($new['authorPHID']) { $author = $this->renderHandleLink($new['authorPHID']); } else { $author = $new['authorName']; } $committer = null; if ($new['committerPHID']) { $committer = $this->renderHandleLink($new['committerPHID']); } else if ($new['committerName']) { $committer = $new['committerName']; } if (!$committer) { $committer = $author; $author = null; } if ($author) { $title = pht( '%s committed %s (authored by %s).', $committer, $object_handle, $author); } else { $title = pht( '%s committed %s.', $committer, $object_handle); } return $title; case PhabricatorAuditActionConstants::INLINE: return pht( '%s added inline comments to %s.', $author_handle, $object_handle); case PhabricatorAuditActionConstants::ADD_AUDITORS: if ($add && $rem) { return pht( '%s edited auditors for %s; added: %s, removed: %s.', $author_handle, $object_handle, $this->renderHandleList($add), $this->renderHandleList($rem)); } else if ($add) { return pht( '%s added auditors to %s: %s.', $author_handle, $object_handle, $this->renderHandleList($add)); } else if ($rem) { return pht( '%s removed auditors from %s: %s.', $author_handle, $object_handle, $this->renderHandleList($rem)); } else { return pht( '%s added auditors to %s...', $author_handle, $object_handle); } case PhabricatorAuditActionConstants::ACTION: switch ($new) { case PhabricatorAuditActionConstants::ACCEPT: return pht( '%s accepted %s.', $author_handle, $object_handle); case PhabricatorAuditActionConstants::CONCERN: return pht( '%s raised a concern with %s.', $author_handle, $object_handle); case PhabricatorAuditActionConstants::RESIGN: return pht( '%s resigned from auditing %s.', $author_handle, $object_handle); case PhabricatorAuditActionConstants::CLOSE: return pht( '%s closed the audit of %s.', $author_handle, $object_handle); } } return parent::getTitleForFeed(); } public function getBodyForFeed(PhabricatorFeedStory $story) { switch ($this->getTransactionType()) { case self::TYPE_COMMIT: $data = $this->getNewValue(); return $story->renderSummary($data['summary']); } return parent::getBodyForFeed($story); } public function isInlineCommentTransaction() { switch ($this->getTransactionType()) { case PhabricatorAuditActionConstants::INLINE: return true; } return parent::isInlineCommentTransaction(); } public function getBodyForMail() { switch ($this->getTransactionType()) { case self::TYPE_COMMIT: $data = $this->getNewValue(); return $data['description']; } return parent::getBodyForMail(); } public function getMailTags() { $tags = array(); switch ($this->getTransactionType()) { case DiffusionCommitAcceptTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_ACTION_ACCEPT; break; case DiffusionCommitConcernTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_ACTION_CONCERN; break; case DiffusionCommitResignTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_ACTION_RESIGN; break; case DiffusionCommitAuditorsTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_ADD_AUDITORS; break; case PhabricatorAuditActionConstants::ACTION: switch ($this->getNewValue()) { case PhabricatorAuditActionConstants::CONCERN: $tags[] = self::MAILTAG_ACTION_CONCERN; break; case PhabricatorAuditActionConstants::ACCEPT: $tags[] = self::MAILTAG_ACTION_ACCEPT; break; case PhabricatorAuditActionConstants::RESIGN: $tags[] = self::MAILTAG_ACTION_RESIGN; break; case PhabricatorAuditActionConstants::CLOSE: $tags[] = self::MAILTAG_ACTION_CLOSE; break; } break; case PhabricatorAuditActionConstants::ADD_AUDITORS: $tags[] = self::MAILTAG_ADD_AUDITORS; break; case PhabricatorAuditActionConstants::ADD_CCS: $tags[] = self::MAILTAG_ADD_CCS; break; case PhabricatorAuditActionConstants::INLINE: case PhabricatorTransactions::TYPE_COMMENT: $tags[] = self::MAILTAG_COMMENT; break; case self::TYPE_COMMIT: $tags[] = self::MAILTAG_COMMIT; break; case PhabricatorTransactions::TYPE_EDGE: switch ($this->getMetadataValue('edge:type')) { case PhabricatorProjectObjectHasProjectEdgeType::EDGECONST: $tags[] = self::MAILTAG_PROJECTS; break; case PhabricatorObjectHasSubscriberEdgeType::EDGECONST: $tags[] = self::MAILTAG_ADD_CCS; break; default: $tags[] = self::MAILTAG_OTHER; break; } break; default: $tags[] = self::MAILTAG_OTHER; break; } return $tags; } public function shouldDisplayGroupWith(array $group) { // Make the "This commit now requires audit." state message stand alone. $type_state = DiffusionCommitStateTransaction::TRANSACTIONTYPE; if ($this->getTransactionType() == $type_state) { return false; } foreach ($group as $xaction) { if ($xaction->getTransactionType() == $type_state) { return false; } } return parent::shouldDisplayGroupWith($group); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/storage/PhabricatorAuditInlineComment.php
src/applications/audit/storage/PhabricatorAuditInlineComment.php
<?php final class PhabricatorAuditInlineComment extends PhabricatorInlineComment { protected function newStorageObject() { return new PhabricatorAuditTransactionComment(); } public function getControllerURI() { return urisprintf( '/diffusion/inline/edit/%s/', $this->getCommitPHID()); } public function supportsHiding() { return false; } public function isHidden() { return false; } public function getTransactionCommentForSave() { $content_source = PhabricatorContentSource::newForSource( PhabricatorOldWorldContentSource::SOURCECONST); $this->getStorageObject() ->setViewPolicy('public') ->setEditPolicy($this->getAuthorPHID()) ->setContentSource($content_source) ->setCommentVersion(1); return $this->getStorageObject(); } public static function newFromModernComment( PhabricatorAuditTransactionComment $comment) { $obj = new PhabricatorAuditInlineComment(); $obj->setStorageObject($comment); return $obj; } public function setPathID($id) { $this->getStorageObject()->setPathID($id); return $this; } public function getPathID() { return $this->getStorageObject()->getPathID(); } public function setCommitPHID($commit_phid) { $this->getStorageObject()->setCommitPHID($commit_phid); return $this; } public function getCommitPHID() { return $this->getStorageObject()->getCommitPHID(); } public function setChangesetID($id) { return $this->setPathID($id); } public function getChangesetID() { return $this->getPathID(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/storage/PhabricatorAuditTransactionComment.php
src/applications/audit/storage/PhabricatorAuditTransactionComment.php
<?php final class PhabricatorAuditTransactionComment extends PhabricatorApplicationTransactionComment implements PhabricatorInlineCommentInterface { protected $commitPHID; protected $pathID; protected $isNewFile = 0; protected $lineNumber = 0; protected $lineLength = 0; protected $fixedState; protected $hasReplies = 0; protected $replyToCommentPHID; protected $legacyCommentID; protected $attributes = array(); private $replyToComment = self::ATTACHABLE; private $inlineContext = self::ATTACHABLE; public function getApplicationTransactionObject() { return new PhabricatorAuditTransaction(); } public function shouldUseMarkupCache($field) { // Only cache submitted comments. return ($this->getTransactionPHID() != null); } protected function getConfiguration() { $config = parent::getConfiguration(); $config[self::CONFIG_COLUMN_SCHEMA] = array( 'commitPHID' => 'phid?', 'pathID' => 'id?', 'isNewFile' => 'bool', 'lineNumber' => 'uint32', 'lineLength' => 'uint32', 'fixedState' => 'text12?', 'hasReplies' => 'bool', 'replyToCommentPHID' => 'phid?', 'legacyCommentID' => 'id?', ) + $config[self::CONFIG_COLUMN_SCHEMA]; $config[self::CONFIG_KEY_SCHEMA] = array( 'key_path' => array( 'columns' => array('pathID'), ), 'key_draft' => array( 'columns' => array('authorPHID', 'transactionPHID'), ), 'key_commit' => array( 'columns' => array('commitPHID'), ), 'key_legacy' => array( 'columns' => array('legacyCommentID'), ), ) + $config[self::CONFIG_KEY_SCHEMA]; $config[self::CONFIG_SERIALIZATION] = array( 'attributes' => self::SERIALIZATION_JSON, ) + idx($config, self::CONFIG_SERIALIZATION, array()); return $config; } public function attachReplyToComment( PhabricatorAuditTransactionComment $comment = null) { $this->replyToComment = $comment; return $this; } public function getReplyToComment() { return $this->assertAttached($this->replyToComment); } public function getAttribute($key, $default = null) { return idx($this->attributes, $key, $default); } public function setAttribute($key, $value) { $this->attributes[$key] = $value; return $this; } public function newInlineCommentObject() { return PhabricatorAuditInlineComment::newFromModernComment($this); } public function getInlineContext() { return $this->assertAttached($this->inlineContext); } public function attachInlineContext( PhabricatorInlineCommentContext $context = null) { $this->inlineContext = $context; return $this; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/management/PhabricatorAuditManagementDeleteWorkflow.php
src/applications/audit/management/PhabricatorAuditManagementDeleteWorkflow.php
<?php final class PhabricatorAuditManagementDeleteWorkflow extends PhabricatorAuditManagementWorkflow { protected function didConstruct() { $this ->setName('delete') ->setExamples('**delete** [--dry-run] ...') ->setSynopsis(pht('Delete audit requests matching parameters.')) ->setArguments( array( array( 'name' => 'dry-run', 'help' => pht( 'Show what would be deleted, but do not actually delete '. 'anything.'), ), array( 'name' => 'users', 'param' => 'names', 'help' => pht('Select only audits by a given list of users.'), ), array( 'name' => 'repositories', 'param' => 'repos', 'help' => pht( 'Select only audits in a given list of repositories.'), ), array( 'name' => 'commits', 'param' => 'commits', 'help' => pht('Select only audits for the given commits.'), ), array( 'name' => 'min-commit-date', 'param' => 'date', 'help' => pht( 'Select only audits for commits on or after the given date.'), ), array( 'name' => 'max-commit-date', 'param' => 'date', 'help' => pht( 'Select only audits for commits on or before the given date.'), ), array( 'name' => 'status', 'param' => 'status', 'help' => pht( 'Select only audits in the given status. By default, '. 'only open audits are selected.'), ), array( 'name' => 'ids', 'param' => 'ids', 'help' => pht('Select only audits with the given IDs.'), ), )); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $users = $this->loadUsers($args->getArg('users')); $repos = $this->loadRepos($args->getArg('repositories')); $commits = $this->loadCommits($args->getArg('commits')); $ids = $this->parseList($args->getArg('ids')); $status = $args->getArg('status'); $min_date = $this->loadDate($args->getArg('min-commit-date')); $max_date = $this->loadDate($args->getArg('max-commit-date')); if ($min_date && $max_date && ($min_date > $max_date)) { throw new PhutilArgumentUsageException( pht('Specified maximum date must come after specified minimum date.')); } $is_dry_run = $args->getArg('dry-run'); $query = id(new DiffusionCommitQuery()) ->setViewer($this->getViewer()) ->needAuditRequests(true); if ($status) { $query->withStatuses(array($status)); } $id_map = array(); if ($ids) { $id_map = array_fuse($ids); $query->withAuditIDs($ids); } if ($repos) { $query->withRepositoryIDs(mpull($repos, 'getID')); // See T13457. If we're iterating over commits in a single large // repository, the lack of a "<repositoryID, [id]>" key can slow things // down. Iterate in a specific order to use a key which is present // on the table ("<repositoryID, epoch, [id]>"). $query->setOrderVector(array('-epoch', '-id')); } $auditor_map = array(); if ($users) { $auditor_map = array_fuse(mpull($users, 'getPHID')); $query->withAuditorPHIDs($auditor_map); } if ($commits) { $query->withPHIDs(mpull($commits, 'getPHID')); } $commit_iterator = id(new PhabricatorQueryIterator($query)); // See T13457. We may be examining many commits; each commit is small so // we can safely increase the page size to improve performance a bit. $commit_iterator->setPageSize(1000); $audits = array(); foreach ($commit_iterator as $commit) { $commit_audits = $commit->getAudits(); foreach ($commit_audits as $key => $audit) { if ($id_map && empty($id_map[$audit->getID()])) { unset($commit_audits[$key]); continue; } if ($auditor_map && empty($auditor_map[$audit->getAuditorPHID()])) { unset($commit_audits[$key]); continue; } if ($min_date && $commit->getEpoch() < $min_date) { unset($commit_audits[$key]); continue; } if ($max_date && $commit->getEpoch() > $max_date) { unset($commit_audits[$key]); continue; } } if (!$commit_audits) { continue; } $handles = id(new PhabricatorHandleQuery()) ->setViewer($viewer) ->withPHIDs(mpull($commit_audits, 'getAuditorPHID')) ->execute(); foreach ($commit_audits as $audit) { $audit_id = $audit->getID(); $status = $audit->getAuditRequestStatusObject(); $description = sprintf( '%10d %-16s %-16s %s: %s', $audit_id, $handles[$audit->getAuditorPHID()]->getName(), $status->getStatusName(), $commit->getRepository()->formatCommitName( $commit->getCommitIdentifier()), trim($commit->getSummary())); $audits[] = array( 'auditID' => $audit_id, 'commitPHID' => $commit->getPHID(), 'description' => $description, ); } } if (!$audits) { echo tsprintf( "%s\n", pht('No audits match the query.')); return 0; } foreach ($audits as $audit_spec) { echo tsprintf( "%s\n", $audit_spec['description']); } if ($is_dry_run) { echo tsprintf( "%s\n", pht('This is a dry run, so no changes will be made.')); return 0; } $message = pht( 'Really delete these %s audit(s)? They will be permanently deleted '. 'and can not be recovered.', phutil_count($audits)); if (!phutil_console_confirm($message)) { echo tsprintf( "%s\n", pht('User aborted the workflow.')); return 1; } $audits_by_commit = igroup($audits, 'commitPHID'); foreach ($audits_by_commit as $commit_phid => $audit_specs) { $audit_ids = ipull($audit_specs, 'auditID'); $audits = id(new PhabricatorRepositoryAuditRequest())->loadAllWhere( 'id IN (%Ld)', $audit_ids); foreach ($audits as $audit) { $id = $audit->getID(); echo tsprintf( "%s\n", pht('Deleting audit %d...', $id)); $audit->delete(); } $this->synchronizeCommitAuditState($commit_phid); } return 0; } private function loadUsers($users) { $users = $this->parseList($users); if (!$users) { return null; } $objects = id(new PhabricatorPeopleQuery()) ->setViewer($this->getViewer()) ->withUsernames($users) ->execute(); $objects = mpull($objects, null, 'getUsername'); foreach ($users as $name) { if (empty($objects[$name])) { throw new PhutilArgumentUsageException( pht('No such user with username "%s"!', $name)); } } return $objects; } private function parseList($list) { $list = preg_split('/\s*,\s*/', $list); foreach ($list as $key => $item) { $list[$key] = trim($item); } foreach ($list as $key => $item) { if (!strlen($item)) { unset($list[$key]); } } return $list; } private function loadRepos($identifiers) { $identifiers = $this->parseList($identifiers); if (!$identifiers) { return null; } $query = id(new PhabricatorRepositoryQuery()) ->setViewer($this->getViewer()) ->withIdentifiers($identifiers); $repos = $query->execute(); $map = $query->getIdentifierMap(); foreach ($identifiers as $identifier) { if (empty($map[$identifier])) { throw new PhutilArgumentUsageException( pht('No repository "%s" exists!', $identifier)); } } return $repos; } private function loadDate($date) { if (!$date) { return null; } $epoch = strtotime($date); if (!$epoch || $epoch < 1) { throw new PhutilArgumentUsageException( pht( 'Unable to parse date "%s". Use a format like "%s".', $date, '2000-01-01')); } return $epoch; } private function loadCommits($commits) { $names = $this->parseList($commits); if (!$names) { return null; } $query = id(new DiffusionCommitQuery()) ->setViewer($this->getViewer()) ->withIdentifiers($names); $commits = $query->execute(); $map = $query->getIdentifierMap(); foreach ($names as $name) { if (empty($map[$name])) { throw new PhutilArgumentUsageException( pht('No such commit "%s"!', $name)); } } return $commits; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/management/PhabricatorAuditUpdateOwnersManagementWorkflow.php
src/applications/audit/management/PhabricatorAuditUpdateOwnersManagementWorkflow.php
<?php final class PhabricatorAuditUpdateOwnersManagementWorkflow extends PhabricatorAuditManagementWorkflow { protected function didConstruct() { $this ->setName('update-owners') ->setExamples('**update-owners** ...') ->setSynopsis(pht('Update package relationships for commits.')) ->setArguments( array_merge( $this->getCommitConstraintArguments(), array())); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $objects = $this->loadCommitsWithConstraints($args); foreach ($objects as $object) { $commits = $this->loadCommitsForConstraintObject($object); foreach ($commits as $commit) { $repository = $commit->getRepository(); $affected_paths = PhabricatorOwnerPathQuery::loadAffectedPaths( $repository, $commit, $viewer); $affected_packages = PhabricatorOwnersPackage::loadAffectedPackages( $repository, $affected_paths); $monograms = mpull($affected_packages, 'getMonogram'); if ($monograms) { $monograms = implode(', ', $monograms); } else { $monograms = pht('none'); } echo tsprintf( "%s\n", pht( 'Updating "%s" (%s)...', $commit->getDisplayName(), $monograms)); $commit->writeOwnersEdges(mpull($affected_packages, 'getPHID')); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/management/PhabricatorAuditManagementWorkflow.php
src/applications/audit/management/PhabricatorAuditManagementWorkflow.php
<?php abstract class PhabricatorAuditManagementWorkflow extends PhabricatorManagementWorkflow { protected function getCommitConstraintArguments() { return array( array( 'name' => 'all', 'help' => pht('Update all commits in all repositories.'), ), array( 'name' => 'objects', 'wildcard' => true, 'help' => pht('Update named commits and repositories.'), ), ); } protected function loadCommitsWithConstraints(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $all = $args->getArg('all'); $names = $args->getArg('objects'); if (!$names && !$all) { throw new PhutilArgumentUsageException( pht( 'Specify "--all" to affect everything, or a list of specific '. 'commits or repositories to affect.')); } else if ($names && $all) { throw new PhutilArgumentUsageException( pht( 'Specify either a list of objects to affect or "--all", but not '. 'both.')); } if ($all) { $objects = new LiskMigrationIterator(new PhabricatorRepository()); } else { $query = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withNames($names); $query->execute(); $objects = array(); $results = $query->getNamedResults(); foreach ($names as $name) { if (!isset($results[$name])) { throw new PhutilArgumentUsageException( pht( 'Object "%s" is not a valid object.', $name)); } $object = $results[$name]; if (!($object instanceof PhabricatorRepository) && !($object instanceof PhabricatorRepositoryCommit)) { throw new PhutilArgumentUsageException( pht( 'Object "%s" is not a valid repository or commit.', $name)); } $objects[] = $object; } } return $objects; } protected function loadCommitsForConstraintObject($object) { $viewer = $this->getViewer(); if ($object instanceof PhabricatorRepository) { $commits = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withRepository($object) ->execute(); } else { $commits = array($object); } return $commits; } protected function synchronizeCommitAuditState($commit_phid) { $viewer = $this->getViewer(); $commit = id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withPHIDs(array($commit_phid)) ->needAuditRequests(true) ->executeOne(); if (!$commit) { return; } $old_status = $commit->getAuditStatusObject(); $commit->updateAuditStatus($commit->getAudits()); $new_status = $commit->getAuditStatusObject(); if ($old_status->getKey() == $new_status->getKey()) { echo tsprintf( "%s\n", pht( 'No synchronization changes for "%s".', $commit->getDisplayName())); } else { echo tsprintf( "%s\n", pht( 'Synchronizing "%s": "%s" -> "%s".', $commit->getDisplayName(), $old_status->getName(), $new_status->getName())); $commit->save(); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/management/PhabricatorAuditSynchronizeManagementWorkflow.php
src/applications/audit/management/PhabricatorAuditSynchronizeManagementWorkflow.php
<?php final class PhabricatorAuditSynchronizeManagementWorkflow extends PhabricatorAuditManagementWorkflow { protected function didConstruct() { $this ->setName('synchronize') ->setExamples( "**synchronize** __repository__ ...\n". "**synchronize** __commit__ ...\n". "**synchronize** --all") ->setSynopsis( pht( 'Update commits to make their summary audit state reflect the '. 'state of their actual audit requests. This can fix inconsistencies '. 'in database state if audit requests have been mangled '. 'accidentally (or on purpose).')) ->setArguments( array_merge( $this->getCommitConstraintArguments(), array())); } public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $objects = $this->loadCommitsWithConstraints($args); foreach ($objects as $object) { $commits = $this->loadCommitsForConstraintObject($object); foreach ($commits as $commit) { $this->synchronizeCommitAuditState($commit->getPHID()); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/query/PhabricatorAuditTransactionQuery.php
src/applications/audit/query/PhabricatorAuditTransactionQuery.php
<?php final class PhabricatorAuditTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhabricatorAuditTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/query/DiffusionInternalCommitSearchEngine.php
src/applications/audit/query/DiffusionInternalCommitSearchEngine.php
<?php final class DiffusionInternalCommitSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Diffusion Raw Commits'); } public function getApplicationClassName() { return 'PhabricatorDiffusionApplication'; } public function newQuery() { return new DiffusionCommitQuery(); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['repositoryPHIDs']) { $query->withRepositoryPHIDs($map['repositoryPHIDs']); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorSearchDatasourceField()) ->setLabel(pht('Repositories')) ->setKey('repositoryPHIDs') ->setDatasource(new DiffusionRepositoryFunctionDatasource()) ->setDescription(pht('Find commits in particular repositories.')), ); } protected function getURI($path) { return null; } protected function renderResultList( array $commits, PhabricatorSavedQuery $query, array $handles) { return null; } protected function getObjectWireFieldsForConduit( $object, array $field_extensions, array $extension_data) { $commit = $object; $viewer = $this->requireViewer(); $repository = $commit->getRepository(); $identifier = $commit->getCommitIdentifier(); id(new DiffusionRepositoryClusterEngine()) ->setViewer($viewer) ->setRepository($repository) ->synchronizeWorkingCopyBeforeRead(); $ref = id(new DiffusionLowLevelCommitQuery()) ->setRepository($repository) ->withIdentifier($identifier) ->execute(); return array( 'ref' => $ref->newDictionary(), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/query/PhabricatorCommitSearchEngine.php
src/applications/audit/query/PhabricatorCommitSearchEngine.php
<?php final class PhabricatorCommitSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Diffusion Commits'); } public function getApplicationClassName() { return 'PhabricatorDiffusionApplication'; } public function newQuery() { return id(new DiffusionCommitQuery()) ->needAuditRequests(true) ->needCommitData(true) ->needIdentities(true) ->needDrafts(true); } protected function newResultBuckets() { return DiffusionCommitResultBucket::getAllResultBuckets(); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['responsiblePHIDs']) { $query->withResponsiblePHIDs($map['responsiblePHIDs']); } if ($map['auditorPHIDs']) { $query->withAuditorPHIDs($map['auditorPHIDs']); } if ($map['authorPHIDs']) { $query->withAuthorPHIDs($map['authorPHIDs']); } if ($map['statuses']) { $query->withStatuses($map['statuses']); } if ($map['repositoryPHIDs']) { $query->withRepositoryPHIDs($map['repositoryPHIDs']); } if ($map['packagePHIDs']) { $query->withPackagePHIDs($map['packagePHIDs']); } if ($map['unreachable'] !== null) { $query->withUnreachable($map['unreachable']); } if ($map['permanent'] !== null) { $query->withPermanent($map['permanent']); } if ($map['ancestorsOf']) { $query->withAncestorsOf($map['ancestorsOf']); } if ($map['identifiers']) { $query->withIdentifiers($map['identifiers']); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorSearchDatasourceField()) ->setLabel(pht('Responsible Users')) ->setKey('responsiblePHIDs') ->setConduitKey('responsible') ->setAliases(array('responsible', 'responsibles', 'responsiblePHID')) ->setDatasource(new DifferentialResponsibleDatasource()) ->setDescription( pht( 'Find commits where given users, projects, or packages are '. 'responsible for the next steps in the audit workflow.')), id(new PhabricatorUsersSearchField()) ->setLabel(pht('Authors')) ->setKey('authorPHIDs') ->setConduitKey('authors') ->setAliases(array('author', 'authors', 'authorPHID')) ->setDescription(pht('Find commits authored by particular users.')), id(new PhabricatorSearchDatasourceField()) ->setLabel(pht('Auditors')) ->setKey('auditorPHIDs') ->setConduitKey('auditors') ->setAliases(array('auditor', 'auditors', 'auditorPHID')) ->setDatasource(new DiffusionAuditorFunctionDatasource()) ->setDescription( pht( 'Find commits where given users, projects, or packages are '. 'auditors.')), id(new PhabricatorSearchCheckboxesField()) ->setLabel(pht('Audit Status')) ->setKey('statuses') ->setAliases(array('status')) ->setOptions(DiffusionCommitAuditStatus::newOptions()) ->setDeprecatedOptions( DiffusionCommitAuditStatus::newDeprecatedOptions()) ->setDescription(pht('Find commits with given audit statuses.')), id(new PhabricatorSearchDatasourceField()) ->setLabel(pht('Repositories')) ->setKey('repositoryPHIDs') ->setConduitKey('repositories') ->setAliases(array('repository', 'repositories', 'repositoryPHID')) ->setDatasource(new DiffusionRepositoryFunctionDatasource()) ->setDescription(pht('Find commits in particular repositories.')), id(new PhabricatorSearchDatasourceField()) ->setLabel(pht('Packages')) ->setKey('packagePHIDs') ->setConduitKey('packages') ->setAliases(array('package', 'packages', 'packagePHID')) ->setDatasource(new PhabricatorOwnersPackageDatasource()) ->setDescription( pht('Find commits which affect given packages.')), id(new PhabricatorSearchThreeStateField()) ->setLabel(pht('Unreachable')) ->setKey('unreachable') ->setOptions( pht('(Show All)'), pht('Show Only Unreachable Commits'), pht('Hide Unreachable Commits')) ->setDescription( pht( 'Find or exclude unreachable commits which are not ancestors of '. 'any branch, tag, or ref.')), id(new PhabricatorSearchThreeStateField()) ->setLabel(pht('Permanent')) ->setKey('permanent') ->setOptions( pht('(Show All)'), pht('Show Only Permanent Commits'), pht('Hide Permanent Commits')) ->setDescription( pht( 'Find or exclude permanent commits which are ancestors of '. 'any permanent branch, tag, or ref.')), id(new PhabricatorSearchStringListField()) ->setLabel(pht('Ancestors Of')) ->setKey('ancestorsOf') ->setDescription( pht( 'Find commits which are ancestors of a particular ref, '. 'like "master".')), id(new PhabricatorSearchStringListField()) ->setLabel(pht('Identifiers')) ->setKey('identifiers') ->setDescription( pht( 'Find commits with particular identifiers (usually, hashes). '. 'Supports full or partial identifiers (like "abcd12340987..." or '. '"abcd1234") and qualified or unqualified identifiers (like '. '"rXabcd1234" or "abcd1234").')), ); } protected function getURI($path) { return '/diffusion/commit/'.$path; } protected function getBuiltinQueryNames() { $names = array(); if ($this->requireViewer()->isLoggedIn()) { $names['active'] = pht('Active Audits'); $names['authored'] = pht('Authored'); $names['audited'] = pht('Audited'); } $names['all'] = pht('All Commits'); return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); $viewer = $this->requireViewer(); $viewer_phid = $viewer->getPHID(); switch ($query_key) { case 'all': return $query; case 'active': $bucket_key = DiffusionCommitRequiredActionResultBucket::BUCKETKEY; $open = DiffusionCommitAuditStatus::getOpenStatusConstants(); $query ->setParameter('responsiblePHIDs', array($viewer_phid)) ->setParameter('statuses', $open) ->setParameter('bucket', $bucket_key) ->setParameter('unreachable', false); return $query; case 'authored': $query ->setParameter('authorPHIDs', array($viewer_phid)); return $query; case 'audited': $query ->setParameter('auditorPHIDs', array($viewer_phid)); return $query; } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $commits, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($commits, 'PhabricatorRepositoryCommit'); $viewer = $this->requireViewer(); $bucket = $this->getResultBucket($query); $template = id(new DiffusionCommitGraphView()) ->setViewer($viewer) ->setShowAuditors(true); $views = array(); if ($bucket) { $bucket->setViewer($viewer); try { $groups = $bucket->newResultGroups($query, $commits); foreach ($groups as $group) { // Don't show groups in Dashboard Panels if ($group->getObjects() || !$this->isPanelContext()) { $item_list = id(clone $template) ->setCommits($group->getObjects()) ->newObjectItemListView(); $views[] = $item_list ->setHeader($group->getName()) ->setNoDataString($group->getNoDataString()); } } } catch (Exception $ex) { $this->addError($ex->getMessage()); } } if (!$views) { $item_list = id(clone $template) ->setCommits($commits) ->newObjectItemListView(); $views[] = $item_list ->setNoDataString(pht('No commits found.')); } return id(new PhabricatorApplicationSearchResultView()) ->setContent($views); } protected function getNewUserBody() { $view = id(new PHUIBigInfoView()) ->setIcon('fa-check-circle-o') ->setTitle(pht('Welcome to Audit')) ->setDescription( pht('Post-commit code review and auditing. Audits you are assigned '. 'to will appear here.')); 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/audit/mail/PhabricatorAuditReplyHandler.php
src/applications/audit/mail/PhabricatorAuditReplyHandler.php
<?php final class PhabricatorAuditReplyHandler extends PhabricatorApplicationTransactionReplyHandler { public function validateMailReceiver($mail_receiver) { if (!($mail_receiver instanceof PhabricatorRepositoryCommit)) { throw new Exception( pht( 'Mail receiver is not a %s!', 'PhabricatorRepositoryCommit')); } } public function getObjectPrefix() { return 'COMMIT'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/mail/PhabricatorAuditMailReceiver.php
src/applications/audit/mail/PhabricatorAuditMailReceiver.php
<?php final class PhabricatorAuditMailReceiver extends PhabricatorObjectMailReceiver { public function isEnabled() { return PhabricatorApplication::isClassInstalled( 'PhabricatorDiffusionApplication'); } protected function getObjectPattern() { return 'COMMIT[1-9]\d*'; } protected function loadObject($pattern, PhabricatorUser $viewer) { $id = (int)preg_replace('/^COMMIT/i', '', $pattern); return id(new DiffusionCommitQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->needAuditRequests(true) ->executeOne(); } protected function getTransactionReplyHandler() { return new PhabricatorAuditReplyHandler(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/editor/PhabricatorAuditEditor.php
src/applications/audit/editor/PhabricatorAuditEditor.php
<?php final class PhabricatorAuditEditor extends PhabricatorApplicationTransactionEditor { const MAX_FILES_SHOWN_IN_EMAIL = 1000; private $affectedFiles; private $rawPatch; private $auditorPHIDs = array(); private $didExpandInlineState = false; private $oldAuditStatus = null; public function setRawPatch($patch) { $this->rawPatch = $patch; return $this; } public function getRawPatch() { return $this->rawPatch; } public function getEditorApplicationClass() { return 'PhabricatorDiffusionApplication'; } public function getEditorObjectsDescription() { return pht('Audits'); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorTransactions::TYPE_COMMENT; $types[] = PhabricatorTransactions::TYPE_EDGE; $types[] = PhabricatorTransactions::TYPE_INLINESTATE; $types[] = PhabricatorAuditTransaction::TYPE_COMMIT; // TODO: These will get modernized eventually, but that can happen one // at a time later on. $types[] = PhabricatorAuditActionConstants::INLINE; return $types; } protected function expandTransactions( PhabricatorLiskDAO $object, array $xactions) { foreach ($xactions as $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorTransactions::TYPE_INLINESTATE: $this->didExpandInlineState = true; break; } } $this->oldAuditStatus = $object->getAuditStatus(); return parent::expandTransactions($object, $xactions); } protected function transactionHasEffect( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditActionConstants::INLINE: return $xaction->hasComment(); } return parent::transactionHasEffect($object, $xaction); } protected function getCustomTransactionOldValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditActionConstants::INLINE: case PhabricatorAuditTransaction::TYPE_COMMIT: return null; } return parent::getCustomTransactionOldValue($object, $xaction); } protected function getCustomTransactionNewValue( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditActionConstants::INLINE: case PhabricatorAuditTransaction::TYPE_COMMIT: return $xaction->getNewValue(); } return parent::getCustomTransactionNewValue($object, $xaction); } protected function applyCustomInternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditActionConstants::INLINE: $comment = $xaction->getComment(); $comment->setAttribute('editing', false); PhabricatorVersionedDraft::purgeDrafts( $comment->getPHID(), $this->getActingAsPHID()); return; case PhabricatorAuditTransaction::TYPE_COMMIT: return; } return parent::applyCustomInternalTransaction($object, $xaction); } protected function applyCustomExternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditTransaction::TYPE_COMMIT: return; case PhabricatorAuditActionConstants::INLINE: $reply = $xaction->getComment()->getReplyToComment(); if ($reply && !$reply->getHasReplies()) { $reply->setHasReplies(1)->save(); } return; } return parent::applyCustomExternalTransaction($object, $xaction); } protected function applyBuiltinExternalTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorTransactions::TYPE_INLINESTATE: $table = new PhabricatorAuditTransactionComment(); $conn_w = $table->establishConnection('w'); foreach ($xaction->getNewValue() as $phid => $state) { queryfx( $conn_w, 'UPDATE %T SET fixedState = %s WHERE phid = %s', $table->getTableName(), $state, $phid); } break; } return parent::applyBuiltinExternalTransaction($object, $xaction); } protected function applyFinalEffects( PhabricatorLiskDAO $object, array $xactions) { // Load auditors explicitly; we may not have them if the caller was a // generic piece of infrastructure. $commit = id(new DiffusionCommitQuery()) ->setViewer($this->requireActor()) ->withIDs(array($object->getID())) ->needAuditRequests(true) ->executeOne(); if (!$commit) { throw new Exception( pht('Failed to load commit during transaction finalization!')); } $object->attachAudits($commit->getAudits()); $actor_phid = $this->getActingAsPHID(); $actor_is_author = ($object->getAuthorPHID()) && ($actor_phid == $object->getAuthorPHID()); $import_status_flag = null; foreach ($xactions as $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditTransaction::TYPE_COMMIT: $import_status_flag = PhabricatorRepositoryCommit::IMPORTED_PUBLISH; break; } } $old_status = $this->oldAuditStatus; $requests = $object->getAudits(); $object->updateAuditStatus($requests); $new_status = $object->getAuditStatus(); $object->save(); if ($import_status_flag) { $object->writeImportStatusFlag($import_status_flag); } // If the commit has changed state after this edit, add an informational // transaction about the state change. if ($old_status != $new_status) { if ($object->isAuditStatusPartiallyAudited()) { // This state isn't interesting enough to get a transaction. The // best way we could lead the user forward is something like "This // commit still requires additional audits." but that's redundant and // probably not very useful. } else { $xaction = $object->getApplicationTransactionTemplate() ->setTransactionType(DiffusionCommitStateTransaction::TRANSACTIONTYPE) ->setOldValue($old_status) ->setNewValue($new_status); $xaction = $this->populateTransaction($object, $xaction); $xaction->save(); } } // Collect auditor PHIDs for building mail. $this->auditorPHIDs = mpull($object->getAudits(), 'getAuditorPHID'); return $xactions; } protected function expandTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { $auditors_type = DiffusionCommitAuditorsTransaction::TRANSACTIONTYPE; $xactions = parent::expandTransaction($object, $xaction); switch ($xaction->getTransactionType()) { case PhabricatorAuditTransaction::TYPE_COMMIT: $phids = $this->getAuditRequestTransactionPHIDsFromCommitMessage( $object); if ($phids) { $xactions[] = $object->getApplicationTransactionTemplate() ->setTransactionType($auditors_type) ->setNewValue( array( '+' => array_fuse($phids), )); $this->addUnmentionablePHIDs($phids); } break; default: break; } if (!$this->didExpandInlineState) { switch ($xaction->getTransactionType()) { case PhabricatorTransactions::TYPE_COMMENT: $this->didExpandInlineState = true; $query_template = id(new DiffusionDiffInlineCommentQuery()) ->withCommitPHIDs(array($object->getPHID())); $state_xaction = $this->newInlineStateTransaction( $object, $query_template); if ($state_xaction) { $xactions[] = $state_xaction; } break; } } return $xactions; } private function getAuditRequestTransactionPHIDsFromCommitMessage( PhabricatorRepositoryCommit $commit) { $actor = $this->getActor(); $data = $commit->getCommitData(); $message = $data->getCommitMessage(); $result = DifferentialCommitMessageParser::newStandardParser($actor) ->setRaiseMissingFieldErrors(false) ->parseFields($message); $field_key = DifferentialAuditorsCommitMessageField::FIELDKEY; $phids = idx($result, $field_key, null); if (!$phids) { return array(); } // If a commit lists its author as an auditor, just pretend it does not. foreach ($phids as $key => $phid) { if ($phid == $commit->getAuthorPHID()) { unset($phids[$key]); } } if (!$phids) { return array(); } return $phids; } protected function sortTransactions(array $xactions) { $xactions = parent::sortTransactions($xactions); $head = array(); $tail = array(); foreach ($xactions as $xaction) { $type = $xaction->getTransactionType(); if ($type == PhabricatorAuditActionConstants::INLINE) { $tail[] = $xaction; } else { $head[] = $xaction; } } return array_values(array_merge($head, $tail)); } protected function supportsSearch() { return true; } protected function expandCustomRemarkupBlockTransactions( PhabricatorLiskDAO $object, array $xactions, array $changes, PhutilMarkupEngine $engine) { $actor = $this->getActor(); $result = array(); // Some interactions (like "Fixes Txxx" interacting with Maniphest) have // already been processed, so we're only re-parsing them here to avoid // generating an extra redundant mention. Other interactions are being // processed for the first time. // We're only recognizing magic in the commit message itself, not in // audit comments. $is_commit = false; foreach ($xactions as $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditTransaction::TYPE_COMMIT: $is_commit = true; break; } } if (!$is_commit) { return $result; } $flat_blocks = mpull($changes, 'getNewValue'); $huge_block = implode("\n\n", $flat_blocks); $phid_map = array(); $monograms = array(); $task_refs = id(new ManiphestCustomFieldStatusParser()) ->parseCorpus($huge_block); foreach ($task_refs as $match) { foreach ($match['monograms'] as $monogram) { $monograms[] = $monogram; } } $rev_refs = id(new DifferentialCustomFieldDependsOnParser()) ->parseCorpus($huge_block); foreach ($rev_refs as $match) { foreach ($match['monograms'] as $monogram) { $monograms[] = $monogram; } } $objects = id(new PhabricatorObjectQuery()) ->setViewer($this->getActor()) ->withNames($monograms) ->execute(); $phid_map[] = mpull($objects, 'getPHID', 'getPHID'); $reverts_refs = id(new DifferentialCustomFieldRevertsParser()) ->parseCorpus($huge_block); $reverts = array_mergev(ipull($reverts_refs, 'monograms')); if ($reverts) { $reverted_objects = DiffusionCommitRevisionQuery::loadRevertedObjects( $actor, $object, $reverts, $object->getRepository()); $reverted_phids = mpull($reverted_objects, 'getPHID', 'getPHID'); $reverts_edge = DiffusionCommitRevertsCommitEdgeType::EDGECONST; $result[] = id(new PhabricatorAuditTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDGE) ->setMetadataValue('edge:type', $reverts_edge) ->setNewValue(array('+' => $reverted_phids)); $phid_map[] = $reverted_phids; } // See T13463. Copy "related task" edges from the associated revision, if // one exists. $revision = DiffusionCommitRevisionQuery::loadRevisionForCommit( $actor, $object); if ($revision) { $task_phids = PhabricatorEdgeQuery::loadDestinationPHIDs( $revision->getPHID(), DifferentialRevisionHasTaskEdgeType::EDGECONST); $task_phids = array_fuse($task_phids); if ($task_phids) { $related_edge = DiffusionCommitHasTaskEdgeType::EDGECONST; $result[] = id(new PhabricatorAuditTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDGE) ->setMetadataValue('edge:type', $related_edge) ->setNewValue(array('+' => $task_phids)); } // Mark these objects as unmentionable, since the explicit relationship // is stronger and any mentions are redundant. $phid_map[] = $task_phids; } $phid_map = array_mergev($phid_map); $this->addUnmentionablePHIDs($phid_map); return $result; } protected function buildReplyHandler(PhabricatorLiskDAO $object) { $reply_handler = new PhabricatorAuditReplyHandler(); $reply_handler->setMailReceiver($object); return $reply_handler; } protected function getMailSubjectPrefix() { return pht('[Diffusion]'); } protected function getMailThreadID(PhabricatorLiskDAO $object) { // For backward compatibility, use this legacy thread ID. return 'diffusion-audit-'.$object->getPHID(); } protected function buildMailTemplate(PhabricatorLiskDAO $object) { $identifier = $object->getCommitIdentifier(); $repository = $object->getRepository(); $summary = $object->getSummary(); $name = $repository->formatCommitName($identifier); $subject = "{$name}: {$summary}"; $template = id(new PhabricatorMetaMTAMail()) ->setSubject($subject); $this->attachPatch( $template, $object); return $template; } protected function getMailTo(PhabricatorLiskDAO $object) { $this->requireAuditors($object); $phids = array(); if ($object->getAuthorPHID()) { $phids[] = $object->getAuthorPHID(); } foreach ($object->getAudits() as $audit) { if (!$audit->isResigned()) { $phids[] = $audit->getAuditorPHID(); } } $phids[] = $this->getActingAsPHID(); return $phids; } protected function newMailUnexpandablePHIDs(PhabricatorLiskDAO $object) { $this->requireAuditors($object); $phids = array(); foreach ($object->getAudits() as $auditor) { if ($auditor->isResigned()) { $phids[] = $auditor->getAuditorPHID(); } } return $phids; } protected function getObjectLinkButtonLabelForMail( PhabricatorLiskDAO $object) { return pht('View Commit'); } protected function buildMailBody( PhabricatorLiskDAO $object, array $xactions) { $body = parent::buildMailBody($object, $xactions); $type_inline = PhabricatorAuditActionConstants::INLINE; $type_push = PhabricatorAuditTransaction::TYPE_COMMIT; $is_commit = false; $inlines = array(); foreach ($xactions as $xaction) { if ($xaction->getTransactionType() == $type_inline) { $inlines[] = $xaction; } if ($xaction->getTransactionType() == $type_push) { $is_commit = true; } } if ($inlines) { $body->addTextSection( pht('INLINE COMMENTS'), $this->renderInlineCommentsForMail($object, $inlines)); } if ($is_commit) { $data = $object->getCommitData(); $body->addTextSection(pht('AFFECTED FILES'), $this->affectedFiles); $this->inlinePatch( $body, $object); } $data = $object->getCommitData(); $user_phids = array(); $author_phid = $object->getAuthorPHID(); if ($author_phid) { $user_phids[$author_phid][] = pht('Author'); } $committer_phid = $data->getCommitDetail('committerPHID'); if ($committer_phid && ($committer_phid != $author_phid)) { $user_phids[$committer_phid][] = pht('Committer'); } foreach ($this->auditorPHIDs as $auditor_phid) { $user_phids[$auditor_phid][] = pht('Auditor'); } // TODO: It would be nice to show pusher here too, but that information // is a little tricky to get at right now. if ($user_phids) { $handle_phids = array_keys($user_phids); $handles = id(new PhabricatorHandleQuery()) ->setViewer($this->requireActor()) ->withPHIDs($handle_phids) ->execute(); $user_info = array(); foreach ($user_phids as $phid => $roles) { $user_info[] = pht( '%s (%s)', $handles[$phid]->getName(), implode(', ', $roles)); } $body->addTextSection( pht('USERS'), implode("\n", $user_info)); } $monogram = $object->getRepository()->formatCommitName( $object->getCommitIdentifier()); $body->addLinkSection( pht('COMMIT'), PhabricatorEnv::getProductionURI('/'.$monogram)); return $body; } private function attachPatch( PhabricatorMetaMTAMail $template, PhabricatorRepositoryCommit $commit) { if (!$this->getRawPatch()) { return; } $attach_key = 'metamta.diffusion.attach-patches'; $attach_patches = PhabricatorEnv::getEnvConfig($attach_key); if (!$attach_patches) { return; } $repository = $commit->getRepository(); $encoding = $repository->getDetail('encoding', 'UTF-8'); $raw_patch = $this->getRawPatch(); $commit_name = $repository->formatCommitName( $commit->getCommitIdentifier()); $template->addAttachment( new PhabricatorMailAttachment( $raw_patch, $commit_name.'.patch', 'text/x-patch; charset='.$encoding)); } private function inlinePatch( PhabricatorMetaMTAMailBody $body, PhabricatorRepositoryCommit $commit) { if (!$this->getRawPatch()) { return; } $inline_key = 'metamta.diffusion.inline-patches'; $inline_patches = PhabricatorEnv::getEnvConfig($inline_key); if (!$inline_patches) { return; } $repository = $commit->getRepository(); $raw_patch = $this->getRawPatch(); $result = null; $len = substr_count($raw_patch, "\n"); if ($len <= $inline_patches) { // We send email as utf8, so we need to convert the text to utf8 if // we can. $encoding = $repository->getDetail('encoding', 'UTF-8'); if ($encoding) { $raw_patch = phutil_utf8_convert($raw_patch, 'UTF-8', $encoding); } $result = phutil_utf8ize($raw_patch); } if ($result) { $result = "PATCH\n\n{$result}\n"; } $body->addRawSection($result); } private function renderInlineCommentsForMail( PhabricatorLiskDAO $object, array $inline_xactions) { $inlines = mpull($inline_xactions, 'getComment'); $block = array(); $path_map = id(new DiffusionPathQuery()) ->withPathIDs(mpull($inlines, 'getPathID')) ->execute(); $path_map = ipull($path_map, 'path', 'id'); foreach ($inlines as $inline) { $path = idx($path_map, $inline->getPathID()); if ($path === null) { continue; } $start = $inline->getLineNumber(); $len = $inline->getLineLength(); if ($len) { $range = $start.'-'.($start + $len); } else { $range = $start; } $content = $inline->getContent(); $block[] = "{$path}:{$range} {$content}"; } return implode("\n", $block); } public function getMailTagsMap() { return array( PhabricatorAuditTransaction::MAILTAG_COMMIT => pht('A commit is created.'), PhabricatorAuditTransaction::MAILTAG_ACTION_CONCERN => pht('A commit has a concerned raised against it.'), PhabricatorAuditTransaction::MAILTAG_ACTION_ACCEPT => pht('A commit is accepted.'), PhabricatorAuditTransaction::MAILTAG_ACTION_RESIGN => pht('A commit has an auditor resign.'), PhabricatorAuditTransaction::MAILTAG_ACTION_CLOSE => pht('A commit is closed.'), PhabricatorAuditTransaction::MAILTAG_ADD_AUDITORS => pht('A commit has auditors added.'), PhabricatorAuditTransaction::MAILTAG_ADD_CCS => pht("A commit's subscribers change."), PhabricatorAuditTransaction::MAILTAG_PROJECTS => pht("A commit's projects change."), PhabricatorAuditTransaction::MAILTAG_COMMENT => pht('Someone comments on a commit.'), PhabricatorAuditTransaction::MAILTAG_OTHER => pht('Other commit activity not listed above occurs.'), ); } protected function shouldApplyHeraldRules( PhabricatorLiskDAO $object, array $xactions) { foreach ($xactions as $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditTransaction::TYPE_COMMIT: $repository = $object->getRepository(); $publisher = $repository->newPublisher(); if (!$publisher->shouldPublishCommit($object)) { return false; } return true; default: break; } } return parent::shouldApplyHeraldRules($object, $xactions); } protected function buildHeraldAdapter( PhabricatorLiskDAO $object, array $xactions) { return id(new HeraldCommitAdapter()) ->setObject($object); } protected function didApplyHeraldRules( PhabricatorLiskDAO $object, HeraldAdapter $adapter, HeraldTranscript $transcript) { $limit = self::MAX_FILES_SHOWN_IN_EMAIL; $files = $adapter->loadAffectedPaths(); sort($files); if (count($files) > $limit) { array_splice($files, $limit); $files[] = pht( '(This commit affected more than %d files. Only %d are shown here '. 'and additional ones are truncated.)', $limit, $limit); } $this->affectedFiles = implode("\n", $files); return array(); } private function isCommitMostlyImported(PhabricatorLiskDAO $object) { $has_message = PhabricatorRepositoryCommit::IMPORTED_MESSAGE; $has_changes = PhabricatorRepositoryCommit::IMPORTED_CHANGE; // Don't publish feed stories or email about events which occur during // import. In particular, this affects tasks being attached when they are // closed by "Fixes Txxxx" in a commit message. See T5851. $mask = ($has_message | $has_changes); return $object->isPartiallyImported($mask); } private function shouldPublishRepositoryActivity( PhabricatorLiskDAO $object, array $xactions) { // not every code path loads the repository so tread carefully // TODO: They should, and then we should simplify this. $repository = $object->getRepository($assert_attached = false); if ($repository != PhabricatorLiskDAO::ATTACHABLE) { $publisher = $repository->newPublisher(); if (!$publisher->shouldPublishCommit($object)) { return false; } } return $this->isCommitMostlyImported($object); } protected function shouldSendMail( PhabricatorLiskDAO $object, array $xactions) { return $this->shouldPublishRepositoryActivity($object, $xactions); } protected function shouldEnableMentions( PhabricatorLiskDAO $object, array $xactions) { return $this->shouldPublishRepositoryActivity($object, $xactions); } protected function shouldPublishFeedStory( PhabricatorLiskDAO $object, array $xactions) { return $this->shouldPublishRepositoryActivity($object, $xactions); } protected function getCustomWorkerState() { return array( 'rawPatch' => $this->rawPatch, 'affectedFiles' => $this->affectedFiles, 'auditorPHIDs' => $this->auditorPHIDs, ); } protected function getCustomWorkerStateEncoding() { return array( 'rawPatch' => self::STORAGE_ENCODING_BINARY, ); } protected function loadCustomWorkerState(array $state) { $this->rawPatch = idx($state, 'rawPatch'); $this->affectedFiles = idx($state, 'affectedFiles'); $this->auditorPHIDs = idx($state, 'auditorPHIDs'); return $this; } protected function willPublish(PhabricatorLiskDAO $object, array $xactions) { return id(new DiffusionCommitQuery()) ->setViewer($this->requireActor()) ->withIDs(array($object->getID())) ->needAuditRequests(true) ->needCommitData(true) ->executeOne(); } private function requireAuditors(PhabricatorRepositoryCommit $commit) { if ($commit->hasAttachedAudits()) { return; } $with_auditors = id(new DiffusionCommitQuery()) ->setViewer($this->getActor()) ->needAuditRequests(true) ->withPHIDs(array($commit->getPHID())) ->executeOne(); if (!$with_auditors) { throw new Exception( pht( 'Failed to reload commit ("%s").', $commit->getPHID())); } $commit->attachAudits($with_auditors->getAudits()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/editor/PhabricatorAuditCommentEditor.php
src/applications/audit/editor/PhabricatorAuditCommentEditor.php
<?php final class PhabricatorAuditCommentEditor extends PhabricatorEditor { public static function getMailThreading( PhabricatorRepository $repository, PhabricatorRepositoryCommit $commit) { return array( 'diffusion-audit-'.$commit->getPHID(), pht( 'Commit %s', $commit->getMonogram()), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/application/PhabricatorAuditApplication.php
src/applications/audit/application/PhabricatorAuditApplication.php
<?php final class PhabricatorAuditApplication extends PhabricatorApplication { public function getBaseURI() { return '/diffusion/commit/'; } public function getIcon() { return 'fa-check-circle-o'; } public function getName() { return pht('Audit'); } public function getShortDescription() { return pht('Browse and Audit Commits'); } public function canUninstall() { // Audit was once a separate application, but has largely merged with // Diffusion. return false; } public function isPinnedByDefault(PhabricatorUser $viewer) { return parent::isClassInstalledForViewer( 'PhabricatorDiffusionApplication', $viewer); } public function getApplicationOrder() { return 0.130; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/view/PhabricatorAuditTransactionView.php
src/applications/audit/view/PhabricatorAuditTransactionView.php
<?php final class PhabricatorAuditTransactionView extends PhabricatorApplicationTransactionView { private $pathMap = array(); public function setPathMap(array $path_map) { $this->pathMap = $path_map; return $this; } public function getPathMap() { return $this->pathMap; } // TODO: This shares a lot of code with Differential and Pholio and should // probably be merged up. protected function shouldGroupTransactions( PhabricatorApplicationTransaction $u, PhabricatorApplicationTransaction $v) { if ($u->getAuthorPHID() != $v->getAuthorPHID()) { // Don't group transactions by different authors. return false; } if (($v->getDateCreated() - $u->getDateCreated()) > 60) { // Don't group if transactions that happened more than 60s apart. return false; } switch ($u->getTransactionType()) { case PhabricatorTransactions::TYPE_COMMENT: case PhabricatorAuditActionConstants::INLINE: break; default: return false; } switch ($v->getTransactionType()) { case PhabricatorAuditActionConstants::INLINE: return true; } return parent::shouldGroupTransactions($u, $v); } protected function renderTransactionContent( PhabricatorApplicationTransaction $xaction) { $out = array(); $type_inline = PhabricatorAuditActionConstants::INLINE; $group = $xaction->getTransactionGroup(); if ($xaction->getTransactionType() == $type_inline) { array_unshift($group, $xaction); } else { $out[] = parent::renderTransactionContent($xaction); } if ($this->getIsPreview()) { return $out; } if (!$group) { return $out; } $inlines = array(); foreach ($group as $xaction) { switch ($xaction->getTransactionType()) { case PhabricatorAuditActionConstants::INLINE: $inlines[] = $xaction; break; default: throw new Exception(pht('Unknown grouped transaction type!')); } } $structs = array(); foreach ($inlines as $key => $inline) { $comment = $inline->getComment(); if (!$comment) { // TODO: Migrate these away? They probably do not exist on normal // non-development installs. unset($inlines[$key]); continue; } $path_id = $comment->getPathID(); $path = idx($this->pathMap, $path_id); if ($path === null) { continue; } $structs[] = array( 'inline' => $inline, 'path' => $path, 'sort' => (string)id(new PhutilSortVector()) ->addString($path) ->addInt($comment->getLineNumber()) ->addInt($comment->getLineLength()) ->addInt($inline->getID()), ); } if (!$structs) { return $out; } $structs = isort($structs, 'sort'); $structs = igroup($structs, 'path'); $inline_view = new PhabricatorInlineSummaryView(); foreach ($structs as $path => $group) { $inlines = ipull($group, 'inline'); $items = array(); foreach ($inlines as $inline) { $comment = $inline->getComment(); $items[] = array( 'id' => $comment->getID(), 'line' => $comment->getLineNumber(), 'length' => $comment->getLineLength(), 'content' => parent::renderTransactionContent($inline), ); } $inline_view->addCommentGroup($path, $items); } $out[] = $inline_view; return $out; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/conduit/AuditQueryConduitAPIMethod.php
src/applications/audit/conduit/AuditQueryConduitAPIMethod.php
<?php final class AuditQueryConduitAPIMethod extends AuditConduitAPIMethod { const AUDIT_LEGACYSTATUS_ANY = 'audit-status-any'; const AUDIT_LEGACYSTATUS_OPEN = 'audit-status-open'; const AUDIT_LEGACYSTATUS_CONCERN = 'audit-status-concern'; const AUDIT_LEGACYSTATUS_ACCEPTED = 'audit-status-accepted'; const AUDIT_LEGACYSTATUS_PARTIAL = 'audit-status-partial'; public function getAPIMethodName() { return 'audit.query'; } public function getMethodDescription() { return pht('Query audit requests.'); } public function getMethodStatus() { return self::METHOD_STATUS_FROZEN; } public function getMethodStatusDescription() { return pht( 'This method is frozen and will eventually be deprecated. New code '. 'should use "diffusion.commit.search" instead.'); } protected function defineParamTypes() { $statuses = array( self::AUDIT_LEGACYSTATUS_ANY, self::AUDIT_LEGACYSTATUS_OPEN, self::AUDIT_LEGACYSTATUS_CONCERN, self::AUDIT_LEGACYSTATUS_ACCEPTED, self::AUDIT_LEGACYSTATUS_PARTIAL, ); $status_const = $this->formatStringConstants($statuses); return array( 'auditorPHIDs' => 'optional list<phid>', 'commitPHIDs' => 'optional list<phid>', 'status' => ('optional '.$status_const. ' (default = "audit-status-any")'), 'offset' => 'optional int', 'limit' => 'optional int (default = 100)', ); } protected function defineReturnType() { return 'list<dict>'; } protected function execute(ConduitAPIRequest $request) { $query = id(new DiffusionCommitQuery()) ->setViewer($request->getUser()) ->needAuditRequests(true); $auditor_phids = $request->getValue('auditorPHIDs', array()); if ($auditor_phids) { $query->withAuditorPHIDs($auditor_phids); } $commit_phids = $request->getValue('commitPHIDs', array()); if ($commit_phids) { $query->withPHIDs($commit_phids); } $status_map = array( self::AUDIT_LEGACYSTATUS_OPEN => array( DiffusionCommitAuditStatus::NEEDS_AUDIT, DiffusionCommitAuditStatus::CONCERN_RAISED, ), self::AUDIT_LEGACYSTATUS_CONCERN => array( DiffusionCommitAuditStatus::CONCERN_RAISED, ), self::AUDIT_LEGACYSTATUS_ACCEPTED => array( DiffusionCommitAuditStatus::AUDITED, ), self::AUDIT_LEGACYSTATUS_PARTIAL => array( DiffusionCommitAuditStatus::PARTIALLY_AUDITED, ), ); $status = $request->getValue('status'); if (isset($status_map[$status])) { $query->withStatuses($status_map[$status]); } // NOTE: These affect the number of commits identified, which is sort of // reasonable but means the method may return an arbitrary number of // actual audit requests. $query->setOffset($request->getValue('offset', 0)); $query->setLimit($request->getValue('limit', 100)); $commits = $query->execute(); $auditor_map = array_fuse($auditor_phids); $results = array(); foreach ($commits as $commit) { $requests = $commit->getAudits(); foreach ($requests as $request) { // If this audit isn't triggered for one of the requested PHIDs, // skip it. if ($auditor_map && empty($auditor_map[$request->getAuditorPHID()])) { continue; } $results[] = array( 'id' => $request->getID(), 'commitPHID' => $request->getCommitPHID(), 'auditorPHID' => $request->getAuditorPHID(), 'reasons' => array(), 'status' => $request->getAuditStatus(), ); } } return $results; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/conduit/AuditConduitAPIMethod.php
src/applications/audit/conduit/AuditConduitAPIMethod.php
<?php abstract class AuditConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass( 'PhabricatorDiffusionApplication'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/constants/PhabricatorAuditRequestStatus.php
src/applications/audit/constants/PhabricatorAuditRequestStatus.php
<?php final class PhabricatorAuditRequestStatus extends Phobject { const AUDIT_REQUIRED = 'audit-required'; const CONCERNED = 'concerned'; const ACCEPTED = 'accepted'; const AUDIT_REQUESTED = 'requested'; const RESIGNED = 'resigned'; private $key; public static function newForStatus($status) { $result = new self(); $result->key = $status; return $result; } public function getIconIcon() { return $this->getMapProperty('icon'); } public function getIconColor() { return $this->getMapProperty('icon.color'); } public function getStatusName() { $name = $this->getMapProperty('name'); if ($name !== null) { return $name; } return pht('Unknown Audit Request Status ("%s")', $this->key); } public function getStatusValue() { return $this->key; } public function getStatusValueForConduit() { return $this->getMapProperty('value.conduit'); } public function isResigned() { return ($this->key === self::RESIGNED); } private function getMapProperty($key, $default = null) { $map = self::newStatusMap(); $spec = idx($map, $this->key, array()); return idx($spec, $key, $default); } private static function newStatusMap() { return array( self::AUDIT_REQUIRED => array( 'name' => pht('Audit Required'), 'icon' => 'fa-exclamation-circle', 'icon.color' => 'orange', 'value.conduit' => 'audit-required', ), self::AUDIT_REQUESTED => array( 'name' => pht('Audit Requested'), 'icon' => 'fa-exclamation-circle', 'icon.color' => 'orange', 'value.conduit' => 'audit-requested', ), self::CONCERNED => array( 'name' => pht('Concern Raised'), 'icon' => 'fa-times-circle', 'icon.color' => 'red', 'value.conduit' => 'concern-raised', ), self::ACCEPTED => array( 'name' => pht('Accepted'), 'icon' => 'fa-check-circle', 'icon.color' => 'green', 'value.conduit' => 'accepted', ), self::RESIGNED => array( 'name' => pht('Resigned'), 'icon' => 'fa-times', 'icon.color' => 'grey', 'value.conduit' => 'resigned', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/audit/constants/PhabricatorAuditActionConstants.php
src/applications/audit/constants/PhabricatorAuditActionConstants.php
<?php final class PhabricatorAuditActionConstants extends Phobject { const CONCERN = 'concern'; const ACCEPT = 'accept'; const COMMENT = 'comment'; const RESIGN = 'resign'; const CLOSE = 'close'; const ADD_CCS = 'add_ccs'; const ADD_AUDITORS = 'add_auditors'; const INLINE = 'audit:inline'; const ACTION = 'audit:action'; }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/controller/PhrequentListController.php
src/applications/phrequent/controller/PhrequentListController.php
<?php final class PhrequentListController extends PhrequentController { private $queryKey; public function shouldAllowPublic() { return true; } public function willProcessRequest(array $data) { $this->queryKey = idx($data, 'queryKey'); } public function processRequest() { $controller = id(new PhabricatorApplicationSearchController()) ->setQueryKey($this->queryKey) ->setSearchEngine(new PhrequentSearchEngine()) ->setNavigation($this->buildSideNavView()); return $this->delegateToController($controller); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/controller/PhrequentController.php
src/applications/phrequent/controller/PhrequentController.php
<?php abstract class PhrequentController extends PhabricatorController { protected function buildSideNavView() { $user = $this->getRequest()->getUser(); $nav = new AphrontSideNavFilterView(); $nav->setBaseURI(new PhutilURI($this->getApplicationURI())); id(new PhrequentSearchEngine()) ->setViewer($user) ->addNavigationItems($nav->getMenu()); $nav->selectFilter(null); return $nav; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/controller/PhrequentTrackController.php
src/applications/phrequent/controller/PhrequentTrackController.php
<?php final class PhrequentTrackController extends PhrequentController { private $verb; private $phid; public function willProcessRequest(array $data) { $this->phid = $data['phid']; $this->verb = $data['verb']; } public function processRequest() { $request = $this->getRequest(); $viewer = $request->getUser(); $phid = $this->phid; $handle = id(new PhabricatorHandleQuery()) ->setViewer($viewer) ->withPHIDs(array($phid)) ->executeOne(); $done_uri = $handle->getURI(); $current_timer = null; switch ($this->verb) { case 'start': $button_text = pht('Start Tracking'); $title_text = pht('Start Tracking Time'); $inner_text = pht('What time did you start working?'); $action_text = pht('Start Timer'); $label_text = pht('Start Time'); break; case 'stop': $button_text = pht('Stop Tracking'); $title_text = pht('Stop Tracking Time'); $inner_text = pht('What time did you stop working?'); $action_text = pht('Stop Timer'); $label_text = pht('Stop Time'); $current_timer = id(new PhrequentUserTimeQuery()) ->setViewer($viewer) ->withUserPHIDs(array($viewer->getPHID())) ->withObjectPHIDs(array($phid)) ->withEnded(PhrequentUserTimeQuery::ENDED_NO) ->executeOne(); if (!$current_timer) { return $this->newDialog() ->setTitle(pht('Not Tracking Time')) ->appendParagraph( pht('You are not currently tracking time on this object.')) ->addCancelButton($done_uri); } break; default: return new Aphront404Response(); } $errors = array(); $v_note = null; $e_date = null; $timestamp = AphrontFormDateControlValue::newFromEpoch( $viewer, time()); if ($request->isDialogFormPost()) { $v_note = $request->getStr('note'); $timestamp = AphrontFormDateControlValue::newFromRequest( $request, 'epoch'); if (!$timestamp->isValid()) { $errors[] = pht('Please choose a valid date.'); $e_date = pht('Invalid'); } else { $max_time = PhabricatorTime::getNow(); if ($timestamp->getEpoch() > $max_time) { if ($this->isStoppingTracking()) { $errors[] = pht( 'You can not stop tracking time at a future time. Enter the '. 'current time, or a time in the past.'); } else { $errors[] = pht( 'You can not start tracking time at a future time. Enter the '. 'current time, or a time in the past.'); } $e_date = pht('Invalid'); } if ($this->isStoppingTracking()) { $min_time = $current_timer->getDateStarted(); if ($min_time > $timestamp->getEpoch()) { $errors[] = pht('Stop time must be after start time.'); $e_date = pht('Invalid'); } } } if (!$errors) { $editor = new PhrequentTrackingEditor(); if ($this->isStartingTracking()) { $editor->startTracking( $viewer, $this->phid, $timestamp->getEpoch()); } else if ($this->isStoppingTracking()) { $editor->stopTracking( $viewer, $this->phid, $timestamp->getEpoch(), $v_note); } return id(new AphrontRedirectResponse())->setURI($done_uri); } } $dialog = $this->newDialog() ->setTitle($title_text) ->setWidth(AphrontDialogView::WIDTH_FORM) ->setErrors($errors) ->appendParagraph($inner_text); $form = new PHUIFormLayoutView(); if ($this->isStoppingTracking()) { $start_time = $current_timer->getDateStarted(); $start_string = pht( '%s (%s ago)', phabricator_datetime($start_time, $viewer), phutil_format_relative_time(PhabricatorTime::getNow() - $start_time)); $form->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('Started At')) ->setValue($start_string)); } $form->appendChild( id(new AphrontFormDateControl()) ->setUser($viewer) ->setName('epoch') ->setLabel($action_text) ->setError($e_date) ->setValue($timestamp)); if ($this->isStoppingTracking()) { $form->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Note')) ->setName('note') ->setValue($v_note)); } $dialog->appendChild($form); $dialog->addCancelButton($done_uri); $dialog->addSubmitButton($action_text); return $dialog; } private function isStartingTracking() { return $this->verb === 'start'; } private function isStoppingTracking() { return $this->verb === 'stop'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/engineextension/PhrequentCurtainExtension.php
src/applications/phrequent/engineextension/PhrequentCurtainExtension.php
<?php final class PhrequentCurtainExtension extends PHUICurtainExtension { const EXTENSIONKEY = 'phrequent.time'; public function shouldEnableForObject($object) { return ($object instanceof PhrequentTrackableInterface); } public function getExtensionApplication() { return new PhabricatorPhrequentApplication(); } public function buildCurtainPanel($object) { $viewer = $this->getViewer(); $events = id(new PhrequentUserTimeQuery()) ->setViewer($viewer) ->withObjectPHIDs(array($object->getPHID())) ->needPreemptingEvents(true) ->execute(); $event_groups = mgroup($events, 'getUserPHID'); if (!$events) { return; } $handles = $viewer->loadHandles(array_keys($event_groups)); $status_view = new PHUIStatusListView(); $now = PhabricatorTime::getNow(); foreach ($event_groups as $user_phid => $event_group) { $item = new PHUIStatusItemView(); $item->setTarget($handles[$user_phid]->renderLink()); $state = 'stopped'; foreach ($event_group as $event) { if ($event->getDateEnded() === null) { if ($event->isPreempted()) { $state = 'suspended'; } else { $state = 'active'; break; } } } switch ($state) { case 'active': $item->setIcon( PHUIStatusItemView::ICON_CLOCK, 'green', pht('Working Now')); break; case 'suspended': $item->setIcon( PHUIStatusItemView::ICON_CLOCK, 'yellow', pht('Interrupted')); break; case 'stopped': $item->setIcon( PHUIStatusItemView::ICON_CLOCK, 'bluegrey', pht('Not Working Now')); break; } $block = new PhrequentTimeBlock($event_group); $duration = $block->getTimeSpentOnObject( $object->getPHID(), $now); $duration_display = phutil_format_relative_time_detailed( $duration, $levels = 3); $item->setNote($duration_display); $status_view->addItem($item); } return $this->newPanel() ->setHeaderText(pht('Time Spent')) ->setOrder(40000) ->appendChild($status_view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/storage/PhrequentTimeBlock.php
src/applications/phrequent/storage/PhrequentTimeBlock.php
<?php final class PhrequentTimeBlock extends Phobject { private $events; public function __construct(array $events) { assert_instances_of($events, 'PhrequentUserTime'); $this->events = $events; } public function getTimeSpentOnObject($phid, $now) { $slices = idx($this->getObjectTimeRanges(), $phid); if (!$slices) { return null; } return $slices->getDuration($now); } public function getObjectTimeRanges() { $ranges = array(); $range_start = time(); foreach ($this->events as $event) { $range_start = min($range_start, $event->getDateStarted()); } $object_ranges = array(); $object_ongoing = array(); foreach ($this->events as $event) { // First, convert each event's preempting stack into a linear timeline // of events. $timeline = array(); $timeline[] = array( 'event' => $event, 'at' => (int)$event->getDateStarted(), 'type' => 'start', ); $timeline[] = array( 'event' => $event, 'at' => (int)nonempty($event->getDateEnded(), PHP_INT_MAX), 'type' => 'end', ); $base_phid = $event->getObjectPHID(); if (!$event->getDateEnded()) { $object_ongoing[$base_phid] = true; } $preempts = $event->getPreemptingEvents(); foreach ($preempts as $preempt) { $same_object = ($preempt->getObjectPHID() == $base_phid); $timeline[] = array( 'event' => $preempt, 'at' => (int)$preempt->getDateStarted(), 'type' => $same_object ? 'start' : 'push', ); $timeline[] = array( 'event' => $preempt, 'at' => (int)nonempty($preempt->getDateEnded(), PHP_INT_MAX), 'type' => $same_object ? 'end' : 'pop', ); } // Now, figure out how much time was actually spent working on the // object. usort($timeline, array(__CLASS__, 'sortTimeline')); $stack = array(); $depth = null; // NOTE: "Strata" track the separate layers between each event tracking // the object we care about. Events might look like this: // // |xxxxxxxxxxxxxxxxx| // |yyyyyyy| // |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| // 9AM 5PM // // ...where we care about event "x". When "y" is popped, that shouldn't // pop the top stack -- we need to pop the stack a level down. Each // event tracking "x" creates a new stratum, and we keep track of where // timeline events are among the strata in order to keep stack depths // straight. $stratum = null; $strata = array(); $ranges = array(); foreach ($timeline as $timeline_event) { $id = $timeline_event['event']->getID(); $type = $timeline_event['type']; switch ($type) { case 'start': $stack[] = $depth; $depth = 0; $stratum = count($stack); $strata[$id] = $stratum; $range_start = $timeline_event['at']; break; case 'end': if ($strata[$id] == $stratum) { if ($depth == 0) { $ranges[] = array($range_start, $timeline_event['at']); $depth = array_pop($stack); } else { // Here, we've prematurely ended the current stratum. Merge all // the higher strata into it. This looks like this: // // V // V // |zzzzzzzz| // |xxxxx| // |yyyyyyyyyyyyy| // |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| $depth = array_pop($stack) + $depth; } } else { // Here, we've prematurely ended a deeper stratum. Merge higher // strata. This looks like this: // // V // V // |aaaaaaa| // |xxxxxxxxxxxxxxxxxxx| // |zzzzzzzzzzzzz| // |xxxxxxx| // |yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy| // |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| $extra = $stack[$strata[$id]]; unset($stack[$strata[$id] - 1]); $stack = array_values($stack); $stack[$strata[$id] - 1] += $extra; } // Regardless of how we got here, we need to merge down any higher // strata. $target = $strata[$id]; foreach ($strata as $strata_id => $id_stratum) { if ($id_stratum >= $target) { $strata[$strata_id]--; } } $stratum = count($stack); unset($strata[$id]); break; case 'push': $strata[$id] = $stratum; if ($depth == 0) { $ranges[] = array($range_start, $timeline_event['at']); } $depth++; break; case 'pop': if ($strata[$id] == $stratum) { $depth--; if ($depth == 0) { $range_start = $timeline_event['at']; } } else { $stack[$strata[$id]]--; } unset($strata[$id]); break; } } // Filter out ranges with an indefinite start time. These occur when // popping the stack when there are multiple ongoing events. foreach ($ranges as $key => $range) { if ($range[0] == PHP_INT_MAX) { unset($ranges[$key]); } } $object_ranges[$base_phid][] = $ranges; } // Collapse all the ranges so we don't double-count time. foreach ($object_ranges as $phid => $ranges) { $object_ranges[$phid] = self::mergeTimeRanges(array_mergev($ranges)); } foreach ($object_ranges as $phid => $ranges) { foreach ($ranges as $key => $range) { if ($range[1] == PHP_INT_MAX) { $ranges[$key][1] = null; } } $object_ranges[$phid] = new PhrequentTimeSlices( $phid, isset($object_ongoing[$phid]), $ranges); } // Reorder the ranges to be more stack-like, so the first item is the // top of the stack. $object_ranges = array_reverse($object_ranges, $preserve_keys = true); return $object_ranges; } /** * Returns the current list of work. */ public function getCurrentWorkStack($now, $include_inactive = false) { $ranges = $this->getObjectTimeRanges(); $results = array(); $active = null; foreach ($ranges as $phid => $slices) { if (!$include_inactive) { if (!$slices->getIsOngoing()) { continue; } } $results[] = array( 'phid' => $phid, 'time' => $slices->getDuration($now), 'ongoing' => $slices->getIsOngoing(), ); } return $results; } /** * Merge a list of time ranges (pairs of `<start, end>` epochs) so that no * elements overlap. For example, the ranges: * * array( * array(50, 150), * array(100, 175), * ); * * ...are merged to: * * array( * array(50, 175), * ); * * This is used to avoid double-counting time on objects which had timers * started multiple times. * * @param list<pair<int, int>> List of possibly overlapping time ranges. * @return list<pair<int, int>> Nonoverlapping time ranges. */ public static function mergeTimeRanges(array $ranges) { $ranges = isort($ranges, 0); $result = array(); $current = null; foreach ($ranges as $key => $range) { if ($current === null) { $current = $range; continue; } if ($range[0] <= $current[1]) { $current[1] = max($range[1], $current[1]); continue; } $result[] = $current; $current = $range; } $result[] = $current; return $result; } /** * Sort events in timeline order. Notably, for events which occur on the same * second, we want to process end events after start events. */ public static function sortTimeline(array $u, array $v) { // If these events occur at different times, ordering is obvious. if ($u['at'] != $v['at']) { return ($u['at'] < $v['at']) ? -1 : 1; } $u_end = ($u['type'] == 'end' || $u['type'] == 'pop'); $v_end = ($v['type'] == 'end' || $v['type'] == 'pop'); $u_id = $u['event']->getID(); $v_id = $v['event']->getID(); if ($u_end == $v_end) { // These are both start events or both end events. Sort them by ID. if (!$u_end) { return ($u_id < $v_id) ? -1 : 1; } else { return ($u_id < $v_id) ? 1 : -1; } } else { // Sort them (start, end) if they're the same event, and (end, start) // otherwise. if ($u_id == $v_id) { return $v_end ? -1 : 1; } else { return $v_end ? 1 : -1; } } 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/phrequent/storage/PhrequentUserTime.php
src/applications/phrequent/storage/PhrequentUserTime.php
<?php final class PhrequentUserTime extends PhrequentDAO implements PhabricatorPolicyInterface { protected $userPHID; protected $objectPHID; protected $note; protected $dateStarted; protected $dateEnded; private $preemptingEvents = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_COLUMN_SCHEMA => array( 'objectPHID' => 'phid?', 'note' => 'text?', 'dateStarted' => 'epoch', 'dateEnded' => 'epoch?', ), ) + parent::getConfiguration(); } public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { $policy = PhabricatorPolicies::POLICY_NOONE; switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: // Since it's impossible to perform any meaningful computations with // time if a user can't view some of it, visibility on tracked time is // unrestricted. If we eventually lock it down, it should be per-user. // (This doesn't mean that users can see tracked objects.) return PhabricatorPolicies::getMostOpenPolicy(); } return $policy; } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return ($viewer->getPHID() == $this->getUserPHID()); } public function describeAutomaticCapability($capability) { return null; } public function attachPreemptingEvents(array $events) { $this->preemptingEvents = $events; return $this; } public function getPreemptingEvents() { return $this->assertAttached($this->preemptingEvents); } public function isPreempted() { if ($this->getDateEnded() !== null) { return false; } foreach ($this->getPreemptingEvents() as $event) { if ($event->getDateEnded() === null && $event->getObjectPHID() != $this->getObjectPHID()) { return true; } } return false; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/storage/PhrequentDAO.php
src/applications/phrequent/storage/PhrequentDAO.php
<?php abstract class PhrequentDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'phrequent'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/storage/PhrequentTimeSlices.php
src/applications/phrequent/storage/PhrequentTimeSlices.php
<?php final class PhrequentTimeSlices extends Phobject { private $objectPHID; private $isOngoing; private $ranges; public function __construct($object_phid, $is_ongoing, array $ranges) { $this->objectPHID = $object_phid; $this->isOngoing = $is_ongoing; $this->ranges = $ranges; } public function getObjectPHID() { return $this->objectPHID; } public function getDuration($now) { $total = 0; foreach ($this->ranges as $range) { if ($range[1] === null) { $total += $now - $range[0]; } else { $total += $range[1] - $range[0]; } } return $total; } public function getIsOngoing() { return $this->isOngoing; } public function getRanges() { return $this->ranges; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/storage/__tests__/PhrequentTimeBlockTestCase.php
src/applications/phrequent/storage/__tests__/PhrequentTimeBlockTestCase.php
<?php final class PhrequentTimeBlockTestCase extends PhabricatorTestCase { public function testMergeTimeRanges() { // Overlapping ranges. $input = array( array(50, 150), array(100, 175), ); $expect = array( array(50, 175), ); $this->assertEqual($expect, PhrequentTimeBlock::mergeTimeRanges($input)); // Identical ranges. $input = array( array(1, 1), array(1, 1), array(1, 1), ); $expect = array( array(1, 1), ); $this->assertEqual($expect, PhrequentTimeBlock::mergeTimeRanges($input)); // Range which is a strict subset of another range. $input = array( array(2, 7), array(1, 10), ); $expect = array( array(1, 10), ); $this->assertEqual($expect, PhrequentTimeBlock::mergeTimeRanges($input)); // These are discontinuous and should not be merged. $input = array( array(5, 6), array(7, 8), ); $expect = array( array(5, 6), array(7, 8), ); $this->assertEqual($expect, PhrequentTimeBlock::mergeTimeRanges($input)); // These overlap only on an edge, but should merge. $input = array( array(5, 6), array(6, 7), ); $expect = array( array(5, 7), ); $this->assertEqual($expect, PhrequentTimeBlock::mergeTimeRanges($input)); } public function testPreemptingEvents() { // Roughly, this is: got into work, started T1, had a meeting from 10-11, // left the office around 2 to meet a client at a coffee shop, worked on // T1 again for about 40 minutes, had the meeting from 3-3:30, finished up // on T1, headed back to the office, got another hour of work in, and // headed home. $event = $this->newEvent('T1', 900, 1700); $event->attachPreemptingEvents( array( $this->newEvent('meeting', 1000, 1100), $this->newEvent('offsite', 1400, 1600), $this->newEvent('T1', 1420, 1580), $this->newEvent('offsite meeting', 1500, 1550), )); $block = new PhrequentTimeBlock(array($event)); $ranges = $block->getObjectTimeRanges(); $ranges = $this->reduceRanges($ranges); $this->assertEqual( array( 'T1' => array( array(900, 1000), // Before morning meeting. array(1100, 1400), // After morning meeting. array(1420, 1500), // Coffee, before client meeting. array(1550, 1580), // Coffee, after client meeting. array(1600, 1700), // After returning from off site. ), ), $ranges); $event = $this->newEvent('T2', 100, 300); $event->attachPreemptingEvents( array( $this->newEvent('meeting', 200, null), )); $block = new PhrequentTimeBlock(array($event)); $ranges = $block->getObjectTimeRanges(); $ranges = $this->reduceRanges($ranges); $this->assertEqual( array( 'T2' => array( array(100, 200), ), ), $ranges); } public function testTimelineSort() { $e1 = $this->newEvent('X1', 1, 1)->setID(1); $in = array( array( 'event' => $e1, 'at' => 1, 'type' => 'start', ), array( 'event' => $e1, 'at' => 1, 'type' => 'end', ), ); usort($in, array('PhrequentTimeBlock', 'sortTimeline')); $this->assertEqual( array( 'start', 'end', ), ipull($in, 'type')); } public function testInstantaneousEvent() { $event = $this->newEvent('T1', 8, 8); $event->attachPreemptingEvents(array()); $block = new PhrequentTimeBlock(array($event)); $ranges = $block->getObjectTimeRanges(); $ranges = $this->reduceRanges($ranges); $this->assertEqual( array( 'T1' => array( array(8, 8), ), ), $ranges); } public function testPopAcrossStrata() { $event = $this->newEvent('T1', 1, 1000); $event->attachPreemptingEvents( array( $this->newEvent('T2', 100, 300), $this->newEvent('T1', 200, 400), $this->newEvent('T3', 250, 275), )); $block = new PhrequentTimeBlock(array($event)); $ranges = $block->getObjectTimeRanges(); $ranges = $this->reduceRanges($ranges); $this->assertEqual( array( 'T1' => array( array(1, 100), array(200, 250), array(275, 1000), ), ), $ranges); } public function testEndDeeperStratum() { $event = $this->newEvent('T1', 1, 1000); $event->attachPreemptingEvents( array( $this->newEvent('T2', 100, 900), $this->newEvent('T1', 200, 400), $this->newEvent('T3', 300, 800), $this->newEvent('T1', 350, 600), $this->newEvent('T4', 380, 390), )); $block = new PhrequentTimeBlock(array($event)); $ranges = $block->getObjectTimeRanges(); $ranges = $this->reduceRanges($ranges); $this->assertEqual( array( 'T1' => array( array(1, 100), array(200, 300), array(350, 380), array(390, 600), array(900, 1000), ), ), $ranges); } public function testOngoing() { $event = $this->newEvent('T1', 1, null); $event->attachPreemptingEvents(array()); $block = new PhrequentTimeBlock(array($event)); $ranges = $block->getObjectTimeRanges(); $ranges = $this->reduceRanges($ranges); $this->assertEqual( array( 'T1' => array( array(1, null), ), ), $ranges); } public function testOngoingInterrupted() { $event = $this->newEvent('T1', 1, null); $event->attachPreemptingEvents( array( $this->newEvent('T2', 100, 900), )); $block = new PhrequentTimeBlock(array($event)); $ranges = $block->getObjectTimeRanges(); $ranges = $this->reduceRanges($ranges); $this->assertEqual( array( 'T1' => array( array(1, 100), array(900, null), ), ), $ranges); } public function testOngoingPreempted() { $event = $this->newEvent('T1', 1, null); $event->attachPreemptingEvents( array( $this->newEvent('T2', 100, null), )); $block = new PhrequentTimeBlock(array($event)); $ranges = $block->getObjectTimeRanges(); $ranges = $this->reduceRanges($ranges); $this->assertEqual( array( 'T1' => array( array(1, 100), ), ), $ranges); } public function testSumTimeSlices() { // This block has multiple closed slices. $block = new PhrequentTimeBlock( array( $this->newEvent('T1', 3456, 4456)->attachPreemptingEvents(array()), $this->newEvent('T1', 8000, 9000)->attachPreemptingEvents(array()), )); $this->assertEqual( 2000, $block->getTimeSpentOnObject('T1', 10000)); // This block has an open slice. $block = new PhrequentTimeBlock( array( $this->newEvent('T1', 3456, 4456)->attachPreemptingEvents(array()), $this->newEvent('T1', 8000, null)->attachPreemptingEvents(array()), )); $this->assertEqual( 3000, $block->getTimeSpentOnObject('T1', 10000)); } private function newEvent($object_phid, $start_time, $end_time) { static $id = 0; return id(new PhrequentUserTime()) ->setID(++$id) ->setObjectPHID($object_phid) ->setDateStarted($start_time) ->setDateEnded($end_time); } private function reduceRanges(array $ranges) { $results = array(); foreach ($ranges as $phid => $slices) { $results[$phid] = $slices->getRanges(); } return $results; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/query/PhrequentUserTimeQuery.php
src/applications/phrequent/query/PhrequentUserTimeQuery.php
<?php final class PhrequentUserTimeQuery extends PhabricatorCursorPagedPolicyAwareQuery { const ORDER_ID_ASC = 0; const ORDER_ID_DESC = 1; const ORDER_STARTED_ASC = 2; const ORDER_STARTED_DESC = 3; const ORDER_ENDED_ASC = 4; const ORDER_ENDED_DESC = 5; const ENDED_YES = 0; const ENDED_NO = 1; const ENDED_ALL = 2; private $ids; private $userPHIDs; private $objectPHIDs; private $ended = self::ENDED_ALL; private $needPreemptingEvents; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withUserPHIDs(array $user_phids) { $this->userPHIDs = $user_phids; return $this; } public function withObjectPHIDs(array $object_phids) { $this->objectPHIDs = $object_phids; return $this; } public function withEnded($ended) { $this->ended = $ended; return $this; } public function setOrder($order) { switch ($order) { case self::ORDER_ID_ASC: $this->setOrderVector(array('-id')); break; case self::ORDER_ID_DESC: $this->setOrderVector(array('id')); break; case self::ORDER_STARTED_ASC: $this->setOrderVector(array('-start', '-id')); break; case self::ORDER_STARTED_DESC: $this->setOrderVector(array('start', 'id')); break; case self::ORDER_ENDED_ASC: $this->setOrderVector(array('-end', '-id')); break; case self::ORDER_ENDED_DESC: $this->setOrderVector(array('end', 'id')); break; default: throw new Exception(pht('Unknown order "%s".', $order)); } return $this; } public function needPreemptingEvents($need_events) { $this->needPreemptingEvents = $need_events; return $this; } protected function buildWhereClause(AphrontDatabaseConnection $conn) { $where = array(); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'id IN (%Ld)', $this->ids); } if ($this->userPHIDs !== null) { $where[] = qsprintf( $conn, 'userPHID IN (%Ls)', $this->userPHIDs); } if ($this->objectPHIDs !== null) { $where[] = qsprintf( $conn, 'objectPHID IN (%Ls)', $this->objectPHIDs); } switch ($this->ended) { case self::ENDED_ALL: break; case self::ENDED_YES: $where[] = qsprintf( $conn, 'dateEnded IS NOT NULL'); break; case self::ENDED_NO: $where[] = qsprintf( $conn, 'dateEnded IS NULL'); break; default: throw new Exception(pht("Unknown ended '%s'!", $this->ended)); } $where[] = $this->buildPagingClause($conn); return $this->formatWhereClause($conn, $where); } public function getOrderableColumns() { return parent::getOrderableColumns() + array( 'start' => array( 'column' => 'dateStarted', 'type' => 'int', ), 'end' => array( 'column' => 'dateEnded', 'type' => 'int', 'null' => 'head', ), ); } protected function newPagingMapFromPartialObject($object) { return array( 'id' => (int)$object->getID(), 'start' => (int)$object->getDateStarted(), 'end' => (int)$object->getDateEnded(), ); } protected function loadPage() { $usertime = new PhrequentUserTime(); $conn = $usertime->establishConnection('r'); $data = queryfx_all( $conn, 'SELECT usertime.* FROM %T usertime %Q %Q %Q', $usertime->getTableName(), $this->buildWhereClause($conn), $this->buildOrderClause($conn), $this->buildLimitClause($conn)); return $usertime->loadAllFromArray($data); } protected function didFilterPage(array $page) { if ($this->needPreemptingEvents) { $usertime = new PhrequentUserTime(); $conn_r = $usertime->establishConnection('r'); $preempt = array(); foreach ($page as $event) { $preempt[] = qsprintf( $conn_r, '(userPHID = %s AND (dateStarted BETWEEN %d AND %d) AND (dateEnded IS NULL OR dateEnded > %d))', $event->getUserPHID(), $event->getDateStarted(), nonempty($event->getDateEnded(), PhabricatorTime::getNow()), $event->getDateStarted()); } $preempting_events = queryfx_all( $conn_r, 'SELECT * FROM %T WHERE %LO ORDER BY dateStarted ASC, id ASC', $usertime->getTableName(), $preempt); $preempting_events = $usertime->loadAllFromArray($preempting_events); $preempting_events = mgroup($preempting_events, 'getUserPHID'); foreach ($page as $event) { $e_start = $event->getDateStarted(); $e_end = $event->getDateEnded(); $select = array(); $user_events = idx($preempting_events, $event->getUserPHID(), array()); foreach ($user_events as $u_event) { if ($u_event->getID() == $event->getID()) { // Don't allow an event to preempt itself. continue; } $u_start = $u_event->getDateStarted(); $u_end = $u_event->getDateEnded(); if ($u_start < $e_start) { // This event started before our event started, so it's not // preempting us. continue; } if ($u_start == $e_start) { if ($u_event->getID() < $event->getID()) { // This event started at the same time as our event started, // but has a lower ID, so it's not preempting us. continue; } } if (($e_end !== null) && ($u_start > $e_end)) { // Our event has ended, and this event started after it ended. continue; } if (($u_end !== null) && ($u_end < $e_start)) { // This event ended before our event began. continue; } $select[] = $u_event; } $event->attachPreemptingEvents($select); } } return $page; } /* -( Helper Functions ) --------------------------------------------------- */ public static function getEndedSearchOptions() { return array( self::ENDED_ALL => pht('All'), self::ENDED_NO => pht('No'), self::ENDED_YES => pht('Yes'), ); } public static function getOrderSearchOptions() { return array( self::ORDER_STARTED_ASC => pht('by furthest start date'), self::ORDER_STARTED_DESC => pht('by nearest start date'), self::ORDER_ENDED_ASC => pht('by furthest end date'), self::ORDER_ENDED_DESC => pht('by nearest end date'), ); } public static function getUserTotalObjectsTracked( PhabricatorUser $user, $limit = PHP_INT_MAX) { $usertime_dao = new PhrequentUserTime(); $conn = $usertime_dao->establishConnection('r'); $count = queryfx_one( $conn, 'SELECT COUNT(usertime.id) N FROM %T usertime '. 'WHERE usertime.userPHID = %s '. 'AND usertime.dateEnded IS NULL '. 'LIMIT %d', $usertime_dao->getTableName(), $user->getPHID(), $limit); return $count['N']; } public static function isUserTrackingObject( PhabricatorUser $user, $phid) { $usertime_dao = new PhrequentUserTime(); $conn = $usertime_dao->establishConnection('r'); $count = queryfx_one( $conn, 'SELECT COUNT(usertime.id) N FROM %T usertime '. 'WHERE usertime.userPHID = %s '. 'AND usertime.objectPHID = %s '. 'AND usertime.dateEnded IS NULL', $usertime_dao->getTableName(), $user->getPHID(), $phid); return $count['N'] > 0; } public static function getUserTimeSpentOnObject( PhabricatorUser $user, $phid) { $usertime_dao = new PhrequentUserTime(); $conn = $usertime_dao->establishConnection('r'); // First calculate all the time spent where the // usertime blocks have ended. $sum_ended = queryfx_one( $conn, 'SELECT SUM(usertime.dateEnded - usertime.dateStarted) N '. 'FROM %T usertime '. 'WHERE usertime.userPHID = %s '. 'AND usertime.objectPHID = %s '. 'AND usertime.dateEnded IS NOT NULL', $usertime_dao->getTableName(), $user->getPHID(), $phid); // Now calculate the time spent where the usertime // blocks have not yet ended. $sum_not_ended = queryfx_one( $conn, 'SELECT SUM(UNIX_TIMESTAMP() - usertime.dateStarted) N '. 'FROM %T usertime '. 'WHERE usertime.userPHID = %s '. 'AND usertime.objectPHID = %s '. 'AND usertime.dateEnded IS NULL', $usertime_dao->getTableName(), $user->getPHID(), $phid); return $sum_ended['N'] + $sum_not_ended['N']; } public function getQueryApplicationClass() { return 'PhabricatorPhrequentApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/query/PhrequentSearchEngine.php
src/applications/phrequent/query/PhrequentSearchEngine.php
<?php final class PhrequentSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Phrequent Time'); } public function getApplicationClassName() { return 'PhabricatorPhrequentApplication'; } public function getPageSize(PhabricatorSavedQuery $saved) { return $saved->getParameter('limit', 1000); } public function buildSavedQueryFromRequest(AphrontRequest $request) { $saved = new PhabricatorSavedQuery(); $saved->setParameter( 'userPHIDs', $this->readUsersFromRequest($request, 'users')); $saved->setParameter('ended', $request->getStr('ended')); $saved->setParameter('order', $request->getStr('order')); return $saved; } public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) { $query = id(new PhrequentUserTimeQuery()) ->needPreemptingEvents(true); $user_phids = $saved->getParameter('userPHIDs'); if ($user_phids) { $query->withUserPHIDs($user_phids); } $ended = $saved->getParameter('ended'); if ($ended != null) { $query->withEnded($ended); } $order = $saved->getParameter('order'); if ($order != null) { $query->setOrder($order); } return $query; } public function buildSearchForm( AphrontFormView $form, PhabricatorSavedQuery $saved_query) { $user_phids = $saved_query->getParameter('userPHIDs', array()); $ended = $saved_query->getParameter( 'ended', PhrequentUserTimeQuery::ENDED_ALL); $order = $saved_query->getParameter( 'order', PhrequentUserTimeQuery::ORDER_ENDED_DESC); $form ->appendControl( id(new AphrontFormTokenizerControl()) ->setDatasource(new PhabricatorPeopleDatasource()) ->setName('users') ->setLabel(pht('Users')) ->setValue($user_phids)) ->appendChild( id(new AphrontFormSelectControl()) ->setLabel(pht('Ended')) ->setName('ended') ->setValue($ended) ->setOptions(PhrequentUserTimeQuery::getEndedSearchOptions())) ->appendChild( id(new AphrontFormSelectControl()) ->setLabel(pht('Order')) ->setName('order') ->setValue($order) ->setOptions(PhrequentUserTimeQuery::getOrderSearchOptions())); } protected function getURI($path) { return '/phrequent/'.$path; } protected function getBuiltinQueryNames() { return array( 'tracking' => pht('Currently Tracking'), 'all' => pht('All Tracked'), ); } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query ->setParameter('order', PhrequentUserTimeQuery::ORDER_ENDED_DESC); case 'tracking': return $query ->setParameter('ended', PhrequentUserTimeQuery::ENDED_NO) ->setParameter('order', PhrequentUserTimeQuery::ORDER_ENDED_DESC); } return parent::buildSavedQueryFromBuiltin($query_key); } protected function getRequiredHandlePHIDsForResultList( array $usertimes, PhabricatorSavedQuery $query) { return array_mergev( array( mpull($usertimes, 'getUserPHID'), mpull($usertimes, 'getObjectPHID'), )); } protected function renderResultList( array $usertimes, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($usertimes, 'PhrequentUserTime'); $viewer = $this->requireViewer(); $view = id(new PHUIObjectItemListView()) ->setUser($viewer); foreach ($usertimes as $usertime) { $item = new PHUIObjectItemView(); if ($usertime->getObjectPHID() === null) { $item->setHeader($usertime->getNote()); } else { $obj = $handles[$usertime->getObjectPHID()]; $item->setHeader($obj->getLinkName()); $item->setHref($obj->getURI()); } $item->setObject($usertime); $item->addByline( pht( 'Tracked: %s', $handles[$usertime->getUserPHID()]->renderLink())); $started_date = phabricator_date($usertime->getDateStarted(), $viewer); $item->addIcon('none', $started_date); $block = new PhrequentTimeBlock(array($usertime)); $time_spent = $block->getTimeSpentOnObject( $usertime->getObjectPHID(), PhabricatorTime::getNow()); $time_spent = $time_spent == 0 ? 'none' : phutil_format_relative_time_detailed($time_spent); if ($usertime->getDateEnded() !== null) { $item->addAttribute( pht( 'Tracked %s', $time_spent)); $item->addAttribute( pht( 'Ended on %s', phabricator_datetime($usertime->getDateEnded(), $viewer))); } else { $item->addAttribute( pht( 'Tracked %s so far', $time_spent)); if ($usertime->getObjectPHID() !== null && $usertime->getUserPHID() === $viewer->getPHID()) { $item->addAction( id(new PHUIListItemView()) ->setIcon('fa-stop') ->addSigil('phrequent-stop-tracking') ->setWorkflow(true) ->setRenderNameAsTooltip(true) ->setName(pht('Stop')) ->setHref( '/phrequent/track/stop/'. $usertime->getObjectPHID().'/')); } $item->setStatusIcon('fa-clock-o green'); } $view->addItem($item); } $result = new PhabricatorApplicationSearchResultView(); $result->setObjectList($view); return $result; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/interface/PhrequentTrackableInterface.php
src/applications/phrequent/interface/PhrequentTrackableInterface.php
<?php interface PhrequentTrackableInterface {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/editor/PhrequentTrackingEditor.php
src/applications/phrequent/editor/PhrequentTrackingEditor.php
<?php final class PhrequentTrackingEditor extends PhabricatorEditor { public function startTracking(PhabricatorUser $user, $phid, $timestamp) { $usertime = new PhrequentUserTime(); $usertime->setDateStarted($timestamp); $usertime->setUserPHID($user->getPHID()); $usertime->setObjectPHID($phid); $usertime->save(); return $phid; } public function stopTracking( PhabricatorUser $user, $phid, $timestamp, $note) { if (!PhrequentUserTimeQuery::isUserTrackingObject($user, $phid)) { // Don't do anything, it's not being tracked. return null; } $usertime_dao = new PhrequentUserTime(); $conn = $usertime_dao->establishConnection('r'); queryfx( $conn, 'UPDATE %T usertime '. 'SET usertime.dateEnded = %d, '. 'usertime.note = %s '. 'WHERE usertime.userPHID = %s '. 'AND usertime.objectPHID = %s '. 'AND usertime.dateEnded IS NULL '. 'ORDER BY usertime.dateStarted, usertime.id DESC '. 'LIMIT 1', $usertime_dao->getTableName(), $timestamp, $note, $user->getPHID(), $phid); return $phid; } public function stopTrackingTop(PhabricatorUser $user, $timestamp, $note) { $times = id(new PhrequentUserTimeQuery()) ->setViewer($user) ->withUserPHIDs(array($user->getPHID())) ->withEnded(PhrequentUserTimeQuery::ENDED_NO) ->setOrder(PhrequentUserTimeQuery::ORDER_STARTED_DESC) ->execute(); if (count($times) === 0) { // Nothing to stop tracking. return null; } $current = head($times); return $this->stopTracking( $user, $current->getObjectPHID(), $timestamp, $note); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/application/PhabricatorPhrequentApplication.php
src/applications/phrequent/application/PhabricatorPhrequentApplication.php
<?php final class PhabricatorPhrequentApplication extends PhabricatorApplication { public function getName() { return pht('Phrequent'); } public function getShortDescription() { return pht('Track Time Spent'); } public function getBaseURI() { return '/phrequent/'; } public function isPrototype() { return true; } public function getIcon() { return 'fa-clock-o'; } public function getApplicationGroup() { return self::GROUP_UTILITIES; } public function getApplicationOrder() { return 0.110; } public function getEventListeners() { return array( new PhrequentUIEventListener(), ); } public function getRoutes() { return array( '/phrequent/' => array( '(?:query/(?P<queryKey>[^/]+)/)?' => 'PhrequentListController', 'track/(?P<verb>[a-z]+)/(?P<phid>[^/]+)/' => 'PhrequentTrackController', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/event/PhrequentUIEventListener.php
src/applications/phrequent/event/PhrequentUIEventListener.php
<?php final class PhrequentUIEventListener extends PhabricatorEventListener { public function register() { $this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS); } public function handleEvent(PhutilEvent $event) { switch ($event->getType()) { case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS: $this->handleActionEvent($event); break; } } private function handleActionEvent($event) { $user = $event->getUser(); $object = $event->getValue('object'); if (!$object || !$object->getPHID()) { // No object, or the object has no PHID yet.. return; } if (!($object instanceof PhrequentTrackableInterface)) { // This object isn't a time trackable object. return; } if (!$this->canUseApplication($event->getUser())) { return; } $tracking = PhrequentUserTimeQuery::isUserTrackingObject( $user, $object->getPHID()); if (!$tracking) { $track_action = id(new PhabricatorActionView()) ->setName(pht('Start Tracking Time')) ->setIcon('fa-clock-o') ->setWorkflow(true) ->setHref('/phrequent/track/start/'.$object->getPHID().'/'); } else { $track_action = id(new PhabricatorActionView()) ->setName(pht('Stop Tracking Time')) ->setIcon('fa-clock-o red') ->setWorkflow(true) ->setHref('/phrequent/track/stop/'.$object->getPHID().'/'); } if (!$user->isLoggedIn()) { $track_action->setDisabled(true); } $this->addActionMenuItems($event, $track_action); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/conduit/PhrequentPopConduitAPIMethod.php
src/applications/phrequent/conduit/PhrequentPopConduitAPIMethod.php
<?php final class PhrequentPopConduitAPIMethod extends PhrequentConduitAPIMethod { public function getAPIMethodName() { return 'phrequent.pop'; } public function getMethodDescription() { return pht('Stop tracking time on an object by popping it from the stack.'); } public function getMethodStatus() { return self::METHOD_STATUS_UNSTABLE; } protected function defineParamTypes() { return array( 'objectPHID' => 'phid', 'stopTime' => 'int', 'note' => 'string', ); } protected function defineReturnType() { return 'phid'; } protected function execute(ConduitAPIRequest $request) { $user = $request->getUser(); $object_phid = $request->getValue('objectPHID'); $timestamp = $request->getValue('stopTime'); $note = $request->getValue('note'); if ($timestamp === null) { $timestamp = time(); } $editor = new PhrequentTrackingEditor(); if (!$object_phid) { return $editor->stopTrackingTop($user, $timestamp, $note); } else { return $editor->stopTracking($user, $object_phid, $timestamp, $note); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/conduit/PhrequentPushConduitAPIMethod.php
src/applications/phrequent/conduit/PhrequentPushConduitAPIMethod.php
<?php final class PhrequentPushConduitAPIMethod extends PhrequentConduitAPIMethod { public function getAPIMethodName() { return 'phrequent.push'; } public function getMethodDescription() { return pht( 'Start tracking time on an object by '. 'pushing it on the tracking stack.'); } public function getMethodStatus() { return self::METHOD_STATUS_UNSTABLE; } protected function defineParamTypes() { return array( 'objectPHID' => 'required phid', 'startTime' => 'int', ); } protected function defineReturnType() { return 'phid'; } protected function execute(ConduitAPIRequest $request) { $user = $request->getUser(); $object_phid = $request->getValue('objectPHID'); $timestamp = $request->getValue('startTime'); if ($timestamp === null) { $timestamp = time(); } $editor = new PhrequentTrackingEditor(); return $editor->startTracking($user, $object_phid, $timestamp); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/conduit/PhrequentTrackingConduitAPIMethod.php
src/applications/phrequent/conduit/PhrequentTrackingConduitAPIMethod.php
<?php final class PhrequentTrackingConduitAPIMethod extends PhrequentConduitAPIMethod { public function getAPIMethodName() { return 'phrequent.tracking'; } public function getMethodDescription() { return pht('Returns current objects being tracked in Phrequent.'); } public function getMethodStatus() { return self::METHOD_STATUS_UNSTABLE; } protected function defineParamTypes() { return array(); } protected function defineReturnType() { return 'array'; } protected function execute(ConduitAPIRequest $request) { $user = $request->getUser(); $times = id(new PhrequentUserTimeQuery()) ->setViewer($user) ->needPreemptingEvents(true) ->withEnded(PhrequentUserTimeQuery::ENDED_NO) ->withUserPHIDs(array($user->getPHID())) ->execute(); $now = time(); $results = id(new PhrequentTimeBlock($times)) ->getCurrentWorkStack($now); return array('data' => $results); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phrequent/conduit/PhrequentConduitAPIMethod.php
src/applications/phrequent/conduit/PhrequentConduitAPIMethod.php
<?php abstract class PhrequentConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass( 'PhabricatorPhrequentApplication'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFFragmentOffset.php
src/applications/phortune/pdf/PhabricatorPDFFragmentOffset.php
<?php final class PhabricatorPDFFragmentOffset extends Phobject { private $fragment; private $offset; public function setFragment(PhabricatorPDFFragment $fragment) { $this->fragment = $fragment; return $this; } public function getFragment() { return $this->fragment; } public function setOffset($offset) { $this->offset = $offset; return $this; } public function getOffset() { return $this->offset; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFCatalogObject.php
src/applications/phortune/pdf/PhabricatorPDFCatalogObject.php
<?php final class PhabricatorPDFCatalogObject extends PhabricatorPDFObject { private $pagesObject; public function setPagesObject(PhabricatorPDFPagesObject $pages_object) { $this->pagesObject = $this->newChildObject($pages_object); return $this; } public function getPagesObject() { return $this->pagesObject; } protected function writeObject() { $this->writeLine('/Type /Catalog'); $pages_object = $this->getPagesObject(); if ($pages_object) { $this->writeLine('/Pages %d 0 R', $pages_object->getObjectIndex()); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFObject.php
src/applications/phortune/pdf/PhabricatorPDFObject.php
<?php abstract class PhabricatorPDFObject extends PhabricatorPDFFragment { private $generator; private $objectIndex; private $children = array(); private $streams = array(); final public function hasRefTableEntry() { return true; } final protected function writeFragment() { $this->writeLine('%d 0 obj', $this->getObjectIndex()); $this->writeLine('<<'); $this->writeObject(); $this->writeLine('>>'); $streams = $this->streams; $this->streams = array(); foreach ($streams as $stream) { $this->writeLine('stream'); $this->writeLine('%s', $stream); $this->writeLine('endstream'); } $this->writeLine('endobj'); } final public function setGenerator( PhabricatorPDFGenerator $generator, $index) { if ($this->getGenerator()) { throw new Exception( pht( 'This PDF object is already registered with a PDF generator. You '. 'can not register an object with more than one generator.')); } $this->generator = $generator; $this->objectIndex = $index; foreach ($this->getChildren() as $child) { $generator->addObject($child); } return $this; } final public function getGenerator() { return $this->generator; } final public function getObjectIndex() { if (!$this->objectIndex) { throw new Exception( pht( 'Trying to get index for object ("%s") which has not been '. 'registered with a generator.', get_class($this))); } return $this->objectIndex; } final protected function newChildObject(PhabricatorPDFObject $object) { if ($this->generator) { throw new Exception( pht( 'Trying to add a new PDF Object child after already registering '. 'the object with a generator.')); } $this->children[] = $object; return $object; } private function getChildren() { return $this->children; } abstract protected function writeObject(); final protected function newStream($raw_data) { $stream_data = gzcompress($raw_data); $this->streams[] = $stream_data; return strlen($stream_data); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFHeadFragment.php
src/applications/phortune/pdf/PhabricatorPDFHeadFragment.php
<?php final class PhabricatorPDFHeadFragment extends PhabricatorPDFFragment { protected function writeFragment() { $this->writeLine('%s', '%PDF-1.3'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFIterator.php
src/applications/phortune/pdf/PhabricatorPDFIterator.php
<?php final class PhabricatorPDFIterator extends Phobject implements Iterator { private $generator; private $hasRewound; private $fragments; private $fragmentKey; private $fragmentBytes; private $fragmentOffsets = array(); private $byteLength; public function setGenerator(PhabricatorPDFGenerator $generator) { if ($this->generator) { throw new Exception( pht( 'This iterator already has a generator. You can not modify the '. 'generator for a given iterator.')); } $this->generator = $generator; return $this; } public function getGenerator() { if (!$this->generator) { throw new Exception( pht( 'This PDF iterator has no associated PDF generator.')); } return $this->generator; } public function getFragmentOffsets() { return $this->fragmentOffsets; } public function current() { return $this->fragmentBytes; } public function key() { return $this->framgentKey; } public function next() { $this->fragmentKey++; if (!$this->valid()) { return; } $fragment = $this->fragments[$this->fragmentKey]; $this->fragmentOffsets[] = id(new PhabricatorPDFFragmentOffset()) ->setFragment($fragment) ->setOffset($this->byteLength); $bytes = $fragment->getAsBytes(); $this->fragmentBytes = $bytes; $this->byteLength += strlen($bytes); } public function rewind() { if ($this->hasRewound) { throw new Exception( pht( 'PDF iterators may not be rewound. Create a new iterator to emit '. 'another PDF.')); } $generator = $this->getGenerator(); $objects = $generator->getObjects(); $this->fragments = array(); $this->fragments[] = new PhabricatorPDFHeadFragment(); foreach ($objects as $object) { $this->fragments[] = $object; } $this->fragments[] = id(new PhabricatorPDFTailFragment()) ->setIterator($this); $this->hasRewound = true; $this->fragmentKey = -1; $this->byteLength = 0; $this->next(); } public function valid() { return isset($this->fragments[$this->fragmentKey]); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFContentsObject.php
src/applications/phortune/pdf/PhabricatorPDFContentsObject.php
<?php final class PhabricatorPDFContentsObject extends PhabricatorPDFObject { private $rawContent; public function setRawContent($raw_content) { $this->rawContent = $raw_content; return $this; } public function getRawContent() { return $this->rawContent; } protected function writeObject() { $data = $this->getRawContent(); $stream_length = $this->newStream($data); $this->writeLine('/Filter /FlateDecode /Length %d', $stream_length); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFFragment.php
src/applications/phortune/pdf/PhabricatorPDFFragment.php
<?php abstract class PhabricatorPDFFragment extends Phobject { private $rope; public function getAsBytes() { $this->rope = new PhutilRope(); $this->writeFragment(); $rope = $this->rope; $this->rope = null; return $rope->getAsString(); } public function hasRefTableEntry() { return false; } abstract protected function writeFragment(); final protected function writeLine($pattern) { $pattern = $pattern."\n"; $argv = func_get_args(); $argv[0] = $pattern; $line = call_user_func_array('sprintf', $argv); $this->rope->append($line); return $this; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFInfoObject.php
src/applications/phortune/pdf/PhabricatorPDFInfoObject.php
<?php final class PhabricatorPDFInfoObject extends PhabricatorPDFObject { final protected function writeObject() { $this->writeLine('/Producer (Phabricator 20190801)'); $this->writeLine('/CreationDate (D:%s)', date('YmdHis')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFTailFragment.php
src/applications/phortune/pdf/PhabricatorPDFTailFragment.php
<?php final class PhabricatorPDFTailFragment extends PhabricatorPDFFragment { private $iterator; public function setIterator(PhabricatorPDFIterator $iterator) { $this->iterator = $iterator; return $this; } public function getIterator() { return $this->iterator; } protected function writeFragment() { $iterator = $this->getIterator(); $generator = $iterator->getGenerator(); $objects = $generator->getObjects(); $xref_offset = null; $this->writeLine('xref'); $this->writeLine('0 %d', count($objects) + 1); $this->writeLine('%010d %05d f ', 0, 0xFFFF); $offset_map = array(); $fragment_offsets = $iterator->getFragmentOffsets(); foreach ($fragment_offsets as $fragment_offset) { $fragment = $fragment_offset->getFragment(); $offset = $fragment_offset->getOffset(); if ($fragment === $this) { $xref_offset = $offset; } if (!$fragment->hasRefTableEntry()) { continue; } $offset_map[$fragment->getObjectIndex()] = $offset; } ksort($offset_map); foreach ($offset_map as $offset) { $this->writeLine('%010d %05d n ', $offset, 0); } $this->writeLine('trailer'); $this->writeLine('<<'); $this->writeLine('/Size %d', count($objects) + 1); $info_object = $generator->getInfoObject(); if ($info_object) { $this->writeLine('/Info %d 0 R', $info_object->getObjectIndex()); } $catalog_object = $generator->getCatalogObject(); if ($catalog_object) { $this->writeLine('/Root %d 0 R', $catalog_object->getObjectIndex()); } $this->writeLine('>>'); $this->writeLine('startxref'); $this->writeLine('%d', $xref_offset); $this->writeLine('%s', '%%EOF'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFGenerator.php
src/applications/phortune/pdf/PhabricatorPDFGenerator.php
<?php final class PhabricatorPDFGenerator extends Phobject { private $objects = array(); private $hasIterator = false; private $infoObject; private $catalogObject; public function addObject(PhabricatorPDFObject $object) { if ($this->hasIterator) { throw new Exception( pht( 'This generator has already emitted an iterator. You can not '. 'modify the PDF document after you begin writing it.')); } $this->objects[] = $object; $index = count($this->objects); $object->setGenerator($this, $index); return $this; } public function getObjects() { return $this->objects; } public function newIterator() { $this->hasIterator = true; return id(new PhabricatorPDFIterator()) ->setGenerator($this); } public function setInfoObject(PhabricatorPDFInfoObject $info_object) { $this->addObject($info_object); $this->infoObject = $info_object; return $this; } public function getInfoObject() { return $this->infoObject; } public function setCatalogObject( PhabricatorPDFCatalogObject $catalog_object) { $this->addObject($catalog_object); $this->catalogObject = $catalog_object; return $this; } public function getCatalogObject() { return $this->catalogObject; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFPageObject.php
src/applications/phortune/pdf/PhabricatorPDFPageObject.php
<?php final class PhabricatorPDFPageObject extends PhabricatorPDFObject { private $pagesObject; private $contentsObject; private $resourcesObject; public function setPagesObject(PhabricatorPDFPagesObject $pages) { $this->pagesObject = $pages; return $this; } public function setContentsObject(PhabricatorPDFContentsObject $contents) { $this->contentsObject = $this->newChildObject($contents); return $this; } public function setResourcesObject(PhabricatorPDFResourcesObject $resources) { $this->resourcesObject = $this->newChildObject($resources); return $this; } protected function writeObject() { $this->writeLine('/Type /Page'); $pages_object = $this->pagesObject; $contents_object = $this->contentsObject; $resources_object = $this->resourcesObject; if ($pages_object) { $pages_index = $pages_object->getObjectIndex(); $this->writeLine('/Parent %d 0 R', $pages_index); } if ($contents_object) { $contents_index = $contents_object->getObjectIndex(); $this->writeLine('/Contents %d 0 R', $contents_index); } if ($resources_object) { $resources_index = $resources_object->getObjectIndex(); $this->writeLine('/Resources %d 0 R', $resources_index); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFResourcesObject.php
src/applications/phortune/pdf/PhabricatorPDFResourcesObject.php
<?php final class PhabricatorPDFResourcesObject extends PhabricatorPDFObject { private $fontObjects = array(); public function addFontObject(PhabricatorPDFFontObject $font) { $this->fontObjects[] = $this->newChildObject($font); return $this; } public function getFontObjects() { return $this->fontObjects; } protected function writeObject() { $this->writeLine('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]'); $fonts = $this->getFontObjects(); foreach ($fonts as $font) { $this->writeLine('/Font <<'); $this->writeLine('/F%d %d 0 R', 1, $font->getObjectIndex()); $this->writeLine('>>'); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFFontObject.php
src/applications/phortune/pdf/PhabricatorPDFFontObject.php
<?php final class PhabricatorPDFFontObject extends PhabricatorPDFObject { protected function writeObject() { $this->writeLine('/Type /Font'); $this->writeLine('/BaseFont /Helvetica-Bold'); $this->writeLine('/Subtype /Type1'); $this->writeLine('/Encoding /WinAnsiEncoding'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/pdf/PhabricatorPDFPagesObject.php
src/applications/phortune/pdf/PhabricatorPDFPagesObject.php
<?php final class PhabricatorPDFPagesObject extends PhabricatorPDFObject { private $pageObjects = array(); public function addPageObject(PhabricatorPDFPageObject $page) { $page->setPagesObject($this); $this->pageObjects[] = $this->newChildObject($page); return $this; } public function getPageObjects() { return $this->pageObjects; } protected function writeObject() { $this->writeLine('/Type /Pages'); $page_objects = $this->getPageObjects(); $this->writeLine('/Count %d', count($page_objects)); $this->writeLine('/MediaBox [%d %d %0.2f %0.2f]', 0, 0, 595.28, 841.89); if ($page_objects) { $kids = array(); foreach ($page_objects as $page_object) { $kids[] = sprintf( '%d 0 R', $page_object->getObjectIndex()); } $this->writeLine('/Kids [%s]', implode(' ', $kids)); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/PhortuneController.php
src/applications/phortune/controller/PhortuneController.php
<?php abstract class PhortuneController extends PhabricatorController { private function loadEnabledProvidersForMerchant(PhortuneMerchant $merchant) { $viewer = $this->getRequest()->getUser(); $provider_configs = id(new PhortunePaymentProviderConfigQuery()) ->setViewer($viewer) ->withMerchantPHIDs(array($merchant->getPHID())) ->execute(); $providers = mpull($provider_configs, 'buildProvider', 'getID'); foreach ($providers as $key => $provider) { if (!$provider->isEnabled()) { unset($providers[$key]); } } return $providers; } protected function loadCreatePaymentMethodProvidersForMerchant( PhortuneMerchant $merchant) { $providers = $this->loadEnabledProvidersForMerchant($merchant); foreach ($providers as $key => $provider) { if (!$provider->canCreatePaymentMethods()) { unset($providers[$key]); continue; } } return $providers; } protected function loadOneTimePaymentProvidersForMerchant( PhortuneMerchant $merchant) { $providers = $this->loadEnabledProvidersForMerchant($merchant); foreach ($providers as $key => $provider) { if (!$provider->canProcessOneTimePayments()) { unset($providers[$key]); continue; } } 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/phortune/controller/PhortuneLandingController.php
src/applications/phortune/controller/PhortuneLandingController.php
<?php final class PhortuneLandingController extends PhortuneController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $accounts = PhortuneAccountQuery::loadAccountsForUser( $viewer, PhabricatorContentSource::newFromRequest($request)); if (count($accounts) == 1) { $account = head($accounts); $next_uri = $account->getURI(); } else { $next_uri = $this->getApplicationURI('account/'); } return id(new AphrontRedirectResponse())->setURI($next_uri); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/product/PhortuneProductViewController.php
src/applications/phortune/controller/product/PhortuneProductViewController.php
<?php final class PhortuneProductViewController extends PhortuneController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $product = id(new PhortuneProductQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); if (!$product) { return new Aphront404Response(); } $title = pht('Product: %s', $product->getProductName()); $header = id(new PHUIHeaderView()) ->setHeader($product->getProductName()) ->setHeaderIcon('fa-gift'); $edit_uri = $this->getApplicationURI('product/edit/'.$product->getID().'/'); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb( pht('Products'), $this->getApplicationURI('product/')); $crumbs->addTextCrumb( pht('#%d', $product->getID()), $request->getRequestURI()); $crumbs->setBorder(true); $properties = id(new PHUIPropertyListView()) ->setUser($viewer) ->addProperty( pht('Price'), $product->getPriceAsCurrency()->formatForDisplay()); $object_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Details')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addPropertyList($properties); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $object_box, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/product/PhortuneProductListController.php
src/applications/phortune/controller/product/PhortuneProductListController.php
<?php final class PhortuneProductListController extends PhabricatorController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $pager = new AphrontCursorPagerView(); $pager->readFromRequest($request); $query = id(new PhortuneProductQuery()) ->setViewer($viewer); $products = $query->executeWithCursorPager($pager); $title = pht('Product List'); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb( pht('Products'), $this->getApplicationURI('product/')); $crumbs->addAction( id(new PHUIListItemView()) ->setName(pht('Create Product')) ->setHref($this->getApplicationURI('product/edit/')) ->setIcon('fa-plus-square')); $crumbs->setBorder(true); $product_list = id(new PHUIObjectItemListView()) ->setUser($viewer) ->setNoDataString(pht('No products.')); foreach ($products as $product) { $view_uri = $this->getApplicationURI( 'product/view/'.$product->getID().'/'); $price = $product->getPriceAsCurrency(); $item = id(new PHUIObjectItemView()) ->setObjectName($product->getID()) ->setHeader($product->getProductName()) ->setHref($view_uri) ->addAttribute($price->formatForDisplay()) ->setImageIcon('fa-gift'); $product_list->addItem($item); } $box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Products')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setObjectList($product_list); $header = id(new PHUIHeaderView()) ->setHeader(pht('Products')) ->setHeaderIcon('fa-gift'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $box, $pager, )); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/external/PhortuneExternalOrderController.php
src/applications/phortune/controller/external/PhortuneExternalOrderController.php
<?php final class PhortuneExternalOrderController extends PhortuneExternalController { protected function handleExternalRequest(AphrontRequest $request) { $xviewer = $this->getExternalViewer(); $email = $this->getAccountEmail(); $account = $email->getAccount(); $order = id(new PhortuneCartQuery()) ->setViewer($xviewer) ->withAccountPHIDs(array($account->getPHID())) ->withIDs(array($request->getURIData('orderID'))) ->executeOne(); if (!$order) { return new Aphront404Response(); } $is_printable = ($request->getURIData('action') === 'print'); $order_view = id(new PhortuneOrderSummaryView()) ->setViewer($xviewer) ->setOrder($order) ->setPrintable($is_printable); $crumbs = null; $curtain = null; $main = array(); $tail = array(); require_celerity_resource('phortune-invoice-css'); if ($is_printable) { $body_class = 'phortune-invoice-view'; $tail[] = $order_view; } else { $body_class = 'phortune-cart-page'; $curtain = $this->newCurtain($order); $crumbs = $this->newExternalCrumbs() ->addTextCrumb($order->getObjectName()) ->setBorder(true); $timeline = $this->buildTransactionTimeline($order) ->setShouldTerminate(true); $main[] = $order_view; $main[] = $timeline; } $column_view = id(new PHUITwoColumnView()) ->setMainColumn($main) ->setFooter($tail); if ($curtain) { $column_view->setCurtain($curtain); } $page = $this->newPage() ->addClass($body_class) ->setTitle( array( $order->getObjectName(), $order->getName(), )) ->appendChild($column_view); if ($crumbs) { $page->setCrumbs($crumbs); } return $page; } private function newCurtain(PhortuneCart $order) { $xviewer = $this->getExternalViewer(); $email = $this->getAccountEmail(); $curtain = $this->newCurtainView($order); $print_uri = $email->getExternalOrderPrintURI($order); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Printable Version')) ->setHref($print_uri) ->setOpenInNewWindow(true) ->setIcon('fa-print')); return $curtain; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/external/PhortuneExternalController.php
src/applications/phortune/controller/external/PhortuneExternalController.php
<?php abstract class PhortuneExternalController extends PhortuneController { private $email; final public function shouldAllowPublic() { return true; } abstract protected function handleExternalRequest(AphrontRequest $request); final protected function hasAccountEmail() { return (bool)$this->email; } final protected function getAccountEmail() { return $this->email; } final protected function getExternalViewer() { return PhabricatorUser::getOmnipotentUser(); } final public function handleRequest(AphrontRequest $request) { $address_key = $request->getURIData('addressKey'); $access_key = $request->getURIData('accessKey'); $viewer = $this->getViewer(); $xviewer = $this->getExternalViewer(); $email = id(new PhortuneAccountEmailQuery()) ->setViewer($xviewer) ->withAddressKeys(array($address_key)) ->executeOne(); if (!$email) { return new Aphront404Response(); } $account = $email->getAccount(); $can_see = PhabricatorPolicyFilter::hasCapability( $viewer, $account, PhabricatorPolicyCapability::CAN_EDIT); $email_display = phutil_tag('strong', array(), $email->getAddress()); $user_display = phutil_tag('strong', array(), $viewer->getUsername()); $actual_key = $email->getAccessKey(); if (!phutil_hashes_are_identical($access_key, $actual_key)) { $dialog = $this->newDialog() ->setTitle(pht('Email Access Link Out of Date')) ->appendParagraph( pht( 'You are trying to access this payment account as: %s', $email_display)) ->appendParagraph( pht( 'The access link you have followed is out of date and no longer '. 'works.')); if ($can_see) { $dialog->appendParagraph( pht( 'You are currently logged in as a user (%s) who has '. 'permission to manage the payment account, so you can '. 'continue to the updated link.', $user_display)); $dialog->addCancelButton( $email->getExternalURI(), pht('Continue to Updated Link')); } else { $dialog->appendParagraph( pht( 'To access information about this payment account, follow '. 'a more recent link or ask a user with access to give you '. 'an updated link.')); } return $dialog; } switch ($email->getStatus()) { case PhortuneAccountEmailStatus::STATUS_ACTIVE: break; case PhortuneAccountEmailStatus::STATUS_DISABLED: return $this->newDialog() ->setTitle(pht('Address Disabled')) ->appendParagraph( pht( 'This email address (%s) has been disabled and no longer has '. 'access to this payment account.', $email_display)); case PhortuneAccountEmailStatus::STATUS_UNSUBSCRIBED: return $this->newDialog() ->setTitle(pht('Permanently Unsubscribed')) ->appendParagraph( pht( 'This email address (%s) has been permanently unsubscribed '. 'and no longer has access to this payment account.', $email_display)); break; default: return new Aphront404Response(); } $this->email = $email; return $this->handleExternalRequest($request); } final protected function newExternalCrumbs() { $viewer = $this->getViewer(); $crumbs = new PHUICrumbsView(); if ($this->hasAccountEmail()) { $email = $this->getAccountEmail(); $account = $email->getAccount(); $crumb_name = pht( 'Payment Account: %s', $account->getName()); $crumb = id(new PHUICrumbView()) ->setIcon('fa-diamond') ->setName($crumb_name) ->setHref($email->getExternalURI()); $crumbs ->addCrumb($crumb); } else { $crumb = id(new PHUICrumbView()) ->setIcon('fa-diamond') ->setText(pht('External Account View')); $crumbs->addCrumb($crumb); } return $crumbs; } final protected function newExternalView() { $email = $this->getAccountEmail(); $xviewer = $this->getExternalViewer(); $origin_phid = $email->getAuthorPHID(); $handles = $xviewer->loadHandles(array($origin_phid)); $messages = array(); $messages[] = pht( 'You are viewing this payment account as: %s', phutil_tag('strong', array(), $email->getAddress())); $messages[] = pht( 'This email address was added to this payment account by: %s', phutil_tag('strong', array(), $handles[$origin_phid]->getFullName())); $messages[] = pht( 'Anyone who has a link to this page can view order history for '. 'this payment account.'); return id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_WARNING) ->setErrors($messages); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/external/PhortuneExternalOverviewController.php
src/applications/phortune/controller/external/PhortuneExternalOverviewController.php
<?php final class PhortuneExternalOverviewController extends PhortuneExternalController { protected function handleExternalRequest(AphrontRequest $request) { $xviewer = $this->getExternalViewer(); $email = $this->getAccountEmail(); $account = $email->getAccount(); $crumbs = $this->newExternalCrumbs() ->addTextCrumb(pht('Viewing As "%s"', $email->getAddress())) ->setBorder(true); $header = id(new PHUIHeaderView()) ->setHeader(pht('Invoices and Receipts: %s', $account->getName())) ->addActionLink( id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-times') ->setText(pht('Unsubscribe')) ->setHref($email->getUnsubscribeURI()) ->setWorkflow(true)); $external_view = $this->newExternalView(); $invoices_view = $this->newInvoicesView(); $receipts_view = $this->newReceiptsView(); $column_view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter( array( $external_view, $invoices_view, $receipts_view, )); return $this->newPage() ->setCrumbs($crumbs) ->setTitle( array( pht('Invoices and Receipts'), $account->getName(), )) ->appendChild($column_view); } private function newInvoicesView() { $xviewer = $this->getExternalViewer(); $email = $this->getAccountEmail(); $account = $email->getAccount(); $invoices = id(new PhortuneCartQuery()) ->setViewer($xviewer) ->withAccountPHIDs(array($account->getPHID())) ->needPurchases(true) ->withInvoices(true) ->execute(); $header = id(new PHUIHeaderView()) ->setHeader(pht('Invoices')); $invoices_table = id(new PhortuneOrderTableView()) ->setViewer($xviewer) ->setAccountEmail($email) ->setCarts($invoices) ->setIsInvoices(true); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($invoices_table); } private function newReceiptsView() { $xviewer = $this->getExternalViewer(); $email = $this->getAccountEmail(); $account = $email->getAccount(); $receipts = id(new PhortuneCartQuery()) ->setViewer($xviewer) ->withAccountPHIDs(array($account->getPHID())) ->needPurchases(true) ->withInvoices(false) ->execute(); $header = id(new PHUIHeaderView()) ->setHeader(pht('Receipts')); $receipts_table = id(new PhortuneOrderTableView()) ->setViewer($xviewer) ->setAccountEmail($email) ->setCarts($receipts); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($receipts_table); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/external/PhortuneExternalUnsubscribeController.php
src/applications/phortune/controller/external/PhortuneExternalUnsubscribeController.php
<?php final class PhortuneExternalUnsubscribeController extends PhortuneExternalController { protected function handleExternalRequest(AphrontRequest $request) { $xviewer = $this->getExternalViewer(); $email = $this->getAccountEmail(); $account = $email->getAccount(); $email_uri = $email->getExternalURI(); if ($request->isFormOrHisecPost()) { $xactions = array(); $xactions[] = $email->getApplicationTransactionTemplate() ->setTransactionType( PhortuneAccountEmailStatusTransaction::TRANSACTIONTYPE) ->setNewValue(PhortuneAccountEmailStatus::STATUS_UNSUBSCRIBED); $email->getApplicationTransactionEditor() ->setActor($xviewer) ->setActingAsPHID($email->getPHID()) ->setContentSourceFromRequest($request) ->setContinueOnMissingFields(true) ->setContinueOnNoEffect(true) ->setCancelURI($email_uri) ->applyTransactions($email, $xactions); return id(new AphrontRedirectResponse())->setURI($email_uri); } $email_display = phutil_tag( 'strong', array(), $email->getAddress()); $account_display = phutil_tag( 'strong', array(), $account->getName()); $submit = pht( 'Permanently Unsubscribe (%s)', $email->getAddress()); return $this->newDialog() ->setTitle(pht('Permanently Unsubscribe')) ->appendParagraph( pht( 'Permanently unsubscribe this email address (%s) from this '. 'payment account (%s)?', $email_display, $account_display)) ->appendParagraph( pht( 'You will no longer receive email and access links will no longer '. 'function.')) ->appendParagraph( pht( 'This action is permanent and can not be undone.')) ->addCancelButton($email_uri) ->addSubmitButton($submit); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/account/PhortuneAccountChargesController.php
src/applications/phortune/controller/account/PhortuneAccountChargesController.php
<?php final class PhortuneAccountChargesController extends PhortuneAccountProfileController { protected function shouldRequireAccountEditCapability() { return false; } protected function handleAccountRequest(AphrontRequest $request) { $account = $this->getAccount(); $title = $account->getName(); $crumbs = $this->buildApplicationCrumbs() ->addTextCrumb(pht('Orders')) ->setBorder(true); $header = $this->buildHeaderView(); $authority = $this->newAccountAuthorityView(); $charge_history = $this->buildChargeHistorySection($account); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter( array( $authority, $charge_history, )); $navigation = $this->buildSideNavView('charges'); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->setNavigation($navigation) ->appendChild($view); } private function buildChargeHistorySection(PhortuneAccount $account) { $viewer = $this->getViewer(); $charges = id(new PhortuneChargeQuery()) ->setViewer($viewer) ->withAccountPHIDs(array($account->getPHID())) ->needCarts(true) ->setLimit(100) ->execute(); $charges_uri = $account->getChargeListURI(); $table = id(new PhortuneChargeTableView()) ->setUser($viewer) ->setCharges($charges); $header = id(new PHUIHeaderView()) ->setHeader(pht('Recent Charges')) ->addActionLink( id(new PHUIButtonView()) ->setTag('a') ->setIcon('fa-list') ->setHref($charges_uri) ->setText(pht('View All Charges'))); return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($table); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/account/PhortuneAccountEmailViewController.php
src/applications/phortune/controller/account/PhortuneAccountEmailViewController.php
<?php final class PhortuneAccountEmailViewController extends PhortuneAccountController { protected function shouldRequireAccountEditCapability() { return true; } protected function handleAccountRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $account = $this->getAccount(); $address = id(new PhortuneAccountEmailQuery()) ->setViewer($viewer) ->withAccountPHIDs(array($account->getPHID())) ->withIDs(array($request->getURIData('addressID'))) ->executeOne(); if (!$address) { return new Aphront404Response(); } $crumbs = $this->buildApplicationCrumbs() ->addTextCrumb(pht('Email Addresses'), $account->getEmailAddressesURI()) ->addTextCrumb($address->getObjectName()) ->setBorder(true); $header = id(new PHUIHeaderView()) ->setHeader(pht('Account Email: %s', $address->getAddress())); $details = $this->newDetailsView($address); $timeline = $this->buildTransactionTimeline( $address, new PhortuneAccountEmailTransactionQuery()); $timeline->setShouldTerminate(true); $curtain = $this->buildCurtainView($address); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setCurtain($curtain) ->setMainColumn( array( $details, $timeline, )); return $this->newPage() ->setTitle($address->getObjectName()) ->setCrumbs($crumbs) ->appendChild($view); } private function buildCurtainView(PhortuneAccountEmail $address) { $viewer = $this->getViewer(); $account = $address->getAccount(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $address, PhabricatorPolicyCapability::CAN_EDIT); $edit_uri = $this->getApplicationURI( urisprintf( 'account/%d/addresses/edit/%d/', $account->getID(), $address->getID())); if ($can_edit) { $external_uri = $address->getExternalURI(); } else { $external_uri = null; } $curtain = $this->newCurtainView($account); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Address')) ->setIcon('fa-pencil') ->setHref($edit_uri) ->setDisabled(!$can_edit) ->setWorkflow(!$can_edit)); switch ($address->getStatus()) { case PhortuneAccountEmailStatus::STATUS_ACTIVE: $disable_name = pht('Disable Address'); $disable_icon = 'fa-times'; $can_disable = true; $disable_action = 'disable'; break; case PhortuneAccountEmailStatus::STATUS_DISABLED: $disable_name = pht('Enable Address'); $disable_icon = 'fa-check'; $can_disable = true; $disable_action = 'enable'; break; case PhortuneAccountEmailStatus::STATUS_UNSUBSCRIBED: $disable_name = pht('Disable Address'); $disable_icon = 'fa-times'; $can_disable = false; $disable_action = 'disable'; break; } $disable_uri = $this->getApplicationURI( urisprintf( 'account/%d/addresses/%d/%s/', $account->getID(), $address->getID(), $disable_action)); $curtain->addAction( id(new PhabricatorActionView()) ->setName($disable_name) ->setIcon($disable_icon) ->setHref($disable_uri) ->setDisabled(!$can_disable) ->setWorkflow(true)); $rotate_uri = $this->getApplicationURI( urisprintf( 'account/%d/addresses/%d/rotate/', $account->getID(), $address->getID())); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Rotate Access Key')) ->setIcon('fa-refresh') ->setHref($rotate_uri) ->setDisabled(!$can_edit) ->setWorkflow(true)); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Show External View')) ->setIcon('fa-eye') ->setHref($external_uri) ->setDisabled(!$can_edit) ->setOpenInNewWindow(true)); return $curtain; } private function newDetailsView(PhortuneAccountEmail $address) { $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setUser($viewer); $access_key = $address->getAccessKey(); // This is not a meaningful security barrier: the full plaintext of the // access key is visible on the page in the link target of the "Show // External View" action. It's just here to make it clear "Rotate Access // Key" actually does something. $prefix_length = 4; $visible_part = substr($access_key, 0, $prefix_length); $masked_part = str_repeat( "\xE2\x80\xA2", strlen($access_key) - $prefix_length); $access_display = $visible_part.$masked_part; $access_display = phutil_tag('tt', array(), $access_display); $view->addProperty(pht('Email Address'), $address->getAddress()); $view->addProperty(pht('Access Key'), $access_display); return id(new PHUIObjectBoxView()) ->setHeaderText(pht('Email Address Details')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->addPropertyList($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/account/PhortuneAccountChargeListController.php
src/applications/phortune/controller/account/PhortuneAccountChargeListController.php
<?php final class PhortuneAccountChargeListController extends PhortuneAccountProfileController { protected function shouldRequireAccountEditCapability() { return false; } protected function handleAccountRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $account = $this->getAccount(); return id(new PhortuneChargeSearchEngine()) ->setAccount($account) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); if ($this->hasAccount()) { $account = $this->getAccount(); $id = $account->getID(); $crumbs->addTextCrumb( pht('Charges'), $account->getChargesURI()); } 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/phortune/controller/account/PhortuneAccountEmailAddressesController.php
src/applications/phortune/controller/account/PhortuneAccountEmailAddressesController.php
<?php final class PhortuneAccountEmailAddressesController extends PhortuneAccountProfileController { protected function shouldRequireAccountEditCapability() { return true; } protected function handleAccountRequest(AphrontRequest $request) { $account = $this->getAccount(); $title = $account->getName(); $crumbs = $this->buildApplicationCrumbs() ->addTextCrumb(pht('Email Addresses')) ->setBorder(true); $header = $this->buildHeaderView(); $authority = $this->newAccountAuthorityView(); $addresses = $this->buildAddressesSection($account); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter( array( $authority, $addresses, )); $navigation = $this->buildSideNavView('addresses'); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->setNavigation($navigation) ->appendChild($view); } private function buildAddressesSection(PhortuneAccount $account) { $viewer = $this->getViewer(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $account, PhabricatorPolicyCapability::CAN_EDIT); $id = $account->getID(); $add = id(new PHUIButtonView()) ->setTag('a') ->setText(pht('Add Address')) ->setIcon('fa-plus') ->setWorkflow(!$can_edit) ->setDisabled(!$can_edit) ->setHref("/phortune/account/{$id}/addresses/edit/"); $header = id(new PHUIHeaderView()) ->setHeader(pht('Billing Email Addresses')) ->addActionLink($add); $addresses = id(new PhortuneAccountEmailQuery()) ->setViewer($viewer) ->withAccountPHIDs(array($account->getPHID())) ->execute(); $list = id(new PHUIObjectItemListView()) ->setUser($viewer) ->setNoDataString( pht( 'There are no billing email addresses associated '. 'with this account.')); $addresses = id(new PhortuneAccountEmailQuery()) ->setViewer($viewer) ->withAccountPHIDs(array($account->getPHID())) ->execute(); foreach ($addresses as $address) { $item = id(new PHUIObjectItemView()) ->setObjectName($address->getObjectName()) ->setHeader($address->getAddress()) ->setHref($address->getURI()); $list->addItem($item); } return id(new PHUIObjectBoxView()) ->setHeader($header) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->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/phortune/controller/account/PhortuneAccountAddManagerController.php
src/applications/phortune/controller/account/PhortuneAccountAddManagerController.php
<?php final class PhortuneAccountAddManagerController extends PhortuneAccountController { protected function shouldRequireAccountEditCapability() { return true; } protected function handleAccountRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $account = $this->getAccount(); $id = $account->getID(); $v_managers = array(); $e_managers = null; $account_uri = $this->getApplicationURI("/account/{$id}/managers/"); if ($request->isFormPost()) { $xactions = array(); $v_managers = $request->getArr('managerPHIDs'); $type_edge = PhabricatorTransactions::TYPE_EDGE; $xactions[] = id(new PhortuneAccountTransaction()) ->setTransactionType($type_edge) ->setMetadataValue( 'edge:type', PhortuneAccountHasMemberEdgeType::EDGECONST) ->setNewValue( array( '+' => array_fuse($v_managers), )); $editor = id(new PhortuneAccountEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true); try { $editor->applyTransactions($account, $xactions); return id(new AphrontRedirectResponse())->setURI($account_uri); } catch (PhabricatorApplicationTransactionValidationException $ex) { $validation_exception = $ex; $e_managers = $ex->getShortMessage($type_edge); } } $account_phid = $account->getPHID(); $handles = $viewer->loadHandles(array($account_phid)); $handle = $handles[$account_phid]; $form = id(new AphrontFormView()) ->setViewer($viewer) ->appendInstructions( pht( 'Choose one or more users to add as account managers. Managers '. 'have full control of the account.')) ->appendControl( id(new AphrontFormStaticControl()) ->setLabel(pht('Payment Account')) ->setValue($handle->renderLink())) ->appendControl( id(new AphrontFormTokenizerControl()) ->setDatasource(new PhabricatorPeopleDatasource()) ->setLabel(pht('Add Managers')) ->setName('managerPHIDs') ->setValue($v_managers) ->setError($e_managers)); return $this->newDialog() ->setTitle(pht('Add New Managers')) ->appendForm($form) ->setWidth(AphrontDialogView::WIDTH_FORM) ->addCancelButton($account_uri) ->addSubmitButton(pht('Add Managers')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phortune/controller/account/PhortuneAccountSubscriptionAutopayController.php
src/applications/phortune/controller/account/PhortuneAccountSubscriptionAutopayController.php
<?php final class PhortuneAccountSubscriptionAutopayController extends PhortuneAccountController { protected function shouldRequireAccountEditCapability() { return true; } protected function handleAccountRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $account = $this->getAccount(); $subscription = id(new PhortuneSubscriptionQuery()) ->setViewer($viewer) ->withIDs(array($request->getURIData('subscriptionID'))) ->withAccountPHIDs(array($account->getPHID())) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$subscription) { return new Aphront404Response(); } $method = id(new PhortunePaymentMethodQuery()) ->setViewer($viewer) ->withIDs(array($request->getURIData('methodID'))) ->withAccountPHIDs(array($subscription->getAccountPHID())) ->withMerchantPHIDs(array($subscription->getMerchantPHID())) ->withStatuses( array( PhortunePaymentMethod::STATUS_ACTIVE, )) ->executeOne(); if (!$method) { return new Aphront404Response(); } $next_uri = $subscription->getURI(); $autopay_phid = $subscription->getDefaultPaymentMethodPHID(); $is_stop = ($autopay_phid === $method->getPHID()); if ($request->isFormOrHisecPost()) { if ($is_stop) { $new_phid = null; } else { $new_phid = $method->getPHID(); } $xactions = array(); $xactions[] = $subscription->getApplicationTransactionTemplate() ->setTransactionType( PhortuneSubscriptionAutopayTransaction::TRANSACTIONTYPE) ->setNewValue($new_phid); $editor = $subscription->getApplicationTransactionEditor() ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setCancelURI($next_uri); $editor->applyTransactions($subscription, $xactions); return id(new AphrontRedirectResponse())->setURI($next_uri); } $method_phid = $method->getPHID(); $subscription_phid = $subscription->getPHID(); $handles = $viewer->loadHandles( array( $method_phid, $subscription_phid, )); $method_handle = $handles[$method_phid]; $subscription_handle = $handles[$subscription_phid]; $method_display = $method_handle->renderLink(); $method_display = phutil_tag( 'strong', array(), $method_display); $subscription_display = $subscription_handle->renderLink(); $subscription_display = phutil_tag( 'strong', array(), $subscription_display); $body = array(); if ($is_stop) { $title = pht('Stop Autopay'); $body[] = pht( 'Remove %s as the automatic payment method for subscription %s?', $method_display, $subscription_display); $body[] = pht( 'This payment method will no longer be charged automatically.'); $submit = pht('Stop Autopay'); } else { $title = pht('Start Autopay'); $body[] = pht( 'Set %s as the automatic payment method for subscription %s?', $method_display, $subscription_display); $body[] = pht( 'This payment method will be used to automatically pay future '. 'charges.'); $submit = pht('Start Autopay'); } $dialog = $this->newDialog() ->setTitle($title) ->addCancelButton($next_uri) ->addSubmitButton($submit); foreach ($body as $graph) { $dialog->appendParagraph($graph); } return $dialog; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false