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 static function getInstance() {
return self::$instance;
} | Return on instance of AphrontWriteGuard if it's active, or null
@return AphrontWriteGuard|null | getInstance | php | phacility/phabricator | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phacility/phabricator/blob/master/src/aphront/writeguard/AphrontWriteGuard.php | Apache-2.0 |
public static function willWrite() {
if (!self::$instance) {
if (!self::$allowUnguardedWrites) {
throw new Exception(
pht(
'Unguarded write! There must be an active %s to perform writes.',
__CLASS__));
} else {
// Unguarded writes are being allowed unconditionally.
return;
}
}
$instance = self::$instance;
if ($instance->allowDepth == 0) {
call_user_func($instance->callback);
}
} | Declare intention to perform a write, validating that writes are allowed.
You should call this method before executing a write whenever you implement
a new storage engine where information can be permanently kept.
Writes are permitted if:
- The request has valid CSRF tokens.
- Unguarded writes have been temporarily enabled by a call to
@{method:beginUnguardedWrites}.
- All write guarding has been disabled with
@{method:allowDangerousUnguardedWrites}.
If none of these conditions are true, this method will throw and prevent
the write.
@return void
@task protect | willWrite | php | phacility/phabricator | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phacility/phabricator/blob/master/src/aphront/writeguard/AphrontWriteGuard.php | Apache-2.0 |
public static function endUnguardedWrites() {
if (!self::$instance) {
return;
}
if (self::$instance->allowDepth <= 0) {
throw new Exception(
pht(
'Imbalanced %s: more %s calls than %s calls.',
__CLASS__,
'endUnguardedWrites()',
'beginUnguardedWrites()'));
}
self::$instance->allowDepth--;
} | Declare that you have finished performing unguarded writes. You must
call this exactly once for each call to @{method:beginUnguardedWrites}.
@return void
@task disable | endUnguardedWrites | php | phacility/phabricator | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phacility/phabricator/blob/master/src/aphront/writeguard/AphrontWriteGuard.php | Apache-2.0 |
public static function allowDangerousUnguardedWrites($allow) {
if (self::$instance) {
throw new Exception(
pht(
'You can not unconditionally disable %s by calling %s while a write '.
'guard is active. Use %s to temporarily allow unguarded writes.',
__CLASS__,
__FUNCTION__.'()',
'beginUnguardedWrites()'));
}
self::$allowUnguardedWrites = true;
} | Allow execution of unguarded writes. This is ONLY appropriate for use in
script contexts or other contexts where you are guaranteed to never be
vulnerable to CSRF concerns. Calling this method is EXTREMELY DANGEROUS
if you do not understand the consequences.
If you need to perform unguarded writes on an otherwise guarded workflow
which is vulnerable to CSRF, use @{method:beginUnguardedWrites}.
@return void
@task disable | allowDangerousUnguardedWrites | php | phacility/phabricator | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phacility/phabricator/blob/master/src/aphront/writeguard/AphrontWriteGuard.php | Apache-2.0 |
private function generateDataURI($resource_name) {
$ext = last(explode('.', $resource_name));
switch ($ext) {
case 'png':
$type = 'image/png';
break;
case 'gif':
$type = 'image/gif';
break;
case 'jpg':
$type = 'image/jpeg';
break;
default:
return null;
}
// In IE8, 32KB is the maximum supported URI length.
$maximum_data_size = (1024 * 32);
$data = $this->celerityMap->getResourceDataForName($resource_name);
if (strlen($data) >= $maximum_data_size) {
// If the data is already too large on its own, just bail before
// encoding it.
return null;
}
$uri = 'data:'.$type.';base64,'.base64_encode($data);
if (strlen($uri) >= $maximum_data_size) {
return null;
}
return $uri;
} | Attempt to generate a data URI for a resource. We'll generate a data URI
if the resource is a valid resource of an appropriate type, and is
small enough. Otherwise, this method will return `null` and we'll end up
using a normal URI instead.
@param string Resource name to attempt to generate a data URI for.
@return string|null Data URI, or null if we declined to generate one. | generateDataURI | php | phacility/phabricator | src/applications/celerity/CelerityResourceTransformer.php | https://github.com/phacility/phabricator/blob/master/src/applications/celerity/CelerityResourceTransformer.php | Apache-2.0 |
public function getAllHostsForRole($role) {
// if the role is explicitly set to false at the top level, then all hosts
// have the role disabled.
if (idx($this->config, $role) === false) {
return array();
}
$hosts = array();
foreach ($this->hosts as $host) {
if ($host->hasRole($role)) {
$hosts[] = $host;
}
}
return $hosts;
} | Get all configured hosts for this service which have the specified role.
@return PhabricatorSearchHost[] | getAllHostsForRole | php | phacility/phabricator | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
public static function getAllServices() {
$cache = PhabricatorCaches::getRequestCache();
$refs = $cache->getKey(self::KEY_REFS);
if (!$refs) {
$refs = self::newRefs();
$cache->setKey(self::KEY_REFS, $refs);
}
return $refs;
} | Get a reference to all configured fulltext search cluster services
@return PhabricatorSearchService[] | getAllServices | php | phacility/phabricator | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
public static function loadAllFulltextStorageEngines() {
return id(new PhutilClassMapQuery())
->setAncestorClass('PhabricatorFulltextStorageEngine')
->setUniqueMethod('getEngineIdentifier')
->execute();
} | Load all valid PhabricatorFulltextStorageEngine subclasses | loadAllFulltextStorageEngines | php | phacility/phabricator | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
public static function executeSearch(PhabricatorSavedQuery $query) {
$result_set = self::newResultSet($query);
return $result_set->getPHIDs();
} | Execute a full-text query and return a list of PHIDs of matching objects.
@return string[]
@throws PhutilAggregateException | executeSearch | php | phacility/phabricator | src/infrastructure/cluster/search/PhabricatorSearchService.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/cluster/search/PhabricatorSearchService.php | Apache-2.0 |
private function determineMode() {
$request = $this->getRequest();
$mode = self::UNSELECTED_MODE;
if ($request->isAjax()) {
$mode = self::SELECTED_MODE;
}
return $mode;
} | Two main modes of operation...
1 - /conpherence/ - UNSELECTED_MODE
2 - /conpherence/<id>/ - SELECTED_MODE
UNSELECTED_MODE is not an Ajax request while the other two are Ajax
requests. | determineMode | php | phacility/phabricator | src/applications/conpherence/controller/ConpherenceListController.php | https://github.com/phacility/phabricator/blob/master/src/applications/conpherence/controller/ConpherenceListController.php | Apache-2.0 |
public function getCustomRuleValues($rule_class) {
$values = array();
foreach ($this->getRules() as $rule) {
if ($rule['rule'] == $rule_class) {
$values[] = $rule['value'];
}
}
return $values;
} | Return a list of all values used by a given rule class to implement this
policy. This is used to bulk load data (like project memberships) in order
to apply policy filters efficiently.
@param string Policy rule classname.
@return list<wild> List of values used in this policy. | getCustomRuleValues | php | phacility/phabricator | src/applications/policy/storage/PhabricatorPolicy.php | https://github.com/phacility/phabricator/blob/master/src/applications/policy/storage/PhabricatorPolicy.php | Apache-2.0 |
public function isStrongerThan(PhabricatorPolicy $other) {
$this_policy = $this->getPHID();
$other_policy = $other->getPHID();
$strengths = array(
PhabricatorPolicies::POLICY_PUBLIC => -2,
PhabricatorPolicies::POLICY_USER => -1,
// (Default policies have strength 0.)
PhabricatorPolicies::POLICY_NOONE => 1,
);
$this_strength = idx($strengths, $this_policy, 0);
$other_strength = idx($strengths, $other_policy, 0);
return ($this_strength > $other_strength);
} | Return `true` if this policy is stronger (more restrictive) than some
other policy.
Because policies are complicated, determining which policies are
"stronger" is not trivial. This method uses a very coarse working
definition of policy strength which is cheap to compute, unambiguous,
and intuitive in the common cases.
This method returns `true` if the //class// of this policy is stronger
than the other policy, even if the policies are (or might be) the same in
practice. For example, "Members of Project X" is considered a stronger
policy than "All Users", even though "Project X" might (in some rare
cases) contain every user.
Generally, the ordering here is:
- Public
- All Users
- (Everything Else)
- No One
In the "everything else" bucket, we can't make any broad claims about
which policy is stronger (and we especially can't make those claims
cheaply).
Even if we fully evaluated each policy, the two policies might be
"Members of X" and "Members of Y", each of which permits access to some
set of unique users. In this case, neither is strictly stronger than
the other.
@param PhabricatorPolicy Other policy.
@return bool `true` if this policy is more restrictive than the other
policy. | isStrongerThan | php | phacility/phabricator | src/applications/policy/storage/PhabricatorPolicy.php | https://github.com/phacility/phabricator/blob/master/src/applications/policy/storage/PhabricatorPolicy.php | Apache-2.0 |
private function resolveSubversionRefs() {
$repository = $this->getRepository();
$max_commit = id(new PhabricatorRepositoryCommit())
->loadOneWhere(
'repositoryID = %d ORDER BY epoch DESC, id DESC LIMIT 1',
$repository->getID());
if (!$max_commit) {
// This repository is empty or hasn't parsed yet, so none of the refs are
// going to resolve.
return array();
}
$max_commit_id = (int)$max_commit->getCommitIdentifier();
$results = array();
foreach ($this->refs as $ref) {
if ($ref == 'HEAD') {
// Resolve "HEAD" to mean "the most recent commit".
$results[$ref][] = array(
'type' => 'commit',
'identifier' => $max_commit_id,
);
continue;
}
if (!preg_match('/^\d+$/', $ref)) {
// This ref is non-numeric, so it doesn't resolve to anything.
continue;
}
// Resolve other commits if we can deduce their existence.
// TODO: When we import only part of a repository, we won't necessarily
// have all of the smaller commits. Should we fail to resolve them here
// for repositories with a subpath? It might let us simplify other things
// elsewhere.
if ((int)$ref <= $max_commit_id) {
$results[$ref][] = array(
'type' => 'commit',
'identifier' => (int)$ref,
);
}
}
return $results;
} | Resolve refs in Subversion repositories.
We can resolve all numeric identifiers and the keyword `HEAD`. | resolveSubversionRefs | php | phacility/phabricator | src/applications/diffusion/query/DiffusionCachedResolveRefsQuery.php | https://github.com/phacility/phabricator/blob/master/src/applications/diffusion/query/DiffusionCachedResolveRefsQuery.php | Apache-2.0 |
protected function willUseSavedQuery(PhabricatorSavedQuery $saved) {
return;
} | Hook for subclasses to adjust saved queries prior to use.
If an application changes how queries are saved, it can implement this
hook to keep old queries working the way users expect, by reading,
adjusting, and overwriting parameters.
@param PhabricatorSavedQuery Saved query which will be executed.
@return void | willUseSavedQuery | php | phacility/phabricator | src/applications/search/engine/PhabricatorApplicationSearchEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/engine/PhabricatorApplicationSearchEngine.php | Apache-2.0 |
protected function getHiddenFields() {
return array();
} | Return a list of field keys which should be hidden from the viewer.
@return list<string> Fields to hide. | getHiddenFields | php | phacility/phabricator | src/applications/search/engine/PhabricatorApplicationSearchEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/engine/PhabricatorApplicationSearchEngine.php | Apache-2.0 |
public function getQueryResultsPageURI($query_key) {
return $this->getURI('query/'.$query_key.'/');
} | Return an application URI corresponding to the results page of a query.
Normally, this is something like `/application/query/QUERYKEY/`.
@param string The query key to build a URI for.
@return string URI where the query can be executed.
@task uri | getQueryResultsPageURI | php | phacility/phabricator | src/applications/search/engine/PhabricatorApplicationSearchEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/engine/PhabricatorApplicationSearchEngine.php | Apache-2.0 |
public function getQueryManagementURI() {
return $this->getURI('query/edit/');
} | Return an application URI for query management. This is used when, e.g.,
a query deletion operation is cancelled.
@return string URI where queries can be managed.
@task uri | getQueryManagementURI | php | phacility/phabricator | src/applications/search/engine/PhabricatorApplicationSearchEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/engine/PhabricatorApplicationSearchEngine.php | Apache-2.0 |
public static function getAllEngines() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->execute();
} | Load all available application search engines.
@return list<PhabricatorApplicationSearchEngine> All available engines.
@task construct | getAllEngines | php | phacility/phabricator | src/applications/search/engine/PhabricatorApplicationSearchEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/engine/PhabricatorApplicationSearchEngine.php | Apache-2.0 |
public static function getEngineByClassName($class_name) {
return idx(self::getAllEngines(), $class_name);
} | Get an engine by class name, if it exists.
@return PhabricatorApplicationSearchEngine|null Engine, or null if it does
not exist.
@task construct | getEngineByClassName | php | phacility/phabricator | src/applications/search/engine/PhabricatorApplicationSearchEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/engine/PhabricatorApplicationSearchEngine.php | Apache-2.0 |
protected function readSubscribersFromRequest(
AphrontRequest $request,
$key) {
return $this->readUsersFromRequest(
$request,
$key,
array(
PhabricatorProjectProjectPHIDType::TYPECONST,
));
} | Read a list of subscribers from a request in a flexible way.
@param AphrontRequest Request to read PHIDs from.
@param string Key to read in the request.
@return list<phid> List of object PHIDs.
@task read | readSubscribersFromRequest | php | phacility/phabricator | src/applications/search/engine/PhabricatorApplicationSearchEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/engine/PhabricatorApplicationSearchEngine.php | Apache-2.0 |
protected function readListFromRequest(
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. | readListFromRequest | php | phacility/phabricator | src/applications/search/engine/PhabricatorApplicationSearchEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/search/engine/PhabricatorApplicationSearchEngine.php | Apache-2.0 |
public function isCreateable() {
return true;
} | Can users create new credentials of this type?
@return bool True if new credentials of this type can be created. | isCreateable | php | phacility/phabricator | src/applications/passphrase/credentialtype/PassphraseCredentialType.php | https://github.com/phacility/phabricator/blob/master/src/applications/passphrase/credentialtype/PassphraseCredentialType.php | Apache-2.0 |
public function shouldShowPasswordField() {
return false;
} | Return true to show an additional "Password" field. This is used by
SSH credentials to strip passwords off private keys.
@return bool True if a password field should be shown to the user.
@task password | shouldShowPasswordField | php | phacility/phabricator | src/applications/passphrase/credentialtype/PassphraseCredentialType.php | https://github.com/phacility/phabricator/blob/master/src/applications/passphrase/credentialtype/PassphraseCredentialType.php | Apache-2.0 |
public function getPasswordLabel() {
return pht('Password');
} | Return the label for the password field, if one is shown.
@return string Human-readable field label.
@task password | getPasswordLabel | php | phacility/phabricator | src/applications/passphrase/credentialtype/PassphraseCredentialType.php | https://github.com/phacility/phabricator/blob/master/src/applications/passphrase/credentialtype/PassphraseCredentialType.php | Apache-2.0 |
public function getUser() {
if (!$this->user) {
throw new Exception(
pht(
'You can not access the user inside the implementation of a Conduit '.
'method which does not require authentication (as per %s).',
'shouldRequireAuthentication()'));
}
return $this->user;
} | Retrieve the authentic identity of the user making the request. If a
method requires authentication (the default) the user object will always
be available. If a method does not require authentication (i.e., overrides
shouldRequireAuthentication() to return false) the user object will NEVER
be available.
@return PhabricatorUser Authentic user, available ONLY if the method
requires authentication. | getUser | php | phacility/phabricator | src/applications/conduit/protocol/ConduitAPIRequest.php | https://github.com/phacility/phabricator/blob/master/src/applications/conduit/protocol/ConduitAPIRequest.php | Apache-2.0 |
private function getProvidesAndRequires($name, $data) {
$parser = new PhutilDocblockParser();
$matches = array();
$ok = preg_match('@/[*][*].*?[*]/@s', $data, $matches);
if (!$ok) {
throw new Exception(
pht(
'Resource "%s" does not have a header doc comment. Encode '.
'dependency data in a header docblock.',
$name));
}
list($description, $metadata) = $parser->parse($matches[0]);
$provides = $this->parseResourceSymbolList(idx($metadata, 'provides'));
$requires = $this->parseResourceSymbolList(idx($metadata, 'requires'));
if (!$provides) {
// Tests and documentation-only JS is permitted to @provide no targets.
return array(null, null);
}
if (count($provides) > 1) {
throw new Exception(
pht(
'Resource "%s" must %s at most one Celerity target.',
$name,
'@provide'));
}
return array(head($provides), $requires);
} | Parse the `@provides` and `@requires` symbols out of a text resource, like
JS or CSS.
@param string Resource name.
@param string Resource data.
@return pair<string|null, list<string>|null> The `@provides` symbol and
the list of `@requires` symbols. If the resource is not part of the
dependency graph, both are null. | getProvidesAndRequires | php | phacility/phabricator | src/applications/celerity/CelerityResourceMapGenerator.php | https://github.com/phacility/phabricator/blob/master/src/applications/celerity/CelerityResourceMapGenerator.php | Apache-2.0 |
public function setFetchAllBoards($fetch_all) {
$this->fetchAllBoards = $fetch_all;
return $this;
} | Fetch all boards, even if the board is disabled. | setFetchAllBoards | php | phacility/phabricator | src/applications/project/engine/PhabricatorBoardLayoutEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/project/engine/PhabricatorBoardLayoutEngine.php | Apache-2.0 |
public static function isEmailVerificationRequired() {
// NOTE: Configuring required email domains implies required verification.
return PhabricatorEnv::getEnvConfig('auth.require-email-verification') ||
PhabricatorEnv::getEnvConfig('auth.email-domains');
} | Check if this install requires email verification.
@return bool True if email addresses must be verified.
@task restrictions | isEmailVerificationRequired | php | phacility/phabricator | src/applications/people/storage/PhabricatorUserEmail.php | https://github.com/phacility/phabricator/blob/master/src/applications/people/storage/PhabricatorUserEmail.php | Apache-2.0 |
public function sendVerificationEmail(PhabricatorUser $user) {
$username = $user->getUsername();
$address = $this->getAddress();
$link = PhabricatorEnv::getProductionURI($this->getVerificationURI());
$is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');
$signature = null;
if (!$is_serious) {
$signature = pht(
"Get Well Soon,\n%s",
PlatformSymbols::getPlatformServerName());
}
$body = sprintf(
"%s\n\n%s\n\n %s\n\n%s",
pht('Hi %s', $username),
pht(
'Please verify that you own this email address (%s) by '.
'clicking this link:',
$address),
$link,
$signature);
id(new PhabricatorMetaMTAMail())
->addRawTos(array($address))
->setForceDelivery(true)
->setSubject(
pht(
'[%s] Email Verification',
PlatformSymbols::getPlatformServerName()))
->setBody($body)
->setRelatedPHID($user->getPHID())
->saveAndSend();
return $this;
} | Send a verification email from $user to this address.
@param PhabricatorUser The user sending the verification.
@return this
@task email | sendVerificationEmail | php | phacility/phabricator | src/applications/people/storage/PhabricatorUserEmail.php | https://github.com/phacility/phabricator/blob/master/src/applications/people/storage/PhabricatorUserEmail.php | Apache-2.0 |
public function sendOldPrimaryEmail(
PhabricatorUser $user,
PhabricatorUserEmail $new) {
$username = $user->getUsername();
$old_address = $this->getAddress();
$new_address = $new->getAddress();
$body = sprintf(
"%s\n\n%s\n",
pht('Hi %s', $username),
pht(
'This email address (%s) is no longer your primary email address. '.
'Going forward, all email will be sent to your new primary email '.
'address (%s).',
$old_address,
$new_address));
id(new PhabricatorMetaMTAMail())
->addRawTos(array($old_address))
->setForceDelivery(true)
->setSubject(
pht(
'[%s] Primary Address Changed',
PlatformSymbols::getPlatformServerName()))
->setBody($body)
->setFrom($user->getPHID())
->setRelatedPHID($user->getPHID())
->saveAndSend();
} | Send a notification email from $user to this address, informing the
recipient that this is no longer their account's primary address.
@param PhabricatorUser The user sending the notification.
@param PhabricatorUserEmail New primary email address.
@return this
@task email | sendOldPrimaryEmail | php | phacility/phabricator | src/applications/people/storage/PhabricatorUserEmail.php | https://github.com/phacility/phabricator/blob/master/src/applications/people/storage/PhabricatorUserEmail.php | Apache-2.0 |
public function sendNewPrimaryEmail(PhabricatorUser $user) {
$username = $user->getUsername();
$new_address = $this->getAddress();
$body = sprintf(
"%s\n\n%s\n",
pht('Hi %s', $username),
pht(
'This is now your primary email address (%s). Going forward, '.
'all email will be sent here.',
$new_address));
id(new PhabricatorMetaMTAMail())
->addRawTos(array($new_address))
->setForceDelivery(true)
->setSubject(
pht(
'[%s] Primary Address Changed',
PlatformSymbols::getPlatformServerName()))
->setBody($body)
->setFrom($user->getPHID())
->setRelatedPHID($user->getPHID())
->saveAndSend();
return $this;
} | Send a notification email from $user to this address, informing the
recipient that this is now their account's new primary email address.
@param PhabricatorUser The user sending the verification.
@return this
@task email | sendNewPrimaryEmail | php | phacility/phabricator | src/applications/people/storage/PhabricatorUserEmail.php | https://github.com/phacility/phabricator/blob/master/src/applications/people/storage/PhabricatorUserEmail.php | Apache-2.0 |
public function loadLastModifiedCommitID($commit_id, $path_id, $time = 0.5) {
$commit_id = (int)$commit_id;
$path_id = (int)$path_id;
$bucket_data = null;
$data_key = null;
$seen = array();
$t_start = microtime(true);
$iterations = 0;
while (true) {
$bucket_key = $this->getBucketKey($commit_id);
if (($data_key != $bucket_key) || $bucket_data === null) {
$bucket_data = $this->getBucketData($bucket_key);
$data_key = $bucket_key;
}
if (empty($bucket_data[$commit_id])) {
// Rebuild the cache bucket, since the commit might be a very recent
// one that we'll pick up by rebuilding.
$bucket_data = $this->getBucketData($bucket_key, $bucket_data);
if (empty($bucket_data[$commit_id])) {
// A rebuild didn't help. This can occur legitimately if the commit
// is new and hasn't parsed yet.
return false;
}
// Otherwise, the rebuild gave us the data, so we can keep going.
$did_fill = true;
} else {
$did_fill = false;
}
// Sanity check so we can survive and recover from bad data.
if (isset($seen[$commit_id])) {
phlog(pht('Unexpected infinite loop in %s!', __CLASS__));
return false;
} else {
$seen[$commit_id] = true;
}
// `$data` is a list: the commit's parent IDs, followed by `null`,
// followed by the modified paths in ascending order. We figure out the
// first parent first, then check if the path was touched. If the path
// was touched, this is the commit we're after. If not, walk backward
// in the tree.
$items = $bucket_data[$commit_id];
$size = count($items);
// Walk past the parent information.
$parent_id = null;
for ($ii = 0;; ++$ii) {
if ($items[$ii] === null) {
break;
}
if ($parent_id === null) {
$parent_id = $items[$ii];
}
}
// Look for a modification to the path.
for (; $ii < $size; ++$ii) {
$item = $items[$ii];
if ($item > $path_id) {
break;
}
if ($item === $path_id) {
return $commit_id;
}
}
if ($parent_id) {
$commit_id = $parent_id;
// Periodically check if we've spent too long looking for a result
// in the cache, and return so we can fall back to a VCS operation.
// This keeps us from having a degenerate worst case if, e.g., the
// cache is cold and we need to inspect a very large number of blocks
// to satisfy the query.
++$iterations;
// If we performed a cache fill in this cycle, always check the time
// limit, since cache fills may take a significant amount of time.
if ($did_fill || ($iterations % 64 === 0)) {
$t_end = microtime(true);
if (($t_end - $t_start) > $time) {
return false;
}
}
continue;
}
// If we have an explicit 0, that means this commit really has no parents.
// Usually, it is the first commit in the repository.
if ($parent_id === 0) {
return null;
}
// If we didn't find a parent, the parent data isn't available. We fail
// to find an answer in the cache and fall back to querying the VCS.
return false;
}
} | Search the graph cache for the most modification to a path.
@param int The commit ID to search ancestors of.
@param int The path ID to search for changes to.
@param float Maximum number of seconds to spend trying to satisfy this
query using the graph cache. By default, `0.5` (500ms).
@return mixed Commit ID, or `null` if no ancestors exist, or `false` if
the graph cache was unable to determine the answer.
@task query | loadLastModifiedCommitID | php | phacility/phabricator | src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | Apache-2.0 |
private function getBucketKey($commit_id) {
return (int)floor($commit_id / $this->getBucketSize());
} | Get the bucket key for a given commit ID.
@param int Commit ID.
@return int Bucket key.
@task cache | getBucketKey | php | phacility/phabricator | src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | Apache-2.0 |
private function getBucketCacheKey($bucket_key) {
static $prefix;
if ($prefix === null) {
$self = get_class($this);
$size = $this->getBucketSize();
$prefix = "{$self}:{$size}:2:";
}
return $prefix.$bucket_key;
} | Get the cache key for a given bucket key (from @{method:getBucketKey}).
@param int Bucket key.
@return string Cache key.
@task cache | getBucketCacheKey | php | phacility/phabricator | src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | Apache-2.0 |
private function getBucketSize() {
return 4096;
} | Get the number of items per bucket.
@return int Number of items to store per bucket.
@task cache | getBucketSize | php | phacility/phabricator | src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | Apache-2.0 |
private function getBucketData($bucket_key, $rebuild_data = null) {
$cache_key = $this->getBucketCacheKey($bucket_key);
// TODO: This cache stuff could be handled more gracefully, but the
// database cache currently requires values to be strings and needs
// some tweaking to support this as part of a stack. Our cache semantics
// here are also unusual (not purely readthrough) because this cache is
// appendable.
$cache_level1 = PhabricatorCaches::getRepositoryGraphL1Cache();
$cache_level2 = PhabricatorCaches::getRepositoryGraphL2Cache();
if ($rebuild_data === null) {
$bucket_data = $cache_level1->getKey($cache_key);
if ($bucket_data) {
return $bucket_data;
}
$bucket_data = $cache_level2->getKey($cache_key);
if ($bucket_data) {
$unserialized = @unserialize($bucket_data);
if ($unserialized) {
// Fill APC if we got a database hit but missed in APC.
$cache_level1->setKey($cache_key, $unserialized);
return $unserialized;
}
}
}
if (!is_array($rebuild_data)) {
$rebuild_data = array();
}
$bucket_data = $this->rebuildBucket($bucket_key, $rebuild_data);
// Don't bother writing the data if we didn't update anything.
if ($bucket_data !== $rebuild_data) {
$cache_level2->setKey($cache_key, serialize($bucket_data));
$cache_level1->setKey($cache_key, $bucket_data);
}
return $bucket_data;
} | Retrieve or build a graph cache bucket from the cache.
Normally, this operates as a readthrough cache call. It can also be used
to force a cache update by passing the existing data to `$rebuild_data`.
@param int Bucket key, from @{method:getBucketKey}.
@param mixed Current data, to force a cache rebuild of this bucket.
@return array Data from the cache.
@task cache | getBucketData | php | phacility/phabricator | src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/graphcache/PhabricatorRepositoryGraphCache.php | Apache-2.0 |
public function loadObjects(
PhabricatorObjectQuery $query,
array $phids) {
$object_query = $this->buildQueryForObjects($query, $phids)
->setViewer($query->getViewer())
->setParentQuery($query);
// If the user doesn't have permission to use the application at all,
// just mark all the PHIDs as filtered. This primarily makes these
// objects show up as "Restricted" instead of "Unknown" when loaded as
// handles, which is technically true.
if (!$object_query->canViewerUseQueryApplication()) {
$object_query->addPolicyFilteredPHIDs(array_fuse($phids));
return array();
}
return $object_query->execute();
} | Load objects of this type, by PHID. For most PHID types, it is only
necessary to implement @{method:buildQueryForObjects} to get object
loading to work.
@param PhabricatorObjectQuery Query being executed.
@param list<phid> PHIDs to load.
@return list<wild> Corresponding objects. | loadObjects | php | phacility/phabricator | src/applications/phid/type/PhabricatorPHIDType.php | https://github.com/phacility/phabricator/blob/master/src/applications/phid/type/PhabricatorPHIDType.php | Apache-2.0 |
public function getCloneName() {
$name = $this->getRepositorySlug();
// Make some reasonable effort to produce reasonable default directory
// names from repository names.
if ($name === null || !strlen($name)) {
$name = $this->getName();
$name = phutil_utf8_strtolower($name);
$name = preg_replace('@[ -/:->]+@', '-', $name);
$name = trim($name, '-');
if (!strlen($name)) {
$name = $this->getCallsign();
}
}
return $name;
} | Get the name of the directory this repository should clone or checkout
into. For example, if the repository name is "Example Repository", a
reasonable name might be "example-repository". This is used to help users
get reasonable results when cloning repositories, since they generally do
not want to clone into directories called "X/" or "Example Repository/".
@return string | getCloneName | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function getRemoteURI() {
return (string)$this->getRemoteURIObject();
} | Get the remote URI for this repository.
@return string
@task uri | getRemoteURI | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function getRemoteURIEnvelope() {
$uri = $this->getRemoteURIObject();
$remote_protocol = $this->getRemoteProtocol();
if ($remote_protocol == 'http' || $remote_protocol == 'https') {
// For SVN, we use `--username` and `--password` flags separately, so
// don't add any credentials here.
if (!$this->isSVN()) {
$credential_phid = $this->getCredentialPHID();
if ($credential_phid) {
$key = PassphrasePasswordKey::loadFromPHID(
$credential_phid,
PhabricatorUser::getOmnipotentUser());
$uri->setUser($key->getUsernameEnvelope()->openEnvelope());
$uri->setPass($key->getPasswordEnvelope()->openEnvelope());
}
}
}
return new PhutilOpaqueEnvelope((string)$uri);
} | Get the remote URI for this repository, including credentials if they're
used by this repository.
@return PhutilOpaqueEnvelope URI, possibly including credentials.
@task uri | getRemoteURIEnvelope | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function getPublicCloneURI() {
return (string)$this->getCloneURIObject();
} | Get the clone (or checkout) URI for this repository, without authentication
information.
@return string Repository URI.
@task uri | getPublicCloneURI | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function getRemoteProtocol() {
$uri = $this->getRemoteURIObject();
return $uri->getProtocol();
} | Get the protocol for the repository's remote.
@return string Protocol, like "ssh" or "git".
@task uri | getRemoteProtocol | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function getRemoteURIObject() {
$raw_uri = $this->getDetail('remote-uri');
if ($raw_uri === null || !strlen($raw_uri)) {
return new PhutilURI('');
}
if (!strncmp($raw_uri, '/', 1)) {
return new PhutilURI('file://'.$raw_uri);
}
return new PhutilURI($raw_uri);
} | Get a parsed object representation of the repository's remote URI..
@return wild A @{class@arcanist:PhutilURI}.
@task uri | getRemoteURIObject | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function getCloneURIObject() {
if (!$this->isHosted()) {
if ($this->isSVN()) {
// Make sure we pick up the "Import Only" path for Subversion, so
// the user clones the repository starting at the correct path, not
// from the root.
$base_uri = $this->getSubversionBaseURI();
$base_uri = new PhutilURI($base_uri);
$path = $base_uri->getPath();
if (!$path) {
$path = '/';
}
// If the trailing "@" is not required to escape the URI, strip it for
// readability.
if (!preg_match('/@.*@/', $path)) {
$path = rtrim($path, '@');
}
$base_uri->setPath($path);
return $base_uri;
} else {
return $this->getRemoteURIObject();
}
}
// TODO: This should be cleaned up to deal with all the new URI handling.
$another_copy = id(new PhabricatorRepositoryQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs(array($this->getPHID()))
->needURIs(true)
->executeOne();
$clone_uris = $another_copy->getCloneURIs();
if (!$clone_uris) {
return null;
}
return head($clone_uris)->getEffectiveURI();
} | Get the "best" clone/checkout URI for this repository, on any protocol. | getCloneURIObject | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
private function shouldUseSSH() {
if ($this->isHosted()) {
return false;
}
$protocol = $this->getRemoteProtocol();
if ($this->isSSHProtocol($protocol)) {
return true;
}
return false;
} | Determine if we should connect to the remote using SSH flags and
credentials.
@return bool True to use the SSH protocol.
@task uri | shouldUseSSH | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
private function shouldUseHTTP() {
if ($this->isHosted()) {
return false;
}
$protocol = $this->getRemoteProtocol();
return ($protocol == 'http' || $protocol == 'https');
} | Determine if we should connect to the remote using HTTP flags and
credentials.
@return bool True to use the HTTP protocol.
@task uri | shouldUseHTTP | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
private function shouldUseSVNProtocol() {
if ($this->isHosted()) {
return false;
}
$protocol = $this->getRemoteProtocol();
return ($protocol == 'svn');
} | Determine if we should connect to the remote using SVN flags and
credentials.
@return bool True to use the SVN protocol.
@task uri | shouldUseSVNProtocol | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
private function isSSHProtocol($protocol) {
return ($protocol == 'ssh' || $protocol == 'svn+ssh');
} | Determine if a protocol is SSH or SSH-like.
@param string A protocol string, like "http" or "ssh".
@return bool True if the protocol is SSH-like.
@task uri | isSSHProtocol | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
private function assertLocalExists() {
if (!$this->usesLocalWorkingCopy()) {
return;
}
$local = $this->getLocalPath();
Filesystem::assertExists($local);
Filesystem::assertIsDirectory($local);
Filesystem::assertReadable($local);
} | Raise more useful errors when there are basic filesystem problems. | assertLocalExists | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function isWorkingCopyBare() {
switch ($this->getVersionControlSystem()) {
case PhabricatorRepositoryType::REPOSITORY_TYPE_SVN:
case PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL:
return false;
case PhabricatorRepositoryType::REPOSITORY_TYPE_GIT:
$local = $this->getLocalPath();
if (Filesystem::pathExists($local.'/.git')) {
return false;
} else {
return true;
}
}
} | Determine if the working copy is bare or not. In Git, this corresponds
to `--bare`. In Mercurial, `--noupdate`. | isWorkingCopyBare | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function loadUpdateInterval($minimum = 15) {
// First, check if we've hit errors recently. If we have, wait one period
// for each consecutive error. Normally, this corresponds to a backoff of
// 15s, 30s, 45s, etc.
$message_table = new PhabricatorRepositoryStatusMessage();
$conn = $message_table->establishConnection('r');
$error_count = queryfx_one(
$conn,
'SELECT MAX(messageCount) error_count FROM %T
WHERE repositoryID = %d
AND statusType IN (%Ls)
AND statusCode IN (%Ls)',
$message_table->getTableName(),
$this->getID(),
array(
PhabricatorRepositoryStatusMessage::TYPE_INIT,
PhabricatorRepositoryStatusMessage::TYPE_FETCH,
),
array(
PhabricatorRepositoryStatusMessage::CODE_ERROR,
));
$error_count = (int)$error_count['error_count'];
if ($error_count > 0) {
return (int)($minimum * $error_count);
}
// If a repository is still importing, always pull it as frequently as
// possible. This prevents us from hanging for a long time at 99.9% when
// importing an inactive repository.
if ($this->isImporting()) {
return $minimum;
}
$window_start = (PhabricatorTime::getNow() + $minimum);
$table = id(new PhabricatorRepositoryCommit());
$last_commit = queryfx_one(
$table->establishConnection('r'),
'SELECT epoch FROM %T
WHERE repositoryID = %d AND epoch <= %d
ORDER BY epoch DESC LIMIT 1',
$table->getTableName(),
$this->getID(),
$window_start);
if ($last_commit) {
$time_since_commit = ($window_start - $last_commit['epoch']);
} else {
// If the repository has no commits, treat the creation date as
// though it were the date of the last commit. This makes empty
// repositories update quickly at first but slow down over time
// if they don't see any activity.
$time_since_commit = ($window_start - $this->getDateCreated());
}
$last_few_days = phutil_units('3 days in seconds');
if ($time_since_commit <= $last_few_days) {
// For repositories with activity in the recent past, we wait one
// extra second for every 10 minutes since the last commit. This
// shorter backoff is intended to handle weekends and other short
// breaks from development.
$smart_wait = ($time_since_commit / 600);
} else {
// For repositories without recent activity, we wait one extra second
// for every 4 minutes since the last commit. This longer backoff
// handles rarely used repositories, up to the maximum.
$smart_wait = ($time_since_commit / 240);
}
// We'll never wait more than 6 hours to pull a repository.
$longest_wait = phutil_units('6 hours in seconds');
$smart_wait = min($smart_wait, $longest_wait);
$smart_wait = max($minimum, $smart_wait);
return (int)$smart_wait;
} | Load the pull frequency for this repository, based on the time since the
last activity.
We pull rarely used repositories less frequently. This finds the most
recent commit which is older than the current time (which prevents us from
spinning on repositories with a silly commit post-dated to some time in
2037). We adjust the pull frequency based on when the most recent commit
occurred.
@param int The minimum update interval to use, in seconds.
@return int Repository update interval, in seconds. | loadUpdateInterval | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function getCopyTimeLimit() {
return $this->getDetail('limit.copy');
} | Time limit for cloning or copying this repository.
This limit is used to timeout operations like `git clone` or `git fetch`
when doing intracluster synchronization, building working copies, etc.
@return int Maximum number of seconds to spend copying this repository. | getCopyTimeLimit | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function getAlmanacServiceURI(
PhabricatorUser $viewer,
array $options) {
$refs = $this->getAlmanacServiceRefs($viewer, $options);
if (!$refs) {
return null;
}
$ref = head($refs);
return $ref->getURI();
} | Retrieve the service URI for the device hosting this repository.
See @{method:newConduitClient} for a general discussion of interacting
with repository services. This method provides lower-level resolution of
services, returning raw URIs.
@param PhabricatorUser Viewing user.
@param map<string, wild> Constraints on selectable services.
@return string|null URI, or `null` for local repositories. | getAlmanacServiceURI | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function newConduitClient(
PhabricatorUser $viewer,
$never_proxy = false) {
$uri = $this->getAlmanacServiceURI(
$viewer,
array(
'neverProxy' => $never_proxy,
'protocols' => array(
'http',
'https',
),
// At least today, no Conduit call can ever write to a repository,
// so it's fine to send anything to a read-only node.
'writable' => false,
));
if ($uri === null) {
return null;
}
$domain = id(new PhutilURI(PhabricatorEnv::getURI('/')))->getDomain();
$client = id(new ConduitClient($uri))
->setHost($domain);
if ($viewer->isOmnipotent()) {
// If the caller is the omnipotent user (normally, a daemon), we will
// sign the request with this host's asymmetric keypair.
$public_path = AlmanacKeys::getKeyPath('device.pub');
try {
$public_key = Filesystem::readFile($public_path);
} catch (Exception $ex) {
throw new PhutilAggregateException(
pht(
'Unable to read device public key while attempting to make '.
'authenticated method call within the cluster. '.
'Use `%s` to register keys for this device. Exception: %s',
'bin/almanac register',
$ex->getMessage()),
array($ex));
}
$private_path = AlmanacKeys::getKeyPath('device.key');
try {
$private_key = Filesystem::readFile($private_path);
$private_key = new PhutilOpaqueEnvelope($private_key);
} catch (Exception $ex) {
throw new PhutilAggregateException(
pht(
'Unable to read device private key while attempting to make '.
'authenticated method call within the cluster. '.
'Use `%s` to register keys for this device. Exception: %s',
'bin/almanac register',
$ex->getMessage()),
array($ex));
}
$client->setSigningKeys($public_key, $private_key);
} else {
// If the caller is a normal user, we generate or retrieve a cluster
// API token.
$token = PhabricatorConduitToken::loadClusterTokenForUser($viewer);
if ($token) {
$client->setConduitToken($token->getToken());
}
}
return $client;
} | Build a new Conduit client in order to make a service call to this
repository.
If the repository is hosted locally, this method may return `null`. The
caller should use `ConduitCall` or other local logic to complete the
request.
By default, we will return a @{class:ConduitClient} for any repository with
a service, even if that service is on the current device.
We do this because this configuration does not make very much sense in a
production context, but is very common in a test/development context
(where the developer's machine is both the web host and the repository
service). By proxying in development, we get more consistent behavior
between development and production, and don't have a major untested
codepath.
The `$never_proxy` parameter can be used to prevent this local proxying.
If the flag is passed:
- The method will return `null` (implying a local service call)
if the repository service is hosted on the current device.
- The method will throw if it would need to return a client.
This is used to prevent loops in Conduit: the first request will proxy,
even in development, but the second request will be identified as a
cluster request and forced not to proxy.
For lower-level service resolution, see @{method:getAlmanacServiceURI}.
@param PhabricatorUser Viewing user.
@param bool `true` to throw if a client would be returned.
@return ConduitClient|null Client, or `null` for local repositories. | newConduitClient | php | phacility/phabricator | src/applications/repository/storage/PhabricatorRepository.php | https://github.com/phacility/phabricator/blob/master/src/applications/repository/storage/PhabricatorRepository.php | Apache-2.0 |
public function canWriteFiles() {
return (bool)$this->getWritableEngine();
} | We can write chunks if we have at least one valid storage engine
underneath us. | canWriteFiles | php | phacility/phabricator | src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | Apache-2.0 |
public static function getChunkedHash(PhabricatorUser $viewer, $hash) {
if (!$viewer->getPHID()) {
throw new Exception(
pht('Unable to compute chunked hash without real viewer!'));
}
$input = $viewer->getAccountSecret().':'.$hash.':'.$viewer->getPHID();
return self::getChunkedHashForInput($input);
} | Compute a chunked file hash for the viewer.
We can not currently compute a real hash for chunked file uploads (because
no process sees all of the file data).
We also can not trust the hash that the user claims to have computed. If
we trust the user, they can upload some `evil.exe` and claim it has the
same file hash as `good.exe`. When another user later uploads the real
`good.exe`, we'll just create a reference to the existing `evil.exe`. Users
who download `good.exe` will then receive `evil.exe`.
Instead, we rehash the user's claimed hash with account secrets. This
allows users to resume file uploads, but not collide with other users.
Ideally, we'd like to be able to verify hashes, but this is complicated
and time consuming and gives us a fairly small benefit.
@param PhabricatorUser Viewing user.
@param string Claimed file hash.
@return string Rehashed file hash. | getChunkedHash | php | phacility/phabricator | src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | Apache-2.0 |
private function getWritableEngine() {
// NOTE: We can't just load writable engines or we'll loop forever.
$engines = parent::loadAllEngines();
foreach ($engines as $engine) {
if ($engine->isChunkEngine()) {
continue;
}
if ($engine->isTestEngine()) {
continue;
}
if (!$engine->canWriteFiles()) {
continue;
}
if ($engine->hasFilesizeLimit()) {
if ($engine->getFilesizeLimit() < $this->getChunkSize()) {
continue;
}
}
return true;
}
return false;
} | Find a storage engine which is suitable for storing chunks.
This engine must be a writable engine, have a filesize limit larger than
the chunk limit, and must not be a chunk engine itself. | getWritableEngine | php | phacility/phabricator | src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | https://github.com/phacility/phabricator/blob/master/src/applications/files/engine/PhabricatorChunkedFileStorageEngine.php | Apache-2.0 |
public function setGroupBy($group) {
$this->groupBy = $group;
return $this;
} | NOTE: this is done in PHP and not in MySQL, which means its inappropriate
for large datasets. Pragmatically, this is fine for user flags which are
typically well under 100 flags per user. | setGroupBy | php | phacility/phabricator | src/applications/flag/query/PhabricatorFlagQuery.php | https://github.com/phacility/phabricator/blob/master/src/applications/flag/query/PhabricatorFlagQuery.php | Apache-2.0 |
public function readFieldsFromStorage(
PhabricatorCustomFieldInterface $object) {
$this->readFieldsFromObject($object);
$fields = $this->getFields();
id(new PhabricatorCustomFieldStorageQuery())
->addFields($fields)
->execute();
return $this;
} | Read stored values for all fields which support storage.
@param PhabricatorCustomFieldInterface Object to read field values for.
@return void | readFieldsFromStorage | php | phacility/phabricator | src/infrastructure/customfield/field/PhabricatorCustomFieldList.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/customfield/field/PhabricatorCustomFieldList.php | Apache-2.0 |
public function setExternalConnection(AphrontDatabaseConnection $conn) {
if ($this->conn) {
throw new Exception(
pht(
'Lock is already held, and must be released before the '.
'connection may be changed.'));
}
$this->externalConnection = $conn;
return $this;
} | Use a specific database connection for locking.
By default, `PhabricatorGlobalLock` will lock on the "repository" database
(somewhat arbitrarily). In most cases this is fine, but this method can
be used to lock on a specific connection.
@param AphrontDatabaseConnection
@return this | setExternalConnection | php | phacility/phabricator | src/infrastructure/util/PhabricatorGlobalLock.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/util/PhabricatorGlobalLock.php | Apache-2.0 |
public function needSyntheticPreferences($synthetic) {
$this->synthetic = $synthetic;
return $this;
} | Always return preferences for every queried user.
If no settings exist for a user, a new empty settings object with
appropriate defaults is returned.
@param bool True to generate synthetic preferences for missing users. | needSyntheticPreferences | php | phacility/phabricator | src/applications/settings/query/PhabricatorUserPreferencesQuery.php | https://github.com/phacility/phabricator/blob/master/src/applications/settings/query/PhabricatorUserPreferencesQuery.php | Apache-2.0 |
public function __construct() {
$this->smtp_conn = 0;
$this->error = null;
$this->helo_rply = null;
$this->do_debug = 0;
} | Initialize the class so that the data is in a known state.
@access public
@return void | __construct | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Connect($host, $port = 0, $tval = 30) {
// set the error val to null so there is no confusion
$this->error = null;
// make sure we are __not__ connected
if($this->connected()) {
// already connected, generate error
$this->error = array("error" => "Already connected to a server");
return false;
}
if(empty($port)) {
$port = $this->SMTP_PORT;
}
// connect to the smtp server
$this->smtp_conn = @fsockopen($host, // the host of the server
$port, // the port to use
$errno, // error number if any
$errstr, // error message if any
$tval); // give up after ? secs
// verify we connected properly
if(empty($this->smtp_conn)) {
$this->error = array("error" => "Failed to connect to server",
"errno" => $errno,
"errstr" => $errstr);
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />';
}
return false;
}
// SMTP server can take longer to respond, give longer timeout for first read
// Windows does not have support for this timeout function
if(substr(PHP_OS, 0, 3) != "WIN")
socket_set_timeout($this->smtp_conn, $tval, 0);
// get any announcement
$announce = $this->get_lines();
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />';
}
return true;
} | Connect to the server specified on the port specified.
If the port is not specified use the default SMTP_PORT.
If tval is specified then a connection will try and be
established with the server for that number of seconds.
If tval is not specified the default is 30 seconds to
try on the connection.
SMTP CODE SUCCESS: 220
SMTP CODE FAILURE: 421
@access public
@return bool | Connect | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function StartTLS() {
$this->error = null; # to avoid confusion
if(!$this->connected()) {
$this->error = array("error" => "Called StartTLS() without being connected");
return false;
}
fputs($this->smtp_conn,"STARTTLS" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 220) {
$this->error =
array("error" => "STARTTLS not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
// Begin encrypted connection
if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
return false;
}
return true;
} | Initiate a TLS communication with the server.
SMTP CODE 220 Ready to start TLS
SMTP CODE 501 Syntax error (no parameters allowed)
SMTP CODE 454 TLS not available due to temporary reason
@access public
@return bool success | StartTLS | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Authenticate($username, $password) {
// Start authentication
fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($code != 334) {
$this->error =
array("error" => "AUTH not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
// Send encoded username
fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($code != 334) {
$this->error =
array("error" => "Username not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
// Send encoded password
fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($code != 235) {
$this->error =
array("error" => "Password not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
} | Performs SMTP authentication. Must be run after running the
Hello() method. Returns true if successfully authenticated.
@access public
@return bool | Authenticate | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Connected() {
if(!empty($this->smtp_conn)) {
$sock_status = socket_get_status($this->smtp_conn);
if($sock_status["eof"]) {
// the socket is valid but we are not connected
if($this->do_debug >= 1) {
echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected";
}
$this->Close();
return false;
}
return true; // everything looks good
}
return false;
} | Returns true if connected to a server otherwise false
@access public
@return bool | Connected | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Close() {
$this->error = null; // so there is no confusion
$this->helo_rply = null;
if(!empty($this->smtp_conn)) {
// close the connection and cleanup
fclose($this->smtp_conn);
$this->smtp_conn = 0;
}
} | Closes the socket and cleans up the state of the class.
It is not considered good to use this function without
first trying to use QUIT.
@access public
@return void | Close | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Data($msg_data) {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Data() without being connected");
return false;
}
fputs($this->smtp_conn,"DATA" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 354) {
$this->error =
array("error" => "DATA command not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
/* the server is ready to accept data!
* according to rfc 821 we should not send more than 1000
* including the CRLF
* characters on a single line so we will break the data up
* into lines by \r and/or \n then if needed we will break
* each of those into smaller lines to fit within the limit.
* in addition we will be looking for lines that start with
* a period '.' and append and additional period '.' to that
* line. NOTE: this does not count towards limit.
*/
// normalize the line breaks so we know the explode works
$msg_data = str_replace("\r\n","\n",$msg_data);
$msg_data = str_replace("\r","\n",$msg_data);
$lines = explode("\n",$msg_data);
/* we need to find a good way to determine is headers are
* in the msg_data or if it is a straight msg body
* currently I am assuming rfc 822 definitions of msg headers
* and if the first field of the first line (':' sperated)
* does not contain a space then it _should_ be a header
* and we can process all lines before a blank "" line as
* headers.
*/
$field = substr($lines[0],0,strpos($lines[0],":"));
$in_headers = false;
if(!empty($field) && !strstr($field," ")) {
$in_headers = true;
}
$max_line_length = 998; // used below; set here for ease in change
while(list(,$line) = @each($lines)) {
$lines_out = null;
if($line == "" && $in_headers) {
$in_headers = false;
}
// ok we need to break this line up into several smaller lines
while(strlen($line) > $max_line_length) {
$pos = strrpos(substr($line,0,$max_line_length)," ");
// Patch to fix DOS attack
if(!$pos) {
$pos = $max_line_length - 1;
$lines_out[] = substr($line,0,$pos);
$line = substr($line,$pos);
} else {
$lines_out[] = substr($line,0,$pos);
$line = substr($line,$pos + 1);
}
/* if processing headers add a LWSP-char to the front of new line
* rfc 822 on long msg headers
*/
if($in_headers) {
$line = "\t" . $line;
}
}
$lines_out[] = $line;
// send the lines to the server
while(list(,$line_out) = @each($lines_out)) {
if(strlen($line_out) > 0)
{
if(substr($line_out, 0, 1) == ".") {
$line_out = "." . $line_out;
}
}
fputs($this->smtp_conn,$line_out . $this->CRLF);
}
}
// message data has been sent
fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => "DATA not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
} | Issues a data command and sends the msg_data to the server
finializing the mail transaction. $msg_data is the message
that is to be send with the headers. Each header needs to be
on a single line followed by a <CRLF> with the message headers
and the message body being seperated by and additional <CRLF>.
Implements rfc 821: DATA <CRLF>
SMTP CODE INTERMEDIATE: 354
[data]
<CRLF>.<CRLF>
SMTP CODE SUCCESS: 250
SMTP CODE FAILURE: 552,554,451,452
SMTP CODE FAILURE: 451,554
SMTP CODE ERROR : 500,501,503,421
@access public
@return bool | Data | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Hello($host = '') {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Hello() without being connected");
return false;
}
// if hostname for HELO was not specified send default
if(empty($host)) {
// determine appropriate default to send to server
$host = "localhost";
}
// Send extended hello first (RFC 2821)
if(!$this->SendHello("EHLO", $host)) {
if(!$this->SendHello("HELO", $host)) {
return false;
}
}
return true;
} | Sends the HELO command to the smtp server.
This makes sure that we and the server are in
the same known state.
Implements from rfc 821: HELO <SP> <domain> <CRLF>
SMTP CODE SUCCESS: 250
SMTP CODE ERROR : 500, 501, 504, 421
@access public
@return bool | Hello | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Mail($from) {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Mail() without being connected");
return false;
}
$useVerp = ($this->do_verp ? "XVERP" : "");
fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => "MAIL not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
} | Starts a mail transaction from the email address specified in
$from. Returns true if successful or false otherwise. If True
the mail transaction is started and then one or more Recipient
commands may be called followed by a Data command.
Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
SMTP CODE SUCCESS: 250
SMTP CODE SUCCESS: 552,451,452
SMTP CODE SUCCESS: 500,501,421
@access public
@return bool | Mail | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Quit($close_on_error = true) {
$this->error = null; // so there is no confusion
if(!$this->connected()) {
$this->error = array(
"error" => "Called Quit() without being connected");
return false;
}
// send the quit command to the server
fputs($this->smtp_conn,"quit" . $this->CRLF);
// get any good-bye messages
$byemsg = $this->get_lines();
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />';
}
$rval = true;
$e = null;
$code = substr($byemsg,0,3);
if($code != 221) {
// use e as a tmp var cause Close will overwrite $this->error
$e = array("error" => "SMTP server rejected quit command",
"smtp_code" => $code,
"smtp_rply" => substr($byemsg,4));
$rval = false;
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />';
}
}
if(empty($e) || $close_on_error) {
$this->Close();
}
return $rval;
} | Sends the quit command to the server and then closes the socket
if there is no error or the $close_on_error argument is true.
Implements from rfc 821: QUIT <CRLF>
SMTP CODE SUCCESS: 221
SMTP CODE ERROR : 500
@access public
@return bool | Quit | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Recipient($to) {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Recipient() without being connected");
return false;
}
fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250 && $code != 251) {
$this->error =
array("error" => "RCPT not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
} | Sends the command RCPT to the SMTP server with the TO: argument of $to.
Returns true if the recipient was accepted false if it was rejected.
Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
SMTP CODE SUCCESS: 250,251
SMTP CODE FAILURE: 550,551,552,553,450,451,452
SMTP CODE ERROR : 500,501,503,421
@access public
@return bool | Recipient | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Reset() {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Reset() without being connected");
return false;
}
fputs($this->smtp_conn,"RSET" . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => "RSET failed",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
} | Sends the RSET command to abort and transaction that is
currently in progress. Returns true if successful false
otherwise.
Implements rfc 821: RSET <CRLF>
SMTP CODE SUCCESS: 250
SMTP CODE ERROR : 500,501,504,421
@access public
@return bool | Reset | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function SendAndMail($from) {
$this->error = null; // so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called SendAndMail() without being connected");
return false;
}
fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF);
$rply = $this->get_lines();
$code = substr($rply,0,3);
if($this->do_debug >= 2) {
echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
}
if($code != 250) {
$this->error =
array("error" => "SAML not accepted from server",
"smtp_code" => $code,
"smtp_msg" => substr($rply,4));
if($this->do_debug >= 1) {
echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
}
return false;
}
return true;
} | Starts a mail transaction from the email address specified in
$from. Returns true if successful or false otherwise. If True
the mail transaction is started and then one or more Recipient
commands may be called followed by a Data command. This command
will send the message to the users terminal if they are logged
in and send them an email.
Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
SMTP CODE SUCCESS: 250
SMTP CODE SUCCESS: 552,451,452
SMTP CODE SUCCESS: 500,501,502,421
@access public
@return bool | SendAndMail | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function Turn() {
$this->error = array("error" => "This method, TURN, of the SMTP ".
"is not implemented");
if($this->do_debug >= 1) {
echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />';
}
return false;
} | This is an optional command for SMTP that this class does not
support. This method is here to make the RFC821 Definition
complete for this class and __may__ be implimented in the future
Implements from rfc 821: TURN <CRLF>
SMTP CODE SUCCESS: 250
SMTP CODE FAILURE: 502
SMTP CODE ERROR : 500, 503
@access public
@return bool | Turn | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
private function get_lines() {
$data = "";
while($str = @fgets($this->smtp_conn,515)) {
if($this->do_debug >= 4) {
echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />';
echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />';
}
$data .= $str;
if($this->do_debug >= 4) {
echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />';
}
// if 4th character is a space, we are done reading, break the loop
if(substr($str,3,1) == " ") { break; }
}
return $data;
} | Read in as many lines as possible
either before eof or socket timeout occurs on the operation.
With SMTP we can tell if we have more lines to read if the
4th character is '-' symbol. If it is a space then we don't
need to read anything else.
@access private
@return string | get_lines | php | phacility/phabricator | externals/phpmailer/class.smtp.php | https://github.com/phacility/phabricator/blob/master/externals/phpmailer/class.smtp.php | Apache-2.0 |
public function validateCustomDomain($domain_full_uri) {
$example_domain = 'http://blog.example.com/';
$label = pht('Invalid');
// note this "uri" should be pretty busted given the desired input
// so just use it to test if there's a protocol specified
$uri = new PhutilURI($domain_full_uri);
$domain = $uri->getDomain();
$protocol = $uri->getProtocol();
$path = $uri->getPath();
$supported_protocols = array('http', 'https');
if (!in_array($protocol, $supported_protocols)) {
return pht(
'The custom domain should include a valid protocol in the URI '.
'(for example, "%s"). Valid protocols are "http" or "https".',
$example_domain);
}
if (strlen($path) && $path != '/') {
return pht(
'The custom domain should not specify a path (hosting a Phame '.
'blog at a path is currently not supported). Instead, just provide '.
'the bare domain name (for example, "%s").',
$example_domain);
}
if (strpos($domain, '.') === false) {
return pht(
'The custom domain should contain at least one dot (.) because '.
'some browsers fail to set cookies on domains without a dot. '.
'Instead, use a normal looking domain name like "%s".',
$example_domain);
}
if (!PhabricatorEnv::getEnvConfig('policy.allow-public')) {
$href = PhabricatorEnv::getProductionURI(
'/config/edit/policy.allow-public/');
return pht(
'For custom domains to work, this this server must be '.
'configured to allow the public access policy. Configure this '.
'setting %s, or ask an administrator to configure this setting. '.
'The domain can be specified later once this setting has been '.
'changed.',
phutil_tag(
'a',
array('href' => $href),
pht('here')));
}
return null;
} | Makes sure a given custom blog uri is properly configured in DNS
to point at this Phabricator instance. If there is an error in
the configuration, return a string describing the error and how
to fix it. If there is no error, return an empty string.
@return string | validateCustomDomain | php | phacility/phabricator | src/applications/phame/storage/PhameBlog.php | https://github.com/phacility/phabricator/blob/master/src/applications/phame/storage/PhameBlog.php | Apache-2.0 |
private function getReadmeLanguage($path) {
$path = phutil_utf8_strtolower($path);
if ($path == 'readme') {
return 'remarkup';
}
$ext = last(explode('.', $path));
switch ($ext) {
case 'remarkup':
case 'md':
return 'remarkup';
case 'rainbow':
return 'rainbow';
case 'txt':
default:
return 'text';
}
} | Get the markup language a README should be interpreted as.
@param string Local README path, like "README.txt".
@return string Best markup interpreter (like "remarkup") for this file. | getReadmeLanguage | php | phacility/phabricator | src/applications/diffusion/view/DiffusionReadmeView.php | https://github.com/phacility/phabricator/blob/master/src/applications/diffusion/view/DiffusionReadmeView.php | Apache-2.0 |
public function shouldAllowEmailTrustConfiguration() {
return true;
} | Should we allow the adapter to be marked as "trusted". This is true for
all adapters except those that allow the user to type in emails (see
@{class:PhabricatorPasswordAuthProvider}). | shouldAllowEmailTrustConfiguration | php | phacility/phabricator | src/applications/auth/provider/PhabricatorAuthProvider.php | https://github.com/phacility/phabricator/blob/master/src/applications/auth/provider/PhabricatorAuthProvider.php | Apache-2.0 |
public function hasSetupStep() {
return false;
} | Return true to use a two-step configuration (setup, configure) instead of
the default single-step configuration. In practice, this means that
creating a new provider instance will redirect back to the edit page
instead of the provider list.
@return bool True if this provider uses two-step configuration. | hasSetupStep | php | phacility/phabricator | src/applications/auth/provider/PhabricatorAuthProvider.php | https://github.com/phacility/phabricator/blob/master/src/applications/auth/provider/PhabricatorAuthProvider.php | Apache-2.0 |
public function getMethodSummary() {
return $this->getMethodDescription();
} | Get a short, human-readable text summary of the method.
@return string Short summary of method.
@task info | getMethodSummary | php | phacility/phabricator | src/applications/conduit/method/ConduitAPIMethod.php | https://github.com/phacility/phabricator/blob/master/src/applications/conduit/method/ConduitAPIMethod.php | Apache-2.0 |
public function getID() {
return $this->getAPIMethodName();
} | This is mostly for compatibility with
@{class:PhabricatorCursorPagedPolicyAwareQuery}. | getID | php | phacility/phabricator | src/applications/conduit/method/ConduitAPIMethod.php | https://github.com/phacility/phabricator/blob/master/src/applications/conduit/method/ConduitAPIMethod.php | Apache-2.0 |
public function getMethodStatus() {
return self::METHOD_STATUS_STABLE;
} | Get the status for this method (e.g., stable, unstable or deprecated).
Should return a METHOD_STATUS_* constant. By default, methods are
"stable".
@return const METHOD_STATUS_* constant.
@task status | getMethodStatus | php | phacility/phabricator | src/applications/conduit/method/ConduitAPIMethod.php | https://github.com/phacility/phabricator/blob/master/src/applications/conduit/method/ConduitAPIMethod.php | Apache-2.0 |
public function getMethodStatusDescription() {
return null;
} | Optional description to supplement the method status. In particular, if
a method is deprecated, you can return a string here describing the reason
for deprecation and stable alternatives.
@return string|null Description of the method status, if available.
@task status | getMethodStatusDescription | php | phacility/phabricator | src/applications/conduit/method/ConduitAPIMethod.php | https://github.com/phacility/phabricator/blob/master/src/applications/conduit/method/ConduitAPIMethod.php | Apache-2.0 |
public function getSortOrder() {
$name = $this->getAPIMethodName();
$map = array(
self::METHOD_STATUS_STABLE => 0,
self::METHOD_STATUS_UNSTABLE => 1,
self::METHOD_STATUS_DEPRECATED => 2,
);
$ord = idx($map, $this->getMethodStatus(), 0);
list($head, $tail) = explode('.', $name, 2);
return "{$head}.{$ord}.{$tail}";
} | Return a key which sorts methods by application name, then method status,
then method name. | getSortOrder | php | phacility/phabricator | src/applications/conduit/method/ConduitAPIMethod.php | https://github.com/phacility/phabricator/blob/master/src/applications/conduit/method/ConduitAPIMethod.php | Apache-2.0 |
public function getApplication() {
return null;
} | Optionally, return a @{class:PhabricatorApplication} which this call is
part of. The call will be disabled when the application is uninstalled.
@return PhabricatorApplication|null Related application. | getApplication | php | phacility/phabricator | src/applications/conduit/method/ConduitAPIMethod.php | https://github.com/phacility/phabricator/blob/master/src/applications/conduit/method/ConduitAPIMethod.php | Apache-2.0 |
public function getStaticTitle() {
$title = $this->getTitle();
if (strlen($title)) {
return $title;
}
return pht('Private Room');
} | Get a thread title which doesn't require handles to be attached.
This is a less rich title than @{method:getDisplayTitle}, but does not
require handles to be attached. We use it to build thread handles without
risking cycles or recursion while querying.
@return string Lower quality human-readable title. | getStaticTitle | php | phacility/phabricator | src/applications/conpherence/storage/ConpherenceThread.php | https://github.com/phacility/phabricator/blob/master/src/applications/conpherence/storage/ConpherenceThread.php | Apache-2.0 |
public function getNextEventEpoch($last_epoch, $is_reschedule) {
return $this->getClock()->getNextEventEpoch($last_epoch, $is_reschedule);
} | Return the next time this trigger should execute.
This method can be called either after the daemon executed the trigger
successfully (giving the trigger an opportunity to reschedule itself
into the future, if it is a recurring event) or after the trigger itself
is changed (usually because of an application edit). The `$is_reschedule`
parameter distinguishes between these cases.
@param int|null Epoch of the most recent successful event execution.
@param bool `true` if we're trying to reschedule the event after
execution; `false` if this is in response to a trigger update.
@return int|null Return an epoch to schedule the next event execution,
or `null` to stop the event from executing again. | getNextEventEpoch | php | phacility/phabricator | src/infrastructure/daemon/workers/storage/PhabricatorWorkerTrigger.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/daemon/workers/storage/PhabricatorWorkerTrigger.php | Apache-2.0 |
public function executeTrigger($last_event, $this_event) {
return $this->getAction()->execute($last_event, $this_event);
} | Execute the event.
@param int|null Epoch of previous execution, or null if this is the first
execution.
@param int Scheduled epoch of this execution. This may not be the same
as the current time.
@return void | executeTrigger | php | phacility/phabricator | src/infrastructure/daemon/workers/storage/PhabricatorWorkerTrigger.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/daemon/workers/storage/PhabricatorWorkerTrigger.php | Apache-2.0 |
public function getNextEventPrediction() {
// NOTE: We're basically echoing the database state here, so this won't
// necessarily be accurate if the caller just updated the object but has
// not saved it yet. That's a weird use case and would require more
// gymnastics, so don't bother trying to get it totally correct for now.
if ($this->getEvent()) {
return $this->getEvent()->getNextEventEpoch();
} else {
return $this->getNextEventEpoch(null, $is_reschedule = false);
}
} | Predict the epoch at which this trigger will next fire.
@return int|null Epoch when the event will next fire, or `null` if it is
not planned to trigger. | getNextEventPrediction | php | phacility/phabricator | src/infrastructure/daemon/workers/storage/PhabricatorWorkerTrigger.php | https://github.com/phacility/phabricator/blob/master/src/infrastructure/daemon/workers/storage/PhabricatorWorkerTrigger.php | Apache-2.0 |
public function getGenericDescription() {
return '';
} | The generic description of the implementation. | getGenericDescription | php | phacility/phabricator | src/applications/harbormaster/step/HarbormasterBuildStepImplementation.php | https://github.com/phacility/phabricator/blob/master/src/applications/harbormaster/step/HarbormasterBuildStepImplementation.php | Apache-2.0 |
public function getDescription() {
return $this->getGenericDescription();
} | The description of the implementation, based on the current settings. | getDescription | php | phacility/phabricator | src/applications/harbormaster/step/HarbormasterBuildStepImplementation.php | https://github.com/phacility/phabricator/blob/master/src/applications/harbormaster/step/HarbormasterBuildStepImplementation.php | Apache-2.0 |
public function getSettings() {
return $this->settings;
} | Gets the settings for this build step. | getSettings | php | phacility/phabricator | src/applications/harbormaster/step/HarbormasterBuildStepImplementation.php | https://github.com/phacility/phabricator/blob/master/src/applications/harbormaster/step/HarbormasterBuildStepImplementation.php | Apache-2.0 |
public function getArtifactInputs() {
return array();
} | Return the name of artifacts produced by this command.
Future steps will calculate all available artifact mappings
before them and filter on the type.
@return array The mappings of artifact names to their types. | getArtifactInputs | php | phacility/phabricator | src/applications/harbormaster/step/HarbormasterBuildStepImplementation.php | https://github.com/phacility/phabricator/blob/master/src/applications/harbormaster/step/HarbormasterBuildStepImplementation.php | Apache-2.0 |
public function parseBody($body) {
$body = $this->stripTextBody($body);
$commands = array();
$lines = phutil_split_lines($body, $retain_endings = true);
// We'll match commands at the beginning and end of the mail, but not
// in the middle of the mail body.
list($top_commands, $lines) = $this->stripCommands($lines);
list($end_commands, $lines) = $this->stripCommands(array_reverse($lines));
$lines = array_reverse($lines);
$commands = array_merge($top_commands, array_reverse($end_commands));
$lines = rtrim(implode('', $lines));
return array(
'body' => $lines,
'commands' => $commands,
);
} | Mails can have bodies such as
!claim
taking this task
Or
!assign alincoln
please, take this task I took; its hard
This function parses such an email body and returns a dictionary
containing a clean body text (e.g. "taking this task"), and a list of
commands. For example, this body above might parse as:
array(
'body' => 'please, take this task I took; it's hard',
'commands' => array(
array('assign', 'alincoln'),
),
)
@param string Raw mail text body.
@return dict Parsed body. | parseBody | php | phacility/phabricator | src/applications/metamta/parser/PhabricatorMetaMTAEmailBodyParser.php | https://github.com/phacility/phabricator/blob/master/src/applications/metamta/parser/PhabricatorMetaMTAEmailBodyParser.php | Apache-2.0 |
public function isEnabled() {
return (bool)PhabricatorJIRAAuthProvider::getJIRAProvider();
} | This worker is enabled when a JIRA authentication provider is active. | isEnabled | php | phacility/phabricator | src/applications/doorkeeper/worker/DoorkeeperJIRAFeedWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/doorkeeper/worker/DoorkeeperJIRAFeedWorker.php | Apache-2.0 |
private function findUsersToPossess() {
$object = $this->getStoryObject();
$publisher = $this->getPublisher();
$data = $this->getFeedStory()->getStoryData();
// Figure out all the users related to the object. Users go into one of
// four buckets. For JIRA integration, we don't care about which bucket
// a user is in, since we just want to publish an update to linked objects.
$owner_phid = $publisher->getOwnerPHID($object);
$active_phids = $publisher->getActiveUserPHIDs($object);
$passive_phids = $publisher->getPassiveUserPHIDs($object);
$follow_phids = $publisher->getCCUserPHIDs($object);
$all_phids = array_merge(
array($owner_phid),
$active_phids,
$passive_phids,
$follow_phids);
$all_phids = array_unique(array_filter($all_phids));
// Even if the actor isn't a reviewer, etc., try to use their account so
// we can post in the correct voice. If we miss, we'll try all the other
// related users.
$try_users = array_merge(
array($data->getAuthorPHID()),
$all_phids);
$try_users = array_filter($try_users);
return $try_users;
} | Get a list of users to act as when publishing into JIRA.
@return list<phid> Candidate user PHIDs to act as when publishing this
story.
@task internal | findUsersToPossess | php | phacility/phabricator | src/applications/doorkeeper/worker/DoorkeeperJIRAFeedWorker.php | https://github.com/phacility/phabricator/blob/master/src/applications/doorkeeper/worker/DoorkeeperJIRAFeedWorker.php | Apache-2.0 |
public function applyEdit(
PhabricatorApplicationTransaction $xaction,
PhabricatorApplicationTransactionComment $comment) {
$this->validateEdit($xaction, $comment);
$actor = $this->requireActor();
$this->applyMFAChecks($xaction, $comment);
$comment->setContentSource($this->getContentSource());
$comment->setAuthorPHID($this->getActingAsPHID());
// TODO: This needs to be more sophisticated once we have meta-policies.
$comment->setViewPolicy(PhabricatorPolicies::POLICY_PUBLIC);
$comment->setEditPolicy($this->getActingAsPHID());
$xaction->openTransaction();
$xaction->beginReadLocking();
if ($xaction->getID()) {
$xaction->reload();
}
$new_version = $xaction->getCommentVersion() + 1;
$comment->setCommentVersion($new_version);
$comment->setTransactionPHID($xaction->getPHID());
$comment->save();
$old_comment = $xaction->getComment();
$comment->attachOldComment($old_comment);
$xaction->setCommentVersion($new_version);
$xaction->setCommentPHID($comment->getPHID());
$xaction->setViewPolicy($comment->getViewPolicy());
$xaction->setEditPolicy($comment->getEditPolicy());
$xaction->save();
$xaction->attachComment($comment);
// For comment edits, we need to make sure there are no automagical
// transactions like adding mentions or projects.
if ($new_version > 1) {
$object = id(new PhabricatorObjectQuery())
->withPHIDs(array($xaction->getObjectPHID()))
->setViewer($this->getActor())
->executeOne();
if ($object &&
$object instanceof PhabricatorApplicationTransactionInterface) {
$editor = $object->getApplicationTransactionEditor();
$editor->setActor($this->getActor());
$support_xactions = $editor->getExpandedSupportTransactions(
$object,
$xaction);
if ($support_xactions) {
$editor
->setContentSource($this->getContentSource())
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true)
->applyTransactions($object, $support_xactions);
}
}
}
$xaction->endReadLocking();
$xaction->saveTransaction();
return $this;
} | Edit a transaction's comment. This method effects the required create,
update or delete to set the transaction's comment to the provided comment. | applyEdit | php | phacility/phabricator | src/applications/transactions/editor/PhabricatorApplicationTransactionCommentEditor.php | https://github.com/phacility/phabricator/blob/master/src/applications/transactions/editor/PhabricatorApplicationTransactionCommentEditor.php | Apache-2.0 |
private function validateEdit(
PhabricatorApplicationTransaction $xaction,
PhabricatorApplicationTransactionComment $comment) {
if (!$xaction->getPHID()) {
throw new Exception(
pht(
'Transaction must have a PHID before calling %s!',
'applyEdit()'));
}
$type_comment = PhabricatorTransactions::TYPE_COMMENT;
if ($xaction->getTransactionType() == $type_comment) {
if ($comment->getPHID()) {
throw new Exception(
pht('Transaction comment must not yet have a PHID!'));
}
}
if (!$this->getContentSource()) {
throw new PhutilInvalidStateException('applyEdit');
}
$actor = $this->requireActor();
PhabricatorPolicyFilter::requireCapability(
$actor,
$xaction,
PhabricatorPolicyCapability::CAN_VIEW);
if ($comment->getIsRemoved() && $actor->getIsAdmin()) {
// NOTE: Administrators can remove comments by any user, and don't need
// to pass the edit check.
} else {
PhabricatorPolicyFilter::requireCapability(
$actor,
$xaction,
PhabricatorPolicyCapability::CAN_EDIT);
PhabricatorPolicyFilter::requireCanInteract(
$actor,
$xaction->getObject());
}
} | Validate that the edit is permissible, and the actor has permission to
perform it. | validateEdit | php | phacility/phabricator | src/applications/transactions/editor/PhabricatorApplicationTransactionCommentEditor.php | https://github.com/phacility/phabricator/blob/master/src/applications/transactions/editor/PhabricatorApplicationTransactionCommentEditor.php | Apache-2.0 |
function jsShrink($input) {
return preg_replace_callback('(
(?:
(^|[-+\([{}=,:;!%^&*|?~]|/(?![/*])|return|throw) # context before regexp
(?:\s|//[^\n]*+\n|/\*(?:[^*]|\*(?!/))*+\*/)* # optional space
(/(?![/*])(?:
\\\\[^\n]
|[^[\n/\\\\]++
|\[(?:\\\\[^\n]|[^]])++
)+/) # regexp
|(^
|\'(?:\\\\.|[^\n\'\\\\])*\'
|"(?:\\\\.|[^\n"\\\\])*"
|([0-9A-Za-z_$]+)
|([-+]+)
|.
)
)(?:\s|//[^\n]*+\n|/\*(?:[^*]|\*(?!/))*+\*/)* # optional space
)sx', 'jsShrinkCallback', "$input\n");
} | Remove spaces and comments from JavaScript code
@param string code with commands terminated by semicolon
@return string shrinked code
@link http://vrana.github.com/JsShrink/
@author Jakub Vrana, http://www.vrana.cz/
@copyright 2007 Jakub Vrana
@license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
@license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other) | jsShrink | php | phacility/phabricator | externals/JsShrink/jsShrink.php | https://github.com/phacility/phabricator/blob/master/externals/JsShrink/jsShrink.php | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.