code
stringlengths 17
247k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function setProfiler(PhutilServiceProfiler $profiler) {
$this->profiler = $profiler;
return $this;
} | Set a profiler for cache operations.
@param PhutilServiceProfiler Service profiler.
@return this
@task kvimpl | setProfiler | php | phacility/phabricator | src/infrastructure/cache/PhutilKeyValueCacheProfiler.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/cache/PhutilKeyValueCacheProfiler.php | Apache-2.0 |
public function addRawSection($text) {
if (strlen($text)) {
$text = rtrim($text);
$this->sections[] = $text;
$this->htmlSections[] = phutil_escape_html_newlines(
phutil_tag('div', array(), $text));
}
return $this;
} | Add a raw block of text to the email. This will be rendered as-is.
@param string Block of text.
@return this
@task compose | addRawSection | php | phacility/phabricator | src/applications/metamta/view/PhabricatorMetaMTAMailBody.php | https://github.com/phacility/phabricator/blob/master/src/applications/metamta/view/PhabricatorMetaMTAMailBody.php | Apache-2.0 |
public function addTextSection($header, $section) {
if ($section instanceof PhabricatorMetaMTAMailSection) {
$plaintext = $section->getPlaintext();
$html = $section->getHTML();
} else {
$plaintext = $section;
$html = phutil_escape_html_newlines(phutil_tag('div', array(), $section));
}
$this->addPlaintextSection($header, $plaintext);
$this->addHTMLSection($header, $html);
return $this;
} | Add a block of text with a section header. This is rendered like this:
HEADER
Text is indented.
@param string Header text.
@param string Section text.
@return this
@task compose | addTextSection | php | phacility/phabricator | src/applications/metamta/view/PhabricatorMetaMTAMailBody.php | https://github.com/phacility/phabricator/blob/master/src/applications/metamta/view/PhabricatorMetaMTAMailBody.php | Apache-2.0 |
private function indent($text) {
return rtrim(" ".str_replace("\n", "\n ", $text));
} | Indent a block of text for rendering under a section heading.
@param string Text to indent.
@return string Indented text.
@task render | indent | php | phacility/phabricator | src/applications/metamta/view/PhabricatorMetaMTAMailBody.php | https://github.com/phacility/phabricator/blob/master/src/applications/metamta/view/PhabricatorMetaMTAMailBody.php | Apache-2.0 |
public static function loadUserPreferences(PhabricatorUser $user) {
return id(new PhabricatorUserPreferencesQuery())
->setViewer($user)
->withUsers(array($user))
->needSyntheticPreferences(true)
->executeOne();
} | Load or create a preferences object for the given user.
@param PhabricatorUser User to load or create preferences for. | loadUserPreferences | php | phacility/phabricator | src/applications/settings/storage/PhabricatorUserPreferences.php | https://github.com/phacility/phabricator/blob/master/src/applications/settings/storage/PhabricatorUserPreferences.php | Apache-2.0 |
public static function loadGlobalPreferences(PhabricatorUser $viewer) {
$global = id(new PhabricatorUserPreferencesQuery())
->setViewer($viewer)
->withBuiltinKeys(
array(
self::BUILTIN_GLOBAL_DEFAULT,
))
->executeOne();
if (!$global) {
$global = id(new self())
->attachUser(new PhabricatorUser());
}
return $global;
} | Load or create a global preferences object.
If no global preferences exist, an empty preferences object is returned.
@param PhabricatorUser Viewing user. | loadGlobalPreferences | php | phacility/phabricator | src/applications/settings/storage/PhabricatorUserPreferences.php | https://github.com/phacility/phabricator/blob/master/src/applications/settings/storage/PhabricatorUserPreferences.php | Apache-2.0 |
public function executeExpansion() {
return array_unique(array_mergev($this->execute()));
} | Execute the query, merging results into a single list of unique member
PHIDs. | executeExpansion | php | phacility/phabricator | src/applications/metamta/query/PhabricatorMetaMTAMemberQuery.php | https://github.com/phacility/phabricator/blob/master/src/applications/metamta/query/PhabricatorMetaMTAMemberQuery.php | Apache-2.0 |
public function setCaches(array $caches) {
assert_instances_of($caches, 'PhutilKeyValueCache');
$this->cachesForward = $caches;
$this->cachesBackward = array_reverse($caches);
return $this;
} | Set the caches which comprise this stack.
@param list<PhutilKeyValueCache> Ordered list of key-value caches.
@return this
@task config | setCaches | php | phacility/phabricator | src/infrastructure/cache/PhutilKeyValueCacheStack.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/cache/PhutilKeyValueCacheStack.php | Apache-2.0 |
public function setIgnoreOnNoEffect($ignore) {
$this->ignoreOnNoEffect = $ignore;
return $this;
} | Flag this transaction as a pure side-effect which should be ignored when
applying transactions if it has no effect, even if transaction application
would normally fail. This both provides users with better error messages
and allows transactions to perform optional side effects. | setIgnoreOnNoEffect | php | phacility/phabricator | src/applications/transactions/storage/PhabricatorApplicationTransaction.php | https://github.com/phacility/phabricator/blob/master/src/applications/transactions/storage/PhabricatorApplicationTransaction.php | Apache-2.0 |
private function isSelfSubscription() {
$type = $this->getTransactionType();
if ($type != PhabricatorTransactions::TYPE_SUBSCRIBERS) {
return false;
}
$old = $this->getOldValue();
$new = $this->getNewValue();
$add = array_diff($old, $new);
$rem = array_diff($new, $old);
if ((count($add) + count($rem)) != 1) {
// More than one user affected.
return false;
}
$affected_phid = head(array_merge($add, $rem));
if ($affected_phid != $this->getAuthorPHID()) {
// Affected user is someone else.
return false;
}
return true;
} | Test if this transaction is just a user subscribing or unsubscribing
themselves. | isSelfSubscription | php | phacility/phabricator | src/applications/transactions/storage/PhabricatorApplicationTransaction.php | https://github.com/phacility/phabricator/blob/master/src/applications/transactions/storage/PhabricatorApplicationTransaction.php | Apache-2.0 |
public static function loadLocks($owner_phid) {
return id(new DrydockSlotLock())->loadAllWhere(
'ownerPHID = %s',
$owner_phid);
} | Load all locks held by a particular owner.
@param phid Owner PHID.
@return list<DrydockSlotLock> All held locks.
@task info | loadLocks | php | phacility/phabricator | src/applications/drydock/storage/DrydockSlotLock.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/storage/DrydockSlotLock.php | Apache-2.0 |
public static function isLockFree($lock) {
return self::areLocksFree(array($lock));
} | Test if a lock is currently free.
@param string Lock key to test.
@return bool True if the lock is currently free.
@task info | isLockFree | php | phacility/phabricator | src/applications/drydock/storage/DrydockSlotLock.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/storage/DrydockSlotLock.php | Apache-2.0 |
public static function areLocksFree(array $locks) {
$lock_map = self::loadHeldLocks($locks);
return !$lock_map;
} | Test if a list of locks are all currently free.
@param list<string> List of lock keys to test.
@return bool True if all locks are currently free.
@task info | areLocksFree | php | phacility/phabricator | src/applications/drydock/storage/DrydockSlotLock.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/storage/DrydockSlotLock.php | Apache-2.0 |
public static function releaseLocks($owner_phid) {
$table = new DrydockSlotLock();
$conn_w = $table->establishConnection('w');
queryfx(
$conn_w,
'DELETE FROM %T WHERE ownerPHID = %s',
$table->getTableName(),
$owner_phid);
} | Release all locks held by an owner.
@param phid Lock owner PHID.
@return void
@task locks | releaseLocks | php | phacility/phabricator | src/applications/drydock/storage/DrydockSlotLock.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/storage/DrydockSlotLock.php | Apache-2.0 |
public function getHandleIfExists($phid, $default = null) {
if ($this->handles === null) {
$this->loadHandles();
}
return idx($this->handles, $phid, $default);
} | Get a handle from this list if it exists.
This has similar semantics to @{function:idx}. | getHandleIfExists | php | phacility/phabricator | src/applications/phid/handle/pool/PhabricatorHandleList.php | https://github.com/phacility/phabricator/blob/master/src/applications/phid/handle/pool/PhabricatorHandleList.php | Apache-2.0 |
public function newSublist(array $phids) {
foreach ($phids as $phid) {
if (!isset($this[$phid])) {
throw new Exception(
pht(
'Trying to create a new sublist of an existing handle list, '.
'but PHID "%s" does not appear in the parent list.',
$phid));
}
}
return $this->handlePool->newHandleList($phids);
} | Create a new list with a subset of the PHIDs in this list. | newSublist | php | phacility/phabricator | src/applications/phid/handle/pool/PhabricatorHandleList.php | https://github.com/phacility/phabricator/blob/master/src/applications/phid/handle/pool/PhabricatorHandleList.php | Apache-2.0 |
public function renderList() {
return id(new PHUIHandleListView())
->setHandleList($this);
} | Return a @{class:PHUIHandleListView} which can render the handles in
this list. | renderList | php | phacility/phabricator | src/applications/phid/handle/pool/PhabricatorHandleList.php | https://github.com/phacility/phabricator/blob/master/src/applications/phid/handle/pool/PhabricatorHandleList.php | Apache-2.0 |
public function renderHandle($phid) {
if (!isset($this[$phid])) {
throw new Exception(
pht('Trying to render a handle which does not exist!'));
}
return id(new PHUIHandleView())
->setHandleList($this)
->setHandlePHID($phid);
} | Return a @{class:PHUIHandleView} which can render a specific handle. | renderHandle | php | phacility/phabricator | src/applications/phid/handle/pool/PhabricatorHandleList.php | https://github.com/phacility/phabricator/blob/master/src/applications/phid/handle/pool/PhabricatorHandleList.php | Apache-2.0 |
protected function getPrimaryTableAlias() {
return null;
} | Return the alias this query uses to identify the primary table.
Some automatic query constructions may need to be qualified with a table
alias if the query performs joins which make column names ambiguous. If
this is the case, return the alias for the primary table the query
uses; generally the object table which has `id` and `phid` columns.
@return string Alias for the primary table. | getPrimaryTableAlias | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
public function setOrder($order) {
$aliases = $this->getBuiltinOrderAliasMap();
if (empty($aliases[$order])) {
throw new Exception(
pht(
'Query "%s" does not support a builtin order "%s". Supported orders '.
'are: %s.',
get_class($this),
$order,
implode(', ', array_keys($aliases))));
}
$this->builtinOrder = $aliases[$order];
$this->orderVector = null;
return $this;
} | Select a result ordering.
This is a high-level method which selects an ordering from a predefined
list of builtin orders, as provided by @{method:getBuiltinOrders}. These
options are user-facing and not exhaustive, but are generally convenient
and meaningful.
You can also use @{method:setOrderVector} to specify a low-level ordering
across individual orderable columns. This offers greater control but is
also more involved.
@param string Key of a builtin order supported by this query.
@return this
@task order | setOrder | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
public function setGroupVector($vector) {
$this->groupVector = $vector;
$this->orderVector = null;
return $this;
} | Set a grouping order to apply before primary result ordering.
This allows you to preface the query order vector with additional orders,
so you can effect "group by" queries while still respecting "order by".
This is a high-level method which works alongside @{method:setOrder}. For
lower-level control over order vectors, use @{method:setOrderVector}.
@param PhabricatorQueryOrderVector|list<string> List of order keys.
@return this
@task order | setGroupVector | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
protected function getOrderVector() {
if (!$this->orderVector) {
if ($this->builtinOrder !== null) {
$builtin_order = idx($this->getBuiltinOrders(), $this->builtinOrder);
$vector = $builtin_order['vector'];
} else {
$vector = $this->getDefaultOrderVector();
}
if ($this->groupVector) {
$group = PhabricatorQueryOrderVector::newFromVector($this->groupVector);
$group->appendVector($vector);
$vector = $group;
}
$vector = PhabricatorQueryOrderVector::newFromVector($vector);
// We call setOrderVector() here to apply checks to the default vector.
// This catches any errors in the implementation.
$this->setOrderVector($vector);
}
return $this->orderVector;
} | Get the effective order vector.
@return PhabricatorQueryOrderVector Effective vector.
@task order | getOrderVector | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
public function withApplicationSearchContainsConstraint(
PhabricatorCustomFieldIndexStorage $index,
$value) {
$values = (array)$value;
$data_values = array();
$constraint_values = array();
foreach ($values as $value) {
if ($value instanceof PhabricatorQueryConstraint) {
$constraint_values[] = $value;
} else {
$data_values[] = $value;
}
}
$alias = 'appsearch_'.count($this->applicationSearchConstraints);
$this->applicationSearchConstraints[] = array(
'type' => $index->getIndexValueType(),
'cond' => '=',
'table' => $index->getTableName(),
'index' => $index->getIndexKey(),
'alias' => $alias,
'value' => $values,
'data' => $data_values,
'constraints' => $constraint_values,
);
return $this;
} | Constrain the query with an ApplicationSearch index, requiring field values
contain at least one of the values in a set.
This constraint can build the most common types of queries, like:
- Find users with shirt sizes "X" or "XL".
- Find shoes with size "13".
@param PhabricatorCustomFieldIndexStorage Table where the index is stored.
@param string|list<string> One or more values to filter by.
@return this
@task appsearch | withApplicationSearchContainsConstraint | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
public function withApplicationSearchRangeConstraint(
PhabricatorCustomFieldIndexStorage $index,
$min,
$max) {
$index_type = $index->getIndexValueType();
if ($index_type != 'int') {
throw new Exception(
pht(
'Attempting to apply a range constraint to a field with index type '.
'"%s", expected type "%s".',
$index_type,
'int'));
}
$alias = 'appsearch_'.count($this->applicationSearchConstraints);
$this->applicationSearchConstraints[] = array(
'type' => $index->getIndexValueType(),
'cond' => 'range',
'table' => $index->getTableName(),
'index' => $index->getIndexKey(),
'alias' => $alias,
'value' => array($min, $max),
'data' => null,
'constraints' => null,
);
return $this;
} | Constrain the query with an ApplicationSearch index, requiring values
exist in a given range.
This constraint is useful for expressing date ranges:
- Find events between July 1st and July 7th.
The ends of the range are inclusive, so a `$min` of `3` and a `$max` of
`5` will match fields with values `3`, `4`, or `5`. Providing `null` for
either end of the range will leave that end of the constraint open.
@param PhabricatorCustomFieldIndexStorage Table where the index is stored.
@param int|null Minimum permissible value, inclusive.
@param int|null Maximum permissible value, inclusive.
@return this
@task appsearch | withApplicationSearchRangeConstraint | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
protected function getApplicationSearchObjectPHIDColumn(
AphrontDatabaseConnection $conn) {
if ($this->getPrimaryTableAlias()) {
return qsprintf($conn, '%T.phid', $this->getPrimaryTableAlias());
} else {
return qsprintf($conn, 'phid');
}
} | Get the name of the query's primary object PHID column, for constructing
JOIN clauses. Normally (and by default) this is just `"phid"`, but it may
be something more exotic.
See @{method:getPrimaryTableAlias} if the column needs to be qualified with
a table alias.
@param AphrontDatabaseConnection Connection executing queries.
@return PhutilQueryString Column name.
@task appsearch | getApplicationSearchObjectPHIDColumn | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
protected function getApplicationSearchMayJoinMultipleRows() {
foreach ($this->applicationSearchConstraints as $constraint) {
$type = $constraint['type'];
$value = $constraint['value'];
$cond = $constraint['cond'];
switch ($cond) {
case '=':
switch ($type) {
case 'string':
case 'int':
if (count($value) > 1) {
return true;
}
break;
default:
throw new Exception(pht('Unknown index type "%s"!', $type));
}
break;
case 'range':
// NOTE: It's possible to write a custom field where multiple rows
// match a range constraint, but we don't currently ship any in the
// upstream and I can't immediately come up with cases where this
// would make sense.
break;
default:
throw new Exception(pht('Unknown constraint condition "%s"!', $cond));
}
}
return false;
} | Determine if the JOINs built by ApplicationSearch might cause each primary
object to return multiple result rows. Generally, this means the query
needs an extra GROUP BY clause.
@return bool True if the query may return multiple rows for each object.
@task appsearch | getApplicationSearchMayJoinMultipleRows | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
protected function buildApplicationSearchGroupClause(
AphrontDatabaseConnection $conn) {
if ($this->getApplicationSearchMayJoinMultipleRows()) {
return qsprintf(
$conn,
'GROUP BY %Q',
$this->getApplicationSearchObjectPHIDColumn($conn));
} else {
return qsprintf($conn, '');
}
} | Construct a GROUP BY clause appropriate for ApplicationSearch constraints.
@param AphrontDatabaseConnection Connection executing the query.
@return string Group clause.
@task appsearch | buildApplicationSearchGroupClause | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
private function validateEdgeLogicConstraints() {
if ($this->edgeLogicConstraintsAreValid) {
return $this;
}
foreach ($this->edgeLogicConstraints as $type => $constraints) {
foreach ($constraints as $operator => $list) {
switch ($operator) {
case PhabricatorQueryConstraint::OPERATOR_EMPTY:
throw new PhabricatorEmptyQueryException(
pht('This query specifies an empty constraint.'));
}
}
}
// This should probably be more modular, eventually, but we only do
// project-based edge logic today.
$project_phids = $this->getEdgeLogicValues(
array(
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
),
array(
PhabricatorQueryConstraint::OPERATOR_AND,
PhabricatorQueryConstraint::OPERATOR_OR,
PhabricatorQueryConstraint::OPERATOR_NOT,
PhabricatorQueryConstraint::OPERATOR_ANCESTOR,
));
if ($project_phids) {
$projects = id(new PhabricatorProjectQuery())
->setViewer($this->getViewer())
->setParentQuery($this)
->withPHIDs($project_phids)
->execute();
$projects = mpull($projects, null, 'getPHID');
foreach ($project_phids as $phid) {
if (empty($projects[$phid])) {
throw new PhabricatorEmptyQueryException(
pht(
'This query is constrained by a project you do not have '.
'permission to see.'));
}
}
}
$op_and = PhabricatorQueryConstraint::OPERATOR_AND;
$op_or = PhabricatorQueryConstraint::OPERATOR_OR;
$op_ancestor = PhabricatorQueryConstraint::OPERATOR_ANCESTOR;
foreach ($this->edgeLogicConstraints as $type => $constraints) {
foreach ($constraints as $operator => $list) {
switch ($operator) {
case PhabricatorQueryConstraint::OPERATOR_ONLY:
if (count($list) > 1) {
throw new PhabricatorEmptyQueryException(
pht(
'This query specifies only() more than once.'));
}
$have_and = idx($constraints, $op_and);
$have_or = idx($constraints, $op_or);
$have_ancestor = idx($constraints, $op_ancestor);
if (!$have_and && !$have_or && !$have_ancestor) {
throw new PhabricatorEmptyQueryException(
pht(
'This query specifies only(), but no other constraints '.
'which it can apply to.'));
}
break;
}
}
}
$this->edgeLogicConstraintsAreValid = true;
return $this;
} | Validate edge logic constraints for the query.
@return this
@task edgelogic | validateEdgeLogicConstraints | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
public function withSpacePHIDs(array $space_phids) {
$object = $this->newResultObject();
if (!$object) {
throw new Exception(
pht(
'This query (of class "%s") does not implement newResultObject(), '.
'but must implement this method to enable support for Spaces.',
get_class($this)));
}
if (!($object instanceof PhabricatorSpacesInterface)) {
throw new Exception(
pht(
'This query (of class "%s") returned an object of class "%s" from '.
'getNewResultObject(), but it does not implement the required '.
'interface ("%s"). Objects must implement this interface to enable '.
'Spaces support.',
get_class($this),
get_class($object),
'PhabricatorSpacesInterface'));
}
$this->spacePHIDs = $space_phids;
return $this;
} | Constrain the query to return results from only specific Spaces.
Pass a list of Space PHIDs, or `null` to represent the default space. Only
results in those Spaces will be returned.
Queries are always constrained to include only results from spaces the
viewer has access to.
@param list<phid|null>
@task spaces | withSpacePHIDs | php | phacility/phabricator | src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/query/policy/PhabricatorCursorPagedPolicyAwareQuery.php | Apache-2.0 |
private function waitForUpdates($min_sleep, array $retry_after) {
$this->log(
pht('No repositories need updates right now, sleeping...'));
$sleep_until = time() + $min_sleep;
if ($retry_after) {
$sleep_until = min($sleep_until, min($retry_after));
}
while (($sleep_until - time()) > 0) {
$sleep_duration = ($sleep_until - time());
if ($this->shouldHibernate($sleep_duration)) {
return true;
}
$this->log(
pht(
'Sleeping for %s more second(s)...',
new PhutilNumber($sleep_duration)));
$this->sleep(1);
if ($this->shouldExit()) {
$this->log(pht('Awakened from sleep by graceful shutdown!'));
return false;
}
if ($this->loadRepositoryUpdateMessages()) {
$this->log(pht('Awakened from sleep by pending updates!'));
break;
}
}
return false;
} | Sleep for a short period of time, waiting for update messages from the
@task pull | waitForUpdates | php | phacility/phabricator | src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/daemon/PhabricatorRepositoryPullLocalDaemon.php | Apache-2.0 |
protected function verifyPassword(
PhutilOpaqueEnvelope $password,
PhutilOpaqueEnvelope $hash) {
$actual_hash = $this->getPasswordHash($password)->openEnvelope();
$expect_hash = $hash->openEnvelope();
return phutil_hashes_are_identical($actual_hash, $expect_hash);
} | Verify that a password matches a hash.
The default implementation checks for equality; if a hasher embeds salt in
hashes it should override this method and perform a salt-aware comparison.
@param PhutilOpaqueEnvelope Password to compare.
@param PhutilOpaqueEnvelope Bare password hash.
@return bool True if the passwords match.
@task hasher | verifyPassword | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
protected function canUpgradeInternalHash(PhutilOpaqueEnvelope $hash) {
return false;
} | Check if an existing hash created by this algorithm is upgradeable.
The default implementation returns `false`. However, hash algorithms which
have (for example) an internal cost function may be able to upgrade an
existing hash to a stronger one with a higher cost.
@param PhutilOpaqueEnvelope Bare hash.
@return bool True if the hash can be upgraded without
changing the algorithm (for example, to a
higher cost).
@task hasher | canUpgradeInternalHash | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
private static function parseHashFromStorage(PhutilOpaqueEnvelope $hash) {
$raw_hash = $hash->openEnvelope();
if (strpos($raw_hash, ':') === false) {
throw new Exception(
pht(
'Malformed password hash, expected "name:hash".'));
}
list($name, $hash) = explode(':', $raw_hash);
return array(
'name' => $name,
'hash' => new PhutilOpaqueEnvelope($hash),
);
} | Parse a storage hash into its components, like the hash type and hash
data.
@return map Dictionary of information about the hash.
@task hashing | parseHashFromStorage | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getAllUsableHashers() {
$hashers = self::getAllHashers();
foreach ($hashers as $key => $hasher) {
if (!$hasher->canHashPasswords()) {
unset($hashers[$key]);
}
}
return $hashers;
} | Get all usable password hashers. This may include hashers which are
not desirable or advisable.
@return list<PhabricatorPasswordHasher> Hasher objects.
@task hashing | getAllUsableHashers | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getBestHasher() {
$hashers = self::getAllUsableHashers();
$hashers = msort($hashers, 'getStrength');
$hasher = last($hashers);
if (!$hasher) {
throw new PhabricatorPasswordHasherUnavailableException(
pht(
'There are no password hashers available which are usable for '.
'new passwords.'));
}
return $hasher;
} | Get the best (strongest) available hasher.
@return PhabricatorPasswordHasher Best hasher.
@task hashing | getBestHasher | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getHasherForHash(PhutilOpaqueEnvelope $hash) {
$info = self::parseHashFromStorage($hash);
$name = $info['name'];
$usable = self::getAllUsableHashers();
if (isset($usable[$name])) {
return $usable[$name];
}
$all = self::getAllHashers();
if (isset($all[$name])) {
throw new PhabricatorPasswordHasherUnavailableException(
pht(
'Attempting to compare a password saved with the "%s" hash. The '.
'hasher exists, but is not currently usable. %s',
$name,
$all[$name]->getInstallInstructions()));
}
throw new PhabricatorPasswordHasherUnavailableException(
pht(
'Attempting to compare a password saved with the "%s" hash. No such '.
'hasher is known.',
$name));
} | Get the hasher for a given stored hash.
@return PhabricatorPasswordHasher Corresponding hasher.
@task hashing | getHasherForHash | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function canUpgradeHash(PhutilOpaqueEnvelope $hash) {
if (!strlen($hash->openEnvelope())) {
throw new Exception(
pht('Expected a password hash, received nothing!'));
}
$current_hasher = self::getHasherForHash($hash);
$best_hasher = self::getBestHasher();
if ($current_hasher->getHashName() != $best_hasher->getHashName()) {
// If the algorithm isn't the best one, we can upgrade.
return true;
}
$info = self::parseHashFromStorage($hash);
if ($current_hasher->canUpgradeInternalHash($info['hash'])) {
// If the algorithm provides an internal upgrade, we can also upgrade.
return true;
}
// Already on the best algorithm with the best settings.
return false;
} | Test if a password is using an weaker hash than the strongest available
hash. This can be used to prompt users to upgrade, or automatically upgrade
on login.
@return bool True to indicate that rehashing this password will improve
the hash strength.
@task hashing | canUpgradeHash | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function generateNewPasswordHash(
PhutilOpaqueEnvelope $password) {
$hasher = self::getBestHasher();
return $hasher->getPasswordHashForStorage($password);
} | Generate a new hash for a password, using the best available hasher.
@param PhutilOpaqueEnvelope Password to hash.
@return PhutilOpaqueEnvelope Hashed password, using best available
hasher.
@task hashing | generateNewPasswordHash | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function comparePassword(
PhutilOpaqueEnvelope $password,
PhutilOpaqueEnvelope $hash) {
$hasher = self::getHasherForHash($hash);
$parts = self::parseHashFromStorage($hash);
return $hasher->verifyPassword($password, $parts['hash']);
} | Compare a password to a stored hash.
@param PhutilOpaqueEnvelope Password to compare.
@param PhutilOpaqueEnvelope Stored password hash.
@return bool True if the passwords match.
@task hashing | comparePassword | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getCurrentAlgorithmName(PhutilOpaqueEnvelope $hash) {
$raw_hash = $hash->openEnvelope();
if (!strlen($raw_hash)) {
return pht('None');
}
try {
$current_hasher = self::getHasherForHash($hash);
return $current_hasher->getHumanReadableName();
} catch (Exception $ex) {
$info = self::parseHashFromStorage($hash);
$name = $info['name'];
return pht('Unknown ("%s")', $name);
}
} | Get the human-readable algorithm name for a given hash.
@param PhutilOpaqueEnvelope Storage hash.
@return string Human-readable algorithm name. | getCurrentAlgorithmName | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
public static function getBestAlgorithmName() {
try {
$best_hasher = self::getBestHasher();
return $best_hasher->getHumanReadableName();
} catch (Exception $ex) {
return pht('Unknown');
}
} | Get the human-readable algorithm name for the best available hash.
@return string Human-readable name for best hash. | getBestAlgorithmName | php | phacility/phabricator | src/infrastructure/util/password/PhabricatorPasswordHasher.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/password/PhabricatorPasswordHasher.php | Apache-2.0 |
private function getSleepDuration() {
$sleep = phutil_units('3 minutes in seconds');
$next_triggers = id(new PhabricatorWorkerTriggerQuery())
->setViewer($this->getViewer())
->setOrder(PhabricatorWorkerTriggerQuery::ORDER_EXECUTION)
->withNextEventBetween(0, null)
->setLimit(1)
->needEvents(true)
->execute();
if ($next_triggers) {
$next_trigger = head($next_triggers);
$next_epoch = $next_trigger->getEvent()->getNextEventEpoch();
$until = max(0, $next_epoch - PhabricatorTime::getNow());
$sleep = min($sleep, $until);
}
return $sleep;
} | Get the number of seconds to sleep for before starting the next scheduling
phase.
If no events are scheduled soon, we'll sleep briefly. Otherwise,
we'll sleep until the next scheduled event.
@return int Number of seconds to sleep for. | getSleepDuration | php | phacility/phabricator | src/infrastructure/daemon/workers/PhabricatorTriggerDaemon.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/daemon/workers/PhabricatorTriggerDaemon.php | Apache-2.0 |
private function runGarbageCollection($duration) {
$run_until = (PhabricatorTime::getNow() + $duration);
// NOTE: We always run at least one GC cycle to make sure the GC can make
// progress even if the trigger queue is busy.
do {
$more_garbage = $this->updateGarbageCollection();
if (!$more_garbage) {
// If we don't have any more collection work to perform, we're all
// done.
break;
}
} while (PhabricatorTime::getNow() <= $run_until);
$remaining = max(0, $run_until - PhabricatorTime::getNow());
return $remaining;
} | Run the garbage collector for up to a specified number of seconds.
@param int Number of seconds the GC may run for.
@return int Number of seconds remaining in the time budget.
@task garbage | runGarbageCollection | php | phacility/phabricator | src/infrastructure/daemon/workers/PhabricatorTriggerDaemon.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/daemon/workers/PhabricatorTriggerDaemon.php | Apache-2.0 |
public function isPreflightCheck() {
return false;
} | Should this check execute before we load configuration?
The majority of checks (particularly, those checks which examine
configuration) should run in the normal setup phase, after configuration
loads. However, a small set of critical checks (mostly, tests for PHP
setup and extensions) need to run before we can load configuration.
@return bool True to execute before configuration is loaded. | isPreflightCheck | php | phacility/phabricator | src/applications/config/check/PhabricatorSetupCheck.php | https://github.com/phacility/phabricator/blob/master/src/applications/config/check/PhabricatorSetupCheck.php | Apache-2.0 |
public function isBrowsable() {
return true;
} | Can the user browse through results from this datasource?
Browsable datasources allow the user to switch from typeahead mode to
a browse mode where they can scroll through all results.
By default, datasources are browsable, but some datasources can not
generate a meaningful result set or can't filter results on the server.
@return bool | isBrowsable | php | phacility/phabricator | src/applications/typeahead/datasource/PhabricatorTypeaheadDatasource.php | https://github.com/phacility/phabricator/blob/master/src/applications/typeahead/datasource/PhabricatorTypeaheadDatasource.php | Apache-2.0 |
public static function getBuildStatusName($status) {
$spec = self::getBuildStatusSpec($status);
return $spec['name'];
} | Get a human readable name for a build status constant.
@param const Build status constant.
@return string Human-readable name. | getBuildStatusName | php | phacility/phabricator | src/applications/harbormaster/constants/HarbormasterBuildStatus.php | https://github.com/phacility/phabricator/blob/master/src/applications/harbormaster/constants/HarbormasterBuildStatus.php | Apache-2.0 |
public static function loadRestrictedNamespace(
PhabricatorUser $viewer,
$name) {
// For a name like "x.y.z", produce a list of controlling namespaces like
// ("z", "y.x", "x.y.z").
$names = array();
$parts = explode('.', $name);
for ($ii = 0; $ii < count($parts); $ii++) {
$names[] = implode('.', array_slice($parts, -($ii + 1)));
}
// Load all the possible controlling namespaces.
$namespaces = id(new AlmanacNamespaceQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withNames($names)
->execute();
if (!$namespaces) {
return null;
}
// Find the "nearest" (longest) namespace that exists. If both
// "sub.domain.com" and "domain.com" exist, we only care about the policy
// on the former.
$namespaces = msort($namespaces, 'getNameLength');
$namespace = last($namespaces);
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$namespace,
PhabricatorPolicyCapability::CAN_EDIT);
if ($can_edit) {
return null;
}
return $namespace;
} | Load the namespace which prevents use of an Almanac name, if one exists. | loadRestrictedNamespace | php | phacility/phabricator | src/applications/almanac/storage/AlmanacNamespace.php | https://github.com/phacility/phabricator/blob/master/src/applications/almanac/storage/AlmanacNamespace.php | Apache-2.0 |
public function getEngineIdentifier() {
return 'local-disk';
} | This engine identifies as "local-disk". | getEngineIdentifier | php | phacility/phabricator | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
public function writeFile($data, array $params) {
$root = $this->getLocalDiskFileStorageRoot();
// Generate a random, unique file path like "ab/29/1f918a9ac39201ff". We
// put a couple of subdirectories up front to avoid a situation where we
// have one directory with a zillion files in it, since this is generally
// bad news.
do {
$name = md5(mt_rand());
$name = preg_replace('/^(..)(..)(.*)$/', '\\1/\\2/\\3', $name);
if (!Filesystem::pathExists($root.'/'.$name)) {
break;
}
} while (true);
$parent = $root.'/'.dirname($name);
if (!Filesystem::pathExists($parent)) {
execx('mkdir -p %s', $parent);
}
AphrontWriteGuard::willWrite();
Filesystem::writeFile($root.'/'.$name, $data);
return $name;
} | Write the file data to local disk. Returns the relative path as the
file data handle.
@task impl | writeFile | php | phacility/phabricator | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
public function readFile($handle) {
$path = $this->getLocalDiskFileStorageFullPath($handle);
return Filesystem::readFile($path);
} | Read the file data off local disk.
@task impl | readFile | php | phacility/phabricator | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
public function deleteFile($handle) {
$path = $this->getLocalDiskFileStorageFullPath($handle);
if (Filesystem::pathExists($path)) {
AphrontWriteGuard::willWrite();
Filesystem::remove($path);
}
} | Deletes the file from local disk, if it exists.
@task impl | deleteFile | php | phacility/phabricator | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
private function getLocalDiskFileStorageRoot() {
$root = PhabricatorEnv::getEnvConfig('storage.local-disk.path');
if (!$root || $root == '/' || $root[0] != '/') {
throw new PhabricatorFileStorageConfigurationException(
pht(
"Malformed local disk storage root. You must provide an absolute ".
"path, and can not use '%s' as the root.",
'/'));
}
return rtrim($root, '/');
} | Get the configured local disk path for file storage.
@return string Absolute path to somewhere that files can be stored.
@task internal | getLocalDiskFileStorageRoot | php | phacility/phabricator | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
private function getLocalDiskFileStorageFullPath($handle) {
// Make sure there's no funny business going on here. Users normally have
// no ability to affect the content of handles, but double-check that
// we're only accessing local storage just in case.
if (!preg_match('@^[a-f0-9]{2}/[a-f0-9]{2}/[a-f0-9]{28}\z@', $handle)) {
throw new Exception(
pht(
"Local disk filesystem handle '%s' is malformed!",
$handle));
}
$root = $this->getLocalDiskFileStorageRoot();
return $root.'/'.$handle;
} | Convert a handle into an absolute local disk path.
@param string File data handle.
@return string Absolute path to the corresponding file.
@task internal | getLocalDiskFileStorageFullPath | php | phacility/phabricator | src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorLocalDiskFileStorageEngine.php | Apache-2.0 |
public function setKey($key) {
$this->key = $key;
return $this;
} | Set the primary key for the field, like `projectPHIDs`.
You can set human-readable aliases with @{method:setAliases}.
The key should be a short, unique (within a search engine) string which
does not contain any special characters.
@param string Unique key which identifies the field.
@return this
@task config | setKey | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function setLabel($label) {
$this->label = $label;
return $this;
} | Set a human-readable label for the field.
This should be a short text string, like "Reviewers" or "Colors".
@param string Short, human-readable field label.
@return this
task config | setLabel | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function getLabel() {
return $this->label;
} | Get the field's human-readable label.
@return string Short, human-readable field label.
@task config | getLabel | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function setAliases(array $aliases) {
$this->aliases = $aliases;
return $this;
} | Provide alternate field aliases, usually more human-readable versions
of the key.
These aliases can be used when building GET requests, so you can provide
an alias like `authors` to let users write `&authors=alincoln` instead of
`&authorPHIDs=alincoln`. This is a little easier to use.
@param list<string> List of aliases for this field.
@return this
@task config | setAliases | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function setConduitKey($conduit_key) {
$this->conduitKey = $conduit_key;
return $this;
} | Provide an alternate field key for Conduit.
This can allow you to choose a more usable key for API endpoints.
If no key is provided, the main key is used.
@param string Alternate key for Conduit.
@return this
@task config | setConduitKey | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function getConduitKey() {
if ($this->conduitKey !== null) {
return $this->conduitKey;
}
return $this->getKey();
} | Get the field key for use in Conduit.
@return string Conduit key for this field.
@task config | getConduitKey | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function setDescription($description) {
$this->description = $description;
return $this;
} | Set a human-readable description for this field.
@param string Human-readable description.
@return this
@task config | setDescription | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function getDescription() {
return $this->description;
} | Get this field's human-readable description.
@return string|null Human-readable description.
@task config | getDescription | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function setIsHidden($is_hidden) {
$this->isHidden = $is_hidden;
return $this;
} | Hide this field from the web UI.
@param bool True to hide the field from the web UI.
@return this
@task config | setIsHidden | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
public function getIsHidden() {
return $this->isHidden;
} | Should this field be hidden from the web UI?
@return bool True to hide the field in the web UI.
@task config | getIsHidden | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
protected function getListFromRequest(
AphrontRequest $request,
$key) {
$list = $request->getArr($key, null);
if ($list === null) {
$list = $request->getStrList($key);
}
if (!$list) {
return array();
}
return $list;
} | Read a list of items from the request, in either array format or string
format:
list[]=item1&list[]=item2
list=item1,item2
This provides flexibility when constructing URIs, especially from external
sources.
@param AphrontRequest Request to read strings from.
@param string Key to read in the request.
@return list<string> List of values.
@task utility | getListFromRequest | php | phacility/phabricator | src/applications/search/field/PhabricatorSearchField.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/field/PhabricatorSearchField.php | Apache-2.0 |
private function getAutosteps(array $autotargets) {
$all_steps = HarbormasterBuildStepImplementation::getImplementations();
$all_steps = mpull($all_steps, null, 'getBuildStepAutotargetStepKey');
// Make sure all the targets really exist.
foreach ($autotargets as $autotarget) {
if (empty($all_steps[$autotarget])) {
throw new Exception(
pht(
'No build step provides autotarget "%s"!',
$autotarget));
}
}
return array_select_keys($all_steps, $autotargets);
} | Get all of the @{class:HarbormasterBuildStepImplementation} objects for
a list of autotarget keys.
@param list<string> Autotarget keys, like `"core.arc.lint"`.
@return map<string, object> Map of keys to implementations. | getAutosteps | php | phacility/phabricator | src/applications/harbormaster/engine/HarbormasterTargetEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/harbormaster/engine/HarbormasterTargetEngine.php | Apache-2.0 |
private function executeAllocator(DrydockLease $lease) {
$blueprints = $this->loadBlueprintsForAllocatingLease($lease);
// If we get nothing back, that means no blueprint is defined which can
// ever build the requested resource. This is a permanent failure, since
// we don't expect to succeed no matter how many times we try.
if (!$blueprints) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'No active Drydock blueprint exists which can ever allocate a '.
'resource for lease "%s".',
$lease->getPHID()));
}
// First, try to find a suitable open resource which we can acquire a new
// lease on.
$resources = $this->loadAcquirableResourcesForLease($blueprints, $lease);
list($free_resources, $used_resources) = $this->partitionResources(
$lease,
$resources);
$resource = $this->leaseAnyResource($lease, $free_resources);
if ($resource) {
return $resource;
}
// We're about to try creating a resource. If we're already creating
// something, just yield until that resolves.
$this->yieldForPendingResources($lease);
// We haven't been able to lease an existing resource yet, so now we try to
// create one. We may still have some less-desirable "used" resources that
// we'll sometimes try to lease later if we fail to allocate a new resource.
$resource = $this->newLeasedResource($lease, $blueprints);
if ($resource) {
return $resource;
}
// We haven't been able to lease a desirable "free" resource or create a
// new resource. Try to lease a "used" resource.
$resource = $this->leaseAnyResource($lease, $used_resources);
if ($resource) {
return $resource;
}
// If this lease has already triggered a reclaim, just yield and wait for
// it to resolve.
$this->yieldForReclaimingResources($lease);
// Try to reclaim a resource. This will yield if it reclaims something.
$this->reclaimAnyResource($lease, $blueprints);
// We weren't able to lease, create, or reclaim any resources. We just have
// to wait for resources to become available.
$lease->logEvent(
DrydockLeaseWaitingForResourcesLogType::LOGCONST,
array(
'blueprintPHIDs' => mpull($blueprints, 'getPHID'),
));
throw new PhabricatorWorkerYieldException(15);
} | Find or build a resource which can satisfy a given lease request, then
acquire the lease.
@param DrydockLease Requested lease.
@return void
@task allocator | executeAllocator | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function loadBlueprintsForAllocatingLease(
DrydockLease $lease) {
$viewer = $this->getViewer();
$impls = DrydockBlueprintImplementation::getAllForAllocatingLease($lease);
if (!$impls) {
return array();
}
$blueprint_phids = $lease->getAllowedBlueprintPHIDs();
if (!$blueprint_phids) {
$lease->logEvent(DrydockLeaseNoBlueprintsLogType::LOGCONST);
return array();
}
$query = id(new DrydockBlueprintQuery())
->setViewer($viewer)
->withPHIDs($blueprint_phids)
->withBlueprintClasses(array_keys($impls))
->withDisabled(false);
// The Drydock application itself is allowed to authorize anything. This
// is primarily used for leases generated by CLI administrative tools.
$drydock_phid = id(new PhabricatorDrydockApplication())->getPHID();
$authorizing_phid = $lease->getAuthorizingPHID();
if ($authorizing_phid != $drydock_phid) {
$blueprints = id(clone $query)
->withAuthorizedPHIDs(array($authorizing_phid))
->execute();
if (!$blueprints) {
// If we didn't hit any blueprints, check if this is an authorization
// problem: re-execute the query without the authorization constraint.
// If the second query hits blueprints, the overall configuration is
// fine but this is an authorization problem. If the second query also
// comes up blank, this is some other kind of configuration issue so
// we fall through to the default pathway.
$all_blueprints = $query->execute();
if ($all_blueprints) {
$lease->logEvent(
DrydockLeaseNoAuthorizationsLogType::LOGCONST,
array(
'authorizingPHID' => $authorizing_phid,
));
return array();
}
}
} else {
$blueprints = $query->execute();
}
$keep = array();
foreach ($blueprints as $key => $blueprint) {
if (!$blueprint->canEverAllocateResourceForLease($lease)) {
continue;
}
$keep[$key] = $blueprint;
}
return $keep;
} | Get all the concrete @{class:DrydockBlueprint}s which can possibly
build a resource to satisfy a lease.
@param DrydockLease Requested lease.
@return list<DrydockBlueprint> List of qualifying blueprints.
@task allocator | loadBlueprintsForAllocatingLease | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function loadAcquirableResourcesForLease(
array $blueprints,
DrydockLease $lease) {
assert_instances_of($blueprints, 'DrydockBlueprint');
$viewer = $this->getViewer();
$resources = id(new DrydockResourceQuery())
->setViewer($viewer)
->withBlueprintPHIDs(mpull($blueprints, 'getPHID'))
->withTypes(array($lease->getResourceType()))
->withStatuses(
array(
DrydockResourceStatus::STATUS_ACTIVE,
))
->execute();
return $this->removeUnacquirableResources($resources, $lease);
} | Load a list of all resources which a given lease can possibly be
allocated against.
@param list<DrydockBlueprint> Blueprints which may produce suitable
resources.
@param DrydockLease Requested lease.
@return list<DrydockResource> Resources which may be able to allocate
the lease.
@task allocator | loadAcquirableResourcesForLease | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function removeOverallocatedBlueprints(
array $blueprints,
DrydockLease $lease) {
assert_instances_of($blueprints, 'DrydockBlueprint');
$keep = array();
foreach ($blueprints as $key => $blueprint) {
if (!$blueprint->canAllocateResourceForLease($lease)) {
continue;
}
$keep[$key] = $blueprint;
}
return $keep;
} | Remove blueprints which are too heavily allocated to build a resource for
a lease from a list of blueprints.
@param list<DrydockBlueprint> List of blueprints.
@return list<DrydockBlueprint> List with blueprints that can not allocate
a resource for the lease right now removed.
@task allocator | removeOverallocatedBlueprints | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function rankBlueprints(array $blueprints, DrydockLease $lease) {
assert_instances_of($blueprints, 'DrydockBlueprint');
// TODO: Implement improvements to this ranking algorithm if they become
// available.
shuffle($blueprints);
return $blueprints;
} | Rank blueprints by suitability for building a new resource for a
particular lease.
@param list<DrydockBlueprint> List of blueprints.
@param DrydockLease Requested lease.
@return list<DrydockBlueprint> Ranked list of blueprints.
@task allocator | rankBlueprints | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function rankResources(array $resources, DrydockLease $lease) {
assert_instances_of($resources, 'DrydockResource');
// TODO: Implement improvements to this ranking algorithm if they become
// available.
shuffle($resources);
return $resources;
} | Rank resources by suitability for allocating a particular lease.
@param list<DrydockResource> List of resources.
@param DrydockLease Requested lease.
@return list<DrydockResource> Ranked list of resources.
@task allocator | rankResources | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function allocateResource(
DrydockBlueprint $blueprint,
DrydockLease $lease) {
$resource = $blueprint->allocateResource($lease);
$this->validateAllocatedResource($blueprint, $resource, $lease);
// If this resource was allocated as a pending resource, queue a task to
// activate it.
if ($resource->getStatus() == DrydockResourceStatus::STATUS_PENDING) {
$lease->addAllocatedResourcePHIDs(
array(
$resource->getPHID(),
));
$lease->save();
PhabricatorWorker::scheduleTask(
'DrydockResourceUpdateWorker',
array(
'resourcePHID' => $resource->getPHID(),
// This task will generally yield while the resource activates, so
// wake it back up once the resource comes online. Most of the time,
// we'll be able to lease the newly activated resource.
'awakenOnActivation' => array(
$this->getCurrentWorkerTaskID(),
),
),
array(
'objectPHID' => $resource->getPHID(),
));
}
return $resource;
} | Perform an actual resource allocation with a particular blueprint.
@param DrydockBlueprint The blueprint to allocate a resource from.
@param DrydockLease Requested lease.
@return DrydockResource Allocated resource.
@task allocator | allocateResource | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function validateAllocatedResource(
DrydockBlueprint $blueprint,
$resource,
DrydockLease $lease) {
if (!($resource instanceof DrydockResource)) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: %s must '.
'return an object of type %s or throw, but returned something else.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'allocateResource()',
'DrydockResource'));
}
if (!$resource->isAllocatedResource()) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: %s '.
'must actually allocate the resource it returns.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'allocateResource()'));
}
$resource_type = $resource->getType();
$lease_type = $lease->getResourceType();
if ($resource_type !== $lease_type) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: it '.
'built a resource of type "%s" to satisfy a lease requesting a '.
'resource of type "%s".',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
$resource_type,
$lease_type));
}
} | Check that the resource a blueprint allocated is roughly the sort of
object we expect.
@param DrydockBlueprint Blueprint which built the resource.
@param wild Thing which the blueprint claims is a valid resource.
@param DrydockLease Lease the resource was allocated for.
@return void
@task allocator | validateAllocatedResource | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function acquireLease(
DrydockResource $resource,
DrydockLease $lease) {
$blueprint = $resource->getBlueprint();
$blueprint->acquireLease($resource, $lease);
$this->validateAcquiredLease($blueprint, $resource, $lease);
// If this lease has been acquired but not activated, queue a task to
// activate it.
if ($lease->getStatus() == DrydockLeaseStatus::STATUS_ACQUIRED) {
$this->queueTask(
__CLASS__,
array(
'leasePHID' => $lease->getPHID(),
),
array(
'objectPHID' => $lease->getPHID(),
));
}
} | Perform an actual lease acquisition on a particular resource.
@param DrydockResource Resource to acquire a lease on.
@param DrydockLease Lease to acquire.
@return void
@task acquire | acquireLease | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
private function validateAcquiredLease(
DrydockBlueprint $blueprint,
DrydockResource $resource,
DrydockLease $lease) {
if (!$lease->isAcquiredLease()) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: it '.
'returned from "%s" without acquiring a lease.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'acquireLease()'));
}
$lease_phid = $lease->getResourcePHID();
$resource_phid = $resource->getPHID();
if ($lease_phid !== $resource_phid) {
throw new Exception(
pht(
'Blueprint "%s" (of type "%s") is not properly implemented: it '.
'returned from "%s" with a lease acquired on the wrong resource.',
$blueprint->getBlueprintName(),
$blueprint->getClassName(),
'acquireLease()'));
}
} | Make sure that a lease was really acquired properly.
@param DrydockBlueprint Blueprint which created the resource.
@param DrydockResource Resource which was acquired.
@param DrydockLease The lease which was supposedly acquired.
@return void
@task acquire | validateAcquiredLease | php | phacility/phabricator | src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/drydock/worker/DrydockLeaseUpdateWorker.php | Apache-2.0 |
public function withOwnerPHIDs(array $phids) {
$this->ownerPHIDs = $phids;
return $this;
} | Query owner PHIDs exactly. This does not expand authorities, so a user
PHID will not match projects the user is a member of. | withOwnerPHIDs | php | phacility/phabricator | src/applications/owners/query/PhabricatorOwnersPackageQuery.php | https://github.com/phacility/phabricator/blob/master/src/applications/owners/query/PhabricatorOwnersPackageQuery.php | Apache-2.0 |
public function withAuthorityPHIDs(array $phids) {
$this->authorityPHIDs = $phids;
return $this;
} | Query owner authority. This will expand authorities, so a user PHID will
match both packages they own directly and packages owned by a project they
are a member of. | withAuthorityPHIDs | php | phacility/phabricator | src/applications/owners/query/PhabricatorOwnersPackageQuery.php | https://github.com/phacility/phabricator/blob/master/src/applications/owners/query/PhabricatorOwnersPackageQuery.php | Apache-2.0 |
protected function willFinishOAuthHandshake() {
$jira_magic_word = 'denied';
if ($this->getVerifier() == $jira_magic_word) {
throw new PhutilAuthUserAbortedException();
}
} | JIRA indicates that the user has clicked the "Deny" button by passing a
well known `oauth_verifier` value ("denied"), which we check for here. | willFinishOAuthHandshake | php | phacility/phabricator | src/applications/auth/adapter/PhutilJIRAAuthAdapter.php | https://github.com/phacility/phabricator/blob/master/src/applications/auth/adapter/PhutilJIRAAuthAdapter.php | Apache-2.0 |
public function setRightSideCommentMapping($id, $is_new) {
$this->rightSideChangesetID = $id;
$this->rightSideAttachesToNewFile = $is_new;
return $this;
} | Configure which Changeset comments added to the right side of the visible
diff will be attached to. The ID must be the ID of a real Differential
Changeset.
The complexity here is that we may show an arbitrary side of an arbitrary
changeset as either the left or right part of a diff. This method allows
the left and right halves of the displayed diff to be correctly mapped to
storage changesets.
@param id The Differential Changeset ID that comments added to the right
side of the visible diff should be attached to.
@param bool If true, attach new comments to the right side of the storage
changeset. Note that this may be false, if the left side of
some storage changeset is being shown as the right side of
a display diff.
@return this | setRightSideCommentMapping | php | phacility/phabricator | src/applications/differential/parser/DifferentialChangesetParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialChangesetParser.php | Apache-2.0 |
public function setLeftSideCommentMapping($id, $is_new) {
$this->leftSideChangesetID = $id;
$this->leftSideAttachesToNewFile = $is_new;
return $this;
} | See setRightSideCommentMapping(), but this sets information for the left
side of the display diff. | setLeftSideCommentMapping | php | phacility/phabricator | src/applications/differential/parser/DifferentialChangesetParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialChangesetParser.php | Apache-2.0 |
public function setRenderCacheKey($key) {
$this->renderCacheKey = $key;
return $this;
} | Set a key for identifying this changeset in the render cache. If set, the
parser will attempt to use the changeset render cache, which can improve
performance for frequently-viewed changesets.
By default, there is no render cache key and parsers do not use the cache.
This is appropriate for rarely-viewed changesets.
@param string Key for identifying this changeset in the render cache.
@return this | setRenderCacheKey | php | phacility/phabricator | src/applications/differential/parser/DifferentialChangesetParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialChangesetParser.php | Apache-2.0 |
private function calculateGapsAndMask(
$mask_force,
$feedback_mask,
$range_start,
$range_len) {
$lines_context = $this->getLinesOfContext();
$gaps = array();
$gap_start = 0;
$in_gap = false;
$base_mask = $this->visible + $mask_force + $feedback_mask;
$base_mask[$range_start + $range_len] = true;
for ($ii = $range_start; $ii <= $range_start + $range_len; $ii++) {
if (isset($base_mask[$ii])) {
if ($in_gap) {
$gap_length = $ii - $gap_start;
if ($gap_length <= $lines_context) {
for ($jj = $gap_start; $jj <= $gap_start + $gap_length; $jj++) {
$base_mask[$jj] = true;
}
} else {
$gaps[] = array($gap_start, $gap_length);
}
$in_gap = false;
}
} else {
if (!$in_gap) {
$gap_start = $ii;
$in_gap = true;
}
}
}
$gaps = array_reverse($gaps);
$mask = $base_mask;
return array($gaps, $mask);
} | This function calculates a lot of stuff we need to know to display
the diff:
Gaps - compute gaps in the visible display diff, where we will render
"Show more context" spacers. If a gap is smaller than the context size,
we just display it. Otherwise, we record it into $gaps and will render a
"show more context" element instead of diff text below. A given $gap
is a tuple of $gap_line_number_start and $gap_length.
Mask - compute the actual lines that need to be shown (because they
are near changes lines, near inline comments, or the request has
explicitly asked for them, i.e. resulting from the user clicking
"show more"). The $mask returned is a sparsely populated dictionary
of $visible_line_number => true.
@return array($gaps, $mask) | calculateGapsAndMask | php | phacility/phabricator | src/applications/differential/parser/DifferentialChangesetParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialChangesetParser.php | Apache-2.0 |
private function isCommentVisibleOnRenderedDiff(
PhabricatorInlineComment $comment) {
$changeset_id = $comment->getChangesetID();
$is_new = $comment->getIsNewFile();
if ($changeset_id == $this->rightSideChangesetID &&
$is_new == $this->rightSideAttachesToNewFile) {
return true;
}
if ($changeset_id == $this->leftSideChangesetID &&
$is_new == $this->leftSideAttachesToNewFile) {
return true;
}
return false;
} | Determine if an inline comment will appear on the rendered diff,
taking into consideration which halves of which changesets will actually
be shown.
@param PhabricatorInlineComment Comment to test for visibility.
@return bool True if the comment is visible on the rendered diff. | isCommentVisibleOnRenderedDiff | php | phacility/phabricator | src/applications/differential/parser/DifferentialChangesetParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialChangesetParser.php | Apache-2.0 |
private function isCommentOnRightSideWhenDisplayed(
PhabricatorInlineComment $comment) {
if (!$this->isCommentVisibleOnRenderedDiff($comment)) {
throw new Exception(pht('Comment is not visible on changeset!'));
}
$changeset_id = $comment->getChangesetID();
$is_new = $comment->getIsNewFile();
if ($changeset_id == $this->rightSideChangesetID &&
$is_new == $this->rightSideAttachesToNewFile) {
return true;
}
return false;
} | Determine if a comment will appear on the right side of the display diff.
Note that the comment must appear somewhere on the rendered changeset, as
per isCommentVisibleOnRenderedDiff().
@param PhabricatorInlineComment Comment to test for display
location.
@return bool True for right, false for left. | isCommentOnRightSideWhenDisplayed | php | phacility/phabricator | src/applications/differential/parser/DifferentialChangesetParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialChangesetParser.php | Apache-2.0 |
public function renderModifiedCoverage() {
$na = phutil_tag('em', array(), '-');
$coverage = $this->getCoverage();
if (!$coverage) {
return $na;
}
$covered = 0;
$not_covered = 0;
foreach ($this->new as $k => $new) {
if ($new === null) {
continue;
}
if (!$new['line']) {
continue;
}
if (!$new['type']) {
continue;
}
if (empty($coverage[$new['line'] - 1])) {
continue;
}
switch ($coverage[$new['line'] - 1]) {
case 'C':
$covered++;
break;
case 'U':
$not_covered++;
break;
}
}
if (!$covered && !$not_covered) {
return $na;
}
return sprintf('%d%%', 100 * ($covered / ($covered + $not_covered)));
} | Render "modified coverage" information; test coverage on modified lines.
This synthesizes diff information with unit test information into a useful
indicator of how well tested a change is. | renderModifiedCoverage | php | phacility/phabricator | src/applications/differential/parser/DifferentialChangesetParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialChangesetParser.php | Apache-2.0 |
private function buildLineBackmaps() {
$old_back = array();
$new_back = array();
foreach ($this->old as $ii => $old) {
if ($old === null) {
continue;
}
$old_back[$old['line']] = $old['line'];
}
foreach ($this->new as $ii => $new) {
if ($new === null) {
continue;
}
$new_back[$new['line']] = $new['line'];
}
$max_old_line = 0;
$max_new_line = 0;
foreach ($this->comments as $comment) {
if ($this->isCommentOnRightSideWhenDisplayed($comment)) {
$max_new_line = max($max_new_line, $comment->getLineNumber());
} else {
$max_old_line = max($max_old_line, $comment->getLineNumber());
}
}
$cursor = 1;
for ($ii = 1; $ii <= $max_old_line; $ii++) {
if (empty($old_back[$ii])) {
$old_back[$ii] = $cursor;
} else {
$cursor = $old_back[$ii];
}
}
$cursor = 1;
for ($ii = 1; $ii <= $max_new_line; $ii++) {
if (empty($new_back[$ii])) {
$new_back[$ii] = $cursor;
} else {
$cursor = $new_back[$ii];
}
}
return array($old_back, $new_back);
} | Build maps from lines comments appear on to actual lines. | buildLineBackmaps | php | phacility/phabricator | src/applications/differential/parser/DifferentialChangesetParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialChangesetParser.php | Apache-2.0 |
private function getMinimumBucketCacheKey() {
$limit_key = $this->getLimitKey();
return "limit:min:{$limit_key}";
} | Get the APC key for the smallest stored bucket.
@return string APC key for the smallest stored bucket.
@task ratelimit | getMinimumBucketCacheKey | php | phacility/phabricator | support/startup/PhabricatorClientLimit.php | https://github.com/phacility/phabricator/blob/master/support/startup/PhabricatorClientLimit.php | Apache-2.0 |
private function getCurrentBucketID() {
return (int)(time() / $this->getBucketDuration());
} | Get the current bucket ID for storing rate limit scores.
@return int The current bucket ID. | getCurrentBucketID | php | phacility/phabricator | support/startup/PhabricatorClientLimit.php | https://github.com/phacility/phabricator/blob/master/support/startup/PhabricatorClientLimit.php | Apache-2.0 |
private function getBucketCacheKey($bucket_id) {
$limit_key = $this->getLimitKey();
return "limit:bucket:{$limit_key}:{$bucket_id}";
} | Get the APC key for a given bucket.
@param int Bucket to get the key for.
@return string APC key for the bucket. | getBucketCacheKey | php | phacility/phabricator | support/startup/PhabricatorClientLimit.php | https://github.com/phacility/phabricator/blob/master/support/startup/PhabricatorClientLimit.php | Apache-2.0 |
private function addScore($score) {
$is_apcu = (bool)function_exists('apcu_fetch');
$current = $this->getCurrentBucketID();
$bucket_key = $this->getBucketCacheKey($current);
// There's a bit of a race here, if a second process reads the bucket
// before this one writes it, but it's fine if we occasionally fail to
// record a client's score. If they're making requests fast enough to hit
// rate limiting, we'll get them soon enough.
if ($is_apcu) {
$bucket = apcu_fetch($bucket_key);
} else {
$bucket = apc_fetch($bucket_key);
}
if (!is_array($bucket)) {
$bucket = array();
}
$client_key = $this->getClientKey();
if (empty($bucket[$client_key])) {
$bucket[$client_key] = 0;
}
$bucket[$client_key] += $score;
if ($is_apcu) {
@apcu_store($bucket_key, $bucket);
} else {
@apc_store($bucket_key, $bucket);
}
return $this;
} | Add points to the rate limit score for some client.
@param string Some key which identifies the client making the request.
@param float The cost for this request; more points pushes them toward
the limit faster.
@return this | addScore | php | phacility/phabricator | support/startup/PhabricatorClientLimit.php | https://github.com/phacility/phabricator/blob/master/support/startup/PhabricatorClientLimit.php | Apache-2.0 |
private function getScore() {
$is_apcu = (bool)function_exists('apcu_fetch');
// Identify the oldest bucket stored in APC.
$min_key = $this->getMinimumBucketCacheKey();
if ($is_apcu) {
$min = apcu_fetch($min_key);
} else {
$min = apc_fetch($min_key);
}
// If we don't have any buckets stored yet, store the current bucket as
// the oldest bucket.
$cur = $this->getCurrentBucketID();
if (!$min) {
if ($is_apcu) {
@apcu_store($min_key, $cur);
} else {
@apc_store($min_key, $cur);
}
$min = $cur;
}
// Destroy any buckets that are older than the minimum bucket we're keeping
// track of. Under load this normally shouldn't do anything, but will clean
// up an old bucket once per minute.
$count = $this->getBucketCount();
for ($cursor = $min; $cursor < ($cur - $count); $cursor++) {
$bucket_key = $this->getBucketCacheKey($cursor);
if ($is_apcu) {
apcu_delete($bucket_key);
@apcu_store($min_key, $cursor + 1);
} else {
apc_delete($bucket_key);
@apc_store($min_key, $cursor + 1);
}
}
$client_key = $this->getClientKey();
// Now, sum up the client's scores in all of the active buckets.
$score = 0;
for (; $cursor <= $cur; $cursor++) {
$bucket_key = $this->getBucketCacheKey($cursor);
if ($is_apcu) {
$bucket = apcu_fetch($bucket_key);
} else {
$bucket = apc_fetch($bucket_key);
}
if (isset($bucket[$client_key])) {
$score += $bucket[$client_key];
}
}
return $score;
} | Get the current rate limit score for a given client.
@return float The client's current score.
@task ratelimit | getScore | php | phacility/phabricator | support/startup/PhabricatorClientLimit.php | https://github.com/phacility/phabricator/blob/master/support/startup/PhabricatorClientLimit.php | Apache-2.0 |
protected function getParameterExists(AphrontRequest $request, $key) {
return $request->getExists($key);
} | Test if a parameter exists in a request.
See @{method:getExists}. By default, this method tests if the key is
present in the request.
To call another type's behavior in order to perform this check, use
@{method:getExistsWithType}.
@param AphrontRequest The incoming request.
@param string The key to examine.
@return bool True if a readable value is present in the request.
@task impl | getParameterExists | php | phacility/phabricator | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phacility/phabricator/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
protected function getParameterDefault() {
return null;
} | Return the default value for this parameter type.
See @{method:getDefaultValue}. If unspecified, the default is `null`.
@return wild Default value.
@task impl | getParameterDefault | php | phacility/phabricator | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phacility/phabricator/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
public function request($method, $url, $params=null)
{
if (!$params)
$params = array();
list($rbody, $rcode, $myApiKey) =
$this->_requestRaw($method, $url, $params);
$resp = $this->_interpretResponse($rbody, $rcode);
return array($resp, $myApiKey);
} | @param string $method
@param string $url
@param array|null $params
@return array An array whose first element is the response and second
element is the API key used to make the request. | request | php | phacility/phabricator | externals/stripe-php/lib/Stripe/ApiRequestor.php | https://github.com/phacility/phabricator/blob/master/externals/stripe-php/lib/Stripe/ApiRequestor.php | Apache-2.0 |
private function checkSslCert($url)
{
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
error_log(
'Warning: This version of PHP is too old to check SSL certificates '.
'correctly. Stripe cannot guarantee that the server has a '.
'certificate which is not blacklisted'
);
return true;
}
if (strpos(PHP_VERSION, 'hiphop') !== false) {
error_log(
'Warning: HHVM does not support Stripe\'s SSL certificate '.
'verification. (See http://docs.hhvm.com/manual/en/context.ssl.php) '.
'Stripe cannot guarantee that the server has a certificate which is '.
'not blacklisted'
);
return true;
}
$url = parse_url($url);
$port = isset($url["port"]) ? $url["port"] : 443;
$url = "ssl://{$url["host"]}:{$port}";
$sslContext = stream_context_create(
array('ssl' => array(
'capture_peer_cert' => true,
'verify_peer' => true,
'cafile' => $this->caBundle(),
))
);
$result = stream_socket_client(
$url, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $sslContext
);
if ($errno !== 0) {
$apiBase = Stripe::$apiBase;
throw new Stripe_ApiConnectionError(
'Could not connect to Stripe (' . $apiBase . '). Please check your '.
'internet connection and try again. If this problem persists, '.
'you should check Stripe\'s service status at '.
'https://twitter.com/stripestatus. Reason was: '.$errstr
);
}
$params = stream_context_get_params($result);
$cert = $params['options']['ssl']['peer_certificate'];
openssl_x509_export($cert, $pemCert);
if (self::isBlackListed($pemCert)) {
throw new Stripe_ApiConnectionError(
'Invalid server certificate. You tried to connect to a server that '.
'has a revoked SSL certificate, which means we cannot securely send '.
'data to that server. Please email [email protected] if you need '.
'help connecting to the correct API server.'
);
}
return true;
} | Preflight the SSL certificate presented by the backend. This isn't 100%
bulletproof, in that we're not actually validating the transport used to
communicate with Stripe, merely that the first attempt to does not use a
revoked certificate.
Unfortunately the interface to OpenSSL doesn't make it easy to check the
certificate before sending potentially sensitive data on the wire. This
approach raises the bar for an attacker significantly. | checkSslCert | php | phacility/phabricator | externals/stripe-php/lib/Stripe/ApiRequestor.php | https://github.com/phacility/phabricator/blob/master/externals/stripe-php/lib/Stripe/ApiRequestor.php | Apache-2.0 |
public static function getTimestamps(
PhabricatorUser $user,
$start_day_str,
$days) {
$objects = self::getStartDateTimeObjects($user, $start_day_str);
$start_day = $objects['start_day'];
$timestamps = array();
for ($day = 0; $day < $days; $day++) {
$timestamp = clone $start_day;
$timestamp->modify(sprintf('+%d days', $day));
$timestamps[] = $timestamp;
}
return array(
'today' => $objects['today'],
'epoch_stamps' => $timestamps,
);
} | Public for testing purposes only. You should probably use one of the
functions above. | getTimestamps | php | phacility/phabricator | src/applications/calendar/util/CalendarTimeUtil.php | https://github.com/phacility/phabricator/blob/master/src/applications/calendar/util/CalendarTimeUtil.php | Apache-2.0 |
public function getHasAnyChanges() {
return $this->getHasChanges('any');
} | Returns true if the hunks change anything, including whitespace. | getHasAnyChanges | php | phacility/phabricator | src/applications/differential/parser/DifferentialHunkParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialHunkParser.php | Apache-2.0 |
public function reparseHunksForSpecialAttributes() {
$rebuild_old = array();
$rebuild_new = array();
$old_lines = array_reverse($this->getOldLines());
$new_lines = array_reverse($this->getNewLines());
while (count($old_lines) || count($new_lines)) {
$old_line_data = array_pop($old_lines);
$new_line_data = array_pop($new_lines);
if ($old_line_data) {
$o_type = $old_line_data['type'];
} else {
$o_type = null;
}
if ($new_line_data) {
$n_type = $new_line_data['type'];
} else {
$n_type = null;
}
// This line does not exist in the new file.
if (($o_type != null) && ($n_type == null)) {
$rebuild_old[] = $old_line_data;
$rebuild_new[] = null;
if ($new_line_data) {
array_push($new_lines, $new_line_data);
}
continue;
}
// This line does not exist in the old file.
if (($n_type != null) && ($o_type == null)) {
$rebuild_old[] = null;
$rebuild_new[] = $new_line_data;
if ($old_line_data) {
array_push($old_lines, $old_line_data);
}
continue;
}
$rebuild_old[] = $old_line_data;
$rebuild_new[] = $new_line_data;
}
$this->setOldLines($rebuild_old);
$this->setNewLines($rebuild_new);
$this->updateChangeTypesForNormalization();
return $this;
} | This function takes advantage of the parsing work done in
@{method:parseHunksForLineData} and continues the struggle to hammer this
data into something we can display to a user.
In particular, this function re-parses the hunks to make them equivalent
in length for easy rendering, adding `null` as necessary to pad the
length.
Anyhoo, this function is not particularly well-named but I try.
NOTE: this function must be called after
@{method:parseHunksForLineData}. | reparseHunksForSpecialAttributes | php | phacility/phabricator | src/applications/differential/parser/DifferentialHunkParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/differential/parser/DifferentialHunkParser.php | Apache-2.0 |
function phid_get_type($phid) {
$matches = null;
if (is_string($phid) && preg_match('/^PHID-([^-]{4})-/', $phid, $matches)) {
return $matches[1];
}
return PhabricatorPHIDConstants::PHID_TYPE_UNKNOWN;
} | Look up the type of a PHID. Returns
PhabricatorPHIDConstants::PHID_TYPE_UNKNOWN if it fails to look up the type
@param phid Anything.
@return string A value from PhabricatorPHIDConstants (ideally) | phid_get_type | php | phacility/phabricator | src/applications/phid/utils.php | https://github.com/phacility/phabricator/blob/master/src/applications/phid/utils.php | Apache-2.0 |
private function authenticateUser(
ConduitAPIRequest $api_request,
array $metadata,
$method) {
$request = $this->getRequest();
if ($request->getUser()->getPHID()) {
$request->validateCSRF();
return $this->validateAuthenticatedUser(
$api_request,
$request->getUser());
}
$auth_type = idx($metadata, 'auth.type');
if ($auth_type === ConduitClient::AUTH_ASYMMETRIC) {
$host = idx($metadata, 'auth.host');
if (!$host) {
return array(
'ERR-INVALID-AUTH',
pht(
'Request is missing required "%s" parameter.',
'auth.host'),
);
}
// TODO: Validate that we are the host!
$raw_key = idx($metadata, 'auth.key');
$public_key = PhabricatorAuthSSHPublicKey::newFromRawKey($raw_key);
$ssl_public_key = $public_key->toPKCS8();
// First, verify the signature.
try {
$protocol_data = $metadata;
ConduitClient::verifySignature(
$method,
$api_request->getAllParameters(),
$protocol_data,
$ssl_public_key);
} catch (Exception $ex) {
return array(
'ERR-INVALID-AUTH',
pht(
'Signature verification failure. %s',
$ex->getMessage()),
);
}
// If the signature is valid, find the user or device which is
// associated with this public key.
$stored_key = id(new PhabricatorAuthSSHKeyQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withKeys(array($public_key))
->withIsActive(true)
->executeOne();
if (!$stored_key) {
$key_summary = id(new PhutilUTF8StringTruncator())
->setMaximumBytes(64)
->truncateString($raw_key);
return array(
'ERR-INVALID-AUTH',
pht(
'No user or device is associated with the public key "%s".',
$key_summary),
);
}
$object = $stored_key->getObject();
if ($object instanceof PhabricatorUser) {
$user = $object;
} else {
if ($object->isDisabled()) {
return array(
'ERR-INVALID-AUTH',
pht(
'The key which signed this request is associated with a '.
'disabled device ("%s").',
$object->getName()),
);
}
if (!$stored_key->getIsTrusted()) {
return array(
'ERR-INVALID-AUTH',
pht(
'The key which signed this request is not trusted. Only '.
'trusted keys can be used to sign API calls.'),
);
}
if (!PhabricatorEnv::isClusterRemoteAddress()) {
return array(
'ERR-INVALID-AUTH',
pht(
'This request originates from outside of the cluster address '.
'range. Requests signed with trusted device keys must '.
'originate from within the cluster.'),
);
}
$user = PhabricatorUser::getOmnipotentUser();
// Flag this as an intracluster request.
$api_request->setIsClusterRequest(true);
}
return $this->validateAuthenticatedUser(
$api_request,
$user);
} else if ($auth_type === null) {
// No specified authentication type, continue with other authentication
// methods below.
} else {
return array(
'ERR-INVALID-AUTH',
pht(
'Provided "%s" ("%s") is not recognized.',
'auth.type',
$auth_type),
);
}
$token_string = idx($metadata, 'token');
if ($token_string !== null && strlen($token_string)) {
if (strlen($token_string) != 32) {
return array(
'ERR-INVALID-AUTH',
pht(
'API token "%s" has the wrong length. API tokens should be '.
'32 characters long.',
$token_string),
);
}
$type = head(explode('-', $token_string));
$valid_types = PhabricatorConduitToken::getAllTokenTypes();
$valid_types = array_fuse($valid_types);
if (empty($valid_types[$type])) {
return array(
'ERR-INVALID-AUTH',
pht(
'API token "%s" has the wrong format. API tokens should be '.
'32 characters long and begin with one of these prefixes: %s.',
$token_string,
implode(', ', $valid_types)),
);
}
$token = id(new PhabricatorConduitTokenQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withTokens(array($token_string))
->withExpired(false)
->executeOne();
if (!$token) {
$token = id(new PhabricatorConduitTokenQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withTokens(array($token_string))
->withExpired(true)
->executeOne();
if ($token) {
return array(
'ERR-INVALID-AUTH',
pht(
'API token "%s" was previously valid, but has expired.',
$token_string),
);
} else {
return array(
'ERR-INVALID-AUTH',
pht(
'API token "%s" is not valid.',
$token_string),
);
}
}
// If this is a "cli-" token, it expires shortly after it is generated
// by default. Once it is actually used, we extend its lifetime and make
// it permanent. This allows stray tokens to get cleaned up automatically
// if they aren't being used.
if ($token->getTokenType() == PhabricatorConduitToken::TYPE_COMMANDLINE) {
if ($token->getExpires()) {
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$token->setExpires(null);
$token->save();
unset($unguarded);
}
}
// If this is a "clr-" token, Phabricator must be configured in cluster
// mode and the remote address must be a cluster node.
if ($token->getTokenType() == PhabricatorConduitToken::TYPE_CLUSTER) {
if (!PhabricatorEnv::isClusterRemoteAddress()) {
return array(
'ERR-INVALID-AUTH',
pht(
'This request originates from outside of the cluster address '.
'range. Requests signed with cluster API tokens must '.
'originate from within the cluster.'),
);
}
// Flag this as an intracluster request.
$api_request->setIsClusterRequest(true);
}
$user = $token->getObject();
if (!($user instanceof PhabricatorUser)) {
return array(
'ERR-INVALID-AUTH',
pht('API token is not associated with a valid user.'),
);
}
return $this->validateAuthenticatedUser(
$api_request,
$user);
}
$access_token = idx($metadata, 'access_token');
if ($access_token) {
$token = id(new PhabricatorOAuthServerAccessToken())
->loadOneWhere('token = %s', $access_token);
if (!$token) {
return array(
'ERR-INVALID-AUTH',
pht('Access token does not exist.'),
);
}
$oauth_server = new PhabricatorOAuthServer();
$authorization = $oauth_server->authorizeToken($token);
if (!$authorization) {
return array(
'ERR-INVALID-AUTH',
pht('Access token is invalid or expired.'),
);
}
$user = id(new PhabricatorPeopleQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs(array($token->getUserPHID()))
->executeOne();
if (!$user) {
return array(
'ERR-INVALID-AUTH',
pht('Access token is for invalid user.'),
);
}
$ok = $this->authorizeOAuthMethodAccess($authorization, $method);
if (!$ok) {
return array(
'ERR-OAUTH-ACCESS',
pht('You do not have authorization to call this method.'),
);
}
$api_request->setOAuthToken($token);
return $this->validateAuthenticatedUser(
$api_request,
$user);
}
// For intracluster requests, use a public user if no authentication
// information is provided. We could do this safely for any request,
// but making the API fully public means there's no way to disable badly
// behaved clients.
if (PhabricatorEnv::isClusterRemoteAddress()) {
if (PhabricatorEnv::getEnvConfig('policy.allow-public')) {
$api_request->setIsClusterRequest(true);
$user = new PhabricatorUser();
return $this->validateAuthenticatedUser(
$api_request,
$user);
}
}
// Handle sessionless auth.
// TODO: This is super messy.
// TODO: Remove this in favor of token-based auth.
if (isset($metadata['authUser'])) {
$user = id(new PhabricatorUser())->loadOneWhere(
'userName = %s',
$metadata['authUser']);
if (!$user) {
return array(
'ERR-INVALID-AUTH',
pht('Authentication is invalid.'),
);
}
$token = idx($metadata, 'authToken');
$signature = idx($metadata, 'authSignature');
$certificate = $user->getConduitCertificate();
$hash = sha1($token.$certificate);
if (!phutil_hashes_are_identical($hash, $signature)) {
return array(
'ERR-INVALID-AUTH',
pht('Authentication is invalid.'),
);
}
return $this->validateAuthenticatedUser(
$api_request,
$user);
}
// Handle session-based auth.
// TODO: Remove this in favor of token-based auth.
$session_key = idx($metadata, 'sessionKey');
if (!$session_key) {
return array(
'ERR-INVALID-SESSION',
pht('Session key is not present.'),
);
}
$user = id(new PhabricatorAuthSessionEngine())
->loadUserForSession(PhabricatorAuthSession::TYPE_CONDUIT, $session_key);
if (!$user) {
return array(
'ERR-INVALID-SESSION',
pht('Session key is invalid.'),
);
}
return $this->validateAuthenticatedUser(
$api_request,
$user);
} | Authenticate the client making the request to a Phabricator user account.
@param ConduitAPIRequest Request being executed.
@param dict Request metadata.
@return null|pair Null to indicate successful authentication, or
an error code and error message pair. | authenticateUser | php | phacility/phabricator | src/applications/conduit/controller/PhabricatorConduitAPIController.php | https://github.com/phacility/phabricator/blob/master/src/applications/conduit/controller/PhabricatorConduitAPIController.php | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.