code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
public function isEmptyPattern($pattern) { if (preg_match('/^([A-Za-z]+) +(.*)$/', $pattern ?? '', $matches)) { $pattern = $matches[2]; } if (trim($pattern ?? '') == "") { return true; } return false; }
Returns true if this is a URL that will match without shifting off any of the URL. This is used by the request handler to prevent infinite parsing loops. @param string $pattern @return bool
isEmptyPattern
php
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequest.php
BSD-3-Clause
public function shift($count = 1) { $return = []; if ($count == 1) { return array_shift($this->dirParts); } for ($i=0; $i<$count; $i++) { $value = array_shift($this->dirParts); if ($value === null) { break; } $return[] = $value; } return $return; }
Shift one or more parts off the beginning of the URL. If you specify shifting more than 1 item off, then the items will be returned as an array @param int $count Shift Count @return string|array
shift
php
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequest.php
BSD-3-Clause
public function allParsed() { return sizeof($this->dirParts ?? []) <= $this->unshiftedButParsedParts; }
Returns true if the URL has been completely parsed. This will respect parsed but unshifted directory parts. @return bool
allParsed
php
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequest.php
BSD-3-Clause
public function getIP() { return $this->ip; }
Returns the client IP address which originated this request. @return string
getIP
php
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequest.php
BSD-3-Clause
public function setIP($ip) { if (!filter_var($ip, FILTER_VALIDATE_IP)) { throw new InvalidArgumentException("Invalid ip $ip"); } $this->ip = $ip; return $this; }
Sets the client IP address which originated this request. Use setIPFromHeaderValue if assigning from header value. @param string $ip @return $this
setIP
php
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequest.php
BSD-3-Clause
public function setHttpMethod($method) { if (!HTTPRequest::isValidHttpMethod($method)) { throw new \InvalidArgumentException('HTTPRequest::setHttpMethod: Invalid HTTP method'); } $this->httpMethod = strtoupper($method ?? ''); return $this; }
Explicitly set the HTTP method for this request. @param string $method @return $this
setHttpMethod
php
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequest.php
BSD-3-Clause
public function setScheme($scheme) { $this->scheme = $scheme; return $this; }
Set the URL scheme (e.g. "http" or "https"). Equivalent to PSR-7 getUri()->getScheme(), @param string $scheme @return $this
setScheme
php
silverstripe/silverstripe-framework
src/Control/HTTPRequest.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequest.php
BSD-3-Clause
public function __construct($body = null, $statusCode = null, $statusDescription = null, $protocolVersion = null) { $this->setBody($body); if ($statusCode) { $this->setStatusCode($statusCode, $statusDescription); } if (!$protocolVersion) { if (preg_match('/HTTP\/(?<version>\d+(\.\d+)?)/i', $_SERVER['SERVER_PROTOCOL'] ?? '', $matches)) { $protocolVersion = $matches['version']; } } if ($protocolVersion) { $this->setProtocolVersion($protocolVersion); } }
Create a new HTTP response @param string $body The body of the response @param int $statusCode The numeric status code - 200, 404, etc @param string $statusDescription The text to be given alongside the status code. See {@link setStatusCode()} for more information. @param string $protocolVersion
__construct
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function setProtocolVersion($protocolVersion) { $this->protocolVersion = $protocolVersion; return $this; }
The HTTP version used to respond to this request (typically 1.0 or 1.1) @param string $protocolVersion @return $this
setProtocolVersion
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function setStatusCode($code, $description = null) { if (isset(HTTPResponse::$status_codes[$code])) { $this->statusCode = $code; } else { throw new InvalidArgumentException("Unrecognised HTTP status code '$code'"); } if ($description) { $this->statusDescription = $description; } else { $this->statusDescription = HTTPResponse::$status_codes[$code]; } return $this; }
@param int $code @param string $description Optional. See {@link setStatusDescription()}. No newlines are allowed in the description. If omitted, will default to the standard HTTP description for the given $code value (see {@link $status_codes}). @return $this
setStatusCode
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function setStatusDescription($description) { $this->statusDescription = $description; return $this; }
The text to be given alongside the status code ("reason phrase"). Caution: Will be overwritten by {@link setStatusCode()}. @param string $description @return $this
setStatusDescription
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function isError() { $statusCode = $this->getStatusCode(); return $statusCode && ($statusCode < 200 || $statusCode > 399); }
Returns true if this HTTP response is in error @return bool
isError
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function addHeader($header, $value) { $header = strtolower($header ?? ''); $this->headers[$header] = $this->sanitiseHeader($value); return $this; }
Add a HTTP header to the response, replacing any header of the same name. @param string $header Example: "content-type" @param string $value Example: "text/xml" @return $this
addHeader
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function getHeader($header) { $header = strtolower($header ?? ''); if (isset($this->headers[$header])) { return $this->headers[$header]; } return null; }
Return the HTTP header of the given name. @param string $header @return string
getHeader
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function output() { // Attach appropriate X-Include-JavaScript and X-Include-CSS headers if (Director::is_ajax()) { Requirements::include_in_response($this); } if ($this->isRedirect() && headers_sent()) { $this->htmlRedirect(); } else { $this->outputHeaders(); $this->outputBody(); } }
Send this HTTPResponse to the browser
output
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
protected function htmlRedirect() { $headersSent = headers_sent($file, $line); $location = $this->getHeader('location'); $url = Director::absoluteURL((string) $location); $urlATT = Convert::raw2htmlatt($url); $urlJS = Convert::raw2js($url); $title = (Director::isDev() && $headersSent) ? "{$urlATT}... (output started on {$file}, line {$line})" : "{$urlATT}..."; echo <<<EOT <p>Redirecting to <a href="{$urlATT}" title="Click this link if your browser does not redirect you">{$title}</a></p> <meta http-equiv="refresh" content="1; url={$urlATT}" /> <script type="application/javascript">setTimeout(function(){ window.location.href = "{$urlJS}"; }, 50);</script> EOT ; }
Generate a browser redirect without setting headers
htmlRedirect
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function isFinished() { return $this->isRedirect() || $this->isError(); }
Returns true if this response is "finished", that is, no more script execution should be done. Specifically, returns true if a redirect has already been requested @return bool
isFinished
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function isRedirect() { return in_array($this->getStatusCode(), HTTPResponse::$redirect_codes); }
Determine if this response is a redirect @return bool
isRedirect
php
silverstripe/silverstripe-framework
src/Control/HTTPResponse.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse.php
BSD-3-Clause
public function Title() { return $this->rssField($this->titleField); }
Get the description of this entry @return DBField Returns the description of the entry.
Title
php
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed_Entry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RSS/RSSFeed_Entry.php
BSD-3-Clause
public function rssField($fieldName) { if ($fieldName) { return $this->failover->obj($fieldName); } return null; }
Return the safely casted field @param string $fieldName Name of field @return DBField
rssField
php
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed_Entry.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RSS/RSSFeed_Entry.php
BSD-3-Clause
public function __construct( SS_List $entries, $link, $title, $description = null, $titleField = "Title", $descriptionField = "Content", $authorField = null, $lastModified = null, $etag = null ) { $this->entries = $entries; $this->link = $link; $this->description = $description; $this->title = $title; $this->titleField = $titleField; $this->descriptionField = $descriptionField; $this->authorField = $authorField; $this->lastModified = $lastModified; $this->etag = $etag; parent::__construct(); }
Constructor @param SS_List $entries RSS feed entries @param string $link Link to the feed @param string $title Title of the feed @param string $description Description of the field @param string $titleField Name of the field that should be used for the titles for the feed entries @param string $descriptionField Name of the field that should be used for the description for the feed entries @param string $authorField Name of the field that should be used for the author for the feed entries @param int $lastModified Unix timestamp of the latest modification (latest posting) @param string $etag The ETag is an unique identifier that is changed every time the representation does
__construct
php
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RSS/RSSFeed.php
BSD-3-Clause
public function Description() { return $this->description; }
Get the description of this feed @return string Returns the description of the feed.
Description
php
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RSS/RSSFeed.php
BSD-3-Clause
public function outputToBrowser() { $prevState = SSViewer::config()->uninherited('source_file_comments'); SSViewer::config()->set('source_file_comments', false); $response = Controller::curr()->getResponse(); if (is_int($this->lastModified)) { HTTPCacheControlMiddleware::singleton()->registerModificationDate($this->lastModified); $response->addHeader("Last-Modified", gmdate("D, d M Y H:i:s", $this->lastModified) . ' GMT'); } if (!empty($this->etag)) { $response->addHeader('ETag', "\"{$this->etag}\""); } $response->addHeader("Content-Type", "application/rss+xml; charset=utf-8"); SSViewer::config()->set('source_file_comments', $prevState); return $this->renderWith($this->getTemplates()); }
Output the feed to the browser. @return DBHTMLText
outputToBrowser
php
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RSS/RSSFeed.php
BSD-3-Clause
public function setTemplate($template) { $this->template = $template; }
Set the name of the template to use. Actual template will be resolved via the standard template inclusion process. @param string $template
setTemplate
php
silverstripe/silverstripe-framework
src/Control/RSS/RSSFeed.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/RSS/RSSFeed.php
BSD-3-Clause
public function setData(array|ViewableData $data) { if (is_array($data)) { $data = ArrayData::create($data); } $this->data = $data; $this->dataHasBeenSet = true; return $this; }
Set template data Calling setData() once means that any content set via text()/html()/setBody() will have no effect
setData
php
silverstripe/silverstripe-framework
src/Control/Email/Email.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Email/Email.php
BSD-3-Clause
public function removeData(string $name) { $this->data->{$name} = null; return $this; }
Remove a single piece of template data
removeData
php
silverstripe/silverstripe-framework
src/Control/Email/Email.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Email/Email.php
BSD-3-Clause
public static function checkIP($requestIP, $ips) { Deprecation::notice('5.3.0', 'Use Symfony\Component\HttpFoundation\IpUtils::checkIP() instead'); if (!is_array($ips)) { $ips = [$ips]; } $method = substr_count($requestIP ?? '', ':') > 1 ? 'checkIP6' : 'checkIP4'; foreach ($ips as $ip) { if (IPUtils::$method($requestIP, trim($ip ?? ''))) { return true; } } return false; }
Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets. @param string $requestIP IP to check @param string|array $ips List of IPs or subnets (can be a string if only a single one) @return bool Whether the IP is valid @package framework @subpackage core
checkIP
php
silverstripe/silverstripe-framework
src/Control/Util/IPUtils.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Util/IPUtils.php
BSD-3-Clause
public static function checkIP4($requestIP, $ip) { Deprecation::notice('5.3.0', 'Use Symfony\Component\HttpFoundation\IpUtils::checkIP4() instead'); if (!filter_var($requestIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { return false; } if (false !== strpos($ip ?? '', '/')) { list($address, $netmask) = explode('/', $ip ?? '', 2); if ($netmask === '0') { return filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); } if ($netmask < 0 || $netmask > 32) { return false; } } else { $address = $ip; $netmask = 32; } return 0 === substr_compare(sprintf('%032b', ip2long($requestIP ?? '')), sprintf('%032b', ip2long($address ?? '')), 0, $netmask); }
Compares two IPv4 addresses. In case a subnet is given, it checks if it contains the request IP. @param string $requestIP IPv4 address to check @param string $ip IPv4 address or subnet in CIDR notation @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet
checkIP4
php
silverstripe/silverstripe-framework
src/Control/Util/IPUtils.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Util/IPUtils.php
BSD-3-Clause
public static function checkIP6($requestIP, $ip) { Deprecation::notice('5.3.0', 'Use Symfony\Component\HttpFoundation\IpUtils::checkIP6() instead'); if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1'))) { throw new \RuntimeException('Unable to check IPv6. Check that PHP was not compiled with option "disable-ipv6".'); } if (false !== strpos($ip ?? '', '/')) { list($address, $netmask) = explode('/', $ip ?? '', 2); if ($netmask < 1 || $netmask > 128) { return false; } } else { $address = $ip; $netmask = 128; } $bytesAddr = unpack('n*', @inet_pton($address ?? '')); $bytesTest = unpack('n*', @inet_pton($requestIP ?? '')); if (!$bytesAddr || !$bytesTest) { return false; } for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) { $left = $netmask - 16 * ($i - 1); $left = ($left <= 16) ? $left : 16; $mask = ~(0xffff >> $left) & 0xffff; if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) { return false; } } return true; }
Compares two IPv6 addresses. In case a subnet is given, it checks if it contains the request IP. @author David Soria Parra <[email protected]> @see https://github.com/dsp/v6tools @param string $requestIP IPv6 address to check @param string $ip IPv6 address or subnet in CIDR notation @return bool Whether the IP is valid @throws \RuntimeException When IPV6 support is not enabled
checkIP6
php
silverstripe/silverstripe-framework
src/Control/Util/IPUtils.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Util/IPUtils.php
BSD-3-Clause
public function __construct(...$rules) { $this->rules = $rules; $this->declineUrl = Director::baseURL(); }
Init the middleware with the rules @param ConfirmationMiddleware\Rule[] $rules Rules to check requests against
__construct
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
protected function getConfirmationUrl(HTTPRequest $request, $confirmationStorageId) { $url = $this->confirmationFormUrl; if (substr($url ?? '', 0, 1) === '/') { // add BASE_URL explicitly if not absolute $url = Controller::join_links(Director::baseURL(), $url); } return Controller::join_links( $url, urlencode($confirmationStorageId ?? '') ); }
The URL of the confirmation form ("Security/confirm/middleware" by default) @param HTTPRequest $request Active request @param string $confirmationStorageId ID of the confirmation storage to be used @return string URL of the confirmation form
getConfirmationUrl
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
protected function generateDeclineUrlForRequest(HTTPRequest $request) { return $this->declineUrl; }
Returns the URL where the user to be redirected when declining the action (on the confirmation form) @param HTTPRequest $request Active request @return string URL
generateDeclineUrlForRequest
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
public function setDeclineUrl($url) { $this->declineUrl = $url; return $this; }
Override the default decline url @param string $url @return $this
setDeclineUrl
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
public function canBypass(HTTPRequest $request) { foreach ($this->bypasses as $bypass) { if ($bypass->checkRequestForBypass($request)) { return true; } } return false; }
Check whether the rules can be bypassed without user confirmation @param HTTPRequest $request @return bool
canBypass
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
public function getConfirmationItems(HTTPRequest $request) { $confirmationItems = []; foreach ($this->rules as $rule) { if ($item = $rule->getRequestConfirmationItem($request)) { $confirmationItems[] = $item; } } return $confirmationItems; }
Extract the confirmation items from the request and return @param HTTPRequest $request @return Confirmation\Item[] list of confirmation items
getConfirmationItems
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
protected function processItems(HTTPRequest $request, callable $delegate, $items) { $storage = Injector::inst()->createWithArgs(Confirmation\Storage::class, [$request->getSession(), $this->confirmationId, false]); if (!count($storage->getItems() ?? [])) { return $this->buildConfirmationRedirect($request, $storage, $items); } $confirmed = false; if ($storage->getHttpMethod() === 'POST') { $postVars = $request->postVars(); $csrfToken = $storage->getCsrfToken(); $confirmed = $storage->confirm($postVars) && isset($postVars[$csrfToken]); } else { $confirmed = $storage->check($items); } if (!$confirmed) { return $this->buildConfirmationRedirect($request, $storage, $items); } if ($response = $this->confirmedEffect($request)) { return $response; } $storage->cleanup(); return $delegate($request); }
Process the confirmation items and either perform the confirmedEffect and pass the request to the next middleware, or return a redirect to the confirmation form @param HTTPRequest $request @param callable $delegate @param Confirmation\Item[] $items @return HTTPResponse
processItems
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
protected function confirmedEffect(HTTPRequest $request) { return null; }
The middleware own effects that should be performed on confirmation This method is getting called before the confirmation storage cleanup so that any responses returned here don't trigger a new confirmtation for the same request traits @param HTTPRequest $request @return null|HTTPResponse
confirmedEffect
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
public function setConfirmationStorageId($id) { $this->confirmationId = $id; return $this; }
Override the confirmation storage ID @param string $id @return $this
setConfirmationStorageId
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
public function setConfirmationFormUrl($url) { $this->confirmationFormUrl = $url; return $this; }
Override the confirmation form url @param string $url @return $this
setConfirmationFormUrl
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
public function setBypasses($bypasses) { $this->bypasses = $bypasses; return $this; }
Set the list of bypasses for the confirmation @param ConfirmationMiddleware\Bypass[] $bypasses @return $this
setBypasses
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware.php
BSD-3-Clause
public function process(HTTPRequest $request, callable $delegate) { try { $response = $delegate($request); } catch (HTTPResponse_Exception $ex) { $response = $ex->getResponse(); } if (!$response) { return null; } // Update state based on current request and response objects $this->augmentState($request, $response); // Add all headers to this response object $this->applyToResponse($response); if (isset($ex)) { throw $ex; } return $response; }
Generate response for the given request @param HTTPRequest $request @param callable $delegate @return HTTPResponse @throws HTTPResponse_Exception
process
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
protected function combineVary(...$varies) { $merged = []; foreach ($varies as $vary) { if ($vary && is_string($vary)) { $vary = array_filter(preg_split("/\s*,\s*/", trim($vary ?? '')) ?? []); } if ($vary && is_array($vary)) { $merged = array_merge($merged, $vary); } } return array_unique($merged ?? []); }
Combine vary strings/arrays into a single array, or normalise a single vary @param string|array[] $varies Each vary as a separate arg @return array
combineVary
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function registerModificationDate($date) { $timestamp = is_numeric($date) ? $date : strtotime($date ?? ''); if ($timestamp > $this->modificationDate) { $this->modificationDate = $timestamp; } return $this; }
Register a modification date. Used to calculate the "Last-Modified" HTTP header. Can be called multiple times, and will automatically retain the most recent date. @param string|int $date Date string or timestamp @return HTTPCacheControlMiddleware
registerModificationDate
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
protected function setState($state) { if (!array_key_exists($state, $this->stateDirectives ?? [])) { throw new InvalidArgumentException("Invalid state {$state}"); } $this->state = $state; return $this; }
Set current state. Should only be invoked internally after processing precedence rules. @param string $state @return $this
setState
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
protected function applyChangeLevel($level, $force) { $forcingLevel = $level + ($force ? HTTPCacheControlMiddleware::LEVEL_FORCED : 0); if ($forcingLevel < $this->getForcingLevel()) { return false; } $this->forcingLevel = $forcingLevel; return true; }
Instruct the cache to apply a change with a given level, optionally modifying it with a force flag to increase priority of this action. If the apply level was successful, the change is made and the internal level threshold is incremented. @param int $level Priority of the given change @param bool $force If usercode has requested this action is forced to a higher priority. Note: Even if $force is set to true, other higher-priority forced changes can still cause a change to be rejected if it is below the required threshold. @return bool True if the given change is accepted, and that the internal level threshold is updated (if necessary) to the new minimum level.
applyChangeLevel
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function setStateDirective($states, $directive, $value = true) { if ($value === null) { throw new InvalidArgumentException("Invalid directive value"); } // make sure the directive is in the list of allowed directives $allowedDirectives = $this->config()->get('allowed_directives'); $directive = strtolower($directive ?? ''); if (!in_array($directive, $allowedDirectives ?? [])) { throw new InvalidArgumentException('Directive ' . $directive . ' is not allowed'); } foreach ((array)$states as $state) { if (!array_key_exists($state, $this->stateDirectives ?? [])) { throw new InvalidArgumentException("Invalid state {$state}"); } // Set or unset directive if ($value === false) { unset($this->stateDirectives[$state][$directive]); } else { $this->stateDirectives[$state][$directive] = $value; } } return $this; }
Low level method for setting directives include any experimental or custom ones added via config. You need to specify the state (or states) to apply this directive to. Can also remove directives with false @param array|string $states State(s) to apply this directive to @param string $directive @param int|string|bool $value Flag to set for this value. Set to false to remove, or true to set. String or int value assign a specific value. @return $this
setStateDirective
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function removeStateDirective($states, $directive) { $this->setStateDirective($states, $directive, false); return $this; }
Low level method for removing directives @param array|string $states State(s) to remove this directive from @param string $directive @return $this
removeStateDirective
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function hasStateDirective($state, $directive) { $directive = strtolower($directive ?? ''); return isset($this->stateDirectives[$state][$directive]); }
Low level method to check if a directive is currently set @param string $state State(s) to apply this directive to @param string $directive @return bool
hasStateDirective
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function hasDirective($directive) { return $this->hasStateDirective($this->getState(), $directive); }
Check if the current state has the given directive. @param string $directive @return bool
hasDirective
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function getStateDirective($state, $directive) { $directive = strtolower($directive ?? ''); if (isset($this->stateDirectives[$state][$directive])) { return $this->stateDirectives[$state][$directive]; } return false; }
Low level method to get the value of a directive for a state. Returns false if there is no directive. True means the flag is set, otherwise the value of the directive. @param string $state @param string $directive @return int|string|bool
getStateDirective
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function getDirective($directive) { return $this->getStateDirective($this->getState(), $directive); }
Get the value of the given directive for the current state @param string $directive @return bool|int|string
getDirective
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function getStateDirectives($state) { return $this->stateDirectives[$state]; }
Get directives for the given state @param string $state @return array
getStateDirectives
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function getDirectives() { return $this->getStateDirectives($this->getState()); }
Get all directives for the currently active state @return array
getDirectives
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function setNoStore($noStore = true) { // Affect all non-disabled states $applyTo = [HTTPCacheControlMiddleware::STATE_ENABLED, HTTPCacheControlMiddleware::STATE_PRIVATE, HTTPCacheControlMiddleware::STATE_PUBLIC]; if ($noStore) { $this->setStateDirective($applyTo, 'no-store'); $this->removeStateDirective($applyTo, 'max-age'); $this->removeStateDirective($applyTo, 's-maxage'); } else { $this->removeStateDirective($applyTo, 'no-store'); } return $this; }
The cache should not store anything about the client request or server response. Affects all non-disabled states. Use setStateDirective() instead to set for a single state. Set the no-store directive (also removes max-age and s-maxage for consistency purposes) @param bool $noStore @return $this
setNoStore
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function setNoCache($noCache = true) { // Affect all non-disabled states $applyTo = [HTTPCacheControlMiddleware::STATE_ENABLED, HTTPCacheControlMiddleware::STATE_PRIVATE, HTTPCacheControlMiddleware::STATE_PUBLIC]; if ($noCache) { $this->setStateDirective($applyTo, 'no-cache'); $this->removeStateDirective($applyTo, 'max-age'); $this->removeStateDirective($applyTo, 's-maxage'); } else { $this->removeStateDirective($applyTo, 'no-cache'); } return $this; }
Forces caches to submit the request to the origin server for validation before releasing a cached copy. Affects all non-disabled states. Use setStateDirective() instead to set for a single state. @param bool $noCache @return $this
setNoCache
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function setMaxAge($age) { // Affect all non-disabled states $applyTo = [HTTPCacheControlMiddleware::STATE_ENABLED, HTTPCacheControlMiddleware::STATE_PRIVATE, HTTPCacheControlMiddleware::STATE_PUBLIC]; $this->setStateDirective($applyTo, 'max-age', $age); if ($age) { $this->removeStateDirective($applyTo, 'no-cache'); $this->removeStateDirective($applyTo, 'no-store'); } return $this; }
Specifies the maximum amount of time (seconds) a resource will be considered fresh. This directive is relative to the time of the request. Affects all non-disabled states. Use enableCache(), publicCache() or setStateDirective() instead to set the max age for a single state. @param int $age @return $this
setMaxAge
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function setSharedMaxAge($age) { // Affect all non-disabled states $applyTo = [HTTPCacheControlMiddleware::STATE_ENABLED, HTTPCacheControlMiddleware::STATE_PRIVATE, HTTPCacheControlMiddleware::STATE_PUBLIC]; $this->setStateDirective($applyTo, 's-maxage', $age); if ($age) { $this->removeStateDirective($applyTo, 'no-cache'); $this->removeStateDirective($applyTo, 'no-store'); } return $this; }
Overrides max-age or the Expires header, but it only applies to shared caches (e.g., proxies) and is ignored by a private cache. Affects all non-disabled states. Use setStateDirective() instead to set for a single state. @param int $age @return $this
setSharedMaxAge
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function setMustRevalidate($mustRevalidate = true) { $applyTo = [HTTPCacheControlMiddleware::STATE_ENABLED, HTTPCacheControlMiddleware::STATE_PRIVATE, HTTPCacheControlMiddleware::STATE_PUBLIC]; $this->setStateDirective($applyTo, 'must-revalidate', $mustRevalidate); return $this; }
The cache must verify the status of the stale resources before using it and expired ones should not be used. Affects all non-disabled states. Use setStateDirective() instead to set for a single state. @param bool $mustRevalidate @return $this
setMustRevalidate
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function enableCache($force = false, $maxAge = null) { // Only execute this if its forcing level is high enough if ($this->applyChangeLevel(HTTPCacheControlMiddleware::LEVEL_ENABLED, $force)) { $this->setState(HTTPCacheControlMiddleware::STATE_ENABLED); } if (!is_null($maxAge)) { $this->setMaxAge($maxAge); } return $this; }
Simple way to set cache control header to a cacheable state. Needs either `setMaxAge()` or the `$maxAge` method argument in order to activate caching. The resulting cache-control headers will be chosen from the 'enabled' set of directives. Does not set `public` directive. Usually, `setMaxAge()` is sufficient. Use `publicCache()` if this is explicitly required. See https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#public_vs_private @see https://docs.silverstripe.org/en/developer_guides/performance/http_cache_headers/ @param bool $force Force the cache to public even if its unforced private or public @param int $maxAge Shortcut for `setMaxAge()`, which is required to actually enable the cache. @return $this
enableCache
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function disableCache($force = false) { // Only execute this if its forcing level is high enough if ($this->applyChangeLevel(HTTPCacheControlMiddleware::LEVEL_DISABLED, $force)) { $this->setState(HTTPCacheControlMiddleware::STATE_DISABLED); } return $this; }
Simple way to set cache control header to a non-cacheable state. Use this method over `privateCache()` if you are unsure about caching details. Takes precedence over unforced `enableCache()`, `privateCache()` or `publicCache()` calls. The resulting cache-control headers will be chosen from the 'disabled' set of directives. Removes all state and replaces it with `no-cache, no-store, must-revalidate`. Although `no-store` is sufficient the others are added under recommendation from Mozilla (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#Examples) Does not set `private` directive, use `privateCache()` if this is explicitly required. See https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#public_vs_private @see https://docs.silverstripe.org/en/developer_guides/performance/http_cache_headers/ @param bool $force Force the cache to disabled even if it's forced private or public @return $this
disableCache
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function privateCache($force = false) { // Only execute this if its forcing level is high enough if ($this->applyChangeLevel(HTTPCacheControlMiddleware::LEVEL_PRIVATE, $force)) { $this->setState(HTTPCacheControlMiddleware::STATE_PRIVATE); } return $this; }
Advanced way to set cache control header to a non-cacheable state. Indicates that the response is intended for a single user and must not be stored by a shared cache. A private cache (e.g. Web Browser) may store the response. The resulting cache-control headers will be chosen from the 'private' set of directives. @see https://docs.silverstripe.org/en/developer_guides/performance/http_cache_headers/ @param bool $force Force the cache to private even if it's forced public @return $this
privateCache
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function publicCache($force = false, $maxAge = null) { // Only execute this if its forcing level is high enough if ($this->applyChangeLevel(HTTPCacheControlMiddleware::LEVEL_PUBLIC, $force)) { $this->setState(HTTPCacheControlMiddleware::STATE_PUBLIC); } if (!is_null($maxAge)) { $this->setMaxAge($maxAge); } return $this; }
Advanced way to set cache control header to a cacheable state. Indicates that the response may be cached by any cache. (eg: CDNs, Proxies, Web browsers). Needs either `setMaxAge()` or the `$maxAge` method argument in order to activate caching. The resulting cache-control headers will be chosen from the 'private' set of directives. @see https://docs.silverstripe.org/en/developer_guides/performance/http_cache_headers/ @param bool $force Force the cache to public even if it's private, unless it's been forced private @param int $maxAge Shortcut for `setMaxAge()`, which is required to actually enable the cache. @return $this
publicCache
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function applyToResponse($response) { $headers = $this->generateHeadersFor($response); foreach ($headers as $name => $value) { if (!$response->getHeader($name)) { $response->addHeader($name, $value); } } return $this; }
Generate all headers to add to this object @param HTTPResponse $response @return $this
applyToResponse
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function generateHeadersFor(HTTPResponse $response) { return array_filter([ 'Last-Modified' => $this->generateLastModifiedHeader(), 'Vary' => $this->generateVaryHeader($response), 'Cache-Control' => $this->generateCacheHeader(), 'Expires' => $this->generateExpiresHeader(), ]); }
Generate all headers to output @param HTTPResponse $response @return array
generateHeadersFor
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public static function reset() { Injector::inst()->unregisterNamedObject(__CLASS__); }
Reset registered http cache control and force a fresh instance to be built
reset
php
silverstripe/silverstripe-framework
src/Control/Middleware/HTTPCacheControlMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/HTTPCacheControlMiddleware.php
BSD-3-Clause
public function process(HTTPRequest $request, callable $delegate) { // Handle any redirects $redirect = $this->getRedirect($request); if ($redirect) { return $redirect; } /** @var HTTPResponse $response */ $response = $delegate($request); if ($this->hasBasicAuthPrompt($response) && $request->getScheme() !== 'https' && $this->getForceBasicAuthToSSL() ) { return $this->redirectToScheme($request, 'https'); } return $response; }
Generate response for the given request @param HTTPRequest $request @param callable $delegate @return HTTPResponse
process
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
protected function getRedirect(HTTPRequest $request) { // Check global disable if (!$this->isEnabled()) { return null; } // Get properties of current request $host = $request->getHost(); $scheme = $request->getScheme(); $url = strtok(Environment::getEnv('REQUEST_URI'), '?'); // Check https if ($this->requiresSSL($request)) { $scheme = 'https'; // Promote ssl domain if configured $host = $this->getForceSSLDomain() ?: $host; } // Check www. if ($this->getForceWWW() && strpos($host ?? '', 'www.') !== 0) { $host = "www.{$host}"; } // Check trailing Slash if ($this->requiresTrailingSlashRedirect($request, $url)) { $url = Controller::normaliseTrailingSlash($url); } // No-op if no changes if ($request->getScheme() === $scheme && $request->getHost() === $host && strtok(Environment::getEnv('REQUEST_URI'), '?') === $url ) { return null; } return $this->redirectToScheme($request, $scheme, $host); }
Given request object determine if we should redirect. @param HTTPRequest $request Pre-validated request object @return HTTPResponse|null If a redirect is needed return the response
getRedirect
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
public function throwRedirectIfNeeded(HTTPRequest $request = null) { $request = $this->getOrValidateRequest($request); if (!$request) { return; } $response = $this->getRedirect($request); if ($response) { throw new HTTPResponse_Exception($response); } }
Handles redirection to canonical urls outside of the main middleware chain using HTTPResponseException. Will not do anything if a current HTTPRequest isn't available @param HTTPRequest|null $request Allow HTTPRequest to be used for the base comparison @throws HTTPResponse_Exception
throwRedirectIfNeeded
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
protected function getOrValidateRequest(HTTPRequest $request = null) { if ($request instanceof HTTPRequest) { return $request; } if (Injector::inst()->has(HTTPRequest::class)) { return Injector::inst()->get(HTTPRequest::class); } return null; }
Return a valid request, if one is available, or null if none is available @param HTTPRequest $request @return HTTPRequest|null
getOrValidateRequest
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
protected function requiresSSL(HTTPRequest $request) { // Check if force SSL is enabled if (!$this->getForceSSL()) { return false; } // Already on SSL if ($request->getScheme() === 'https') { return false; } // Veto if any existing patterns fail $patterns = $this->getForceSSLPatterns(); if (!$patterns) { return true; } // Filter redirect based on url $relativeURL = $request->getURL(true); foreach ($patterns as $pattern) { if (preg_match($pattern ?? '', $relativeURL ?? '')) { return true; } } // No patterns match return false; }
Check if a redirect for SSL is necessary @param HTTPRequest $request @return bool
requiresSSL
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
protected function requiresTrailingSlashRedirect(HTTPRequest $request, string $url) { // Get the URL without querystrings or fragment identifiers if (strpos($url, '#') !== false) { $url = explode('#', $url, 2)[0]; } if (strpos($url, '?') !== false) { $url = explode('?', $url, 2)[0]; } // Check if force Trailing Slash is enabled if ($this->getEnforceTrailingSlashConfig() !== true) { return false; } $requestPath = $request->getURL(); // skip if requesting root if ($requestPath === '/' || $requestPath === '') { return false; } // Skip if is AJAX request if (Director::is_ajax()) { return false; } // Skip if request has a file extension if (!empty($request->getExtension())) { return false; } // Skip if any configured ignore paths match $paths = (array) $this->getEnforceTrailingSlashConfigIgnorePaths(); if (!empty($paths)) { foreach ($paths as $path) { if (str_starts_with( $this->trailingSlashForComparison($requestPath), $this->trailingSlashForComparison($path) )) { return false; } } } // Skip if any configured ignore user agents match $agents = (array) $this->getEnforceTrailingSlashConfigIgnoreUserAgents(); if (!empty($agents)) { if (in_array( $request->getHeader('User-Agent'), $agents )) { return false; } } // Already using trailing slash correctly $addTrailingSlash = Controller::config()->uninherited('add_trailing_slash'); $hasTrailingSlash = str_ends_with($url, '/'); if (($addTrailingSlash && $hasTrailingSlash) || (!$addTrailingSlash && !$hasTrailingSlash)) { return false; } return true; }
Check if a redirect for trailing slash is necessary
requiresTrailingSlashRedirect
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
public function getEnabledEnvs() { return $this->enabledEnvs; }
Get enabled flag, or list of environments to enable in. @return array|bool
getEnabledEnvs
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
public function setEnabledEnvs($enabledEnvs) { $this->enabledEnvs = $enabledEnvs; return $this; }
Set enabled flag, or list of environments to enable in. Note: CLI is disabled by default, so `"cli"(string)` or `true(bool)` should be specified if you wish to enable for testing. @param array|bool $enabledEnvs @return $this
setEnabledEnvs
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
protected function isEnabled() { // At least one redirect must be enabled if (!$this->getForceWWW() && !$this->getForceSSL() && $this->getEnforceTrailingSlashConfig() !== true) { return false; } // Filter by env vars $enabledEnvs = $this->getEnabledEnvs(); if (is_bool($enabledEnvs)) { return $enabledEnvs; } // If CLI, EnabledEnvs must contain CLI if (Director::is_cli() && !in_array('cli', $enabledEnvs ?? [])) { return false; } // Check other envs return empty($enabledEnvs) || in_array(Director::get_environment_type(), $enabledEnvs ?? []); }
Ensure this middleware is enabled
isEnabled
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
protected function hasBasicAuthPrompt(HTTPResponse $response = null) { if (!$response) { return false; } return ($response->getStatusCode() === 401 && $response->getHeader('WWW-Authenticate')); }
Determine whether the executed middlewares have added a basic authentication prompt @param HTTPResponse $response @return bool
hasBasicAuthPrompt
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
protected function redirectToScheme(HTTPRequest $request, $scheme, $host = null) { if (!$host) { $host = $request->getHost(); } $url = Controller::join_links("{$scheme}://{$host}", Director::baseURL(), $request->getURL(true)); // Force redirect $response = HTTPResponse::create(); $response->redirect($url, $this->getRedirectType()); return $response; }
Redirect the current URL to the specified HTTP scheme @param HTTPRequest $request @param string $scheme @param string $host @return HTTPResponse
redirectToScheme
php
silverstripe/silverstripe-framework
src/Control/Middleware/CanonicalURLMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/CanonicalURLMiddleware.php
BSD-3-Clause
public function __construct() { parent::__construct( new ConfirmationMiddleware\GetParameter("flush"), new ConfirmationMiddleware\GetParameter("isDev"), new ConfirmationMiddleware\GetParameter("isTest") ); }
Initializes the middleware with the required rules
__construct
php
silverstripe/silverstripe-framework
src/Control/Middleware/URLSpecialsMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/URLSpecialsMiddleware.php
BSD-3-Clause
public function buildImpactRedirect(HTTPRequest $request) { $flush = $this->scheduleFlush($request); $env_type = $this->setSessionEnvType($request); if ($flush || $env_type) { // the token only purpose is to invalidate browser/proxy cache $request['urlspecialstoken'] = bin2hex(random_bytes(4)); $result = new HTTPResponse(); $result->redirect( Controller::join_links( Director::baseURL(), $request->getURL(true) ) ); return $result; } }
Looks up for the special flags passed in the request and schedules the changes accordingly for the next request. Returns a redirect to the same page (with a random token) if there are changes introduced by the flags. Returns null if there is no impact introduced by the flags. @param HTTPRequest $request @return null|HTTPResponse redirect to the same url
buildImpactRedirect
php
silverstripe/silverstripe-framework
src/Control/Middleware/URLSpecialsMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/URLSpecialsMiddleware.php
BSD-3-Clause
private function showMetric(HTTPRequest $request) { return Director::isDev() && array_key_exists('execmetric', $request->getVars() ?? []); }
Check if execution metric should be shown. @param HTTPRequest $request @return bool
showMetric
php
silverstripe/silverstripe-framework
src/Control/Middleware/ExecMetricMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ExecMetricMiddleware.php
BSD-3-Clause
private function formatExecutionTime($start, $end) { $diff = round($end - $start, 4); return $diff . ' seconds'; }
Convert the provided start and end time to a interval in secs. @param float $start @param float $end @return string
formatExecutionTime
php
silverstripe/silverstripe-framework
src/Control/Middleware/ExecMetricMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ExecMetricMiddleware.php
BSD-3-Clause
private function formatPeakMemoryUsage() { $bytes = memory_get_peak_usage(true); return File::format_size($bytes); }
Get the peak memory usage formatted has a string and a meaningful unit. @return string
formatPeakMemoryUsage
php
silverstripe/silverstripe-framework
src/Control/Middleware/ExecMetricMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ExecMetricMiddleware.php
BSD-3-Clause
public function getTrustedProxyIPs() { return $this->trustedProxyIPs; }
Return the comma-separated list of IP ranges that are trusted to provide proxy headers Can also be 'none' or '*' (all) @return string
getTrustedProxyIPs
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
public function setTrustedProxyIPs($trustedProxyIPs) { $this->trustedProxyIPs = $trustedProxyIPs; return $this; }
Set the comma-separated list of IP ranges that are trusted to provide proxy headers Can also be 'none' or '*' (all) @param string $trustedProxyIPs @return $this
setTrustedProxyIPs
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
public function getProxyHostHeaders() { return $this->proxyHostHeaders; }
Return the array of headers from which to lookup the hostname @return array
getProxyHostHeaders
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
public function setProxyHostHeaders($proxyHostHeaders) { $this->proxyHostHeaders = $proxyHostHeaders ?: []; return $this; }
Set the array of headers from which to lookup the hostname. @param array $proxyHostHeaders @return $this
setProxyHostHeaders
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
public function getProxyIPHeaders() { return $this->proxyIPHeaders; }
Return the array of headers from which to lookup the client IP @return array
getProxyIPHeaders
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
public function setProxyIPHeaders($proxyIPHeaders) { $this->proxyIPHeaders = $proxyIPHeaders ?: []; return $this; }
Set the array of headers from which to lookup the client IP. @param array $proxyIPHeaders @return $this
setProxyIPHeaders
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
public function getProxySchemeHeaders() { return $this->proxySchemeHeaders; }
Return the array of headers from which to lookup the client scheme (http/https) @return array
getProxySchemeHeaders
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
public function setProxySchemeHeaders($proxySchemeHeaders) { $this->proxySchemeHeaders = $proxySchemeHeaders ?: []; return $this; }
Set array of headers from which to lookup the client scheme (http/https) Can also specify comma-separated list as a single string. @param array $proxySchemeHeaders @return $this
setProxySchemeHeaders
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
protected function isTrustedProxy(HTTPRequest $request) { $trustedIPs = $this->getTrustedProxyIPs(); // Disabled if (empty($trustedIPs) || $trustedIPs === 'none') { return false; } // Allow all if ($trustedIPs === '*') { return true; } // Validate IP address $ip = $request->getIP(); if ($ip) { return IPUtils::checkIP($ip, preg_split('/\s*,\s*/', $trustedIPs ?? '')); } return false; }
Determine if the current request is coming from a trusted proxy @param HTTPRequest $request @return bool True if the request's source IP is a trusted proxy
isTrustedProxy
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
protected function getIPFromHeaderValue($headerValue) { // Sometimes the IP from a load balancer could be "x.x.x.x, y.y.y.y, z.z.z.z" // so we need to find the most likely candidate $ips = preg_split('/\s*,\s*/', $headerValue ?? ''); // Prioritise filters $filters = [ FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE, FILTER_FLAG_NO_PRIV_RANGE, null ]; foreach ($filters as $filter) { // Find best IP foreach ($ips as $ip) { if (filter_var($ip, FILTER_VALIDATE_IP, $filter ?? 0)) { return $ip; } } } return null; }
Extract an IP address from a header value that has been obtained. Accepts single IP or comma separated string of IPs @param string $headerValue The value from a trusted header @return string The IP address
getIPFromHeaderValue
php
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/TrustedProxyMiddleware.php
BSD-3-Clause
public function getAffectedPermissions() { return $this->affectedPermissions; }
Returns the list of permissions that are affected @return string[]
getAffectedPermissions
php
silverstripe/silverstripe-framework
src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
BSD-3-Clause
public function setAffectedPermissions($permissions) { $this->affectedPermissions = $permissions; return $this; }
Set the list of affected permissions If the user doesn't have at least one of these, we assume they don't have access to the protected action, so we don't ask for a confirmation @param string[] $permissions list of affected permissions @return $this
setAffectedPermissions
php
silverstripe/silverstripe-framework
src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
BSD-3-Clause
public function getEnforceAuthentication() { return $this->enforceAuthentication; }
Returns flag whether we want to enforce authentication or not @return bool
getEnforceAuthentication
php
silverstripe/silverstripe-framework
src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
BSD-3-Clause
public function setEnforceAuthentication($enforce) { $this->enforceAuthentication = $enforce; return $this; }
Set whether we want to enforce authentication We either enforce authentication (redirect to a login form) or silently assume the user does not have permissions and so we don't have to ask for a confirmation @param bool $enforce @return $this
setEnforceAuthentication
php
silverstripe/silverstripe-framework
src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
BSD-3-Clause
public function hasAccess(HTTPRequest $request) { foreach ($this->getAffectedPermissions() as $permission) { if (Permission::check($permission)) { return true; } } return false; }
Check whether the user has permissions to perform the target operation Otherwise we may want to skip the confirmation dialog. WARNING! The user has to be authenticated beforehand @param HTTPRequest $request @return bool
hasAccess
php
silverstripe/silverstripe-framework
src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
BSD-3-Clause
protected function getAuthenticationRedirect(HTTPRequest $request) { $backURL = $request->getURL(true); $loginPage = sprintf( '%s?BackURL=%s', Director::absoluteURL(Security::config()->get('login_url')), urlencode($backURL ?? '') ); $result = new HTTPResponse(); $result->redirect($loginPage); return $result; }
Returns HTTPResponse with a redirect to a login page @param HTTPRequest $request @return HTTPResponse redirect to a login page
getAuthenticationRedirect
php
silverstripe/silverstripe-framework
src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/PermissionAwareConfirmationMiddleware.php
BSD-3-Clause
public function __construct($path) { $this->setPath($path); }
Initialize the rule with the path @param string $path
__construct
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/UrlPathStartswith.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/UrlPathStartswith.php
BSD-3-Clause
protected function buildConfirmationItem($token, $url) { return new Confirmation\Item( $token, _t(__CLASS__ . '.CONFIRMATION_NAME', 'URL begins with "{path}"', ['path' => $this->getPath()]), _t(__CLASS__ . '.CONFIRMATION_DESCRIPTION', 'The complete URL is: "{url}"', ['url' => $url]) ); }
Generates the confirmation item @param string $token @param string $url @return Confirmation\Item
buildConfirmationItem
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/UrlPathStartswith.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/UrlPathStartswith.php
BSD-3-Clause
protected function generateToken($path) { return sprintf('%s::%s', static::class, $path); }
Generates the unique token depending on the path @param string $path URL path @return string
generateToken
php
silverstripe/silverstripe-framework
src/Control/Middleware/ConfirmationMiddleware/UrlPathStartswith.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Middleware/ConfirmationMiddleware/UrlPathStartswith.php
BSD-3-Clause