code
stringlengths 17
296k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public static function has_curr()
{
Deprecation::noticeWithNoReplacment('5.4.0');
return Controller::$controller_stack ? true : false;
} | Tests whether we have a currently active controller or not. True if there is at least 1
controller in the stack.
@return bool
@deprecated 5.4.0 Will be removed without equivalent functionality to replace it | has_curr | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function can($perm, $member = null)
{
if (!$member) {
$member = Security::getCurrentUser();
}
if (is_array($perm)) {
$perm = array_map([$this, 'can'], $perm ?? [], array_fill(0, count($perm ?? []), $member));
return min($perm);
}
if ($this->hasMethod($methodName = 'can' . $perm)) {
return $this->$methodName($member);
} else {
return true;
}
} | Returns true if the member is allowed to do the given action. Defaults to the currently logged
in user.
@param string $perm
@param null|member $member
@return bool | can | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function pushCurrent()
{
// Ensure this controller has a valid session
$this->getRequest()->getSession();
array_unshift(Controller::$controller_stack, $this);
} | Pushes this controller onto the stack of current controllers. This means that any redirection,
session setting, or other things that rely on Controller::curr() will now write to this
controller object.
Note: Ensure this controller is assigned a request with a valid session before pushing
it to the stack. | pushCurrent | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function popCurrent()
{
if ($this === Controller::$controller_stack[0]) {
array_shift(Controller::$controller_stack);
} else {
$class = static::class;
user_error(
"popCurrent called on {$class} controller, but it wasn't at the top of the stack",
E_USER_WARNING
);
}
} | Pop this controller off the top of the stack. | popCurrent | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function redirectedTo()
{
return $this->getResponse() && $this->getResponse()->getHeader('Location');
} | Tests whether a redirection has been requested. If redirect() has been called, it will return
the URL redirected to. Otherwise, it will return null.
@return null|string | redirectedTo | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public static function join_links($arg = null)
{
if (func_num_args() === 1 && is_array($arg)) {
$args = $arg;
} else {
$args = func_get_args();
}
$result = "";
$queryargs = [];
$fragmentIdentifier = null;
foreach ($args as $arg) {
// Find fragment identifier - keep the last one
if (strpos($arg ?? '', '#') !== false) {
list($arg, $fragmentIdentifier) = explode('#', $arg ?? '', 2);
}
// Find querystrings
if (strpos($arg ?? '', '?') !== false) {
list($arg, $suffix) = explode('?', $arg ?? '', 2);
parse_str($suffix ?? '', $localargs);
$queryargs = array_merge($queryargs, $localargs);
}
// Join paths together
if ((is_string($arg) && $arg) || is_numeric($arg)) {
$arg = (string) $arg;
if ($result && substr($result ?? '', -1) != '/' && $arg[0] != '/') {
$result .= "/$arg";
} else {
$result .= (substr($result ?? '', -1) == '/' && $arg[0] == '/') ? ltrim($arg, '/') : $arg;
}
}
}
$result = static::normaliseTrailingSlash($result);
if ($queryargs) {
$result .= '?' . http_build_query($queryargs ?? []);
}
if ($fragmentIdentifier) {
$result .= "#$fragmentIdentifier";
}
return $result;
} | Joins two or more link segments together, putting a slash between them if necessary. Use this
for building the results of {@link Link()} methods. If either of the links have query strings,
then they will be combined and put at the end of the resulting url.
Caution: All parameters are expected to be URI-encoded already.
@param string|array $arg One or more link segments, or list of link segments as an array
@return string | join_links | php | silverstripe/silverstripe-framework | src/Control/Controller.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Controller.php | BSD-3-Clause |
public function __construct($body = null, $statusCode = null, $statusDescription = null)
{
if ($body instanceof HTTPResponse) {
// statusCode and statusDescription should override whatever is passed in the body
if ($statusCode) {
$body->setStatusCode($statusCode);
}
if ($statusDescription) {
$body->setStatusDescription($statusDescription);
}
$this->setResponse($body);
} else {
$response = new HTTPResponse($body, $statusCode, $statusDescription);
// Error responses should always be considered plaintext, for security reasons
$response->addHeader('Content-Type', 'text/plain');
$this->setResponse($response);
}
parent::__construct((string) $this->getResponse()->getBody(), $this->getResponse()->getStatusCode());
} | @param HTTPResponse|string $body Either the plaintext content of the error
message, or an HTTPResponse object representing it. In either case, the
$statusCode and $statusDescription will be the HTTP status of the resulting
response.
@param int $statusCode
@param string $statusDescription
@see HTTPResponse::__construct() | __construct | php | silverstripe/silverstripe-framework | src/Control/HTTPResponse_Exception.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPResponse_Exception.php | BSD-3-Clause |
protected function userAgent(HTTPRequest $request)
{
return $request->getHeader('User-Agent');
} | Get user agent for this request
@param HTTPRequest $request
@return string | userAgent | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
public function __construct($data)
{
if ($data instanceof Session) {
$data = $data->getAll();
}
$this->data = $data;
$this->started = isset($data);
} | Start PHP session, then create a new Session object with the given start data.
@param array|null|Session $data Can be an array of data (such as $_SESSION) or another Session object to clone.
If null, this session is treated as unstarted. | __construct | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
public function restart(HTTPRequest $request)
{
$this->destroy(true, $request);
$this->start($request);
} | Destroy existing session and restart
@param HTTPRequest $request | restart | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
public function isStarted()
{
return $this->started;
} | Determine if this session has started
@return bool | isStarted | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
public function start(HTTPRequest $request)
{
if ($this->isStarted()) {
throw new BadMethodCallException("Session has already started");
}
$session_path = $this->config()->get('session_store_path');
// If the session cookie is already set, then the session can be read even if headers_sent() = true
// This helps with edge-case such as debugging.
$data = [];
if (!session_id() && (!headers_sent() || $this->requestContainsSessionId($request))) {
if (!headers_sent()) {
$cookieParams = $this->buildCookieParams($request);
session_set_cookie_params($cookieParams);
$limiter = $this->config()->get('sessionCacheLimiter');
if (isset($limiter)) {
session_cache_limiter($limiter);
}
// Allow storing the session in a non standard location
if ($session_path) {
session_save_path($session_path);
}
// If we want a secure cookie for HTTPS, use a separate session name. This lets us have a
// separate (less secure) session for non-HTTPS requests
// if headers_sent() is true then it's best to throw the resulting error rather than risk
// a security hole.
if ($cookieParams['secure']) {
session_name($this->config()->get('cookie_name_secure'));
}
session_start();
// Session start emits a cookie, but only if there's no existing session. If there is a session timeout
// tied to this request, make sure the session is held for the entire timeout by refreshing the cookie age.
if ($cookieParams['lifetime'] && $this->requestContainsSessionId($request)) {
Cookie::set(
session_name(),
session_id(),
$cookieParams['lifetime'] / 86400,
$cookieParams['path'],
$cookieParams['domain'],
$cookieParams['secure'],
true
);
}
} else {
// If headers are sent then we can't have a session_cache_limiter otherwise we'll get a warning
session_cache_limiter(null);
}
if (isset($_SESSION)) {
// Initialise data from session store if present
$data = $_SESSION;
// Merge in existing in-memory data, taking priority over session store data
$this->recursivelyApply((array)$this->data, $data);
}
}
// Save any modified session data back to the session store if present, otherwise initialise it to an array.
$this->data = $data;
$this->started = true;
} | Begin session, regardless if a session identifier is present in the request,
or whether any session data needs to be written.
See {@link init()} if you want to "lazy start" a session.
@param HTTPRequest $request The request for which to start a session | start | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
public function save(HTTPRequest $request)
{
if ($this->changedData) {
$this->finalize($request);
if (!$this->isStarted()) {
$this->start($request);
}
// Apply all changes recursively, implicitly writing them to the actual PHP session store.
$this->recursivelyApplyChanges($this->changedData, $this->data, $_SESSION);
}
} | Save data to session
Only save the changes, so that anyone manipulating $_SESSION directly doesn't get burned.
@param HTTPRequest $request | save | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
protected function recursivelyApply($data, &$dest)
{
foreach ($data as $k => $v) {
if (is_array($v)) {
if (!isset($dest[$k]) || !is_array($dest[$k])) {
$dest[$k] = [];
}
$this->recursivelyApply($v, $dest[$k]);
} else {
$dest[$k] = $v;
}
}
} | Recursively apply the changes represented in $data to $dest.
Used to update $_SESSION
@param array $data
@param array $dest | recursivelyApply | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
public function changedData()
{
return $this->changedData;
} | Returns the list of changed keys
@return array | changedData | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
protected function &nestedValueRef($name, &$source)
{
// Find var to change
$var = &$source;
foreach (explode('.', $name ?? '') as $namePart) {
if (!isset($var)) {
$var = [];
}
if (!isset($var[$namePart])) {
$var[$namePart] = null;
}
$var = &$var[$namePart];
}
return $var;
} | Navigate to nested value in source array by name,
creating a null placeholder if it doesn't exist.
@internal
@param string $name
@param array $source
@return mixed Reference to value in $source | nestedValueRef | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
protected function nestedValue($name, $source)
{
// Find var to change
$var = $source;
foreach (explode('.', $name ?? '') as $namePart) {
if (!isset($var[$namePart])) {
return null;
}
$var = $var[$namePart];
}
return $var;
} | Navigate to nested value in source array by name,
returning null if it doesn't exist.
@internal
@param string $name
@param array $source
@return mixed Value in array in $source | nestedValue | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
protected function recursivelyApplyChanges($changes, $source, &$destination)
{
$source = $source ?: [];
foreach ($changes as $key => $changed) {
if ($changed === true) {
// Determine if replacement or removal
if (array_key_exists($key, $source ?? [])) {
$destination[$key] = $source[$key];
} else {
unset($destination[$key]);
}
} else {
// Recursively apply
$destVal = &$this->nestedValueRef($key, $destination);
$sourceVal = $this->nestedValue($key, $source);
$this->recursivelyApplyChanges($changed, $sourceVal, $destVal);
}
}
} | Apply all changes using separate keys and data sources and a destination
@internal
@param array $changes
@param array $source
@param array $destination | recursivelyApplyChanges | php | silverstripe/silverstripe-framework | src/Control/Session.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Session.php | BSD-3-Clause |
protected function inferPublicResourceRequired(&$relativePath)
{
// Normalise path
$relativePath = Path::normalise($relativePath, true);
// Detect public-only request
$publicOnly = stripos($relativePath ?? '', 'public' . DIRECTORY_SEPARATOR) === 0;
if ($publicOnly) {
$relativePath = substr($relativePath ?? '', strlen(Director::publicDir() . DIRECTORY_SEPARATOR));
}
return $publicOnly;
} | Determine if the requested $relativePath requires a public-only resource.
An error will occur if this file isn't immediately available in the public/ assets folder.
@param string $relativePath Requested relative path which may have a public/ prefix.
This prefix will be removed if exists. This path will also be normalised to match DIRECTORY_SEPARATOR
@return bool True if the resource must be a public resource | inferPublicResourceRequired | php | silverstripe/silverstripe-framework | src/Control/SimpleResourceURLGenerator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/SimpleResourceURLGenerator.php | BSD-3-Clause |
protected function resolvePublicResource($relativePath)
{
// Determine if we should search both public and base resources, or only public
$publicOnly = $this->inferPublicResourceRequired($relativePath);
// Search public folder first, and unless `public/` is prefixed, also private base path
$publicPath = Path::join(Director::publicFolder(), $relativePath);
if (file_exists($publicPath ?? '')) {
// String is a literal url committed directly to public folder
return [true, $publicPath, $relativePath];
}
// Fall back to private path (and assume expose will make this available to _resources/)
$privatePath = Path::join(Director::baseFolder(), $relativePath);
if (!$publicOnly && file_exists($privatePath ?? '')) {
// String is private but exposed to _resources/, so rewrite to the symlinked base
$relativePath = Path::join(RESOURCES_DIR, $relativePath);
return [true, $privatePath, $relativePath];
}
// File doesn't exist, fail
return [false, null, $relativePath];
} | Resolve a resource that may either exist in a public/ folder, or be exposed from the base path to
public/_resources/
@param string $relativePath
@return array List of [$exists, $absolutePath, $relativePath] | resolvePublicResource | php | silverstripe/silverstripe-framework | src/Control/SimpleResourceURLGenerator.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/SimpleResourceURLGenerator.php | BSD-3-Clause |
public static function get_inst()
{
return Injector::inst()->get('SilverStripe\\Control\\Cookie_Backend');
} | Fetch the current instance of the cookie backend.
@return Cookie_Backend | get_inst | php | silverstripe/silverstripe-framework | src/Control/Cookie.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Cookie.php | BSD-3-Clause |
public static function set(
$name,
$value,
$expiry = 90,
$path = null,
$domain = null,
$secure = false,
$httpOnly = true
) {
return Cookie::get_inst()->set($name, $value, $expiry, $path, $domain, $secure, $httpOnly);
} | Set a cookie variable.
Expiry time is set in days, and defaults to 90.
@param string $name
@param mixed $value
@param float $expiry
@param string $path
@param string $domain
@param bool $secure
@param bool $httpOnly
See http://php.net/set_session | set | php | silverstripe/silverstripe-framework | src/Control/Cookie.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Cookie.php | BSD-3-Clause |
public static function get($name, $includeUnsent = true)
{
return Cookie::get_inst()->get($name, $includeUnsent);
} | Get the cookie value by name. Returns null if not set.
@param string $name
@param bool $includeUnsent
@return null|string | get | php | silverstripe/silverstripe-framework | src/Control/Cookie.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/Cookie.php | BSD-3-Clause |
public function __construct($cookies = [])
{
$this->current = $this->existing = func_num_args()
? ($cookies ?: []) // Convert empty values to blank arrays
: $_COOKIE;
} | When creating the backend we want to store the existing cookies in our
"existing" array. This allows us to distinguish between cookies we received
or we set ourselves (and didn't get from the browser)
@param array $cookies The existing cookies to load into the cookie jar.
Omit this to default to $_COOKIE | __construct | php | silverstripe/silverstripe-framework | src/Control/CookieJar.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/CookieJar.php | BSD-3-Clause |
public function get($name, $includeUnsent = true)
{
$cookies = $includeUnsent ? $this->current : $this->existing;
if (isset($cookies[$name])) {
return $cookies[$name];
}
//Normalise cookie names by replacing '.' with '_'
$safeName = str_replace('.', '_', $name ?? '');
if (isset($cookies[$safeName])) {
return $cookies[$safeName];
}
return null;
} | Get the cookie value by name
Cookie names are normalised to work around PHP's behaviour of replacing incoming variable name . with _
@param string $name The name of the cookie to get
@param boolean $includeUnsent Include cookies we've yet to send when fetching values
@return string|null The cookie value or null if unset | get | php | silverstripe/silverstripe-framework | src/Control/CookieJar.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/CookieJar.php | BSD-3-Clause |
public function forceExpiry($name, $path = null, $domain = null, $secure = false, $httpOnly = true)
{
$this->set($name, false, -1, $path, $domain, $secure, $httpOnly);
} | Force the expiry of a cookie by name
@param string $name The name of the cookie to expire
@param string $path The path to save the cookie on (falls back to site base)
@param string $domain The domain to make the cookie available on
@param boolean $secure Can the cookie only be sent over SSL?
@param boolean $httpOnly Prevent the cookie being accessible by JS | forceExpiry | php | silverstripe/silverstripe-framework | src/Control/CookieJar.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/CookieJar.php | BSD-3-Clause |
protected function outputCookie(
$name,
$value,
$expiry = 90,
$path = null,
$domain = null,
$secure = false,
$httpOnly = true
) {
$sameSite = $this->getSameSite($name);
Cookie::validateSameSite($sameSite);
// if headers aren't sent, we can set the cookie
if (!headers_sent($file, $line)) {
return setcookie($name ?? '', $value ?? '', [
'expires' => $expiry ?? 0,
'path' => $path ?? '',
'domain' => $domain ?? '',
'secure' => $this->cookieIsSecure($sameSite, (bool) $secure),
'httponly' => $httpOnly ?? false,
'samesite' => $sameSite,
]);
}
if (Cookie::config()->uninherited('report_errors')) {
throw new LogicException(
"Cookie '$name' can't be set. The site started outputting content at line $line in $file"
);
}
return false;
} | The function that actually sets the cookie using PHP
@see http://uk3.php.net/manual/en/function.setcookie.php
@param string $name The name of the cookie
@param string|array $value The value for the cookie to hold
@param int $expiry A Unix timestamp indicating when the cookie expires; 0 means it will expire at the end of the session
@param string $path The path to save the cookie on (falls back to site base)
@param string $domain The domain to make the cookie available on
@param boolean $secure Can the cookie only be sent over SSL?
@param boolean $httpOnly Prevent the cookie being accessible by JS
@return boolean If the cookie was set or not; doesn't mean it's accepted by the browser | outputCookie | php | silverstripe/silverstripe-framework | src/Control/CookieJar.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/CookieJar.php | BSD-3-Clause |
public static function createFromEnvironment()
{
// Clean and update live global variables
$variables = static::cleanEnvironment(Environment::getVariables());
Environment::setVariables($variables); // Currently necessary for SSViewer, etc to work
// Health-check prior to creating environment
return static::createFromVariables($variables, @file_get_contents('php://input'));
} | Create HTTPRequest instance from the current environment variables.
May throw errors if request is invalid.
@throws HTTPResponse_Exception
@return HTTPRequest | createFromEnvironment | php | silverstripe/silverstripe-framework | src/Control/HTTPRequestBuilder.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequestBuilder.php | BSD-3-Clause |
public static function cleanEnvironment(array $variables)
{
// Merge $_FILES into $_POST
$variables['_POST'] = array_merge((array)$variables['_POST'], (array)$variables['_FILES']);
// Merge $_POST, $_GET, and $_COOKIE into $_REQUEST
$variables['_REQUEST'] = array_merge(
(array)$variables['_GET'],
(array)$variables['_POST'],
(array)$variables['_COOKIE']
);
return $variables;
} | Clean up HTTP global vars for $_GET / $_REQUEST prior to bootstrapping
@param array $variables
@return array Cleaned variables | cleanEnvironment | php | silverstripe/silverstripe-framework | src/Control/HTTPRequestBuilder.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequestBuilder.php | BSD-3-Clause |
public function __construct($stream, $contentLength, $statusCode = null, $statusDescription = null)
{
parent::__construct(null, $statusCode, $statusDescription);
$this->setStream($stream);
if ($contentLength) {
$this->addHeader('Content-Length', $contentLength);
}
} | HTTPStreamResponse constructor.
@param resource $stream Data stream
@param int $contentLength size of the stream in bytes
@param int $statusCode The numeric status code - 200, 404, etc
@param string $statusDescription The text to be given alongside the status code. | __construct | php | silverstripe/silverstripe-framework | src/Control/HTTPStreamResponse.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPStreamResponse.php | BSD-3-Clause |
protected function isSeekable()
{
$stream = $this->getStream();
if (!$stream) {
return false;
}
$metadata = stream_get_meta_data($stream);
return $metadata['seekable'];
} | Determine if a stream is seekable
@return bool | isSeekable | php | silverstripe/silverstripe-framework | src/Control/HTTPStreamResponse.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPStreamResponse.php | BSD-3-Clause |
public function getSavedBody()
{
return parent::getBody();
} | Get body prior to stream traversal
@return string | getSavedBody | php | silverstripe/silverstripe-framework | src/Control/HTTPStreamResponse.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPStreamResponse.php | BSD-3-Clause |
protected function outputBody()
{
// If the output has been overwritten, or the stream is irreversible and has
// already been consumed, return the cached body.
$body = $this->getSavedBody();
if ($body) {
echo $body;
return;
}
// Stream to output
if ($this->getStream()) {
$this->consumeStream(function ($stream) {
fpassthru($stream);
});
return;
}
// Fail over
parent::outputBody();
} | Output body of this response to the browser | outputBody | php | silverstripe/silverstripe-framework | src/Control/HTTPStreamResponse.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPStreamResponse.php | BSD-3-Clause |
public function __construct($httpMethod, $url, $getVars = [], $postVars = [], $body = null)
{
$this->httpMethod = strtoupper($httpMethod ?? '');
$this->setUrl($url);
$this->getVars = (array) $getVars;
$this->postVars = (array) $postVars;
$this->body = $body;
$this->scheme = "http";
} | Construct a HTTPRequest from a URL relative to the site root.
@param string $httpMethod
@param string $url
@param array $getVars
@param array $postVars
@param string $body | __construct | 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 setUrl($url)
{
$this->url = $url;
// Normalize URL if its relative (strictly speaking), or has leading slashes
if (Director::is_relative_url($url) || preg_match('/^\//', $url ?? '')) {
$this->url = preg_replace(['/\/+/','/^\//', '/\/$/'], ['/','',''], $this->url ?? '');
}
if (preg_match('/^(.*)\.([A-Za-z][A-Za-z0-9]*)$/', $this->url ?? '', $matches)) {
$this->url = $matches[1];
$this->extension = $matches[2];
}
if ($this->url) {
$this->dirParts = preg_split('|/+|', $this->url ?? '');
} else {
$this->dirParts = [];
}
return $this;
} | Allow the setting of a URL
This is here so that RootURLController can change the URL of the request
without us losing all the other info attached (like headers)
@param string $url The new URL
@return HTTPRequest The updated request | setUrl | 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 requestVars()
{
return ArrayLib::array_merge_recursive($this->getVars, $this->postVars);
} | Returns all combined HTTP GET and POST parameters
passed into this request. If a parameter with the same
name exists in both arrays, the POST value is returned.
@return array | requestVars | 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 getExtension()
{
return $this->extension;
} | Returns a possible file extension found in parsing the URL
as denoted by a "."-character near the end of the URL.
Doesn't necessarily have to belong to an existing file,
as extensions can be also used for content-type-switching.
@return string | getExtension | 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 isMedia()
{
return in_array($this->getExtension(), ['css', 'js', 'jpg', 'jpeg', 'gif', 'png', 'bmp', 'ico']);
} | Checks if the {@link HTTPRequest->getExtension()} on this request matches one of the more common media types
embedded into a webpage - e.g. css, png.
This is useful for things like determining whether to display a fully rendered error page or not. Note that the
media file types is not at all comprehensive.
@return bool | isMedia | 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 addHeader($header, $value)
{
$header = strtolower($header ?? '');
$this->headers[$header] = $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" | addHeader | 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 getHeader($header)
{
$header = strtolower($header ?? '');
return (isset($this->headers[$header])) ? $this->headers[$header] : null;
} | Returns a HTTP Header by name if found in the request
@param string $header Name of the header (Insensitive to case as per <rfc2616 section 4.2 "Message Headers">)
@return mixed | getHeader | 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 removeHeader($header)
{
$header = strtolower($header ?? '');
unset($this->headers[$header]);
return $this;
} | Remove an existing HTTP header by its name,
e.g. "Content-Type".
@param string $header
@return HTTPRequest $this | removeHeader | 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 isAjax()
{
return (
$this->requestVar('ajax') ||
$this->getHeader('x-requested-with') === "XMLHttpRequest"
);
} | Returns true if this request an ajax request,
based on custom HTTP ajax added by common JavaScript libraries,
or based on an explicit "ajax" request parameter.
@return boolean | isAjax | php | silverstripe/silverstripe-framework | src/Control/HTTPRequest.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/Control/HTTPRequest.php | BSD-3-Clause |
public static function send_file($fileData, $fileName, $mimeType = null)
{
if (!$mimeType) {
$mimeType = HTTP::get_mime_type($fileName);
}
$response = new HTTPResponse($fileData);
$response->addHeader("content-type", "$mimeType; name=\"" . addslashes($fileName ?? '') . "\"");
// Note a IE-only fix that inspects this header in HTTP::add_cache_headers().
$response->addHeader("content-disposition", "attachment; filename=\"" . addslashes($fileName ?? '') . "\"");
$response->addHeader("content-length", strlen($fileData ?? ''));
return $response;
} | Construct an HTTPResponse that will deliver a file to the client.
Caution: Since it requires $fileData to be passed as binary data (no stream support),
it's only advisable to send small files through this method.
This function needs to be called inside the controller’s response, e.g.:
<code>$this->setResponse(HTTPRequest::send_file('the content', 'filename.txt'));</code>
@static
@param string $fileData
@param string $fileName
@param string|null $mimeType
@return HTTPResponse | send_file | 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 param($name)
{
$params = $this->params();
if (isset($params[$name])) {
return $params[$name];
} else {
return null;
}
} | Finds a named URL parameter (denoted by "$"-prefix in $url_handlers)
from the full URL, or a parameter specified in the route table
@param string $name
@return string Value of the URL parameter (if found) | param | 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 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 getScheme()
{
return $this->scheme;
} | Return the URL scheme (e.g. "http" or "https").
Equivalent to PSR-7 getUri()->getScheme()
@return string | getScheme | 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 removeHeader($header)
{
$header = strtolower($header ?? '');
unset($this->headers[$header]);
return $this;
} | Remove an existing HTTP header by its name,
e.g. "Content-Type".
@param string $header
@return $this | removeHeader | 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 |
protected function outputBody()
{
// Only show error pages or generic "friendly" errors if the status code signifies
// an error, and the response doesn't have any body yet that might contain
// a more specific error description.
$body = $this->getBody();
if ($this->isError() && empty($body)) {
$handler = Injector::inst()->get(HandlerInterface::class);
$formatter = $handler->getFormatter();
echo $formatter->format([
'code' => $this->statusCode,
]);
} else {
echo $this->body;
}
} | Output body of this response to the browser | outputBody | 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 Description()
{
$description = $this->rssField($this->descriptionField);
// HTML fields need links re-written
if ($description instanceof DBHTMLText) {
return $description->obj('AbsoluteLinks');
}
return $description;
} | Get the description of this entry
@return DBField Returns the description of the entry. | Description | 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 getTemplate()
{
return $this->template;
} | Returns the name of the template to use.
@return string | getTemplate | 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 getTemplates()
{
$templates = SSViewer::get_templates_by_class(static::class, '', __CLASS__);
// Prefer any custom template
if ($this->getTemplate()) {
array_unshift($templates, $this->getTemplate());
}
return $templates;
} | Returns the ordered list of preferred templates for rendering this object.
Will prioritise any custom template first, and then templates based on class hierarchy next.
@return array | getTemplates | 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 |
private function __construct()
{
} | This class should not be instantiated. | __construct | 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 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.