code
stringlengths 15
9.96M
| docstring
stringlengths 1
10.1k
| func_name
stringlengths 1
124
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 6
186
| url
stringlengths 50
236
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function getBool($name, $default = null) {
if (isset($this->requestData[$name])) {
if ($this->requestData[$name] === 'true') {
return true;
} else if ($this->requestData[$name] === 'false') {
return false;
} else {
return (bool)$this->requestData[$name];
}
} else {
return $default;
}
} | @task data | getBool | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public function getStr($name, $default = null) {
if (isset($this->requestData[$name])) {
$str = (string)$this->requestData[$name];
// Normalize newline craziness.
$str = str_replace(
array("\r\n", "\r"),
array("\n", "\n"),
$str);
return $str;
} else {
return $default;
}
} | @task data | getStr | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public function getExists($name) {
return array_key_exists($name, $this->requestData);
} | @task data | getExists | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public function canSetCookies() {
return (bool)$this->getCookieDomainURI();
} | Determine if security policy rules will allow cookies to be set when
responding to the request.
@return bool True if setCookie() will succeed. If this method returns
false, setCookie() will throw.
@task cookie | canSetCookies | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public function setCookie($name, $value) {
$far_future = time() + (60 * 60 * 24 * 365 * 5);
return $this->setCookieWithExpiration($name, $value, $far_future);
} | Set a cookie which does not expire for a long time.
To set a temporary cookie, see @{method:setTemporaryCookie}.
@param string $name Cookie name.
@param string $value Cookie value.
@return $this
@task cookie | setCookie | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public function setTemporaryCookie($name, $value) {
return $this->setCookieWithExpiration($name, $value, 0);
} | Set a cookie which expires soon.
To set a durable cookie, see @{method:setCookie}.
@param string $name Cookie name.
@param string $value Cookie value.
@return $this
@task cookie | setTemporaryCookie | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
private function setCookieWithExpiration(
$name,
$value,
$expire) {
$is_secure = false;
$base_domain_uri = $this->getCookieDomainURI();
if (!$base_domain_uri) {
$configured_as = PhabricatorEnv::getEnvConfig('phabricator.base-uri');
$accessed_as = $this->getHost();
throw new AphrontMalformedRequestException(
pht('Bad Host Header'),
pht(
'This server is configured as "%s", but you are using the domain '.
'name "%s" to access a page which is trying to set a cookie. '.
'Access this service on the configured primary domain or a '.
'configured alternate domain. Cookies will not be set on other '.
'domains for security reasons.',
$configured_as,
$accessed_as),
true);
}
$base_domain = $base_domain_uri->getDomain();
$is_secure = ($base_domain_uri->getProtocol() == 'https');
$name = $this->getPrefixedCookieName($name);
if (php_sapi_name() == 'cli') {
// Do nothing, to avoid triggering "Cannot modify header information"
// warnings.
// TODO: This is effectively a test for whether we're running in a unit
// test or not. Move this actual call to HTTPSink?
} else {
setcookie(
$name,
$value,
$expire,
$path = '/',
$base_domain,
$is_secure,
$http_only = true);
}
$_COOKIE[$name] = $value;
return $this;
} | Set a cookie with a given expiration policy.
@param string $name Cookie name.
@param string $value Cookie value.
@param int $expire Epoch timestamp for cookie expiration.
@return $this
@task cookie | setCookieWithExpiration | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public function getPassthroughRequestParameters($include_quicksand = false) {
return self::flattenData(
$this->getPassthroughRequestData($include_quicksand));
} | Get application request parameters in a flattened form suitable for
inclusion in an HTTP request, excluding parameters with special meanings.
This is primarily useful if you want to ask the user for more input and
then resubmit their request.
@return dict<string, string> Original request parameters. | getPassthroughRequestParameters | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public function getPassthroughRequestData($include_quicksand = false) {
$data = $this->getRequestData();
// Remove magic parameters like __dialog__ and __ajax__.
foreach ($data as $key => $value) {
if ($include_quicksand && $key == self::TYPE_QUICKSAND) {
continue;
}
if (!strncmp($key, '__', 2)) {
unset($data[$key]);
}
}
return $data;
} | Get request data other than "magic" parameters.
@return dict<string, wild> Request data, with magic filtered out. | getPassthroughRequestData | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public function isProxiedClusterRequest() {
return (bool)self::getHTTPHeader('X-Phabricator-Cluster');
} | Is this a proxied request originating from within the Phabricator cluster?
IMPORTANT: This means the request is dangerous!
These requests are **more dangerous** than normal requests (they can not
be safely proxied, because proxying them may cause a loop). Cluster
requests are not guaranteed to come from a trusted source, and should
never be treated as safer than normal requests. They are strictly less
safe. | isProxiedClusterRequest | php | phorgeit/phorge | src/aphront/AphrontRequest.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/AphrontRequest.php | Apache-2.0 |
public static function getURIForRedirect($uri, $is_external) {
$uri_object = new PhutilURI($uri);
if ($is_external) {
// If this is a remote resource it must have a domain set. This
// would also be caught below, but testing for it explicitly first allows
// us to raise a better error message.
if (!strlen($uri_object->getDomain())) {
throw new Exception(
pht(
'Refusing to redirect to external URI "%s". This URI '.
'is not fully qualified, and is missing a domain name. To '.
'redirect to a local resource, remove the external flag.',
(string)$uri));
}
// Check that it's a valid remote resource.
if (!PhabricatorEnv::isValidURIForLink($uri)) {
throw new Exception(
pht(
'Refusing to redirect to external URI "%s". This URI '.
'is not a valid remote web resource.',
(string)$uri));
}
} else {
// If this is a local resource, it must not have a domain set. This allows
// us to raise a better error message than the check below can.
if (strlen($uri_object->getDomain())) {
throw new Exception(
pht(
'Refusing to redirect to local resource "%s". The URI has a '.
'domain, but the redirect is not marked external. Mark '.
'redirects as external to allow redirection off the local '.
'domain.',
(string)$uri));
}
// If this is a local resource, it must be a valid local resource.
if (!PhabricatorEnv::isValidLocalURIForLink($uri)) {
throw new Exception(
pht(
'Refusing to redirect to local resource "%s". This URI is not '.
'formatted in a recognizable way.',
(string)$uri));
}
// Fully qualify the result URI.
$uri = PhabricatorEnv::getURI((string)$uri);
}
return (string)$uri;
} | Format a URI for use in a "Location:" header.
Verifies that a URI redirects to the expected type of resource (local or
remote) and formats it for use in a "Location:" header.
The HTTP spec says "Location:" headers must use absolute URIs. Although
browsers work with relative URIs, we return absolute URIs to avoid
ambiguity. For example, Chrome interprets "Location: /\evil.com" to mean
"perform a protocol-relative redirect to evil.com".
@param string $uri URI to redirect to.
@param bool $is_external True if this URI identifies a remote
resource.
@return string URI for use in a "Location:" header. | getURIForRedirect | php | phorgeit/phorge | src/aphront/response/AphrontRedirectResponse.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/response/AphrontRedirectResponse.php | Apache-2.0 |
public function setDownload($download) {
// Make sure we have a populated string
if (!phutil_nonempty_string($download)) {
$download = 'untitled';
}
$this->download = $download;
return $this;
} | Set a download filename
@param string $download
@return self | setDownload | php | phorgeit/phorge | src/aphront/response/AphrontFileResponse.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/response/AphrontFileResponse.php | Apache-2.0 |
public function getDownload() {
return $this->download;
} | Get the download filename
If this was never set, NULL is given.
@return string|null | getDownload | php | phorgeit/phorge | src/aphront/response/AphrontFileResponse.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/response/AphrontFileResponse.php | Apache-2.0 |
final public function writeHTTPStatus($code, $message = '') {
if (!preg_match('/^\d{3}$/', $code)) {
throw new Exception(pht("Malformed HTTP status code '%s'!", $code));
}
$code = (int)$code;
$this->emitHTTPStatus($code, $message);
} | Write an HTTP status code to the output.
@param int $code Numeric HTTP status code.
@param string $message (optional)
@return void | writeHTTPStatus | php | phorgeit/phorge | src/aphront/sink/AphrontHTTPSink.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/sink/AphrontHTTPSink.php | Apache-2.0 |
final public function writeData($data) {
$this->emitData($data);
} | Write HTTP body data to the output.
@param string $data Body data.
@return void | writeData | php | phorgeit/phorge | src/aphront/sink/AphrontHTTPSink.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/sink/AphrontHTTPSink.php | Apache-2.0 |
final public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
} | Set the current viewer.
Some parameter types perform complex parsing involving lookups. For
example, a type might lookup usernames or project names. These types need
to use the current viewer to execute queries.
@param PhabricatorUser $viewer Current viewer.
@return $this
@task read | setViewer | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final public function getViewer() {
if (!$this->viewer) {
throw new PhutilInvalidStateException('setViewer');
}
return $this->viewer;
} | Get the current viewer.
@return PhabricatorUser Current viewer.
@task read | getViewer | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final public function getExists(AphrontRequest $request, $key) {
return $this->getParameterExists($request, $key);
} | Test if a value is present in a request.
@param AphrontRequest $request The incoming request.
@param string $key The key to examine.
@return bool True if a readable value is present in the request.
@task read | getExists | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final public function getValue(AphrontRequest $request, $key) {
if (!$this->getExists($request, $key)) {
return $this->getParameterDefault();
}
return $this->getParameterValue($request, $key);
} | Read a value from a request.
If the value is not present, a default value is returned (usually `null`).
Use @{method:getExists} to test if a value is present.
@param AphrontRequest $request The incoming request.
@param string $key The key to examine.
@return wild Value, or default if value is not present.
@task read | getValue | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final public function getDefaultValue() {
return $this->getParameterDefault();
} | Get the default value for this parameter type.
@return wild Default value for this type.
@task read | getDefaultValue | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final public function getTypeName() {
return $this->getParameterTypeName();
} | Get a short name for this type, like `string` or `list<phid>`.
@return string Short type name.
@task info | getTypeName | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final public function getFormatDescriptions() {
return $this->getParameterFormatDescriptions();
} | Get a list of human-readable descriptions of acceptable formats for this
type.
For example, a type might return strings like these:
> Any positive integer.
> A comma-separated list of PHIDs.
This is used to explain to users how to specify a type when generating
documentation.
@return list<string> Human-readable list of acceptable formats.
@task info | getFormatDescriptions | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final public function getExamples() {
return $this->getParameterExamples();
} | Get a list of human-readable examples of how to format this type as an
HTTP GET parameter.
For example, a type might return strings like these:
> v=123
> v[]=1&v[]=2
This is used to show users how to specify parameters of this type in
generated documentation.
@return list<string> Human-readable list of format examples.
@task info | getExamples | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final protected function getExistsWithType(
AphrontHTTPParameterType $type,
AphrontRequest $request,
$key) {
$type->setViewer($this->getViewer());
return $type->getParameterExists($request, $key);
} | Call another type's existence check.
This method allows a type to reuse the existence behavior of a different
type. For example, a "list of users" type may have the same basic
existence check that a simpler "list of strings" type has, and can just
call the simpler type to reuse its behavior.
@param AphrontHTTPParameterType $type The other type.
@param AphrontRequest $request Incoming request.
@param string $key Key to examine.
@return bool True if the parameter exists.
@task util | getExistsWithType | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final protected function getValueWithType(
AphrontHTTPParameterType $type,
AphrontRequest $request,
$key) {
$type->setViewer($this->getViewer());
return $type->getValue($request, $key);
} | Call another type's value parser.
This method allows a type to reuse the parsing behavior of a different
type. For example, a "list of users" type may start by running the same
basic parsing that a simpler "list of strings" type does.
@param AphrontHTTPParameterType $type The other type.
@param AphrontRequest $request Incoming request.
@param string $key Key to examine.
@return wild Parsed value.
@task util | getValueWithType | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
final public static function getAllTypes() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getTypeName')
->setSortMethod('getTypeName')
->execute();
} | Get a list of all available parameter types.
@return list<AphrontHTTPParameterType> List of all available types.
@task util | getAllTypes | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
protected function getParameterExists(AphrontRequest $request, $key) {
return $request->getExists($key);
} | Test if a parameter exists in a request.
See @{method:getExists}. By default, this method tests if the key is
present in the request.
To call another type's behavior in order to perform this check, use
@{method:getExistsWithType}.
@param AphrontRequest $request The incoming request.
@param string $key The key to examine.
@return bool True if a readable value is present in the request.
@task impl | getParameterExists | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
protected function getParameterDefault() {
return null;
} | Return the default value for this parameter type.
See @{method:getDefaultValue}. If unspecified, the default is `null`.
@return wild|null Default value (null if unspecified).
@task impl | getParameterDefault | php | phorgeit/phorge | src/aphront/httpparametertype/AphrontHTTPParameterType.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/httpparametertype/AphrontHTTPParameterType.php | Apache-2.0 |
public static function runHTTPRequest(AphrontHTTPSink $sink) {
if (isset($_SERVER['HTTP_X_SETUP_SELFCHECK'])) {
$response = self::newSelfCheckResponse();
return self::writeResponse($sink, $response);
}
PhabricatorStartup::beginStartupPhase('multimeter');
$multimeter = MultimeterControl::newInstance();
$multimeter->setEventContext('<http-init>');
$multimeter->setEventViewer('<none>');
// Build a no-op write guard for the setup phase. We'll replace this with a
// real write guard later on, but we need to survive setup and build a
// request object first.
$write_guard = new AphrontWriteGuard('id');
PhabricatorStartup::beginStartupPhase('preflight');
$response = PhabricatorSetupCheck::willPreflightRequest();
if ($response) {
return self::writeResponse($sink, $response);
}
PhabricatorStartup::beginStartupPhase('env.init');
self::readHTTPPOSTData();
try {
PhabricatorEnv::initializeWebEnvironment();
$database_exception = null;
} catch (PhabricatorClusterStrandedException $ex) {
$database_exception = $ex;
}
// If we're in developer mode, set a flag so that top-level exception
// handlers can add more information.
if (PhabricatorEnv::getEnvConfig('phabricator.developer-mode')) {
$sink->setShowStackTraces(true);
}
if ($database_exception) {
$issue = PhabricatorSetupIssue::newDatabaseConnectionIssue(
$database_exception,
true);
$response = PhabricatorSetupCheck::newIssueResponse($issue);
return self::writeResponse($sink, $response);
}
$multimeter->setSampleRate(
PhabricatorEnv::getEnvConfig('debug.sample-rate'));
$debug_time_limit = PhabricatorEnv::getEnvConfig('debug.time-limit');
if ($debug_time_limit) {
PhabricatorStartup::setDebugTimeLimit($debug_time_limit);
}
// This is the earliest we can get away with this, we need env config first.
PhabricatorStartup::beginStartupPhase('log.access');
PhabricatorAccessLog::init();
$access_log = PhabricatorAccessLog::getLog();
PhabricatorStartup::setAccessLog($access_log);
$address = PhabricatorEnv::getRemoteAddress();
if ($address) {
$address_string = $address->getAddress();
} else {
$address_string = '-';
}
$access_log->setData(
array(
'R' => AphrontRequest::getHTTPHeader('Referer', '-'),
'r' => $address_string,
'M' => idx($_SERVER, 'REQUEST_METHOD', '-'),
));
DarkConsoleXHProfPluginAPI::hookProfiler();
// We just activated the profiler, so we don't need to keep track of
// startup phases anymore: it can take over from here.
PhabricatorStartup::beginStartupPhase('startup.done');
DarkConsoleErrorLogPluginAPI::registerErrorHandler();
$response = PhabricatorSetupCheck::willProcessRequest();
if ($response) {
return self::writeResponse($sink, $response);
}
$host = AphrontRequest::getHTTPHeader('Host');
$path = PhabricatorStartup::getRequestPath();
$application = new self();
$application->setHost($host);
$application->setPath($path);
$request = $application->buildRequest();
// Now that we have a request, convert the write guard into one which
// actually checks CSRF tokens.
$write_guard->dispose();
$write_guard = new AphrontWriteGuard(array($request, 'validateCSRF'));
// Build the server URI implied by the request headers. If an administrator
// has not configured "phabricator.base-uri" yet, we'll use this to generate
// links.
$request_protocol = ($request->isHTTPS() ? 'https' : 'http');
$request_base_uri = "{$request_protocol}://{$host}/";
PhabricatorEnv::setRequestBaseURI($request_base_uri);
$access_log->setData(
array(
'U' => (string)$request->getRequestURI()->getPath(),
));
$processing_exception = null;
try {
$response = $application->processRequest(
$request,
$access_log,
$sink,
$multimeter);
$response_code = $response->getHTTPResponseCode();
} catch (Exception $ex) {
$processing_exception = $ex;
$response_code = 500;
}
$write_guard->dispose();
$access_log->setData(
array(
'c' => $response_code,
'T' => PhabricatorStartup::getMicrosecondsSinceStart(),
));
$multimeter->newEvent(
MultimeterEvent::TYPE_REQUEST_TIME,
$multimeter->getEventContext(),
PhabricatorStartup::getMicrosecondsSinceStart());
$access_log->write();
$multimeter->saveEvents();
DarkConsoleXHProfPluginAPI::saveProfilerSample($access_log);
PhabricatorStartup::disconnectRateLimits(
array(
'viewer' => $request->getUser(),
));
if ($processing_exception) {
throw $processing_exception;
}
} | @phutil-external-symbol class PhabricatorStartup | runHTTPRequest | php | phorgeit/phorge | src/aphront/configuration/AphrontApplicationConfiguration.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/configuration/AphrontApplicationConfiguration.php | Apache-2.0 |
private function buildController() {
$request = $this->getRequest();
// If we're configured to operate in cluster mode, reject requests which
// were not received on a cluster interface.
//
// For example, a host may have an internal address like "170.0.0.1", and
// also have a public address like "51.23.95.16". Assuming the cluster
// is configured on a range like "170.0.0.0/16", we want to reject the
// requests received on the public interface.
//
// Ideally, nodes in a cluster should only be listening on internal
// interfaces, but they may be configured in such a way that they also
// listen on external interfaces, since this is easy to forget about or
// get wrong. As a broad security measure, reject requests received on any
// interfaces which aren't on the whitelist.
$cluster_addresses = PhabricatorEnv::getEnvConfig('cluster.addresses');
if ($cluster_addresses) {
$server_addr = idx($_SERVER, 'SERVER_ADDR');
if (!$server_addr) {
if (php_sapi_name() == 'cli') {
// This is a command line script (probably something like a unit
// test) so it's fine that we don't have SERVER_ADDR defined.
} else {
throw new AphrontMalformedRequestException(
pht('No %s', 'SERVER_ADDR'),
pht(
'This service is configured to operate in cluster mode, but '.
'%s is not defined in the request context. Your webserver '.
'configuration needs to forward %s to PHP so the software can '.
'reject requests received on external interfaces.',
'SERVER_ADDR',
'SERVER_ADDR'));
}
} else {
if (!PhabricatorEnv::isClusterAddress($server_addr)) {
throw new AphrontMalformedRequestException(
pht('External Interface'),
pht(
'This service is configured in cluster mode and the address '.
'this request was received on ("%s") is not whitelisted as '.
'a cluster address.',
$server_addr));
}
}
}
$site = $this->buildSiteForRequest($request);
if ($site->shouldRequireHTTPS()) {
if (!$request->isHTTPS()) {
// Don't redirect intracluster requests: doing so drops headers and
// parameters, imposes a performance penalty, and indicates a
// misconfiguration.
if ($request->isProxiedClusterRequest()) {
throw new AphrontMalformedRequestException(
pht('HTTPS Required'),
pht(
'This request reached a site which requires HTTPS, but the '.
'request is not marked as HTTPS.'));
}
$https_uri = $request->getRequestURI();
$https_uri->setDomain($request->getHost());
$https_uri->setProtocol('https');
// In this scenario, we'll be redirecting to HTTPS using an absolute
// URI, so we need to permit an external redirect.
return $this->buildRedirectController($https_uri, true);
}
}
$maps = $site->getRoutingMaps();
$path = $request->getPath();
$result = $this->routePath($maps, $path);
if ($result) {
return $result;
}
// If we failed to match anything but don't have a trailing slash, try
// to add a trailing slash and issue a redirect if that resolves.
// NOTE: We only do this for GET, since redirects switch to GET and drop
// data like POST parameters.
if (!preg_match('@/$@', $path) && $request->isHTTPGet()) {
$result = $this->routePath($maps, $path.'/');
if ($result) {
$target_uri = $request->getAbsoluteRequestURI();
// We need to restore URI encoding because the webserver has
// interpreted it. For example, this allows us to redirect a path
// like `/tag/aa%20bb` to `/tag/aa%20bb/`, which may eventually be
// resolved meaningfully by an application.
$target_path = phutil_escape_uri($path.'/');
$target_uri->setPath($target_path);
$target_uri = (string)$target_uri;
return $this->buildRedirectController($target_uri, true);
}
}
$result = $site->new404Controller($request);
if ($result) {
return array($result, array());
}
throw new Exception(
pht(
'Aphront site ("%s") failed to build a 404 controller.',
get_class($site)));
} | Build a controller to respond to the request.
@return pair<AphrontController,dict> Controller and dictionary of request
parameters.
@task routing | buildController | php | phorgeit/phorge | src/aphront/configuration/AphrontApplicationConfiguration.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/configuration/AphrontApplicationConfiguration.php | Apache-2.0 |
private function isValidResponseObject($response) {
if ($response instanceof AphrontResponse) {
return true;
}
if ($response instanceof AphrontResponseProducerInterface) {
return true;
}
return false;
} | Tests if a response is of a valid type.
@param wild $response Supposedly valid response.
@return bool True if the object is of a valid type.
@task response | isValidResponseObject | php | phorgeit/phorge | src/aphront/configuration/AphrontApplicationConfiguration.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/configuration/AphrontApplicationConfiguration.php | Apache-2.0 |
private function validateControllerResponse(
AphrontController $controller,
$response) {
if ($this->isValidResponseObject($response)) {
return;
}
throw new Exception(
pht(
'Controller "%s" returned an invalid response from call to "%s". '.
'This method must return an object of class "%s", or an object '.
'which implements the "%s" interface.',
get_class($controller),
'handleRequest()',
'AphrontResponse',
'AphrontResponseProducerInterface'));
} | Verifies that the return value from an @{class:AphrontController} is
of an allowed type.
@param AphrontController $controller Controller which returned the
response.
@param wild $response Supposedly valid response.
@return void
@task response | validateControllerResponse | php | phorgeit/phorge | src/aphront/configuration/AphrontApplicationConfiguration.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/configuration/AphrontApplicationConfiguration.php | Apache-2.0 |
private function validateProducerResponse(
AphrontResponseProducerInterface $producer,
$response) {
if ($this->isValidResponseObject($response)) {
return;
}
throw new Exception(
pht(
'Producer "%s" returned an invalid response from call to "%s". '.
'This method must return an object of class "%s", or an object '.
'which implements the "%s" interface.',
get_class($producer),
'produceAphrontResponse()',
'AphrontResponse',
'AphrontResponseProducerInterface'));
} | Verifies that the return value from an
@{class:AphrontResponseProducerInterface} is of an allowed type.
@param AphrontResponseProducerInterface $producer Object which produced
this response.
@param wild $response Supposedly valid response.
@return void
@task response | validateProducerResponse | php | phorgeit/phorge | src/aphront/configuration/AphrontApplicationConfiguration.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/configuration/AphrontApplicationConfiguration.php | Apache-2.0 |
private function validateErrorHandlerResponse(
AphrontRequestExceptionHandler $handler,
$response) {
if ($this->isValidResponseObject($response)) {
return;
}
throw new Exception(
pht(
'Exception handler "%s" returned an invalid response from call to '.
'"%s". This method must return an object of class "%s", or an object '.
'which implements the "%s" interface.',
get_class($handler),
'handleRequestException()',
'AphrontResponse',
'AphrontResponseProducerInterface'));
} | Verifies that the return value from an
@{class:AphrontRequestExceptionHandler} is of an allowed type.
@param AphrontRequestExceptionHandler $handler Object which produced this
response.
@param wild $response Supposedly valid response.
@return void
@task response | validateErrorHandlerResponse | php | phorgeit/phorge | src/aphront/configuration/AphrontApplicationConfiguration.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/configuration/AphrontApplicationConfiguration.php | Apache-2.0 |
private function produceResponse(AphrontRequest $request, $response) {
$original = $response;
// Detect cycles on the exact same objects. It's still possible to produce
// infinite responses as long as they're all unique, but we can only
// reasonably detect cycles, not guarantee that response production halts.
$seen = array();
while (true) {
// NOTE: It is permissible for an object to be both a response and a
// response producer. If so, being a producer is "stronger". This is
// used by AphrontProxyResponse.
// If this response is a valid response, hand over the request first.
if ($response instanceof AphrontResponse) {
$response->setRequest($request);
}
// If this isn't a producer, we're all done.
if (!($response instanceof AphrontResponseProducerInterface)) {
break;
}
$hash = spl_object_hash($response);
if (isset($seen[$hash])) {
throw new Exception(
pht(
'Failure while producing response for object of class "%s": '.
'encountered production cycle (identical object, of class "%s", '.
'was produced twice).',
get_class($original),
get_class($response)));
}
$seen[$hash] = true;
$new_response = $response->produceAphrontResponse();
$this->validateProducerResponse($response, $new_response);
$response = $new_response;
}
return $response;
} | Resolves a response object into an @{class:AphrontResponse}.
Controllers are permitted to return actual responses of class
@{class:AphrontResponse}, or other objects which implement
@{interface:AphrontResponseProducerInterface} and can produce a response.
If a controller returns a response producer, invoke it now and produce
the real response.
@param AphrontRequest $request Request being handled.
@param AphrontResponse|AphrontResponseProducerInterface $response
Response, or response producer.
@return AphrontResponse Response after any required production.
@task response | produceResponse | php | phorgeit/phorge | src/aphront/configuration/AphrontApplicationConfiguration.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/configuration/AphrontApplicationConfiguration.php | Apache-2.0 |
private function handleThrowable($throwable) {
$handlers = AphrontRequestExceptionHandler::getAllHandlers();
$request = $this->getRequest();
foreach ($handlers as $handler) {
if ($handler->canHandleRequestThrowable($request, $throwable)) {
$response = $handler->handleRequestThrowable($request, $throwable);
$this->validateErrorHandlerResponse($handler, $response);
return $response;
}
}
throw $throwable;
} | Convert an exception which has escaped the controller into a response.
This method delegates exception handling to available subclasses of
@{class:AphrontRequestExceptionHandler}.
@param Throwable $throwable Exception which needs to be handled.
@return wild Response or response producer, or null if no available
handler can produce a response.
@task exception | handleThrowable | php | phorgeit/phorge | src/aphront/configuration/AphrontApplicationConfiguration.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/configuration/AphrontApplicationConfiguration.php | Apache-2.0 |
public function dispose() {
if (!self::$instance) {
throw new Exception(pht(
'Attempting to dispose of write guard, but no write guard is active!'));
}
if ($this->allowDepth > 0) {
throw new Exception(
pht(
'Imbalanced %s: more %s calls than %s calls.',
__CLASS__,
'beginUnguardedWrites()',
'endUnguardedWrites()'));
}
self::$instance = null;
} | Dispose of the active write guard. You must call this method when you are
done with a write guard. You do not normally need to call this yourself.
@return void
@task manage | dispose | php | phorgeit/phorge | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/writeguard/AphrontWriteGuard.php | Apache-2.0 |
public static function isGuardActive() {
return (bool)self::$instance;
} | Determine if there is an active write guard.
@return bool
@task manage | isGuardActive | php | phorgeit/phorge | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/writeguard/AphrontWriteGuard.php | Apache-2.0 |
public static function getInstance() {
return self::$instance;
} | Return on instance of AphrontWriteGuard if it's active, or null
@return AphrontWriteGuard|null | getInstance | php | phorgeit/phorge | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phorgeit/phorge/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 | phorgeit/phorge | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phorgeit/phorge/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 | phorgeit/phorge | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phorgeit/phorge/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 | phorgeit/phorge | src/aphront/writeguard/AphrontWriteGuard.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/writeguard/AphrontWriteGuard.php | Apache-2.0 |
private function newRoutingResult() {
return id(new AphrontRoutingResult())
->setSite($this->getSite())
->setApplication($this->getApplication());
} | Build a new routing result for this map.
@return AphrontRoutingResult New, empty routing result.
@task routing | newRoutingResult | php | phorgeit/phorge | src/aphront/site/AphrontRoutingMap.php | https://github.com/phorgeit/phorge/blob/master/src/aphront/site/AphrontRoutingMap.php | Apache-2.0 |
public function newFileData() {
$workbook = $this->getWorkbook();
$writer = PHPExcel_IOFactory::createWriter($workbook, 'Excel2007');
ob_start();
$writer->save('php://output');
$data = ob_get_clean();
return $data;
} | @phutil-external-symbol class PHPExcel_IOFactory | newFileData | php | phorgeit/phorge | src/infrastructure/export/format/PhabricatorExcelExportFormat.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/export/format/PhabricatorExcelExportFormat.php | Apache-2.0 |
private function newWorkbook() {
include_once 'PHPExcel.php';
return new PHPExcel();
} | @phutil-external-symbol class PHPExcel | newWorkbook | php | phorgeit/phorge | src/infrastructure/export/format/PhabricatorExcelExportFormat.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/export/format/PhabricatorExcelExportFormat.php | Apache-2.0 |
private function getCellName($col, $row = null) {
$col_name = PHPExcel_Cell::stringFromColumnIndex($col);
if ($row === null) {
return $col_name;
}
return $col_name.$row;
} | @phutil-external-symbol class PHPExcel_Cell | getCellName | php | phorgeit/phorge | src/infrastructure/export/format/PhabricatorExcelExportFormat.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/export/format/PhabricatorExcelExportFormat.php | Apache-2.0 |
public function formatPHPExcelCell($cell, $style) {
$cell->setDataType(PHPExcel_Cell_DataType::TYPE_NUMERIC);
} | @phutil-external-symbol class PHPExcel_Cell_DataType | formatPHPExcelCell | php | phorgeit/phorge | src/infrastructure/export/field/PhabricatorIntExportField.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/export/field/PhabricatorIntExportField.php | Apache-2.0 |
public function formatPHPExcelCell($cell, $style) {
$code = PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2;
$style
->getNumberFormat()
->setFormatCode($code);
} | @phutil-external-symbol class PHPExcel_Style_NumberFormat | formatPHPExcelCell | php | phorgeit/phorge | src/infrastructure/export/field/PhabricatorEpochExportField.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/export/field/PhabricatorEpochExportField.php | Apache-2.0 |
public function formatPHPExcelCell($cell, $style) {
$cell->setDataType(PHPExcel_Cell_DataType::TYPE_NUMERIC);
} | @phutil-external-symbol class PHPExcel_Cell_DataType | formatPHPExcelCell | php | phorgeit/phorge | src/infrastructure/export/field/PhabricatorDoubleExportField.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/export/field/PhabricatorDoubleExportField.php | Apache-2.0 |
public function formatPHPExcelCell($cell, $style) {
$cell->setDataType(PHPExcel_Cell_DataType::TYPE_STRING);
} | @phutil-external-symbol class PHPExcel_Cell_DataType | formatPHPExcelCell | php | phorgeit/phorge | src/infrastructure/export/field/PhabricatorExportField.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/export/field/PhabricatorExportField.php | Apache-2.0 |
public function __construct($config) {
$root = dirname(phutil_get_library_root('phabricator'));
require_once $root.'/conf/__init_conf__.php';
$dictionary = phabricator_read_config_file($config);
$dictionary['phabricator.env'] = $config;
$this->setSource(new PhabricatorConfigDictionarySource($dictionary));
} | @phutil-external-symbol function phabricator_read_config_file | __construct | php | phorgeit/phorge | src/infrastructure/env/PhabricatorConfigFileSource.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorConfigFileSource.php | Apache-2.0 |
public static function initializeWebEnvironment() {
self::initializeCommonEnvironment(false);
} | @phutil-external-symbol class PhabricatorStartup | initializeWebEnvironment | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function getEnvConfig($key) {
if (!self::$sourceStack) {
throw new Exception(
pht(
'Trying to read configuration "%s" before configuration has been '.
'initialized.',
$key));
}
if (isset(self::$cache[$key])) {
return self::$cache[$key];
}
if (array_key_exists($key, self::$cache)) {
return self::$cache[$key];
}
$result = self::$sourceStack->getKeys(array($key));
if (array_key_exists($key, $result)) {
self::$cache[$key] = $result[$key];
return $result[$key];
} else {
throw new Exception(
pht(
"No config value specified for key '%s'.",
$key));
}
} | Get the current configuration setting for a given key.
If the key is not found, then throw an Exception.
@task read | getEnvConfig | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function getEnvConfigIfExists($key, $default = null) {
try {
return self::getEnvConfig($key);
} catch (Exception $ex) {
return $default;
}
} | Get the current configuration setting for a given key. If the key
does not exist, return a default value instead of throwing. This is
primarily useful for migrations involving keys which are slated for
removal.
@task read | getEnvConfigIfExists | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function getURI($path) {
return rtrim(self::getAnyBaseURI(), '/').$path;
} | Get the fully-qualified URI for a path.
@task read | getURI | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function getProductionURI($path) {
// If we're passed a URI which already has a domain, simply return it
// unmodified. In particular, files may have URIs which point to a CDN
// domain.
$uri = new PhutilURI($path);
if ($uri->getDomain()) {
return $path;
}
$production_domain = self::getEnvConfig('phabricator.production-uri');
if (!$production_domain) {
$production_domain = self::getAnyBaseURI();
}
return rtrim($production_domain, '/').$path;
} | Get the fully-qualified production URI for a path.
@task read | getProductionURI | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function getCDNURI($path) {
$alt = self::getEnvConfig('security.alternate-file-domain');
if (!$alt) {
$alt = self::getAnyBaseURI();
}
$uri = new PhutilURI($alt);
$uri->setPath($path);
return (string)$uri;
} | Get the fully-qualified production URI for a static resource path.
@task read | getCDNURI | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function getDoclink($resource, $type = 'article') {
$params = array(
'name' => $resource,
'type' => $type,
'jump' => true,
);
$uri = new PhutilURI(
'https://we.phorge.it/diviner/find/',
$params);
return phutil_string_cast($uri);
} | Get the fully-qualified production URI for a documentation resource.
@task read | getDoclink | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function beginScopedEnv() {
return new PhabricatorScopedEnv(self::pushTestEnvironment());
} | @task test | beginScopedEnv | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
private static function pushTestEnvironment() {
self::dropConfigCache();
$source = new PhabricatorConfigDictionarySource(array());
self::$sourceStack->pushSource($source);
return spl_object_hash($source);
} | @task test | pushTestEnvironment | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function popTestEnvironment($key) {
self::dropConfigCache();
$source = self::$sourceStack->popSource();
$stack_key = spl_object_hash($source);
if ($stack_key !== $key) {
self::$sourceStack->pushSource($source);
throw new Exception(
pht(
'Scoped environments were destroyed in a different order than they '.
'were initialized.'));
}
} | @task test | popTestEnvironment | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function isValidURIForLink($uri) {
return self::isValidLocalURIForLink($uri) ||
self::isValidRemoteURIForLink($uri);
} | Detect if a URI satisfies either @{method:isValidLocalURIForLink} or
@{method:isValidRemoteURIForLink}, i.e. is a page on this server or the
URI of some other resource which has a valid protocol. This rejects
garbage URIs and URIs with protocols which do not appear in the
`uri.allowed-protocols` configuration, notably 'javascript:' URIs.
NOTE: This method is generally intended to reject URIs which it may be
unsafe to put in an "href" link attribute.
@param string $uri URI to test.
@return bool True if the URI identifies a web resource.
@task uri | isValidURIForLink | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function isValidLocalURIForLink($uri) {
$uri = (string)$uri;
if (!phutil_nonempty_string($uri)) {
return false;
}
if (preg_match('/\s/', $uri)) {
// PHP hasn't been vulnerable to header injection attacks for a bunch of
// years, but we can safely reject these anyway since they're never valid.
return false;
}
// Chrome (at a minimum) interprets backslashes in Location headers and the
// URL bar as forward slashes. This is probably intended to reduce user
// error caused by confusion over which key is "forward slash" vs "back
// slash".
//
// However, it means a URI like "/\evil.com" is interpreted like
// "//evil.com", which is a protocol relative remote URI.
//
// Since we currently never generate URIs with backslashes in them, reject
// these unconditionally rather than trying to figure out how browsers will
// interpret them.
if (preg_match('/\\\\/', $uri)) {
return false;
}
// Valid URIs must begin with '/', followed by the end of the string or some
// other non-'/' character. This rejects protocol-relative URIs like
// "//evil.com/evil_stuff/".
return (bool)preg_match('@^/([^/]|$)@', $uri);
} | Detect if a URI identifies some page on this server.
NOTE: This method is generally intended to reject URIs which it may be
unsafe to issue a "Location:" redirect to.
@param string $uri URI to test.
@return bool True if the URI identifies a local page.
@task uri | isValidLocalURIForLink | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function isValidRemoteURIForLink($uri) {
try {
self::requireValidRemoteURIForLink($uri);
return true;
} catch (Exception $ex) {
return false;
}
} | Detect if a URI identifies some valid linkable remote resource.
@param string $uri URI to test.
@return bool True if a URI identifies a remote resource with an allowed
protocol.
@task uri | isValidRemoteURIForLink | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function requireValidRemoteURIForLink($raw_uri) {
$uri = new PhutilURI($raw_uri);
$proto = $uri->getProtocol();
if (!$proto) {
throw new Exception(
pht(
'URI "%s" is not a valid linkable resource. A valid linkable '.
'resource URI must specify a protocol.',
$raw_uri));
}
$protocols = self::getEnvConfig('uri.allowed-protocols');
if (!isset($protocols[$proto])) {
throw new Exception(
pht(
'URI "%s" is not a valid linkable resource. A valid linkable '.
'resource URI must use one of these protocols: %s.',
$raw_uri,
implode(', ', array_keys($protocols))));
}
$domain = $uri->getDomain();
if (!$domain) {
throw new Exception(
pht(
'URI "%s" is not a valid linkable resource. A valid linkable '.
'resource URI must specify a domain.',
$raw_uri));
}
} | Detect if a URI identifies a valid linkable remote resource, throwing a
detailed message if it does not.
A valid linkable remote resource can be safely linked or redirected to.
This is primarily a protocol whitelist check.
@param string $raw_uri URI to test.
@return void
@task uri | requireValidRemoteURIForLink | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function isValidRemoteURIForFetch($uri, array $protocols) {
try {
self::requireValidRemoteURIForFetch($uri, $protocols);
return true;
} catch (Exception $ex) {
return false;
}
} | Detect if a URI identifies a valid fetchable remote resource.
@param string $uri URI to test.
@param list<string> $protocols Allowed protocols.
@return bool True if the URI is a valid fetchable remote resource.
@task uri | isValidRemoteURIForFetch | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function requireValidRemoteURIForFetch(
$raw_uri,
array $protocols) {
$uri = new PhutilURI($raw_uri);
$proto = $uri->getProtocol();
if (!$proto) {
throw new Exception(
pht(
'URI "%s" is not a valid fetchable resource. A valid fetchable '.
'resource URI must specify a protocol.',
$raw_uri));
}
$protocols = array_fuse($protocols);
if (!isset($protocols[$proto])) {
throw new Exception(
pht(
'URI "%s" is not a valid fetchable resource. A valid fetchable '.
'resource URI must use one of these protocols: %s.',
$raw_uri,
implode(', ', array_keys($protocols))));
}
$domain = $uri->getDomain();
if (!$domain) {
throw new Exception(
pht(
'URI "%s" is not a valid fetchable resource. A valid fetchable '.
'resource URI must specify a domain.',
$raw_uri));
}
$addresses = gethostbynamel($domain);
if (!$addresses) {
throw new Exception(
pht(
'URI "%s" is not a valid fetchable resource. The domain "%s" could '.
'not be resolved.',
$raw_uri,
$domain));
}
foreach ($addresses as $address) {
if (self::isBlacklistedOutboundAddress($address)) {
throw new Exception(
pht(
'URI "%s" is not a valid fetchable resource. The domain "%s" '.
'resolves to the address "%s", which is blacklisted for '.
'outbound requests.',
$raw_uri,
$domain,
$address));
}
}
$resolved_uri = clone $uri;
$resolved_uri->setDomain(head($addresses));
return array($resolved_uri, $domain);
} | Detect if a URI identifies a valid fetchable remote resource, throwing
a detailed message if it does not.
A valid fetchable remote resource can be safely fetched using a request
originating on this server. This is a primarily an address check against
the outbound address blacklist.
@param string $raw_uri URI to test.
@param list<string> $protocols Allowed protocols.
@return pair<string, string> Pre-resolved URI and domain.
@task uri | requireValidRemoteURIForFetch | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function isBlacklistedOutboundAddress($address) {
$blacklist = self::getEnvConfig('security.outbound-blacklist');
return PhutilCIDRList::newList($blacklist)->containsAddress($address);
} | Determine if an IP address is in the outbound address blacklist.
@param string $address IP address.
@return bool True if the address is blacklisted. | isBlacklistedOutboundAddress | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function envConfigExists($key) {
return array_key_exists($key, self::$sourceStack->getKeys(array($key)));
} | @task internal | envConfigExists | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function getAllConfigKeys() {
return self::$sourceStack->getAllKeys();
} | @task internal | getAllConfigKeys | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public static function getEmptyCWD() {
$root = dirname(phutil_get_library_root('phabricator'));
return $root.'/support/empty/';
} | Get the path to an empty directory which is readable by all of the system
user accounts that Phabricator acts as.
In some cases, a binary needs some valid HOME or CWD to continue, but not
all user accounts have valid home directories and even if they do they
may not be readable after a `sudo` operation.
@return string Path to an empty directory suitable for use as a CWD. | getEmptyCWD | php | phorgeit/phorge | src/infrastructure/env/PhabricatorEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorEnv.php | Apache-2.0 |
public function overrideEnvConfig($key, $value) {
PhabricatorEnv::overrideTestEnvConfig(
$this->key,
$key,
$value);
return $this;
} | Override a configuration key in this scope, setting it to a new value.
@param string $key Key to override.
@param wild $value New value.
@return $this
@task override | overrideEnvConfig | php | phorgeit/phorge | src/infrastructure/env/PhabricatorScopedEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorScopedEnv.php | Apache-2.0 |
public function __construct($stack_key) {
$this->key = $stack_key;
} | @task internal | __construct | php | phorgeit/phorge | src/infrastructure/env/PhabricatorScopedEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorScopedEnv.php | Apache-2.0 |
public function __destruct() {
if (!$this->isPopped) {
PhabricatorEnv::popTestEnvironment($this->key);
$this->isPopped = true;
}
} | Release the scoped environment.
@return void
@task internal | __destruct | php | phorgeit/phorge | src/infrastructure/env/PhabricatorScopedEnv.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/env/PhabricatorScopedEnv.php | Apache-2.0 |
public function isIdle() {
if ($this->isInsideTransaction()) {
return false;
}
if ($this->isHoldingAnyLock()) {
return false;
}
return true;
} | Is this connection idle and safe to close?
A connection is "idle" if it can be safely closed without loss of state.
Connections inside a transaction or holding locks are not idle, even
though they may not actively be executing queries.
@return bool True if the connection is idle and can be safely closed. | isIdle | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function openTransaction() {
$state = $this->getTransactionState();
$point = $state->getSavepointName();
$depth = $state->getDepth();
$new_transaction = ($depth == 0);
if ($new_transaction) {
$this->query('START TRANSACTION');
} else {
$this->query('SAVEPOINT '.$point);
}
$state->increaseDepth();
return $this;
} | Begin a transaction, or set a savepoint if the connection is already
transactional.
@return $this
@task xaction | openTransaction | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function saveTransaction() {
$state = $this->getTransactionState();
$depth = $state->decreaseDepth();
if ($depth == 0) {
$this->query('COMMIT');
}
return $this;
} | Commit a transaction, or stage a savepoint for commit once the entire
transaction completes if inside a transaction stack.
@return $this
@task xaction | saveTransaction | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function killTransaction() {
$state = $this->getTransactionState();
$depth = $state->decreaseDepth();
if ($depth == 0) {
$this->query('ROLLBACK');
} else {
$this->query('ROLLBACK TO SAVEPOINT '.$state->getSavepointName());
}
return $this;
} | Rollback a transaction, or unstage the last savepoint if inside a
transaction stack.
@return $this | killTransaction | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function isInsideTransaction() {
$state = $this->getTransactionState();
return ($state->getDepth() > 0);
} | Returns true if the connection is transactional.
@return bool True if the connection is currently transactional.
@task xaction | isInsideTransaction | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
protected function getTransactionState() {
if (!$this->transactionState) {
$this->transactionState = new AphrontDatabaseTransactionState();
}
return $this->transactionState;
} | Get the current @{class:AphrontDatabaseTransactionState} object, or create
one if none exists.
@return AphrontDatabaseTransactionState Current transaction state.
@task xaction | getTransactionState | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function beginReadLocking() {
$this->getTransactionState()->beginReadLocking();
return $this;
} | @task xaction | beginReadLocking | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function endReadLocking() {
$this->getTransactionState()->endReadLocking();
return $this;
} | @task xaction | endReadLocking | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function isReadLocking() {
return $this->getTransactionState()->isReadLocking();
} | @task xaction | isReadLocking | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function beginWriteLocking() {
$this->getTransactionState()->beginWriteLocking();
return $this;
} | @task xaction | beginWriteLocking | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function endWriteLocking() {
$this->getTransactionState()->endWriteLocking();
return $this;
} | @task xaction | endWriteLocking | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function isWriteLocking() {
return $this->getTransactionState()->isWriteLocking();
} | @task xaction | isWriteLocking | php | phorgeit/phorge | src/infrastructure/storage/connection/AphrontDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/AphrontDatabaseConnection.php | Apache-2.0 |
public function simulateErrorOnNextQuery($error) {
$this->nextError = $error;
return $this;
} | Force the next query to fail with a simulated error. This should be used
ONLY for unit tests. | simulateErrorOnNextQuery | php | phorgeit/phorge | src/infrastructure/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php | Apache-2.0 |
protected function validateUTF8String($string) {
if (phutil_is_utf8($string)) {
return;
}
throw new AphrontCharacterSetQueryException(
pht(
'Attempting to construct a query using a non-utf8 string when '.
'utf8 is expected. Use the `%%B` conversion to escape binary '.
'strings data.'));
} | Check inserts for characters outside of the BMP. Even with the strictest
settings, MySQL will silently truncate data when it encounters these, which
can lead to data loss and security problems. | validateUTF8String | php | phorgeit/phorge | src/infrastructure/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/connection/mysql/AphrontBaseMySQLDatabaseConnection.php | Apache-2.0 |
public function key() {
return $this->current()->getID();
} | [\ReturnTypeWillChange] | key | php | phorgeit/phorge | src/infrastructure/storage/lisk/PhabricatorQueryIterator.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/PhabricatorQueryIterator.php | Apache-2.0 |
public function __construct() {
$id_key = $this->getIDKey();
if ($id_key) {
$this->$id_key = null;
}
} | Build an empty object.
@return object Empty object. | __construct | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function getConnectionNamespace() {
return $this->getDatabaseName();
} | Return a namespace for this object's connections in the connection cache.
Generally, the database name is appropriate. Two connections are considered
equivalent if they have the same connection namespace and mode.
@return string Connection namespace for cache
@task conn | getConnectionNamespace | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function getEstablishedConnection($mode) {
$key = $this->getConnectionNamespace().':'.$mode;
if (isset(self::$connections[$key])) {
return self::$connections[$key];
}
return null;
} | Get an existing, cached connection for this object.
@param mode $mode Connection mode.
@return AphrontDatabaseConnection|null Connection, if it exists in cache.
@task conn | getEstablishedConnection | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
protected function setEstablishedConnection(
$mode,
AphrontDatabaseConnection $connection,
$force_unique = false) {
$key = $this->getConnectionNamespace().':'.$mode;
if ($force_unique) {
$key .= ':unique';
while (isset(self::$connections[$key])) {
$key .= '!';
}
}
self::$connections[$key] = $connection;
return $this;
} | Store a connection in the connection cache.
@param mode $mode Connection mode.
@param AphrontDatabaseConnection $connection Connection to cache.
@param bool $force_unique (optional)
@return $this
@task conn | setEstablishedConnection | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function setForcedConnection(AphrontDatabaseConnection $connection) {
$this->forcedConnection = $connection;
return $this;
} | Force an object to use a specific connection.
This overrides all connection management and forces the object to use
a specific connection when interacting with the database.
@param AphrontDatabaseConnection $connection Connection to force this
object to use.
@task conn | setForcedConnection | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function getConfigOption($option_name) {
$options = $this->getLiskMetadata('config');
if ($options === null) {
$options = $this->getConfiguration();
$this->setLiskMetadata('config', $options);
}
return idx($options, $option_name);
} | Determine the setting of a configuration option for this class of objects.
@param string $option_name Option name, one of the CONFIG_* constants.
@return mixed Option value, if configured (null if unavailable).
@task config | getConfigOption | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function loadAll() {
return $this->loadAllWhere('1 = 1');
} | Loads all of the objects, unconditionally.
@return dict Dictionary of all persisted objects of this type, keyed
on object ID.
@task load | loadAll | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function loadOneWhere($pattern /* , $arg, $arg, $arg ... */) {
$args = func_get_args();
$data = call_user_func_array(
array($this, 'loadRawDataWhere'),
$args);
if (count($data) > 1) {
throw new AphrontCountQueryException(
pht(
'More than one result from %s!',
__FUNCTION__.'()'));
}
$data = reset($data);
if (!$data) {
return null;
}
return $this->loadFromArray($data);
} | Load a single object identified by a 'WHERE' clause. You provide
everything after the 'WHERE', and Lisk builds the first half of the
query. See loadAllWhere(). This method is similar, but returns a single
result instead of a list.
@param string $pattern queryfx()-style SQL WHERE clause.
@param ... Zero or more conversions.
@return object|null Matching object, or null if no object matches.
@task load | loadOneWhere | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function reload() {
if (!$this->getID()) {
throw new Exception(
pht("Unable to reload object that hasn't been loaded!"));
}
$result = $this->loadOneWhere(
'%C = %d',
$this->getIDKey(),
$this->getID());
if (!$result) {
throw new AphrontObjectMissingQueryException();
}
return $this;
} | Reload an object from the database, discarding any changes to persistent
properties. This is primarily useful after entering a transaction but
before applying changes to an object.
@return $this
@task load | reload | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function loadFromArray(array $row) {
$valid_map = $this->getLiskMetadata('validMap', array());
$map = array();
$updated = false;
foreach ($row as $k => $v) {
// We permit (but ignore) extra properties in the array because a
// common approach to building the array is to issue a raw SELECT query
// which may include extra explicit columns or joins.
// This pathway is very hot on some pages, so we're inlining a cache
// and doing some microoptimization to avoid a strtolower() call for each
// assignment. The common path (assigning a valid property which we've
// already seen) always incurs only one empty(). The second most common
// path (assigning an invalid property which we've already seen) costs
// an empty() plus an isset().
if (empty($valid_map[$k])) {
if (isset($valid_map[$k])) {
// The value is set but empty, which means it's false, so we've
// already determined it's not valid. We don't need to check again.
continue;
}
$valid_map[$k] = $this->hasProperty($k);
$updated = true;
if (!$valid_map[$k]) {
continue;
}
}
$map[$k] = $v;
}
if ($updated) {
$this->setLiskMetadata('validMap', $valid_map);
}
$this->willReadData($map);
foreach ($map as $prop => $value) {
$this->$prop = $value;
}
$this->didReadData();
return $this;
} | Initialize this object's properties from a dictionary. Generally, you
load single objects with loadOneWhere(), but sometimes it may be more
convenient to pull data from elsewhere directly (e.g., a complicated
join via @{method:queryData}) and then load from an array representation.
@param dict $row Dictionary of properties, which should be equivalent
to selecting a row from the table or calling
@{method:getProperties}.
@return $this
@task load | loadFromArray | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
public function setID($id) {
$id_key = $this->getIDKey();
$this->$id_key = $id;
return $this;
} | Set unique ID identifying this object. You normally don't need to call this
method unless with `IDS_MANUAL`.
@param mixed $id Unique ID.
@return $this
@task save | setID | php | phorgeit/phorge | src/infrastructure/storage/lisk/LiskDAO.php | https://github.com/phorgeit/phorge/blob/master/src/infrastructure/storage/lisk/LiskDAO.php | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.