<?php
namespace SilverStripe\Control;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\Middleware\CanonicalURLMiddleware;
use SilverStripe\Control\Middleware\HTTPMiddlewareAware;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Extensible;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Kernel;
use SilverStripe\Core\Path;
use SilverStripe\Dev\Deprecation;
use SilverStripe\PolyExecution\PolyCommand;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\Requirements;
use SilverStripe\View\Requirements_Backend;
use SilverStripe\View\TemplateGlobalProvider;
use SilverStripe\ORM\DB;
* Director is responsible for processing URLs, and providing environment information.
*
* The most important part of director is {@link Director::handleRequest()}, which is passed an HTTPRequest and will
* execute the appropriate controller.
*
* @see Director::handleRequest()
* @see Director::$rules
*/
class Director implements TemplateGlobalProvider
{
use Configurable;
use Extensible;
use Injectable;
use HTTPMiddlewareAware;
* Specifies this url is relative to the base.
*
* @var string
*/
const BASE = 'BASE';
* Specifies this url is relative to the site root.
*
* @var string
*/
const ROOT = 'ROOT';
* specifies this url is relative to the current request.
*
* @var string
*/
const REQUEST = 'REQUEST';
* @config
* @var array
*/
private static $rules = [];
* Set current page
*
* @internal
* @var SiteTree
*/
private static $current_page;
* @config
* @var string
*/
private static $alternate_base_folder;
* Base url to populate if cannot be determined otherwise.
* Supports back-ticked vars; E.g. '`SS_BASE_URL`'
*
* @config
* @var string
*/
private static $default_base_url = '`SS_BASE_URL`';
* List of routing rule patterns that must only use the primary database and not a replica
*/
private static array $rule_patterns_must_use_primary_db = [
'dev',
'Security',
];
public function __construct()
{
}
* Test a URL request, returning a response object. This method is a wrapper around
* Director::handleRequest() to assist with functional testing. It will execute the URL given, and
* return the result as an HTTPResponse object.
*
* @param string $url The URL to visit.
* @param array $postVars The $_POST & $_FILES variables.
* @param array|Session $session The {@link Session} object representing the current session.
* By passing the same object to multiple calls of Director::test(), you can simulate a persisted
* session.
* @param string $httpMethod The HTTP method, such as GET or POST. It will default to POST if
* postVars is set, GET otherwise. Overwritten by $postVars['_method'] if present.
* @param string $body The HTTP body.
* @param array $headers HTTP headers with key-value pairs.
* @param array|Cookie_Backend $cookies to populate $_COOKIE.
* @param HTTPRequest $request The {@see SS_HTTP_Request} object generated as a part of this request.
*
* @return HTTPResponse
*
* @throws HTTPResponse_Exception
*/
public static function test(
$url,
$postVars = [],
$session = [],
$httpMethod = null,
$body = null,
$headers = [],
$cookies = [],
&$request = null
) {
return static::mockRequest(
function (HTTPRequest $request) {
return Director::singleton()->handleRequest($request);
},
$url,
$postVars,
$session,
$httpMethod,
$body,
$headers,
$cookies,
$request
);
}
* Mock a request, passing this to the given callback, before resetting.
*
* @param callable $callback Action to pass the HTTPRequst object
* @param string $url The URL to build
* @param array $postVars The $_POST & $_FILES variables.
* @param array|Session $session The {@link Session} object representing the current session.
* By passing the same object to multiple calls of Director::test(), you can simulate a persisted
* session.
* @param string $httpMethod The HTTP method, such as GET or POST. It will default to POST if
* postVars is set, GET otherwise. Overwritten by $postVars['_method'] if present.
* @param string $body The HTTP body.
* @param array $headers HTTP headers with key-value pairs.
* @param array|Cookie_Backend $cookies to populate $_COOKIE.
* @param HTTPRequest $request The {@see SS_HTTP_Request} object generated as a part of this request.
* @return mixed Result of callback
*/
public static function mockRequest(
$callback,
$url,
$postVars = [],
$session = [],
$httpMethod = null,
$body = null,
$headers = [],
$cookies = [],
&$request = null
) {
$finally = [];
$kernel = Injector::inst()->get(Kernel::class);
$kernel->nest();
$finally[] = function () use ($kernel) {
$kernel->activate();
};
$existingVars = Environment::getVariables();
$finally[] = function () use ($existingVars) {
Environment::setVariables($existingVars);
};
$newVars = $existingVars;
if (class_exists(Versioned::class)) {
$oldReadingMode = Versioned::get_reading_mode();
$finally[] = function () use ($oldReadingMode) {
Versioned::set_reading_mode($oldReadingMode);
};
}
$newVars['_SERVER']['REQUEST_METHOD'] = $httpMethod ?: ($postVars ? "POST" : "GET");
$newVars['_POST'] = (array)$postVars;
if ($session instanceof Session) {
$newVars['_SESSION'] = $sessionArray = $session->getAll() ?: [];
$finally[] = function () use ($session, $sessionArray) {
if (isset($_SESSION)) {
foreach ($_SESSION as $key => $value) {
$session->set($key, $value);
}
foreach (array_diff_key($sessionArray ?? [], $_SESSION) as $key => $value) {
$session->clear($key);
}
}
};
} else {
$newVars['_SESSION'] = $session ?: [];
}
$cookieJar = $cookies instanceof Cookie_Backend
? $cookies
: Injector::inst()->createWithArgs(Cookie_Backend::class, [$cookies ?: []]);
$newVars['_COOKIE'] = $cookieJar->getAll(false);
Cookie::config()->set('report_errors', false);
Injector::inst()->registerService($cookieJar, Cookie_Backend::class);
$existingRequirementsBackend = Requirements::backend();
Requirements::set_backend(Requirements_Backend::create());
$finally[] = function () use ($existingRequirementsBackend) {
Requirements::set_backend($existingRequirementsBackend);
};
$url = strtok($url ?? '', '#');
$urlHostPort = static::parseHost($url);
if ($urlHostPort) {
$newVars['_SERVER']['HTTP_HOST'] = $urlHostPort;
}
$url = Director::makeRelative($url);
if (strpos($url ?? '', '?') !== false) {
list($url, $getVarsEncoded) = explode('?', $url ?? '', 2);
parse_str($getVarsEncoded ?? '', $newVars['_GET']);
} else {
$newVars['_GET'] = [];
}
$newVars['_SERVER']['REQUEST_URI'] = Director::baseURL() . ltrim($url ?? '', '/');
$newVars['_REQUEST'] = array_merge($newVars['_GET'], $newVars['_POST']);
$newVars = HTTPRequestBuilder::cleanEnvironment($newVars);
$request = HTTPRequestBuilder::createFromVariables($newVars, $body, ltrim($url ?? '', '/'));
if ($headers) {
foreach ($headers as $k => $v) {
$request->addHeader($k, $v);
}
}
Environment::setVariables($newVars);
try {
return call_user_func($callback, $request);
} finally {
foreach (array_reverse($finally) as $callback) {
call_user_func($callback);
}
}
}
* Process the given URL, creating the appropriate controller and executing it.
*
* Request processing is handled as follows:
* - Director::handleRequest($request) checks each of the Director rules and identifies a controller
* to handle this request.
* - Controller::handleRequest($request) is then called. This will find a rule to handle the URL,
* and call the rule handling method.
* - RequestHandler::handleRequest($request) is recursively called whenever a rule handling method
* returns a RequestHandler object.
*
* In addition to request processing, Director will manage the session, and perform the output of
* the actual response to the browser.
*
* @param HTTPRequest $request
* @return HTTPResponse
* @throws HTTPResponse_Exception
*/
public function handleRequest(HTTPRequest $request)
{
Injector::inst()->registerService($request, HTTPRequest::class);
$primaryDbOnlyRules = Director::config()->uninherited('rule_patterns_must_use_primary_db');
foreach ($primaryDbOnlyRules as $rule) {
if ($request->match($rule)) {
DB::setMustUsePrimary();
break;
}
}
$rules = Director::config()->uninherited('rules');
$this->extend('updateRules', $rules);
$handler = function () {
return new HTTPResponse('No URL rule was matched', 404);
};
foreach ($rules as $pattern => $controllerOptions) {
$arguments = $request->match($pattern, true);
if ($arguments == false) {
continue;
}
if (is_string($controllerOptions)) {
if (substr($controllerOptions ?? '', 0, 2) == '->') {
$controllerOptions = ['Redirect' => substr($controllerOptions ?? '', 2)];
} else {
$controllerOptions = ['Controller' => $controllerOptions];
}
}
$request->setRouteParams($controllerOptions);
$arguments = array_merge($controllerOptions, $arguments);
if (isset($controllerOptions['_PopTokeniser'])) {
$request->shift($controllerOptions['_PopTokeniser']);
}
if (isset($arguments['Redirect'])) {
$handler = function () use ($arguments) {
$response = new HTTPResponse();
$response->redirect(static::absoluteUrl((string) $arguments['Redirect']));
return $response;
};
break;
}
$handler = function (HTTPRequest $request) use ($arguments) {
try {
$controllerObj = Injector::inst()->create($arguments['Controller']);
if ($controllerObj instanceof PolyCommand) {
$controllerObj = PolyCommandController::create($controllerObj);
}
return $controllerObj->handleRequest($request);
} catch (HTTPResponse_Exception $responseException) {
return $responseException->getResponse();
}
};
break;
}
$response = $this->callMiddleware($request, $handler);
Injector::inst()->unregisterNamedObject(HTTPRequest::class);
return $response;
}
* Return the {@link SiteTree} object that is currently being viewed. If there is no SiteTree
* object to return, then this will return the current controller.
*
* @return SiteTree|Controller
*/
public static function get_current_page()
{
return Director::$current_page ? Director::$current_page : Controller::curr();
}
* Set the currently active {@link SiteTree} object that is being used to respond to the request.
*
* @param SiteTree $page
*/
public static function set_current_page($page)
{
Director::$current_page = $page;
}
* Converts the given path or url into an absolute url. This method follows the below rules:
* - Absolute urls (e.g. `http://localhost`) are not modified
* - Relative urls (e.g. `//localhost`) have current protocol added (`http://localhost`)
* - Absolute paths (e.g. `/base/about-us`) are resolved by adding the current protocol and host (`http://localhost/base/about-us`)
* - Relative paths (e.g. `about-us/staff`) must be resolved using one of three methods, disambiguated via the $relativeParent argument:
* - BASE - Append this path to the base url (i.e. behaves as though `<base>` tag is provided in a html document). This is the default.
* - REQUEST - Resolve this path to the current url (i.e. behaves as though no `<base>` tag is provided in a html document)
* - ROOT - Treat this as though it was an absolute path, and append it to the protocol and hostname.
*/
public static function absoluteURL(string $url, string $relativeParent = Director::BASE): string|bool
{
if (preg_match('/^http(s?):\/\//', $url ?? '')) {
return Controller::normaliseTrailingSlash($url);
}
if (strpos($url ?? '', '//') === 0) {
return Controller::normaliseTrailingSlash(Director::protocol() . substr($url ?? '', 2));
}
if ($relativeParent === Director::ROOT || Director::is_root_relative_url($url)) {
$parent = Director::protocolAndHost();
} elseif ($relativeParent === Director::REQUEST) {
if (!isset($_SERVER['REQUEST_URI'])) {
return false;
}
$parent = dirname($_SERVER['REQUEST_URI'] . 'x');
} else {
$parent = Director::absoluteBaseURL();
}
if (empty($url) || $url === '.' || $url === './') {
$url = '/';
}
return Controller::join_links($parent, $url);
}
* Return only host (and optional port) part of a url
*
* @param string $url
* @return string|null Hostname, and optional port, or null if not a valid host
*/
protected static function parseHost($url)
{
$host = parse_url($url ?? '', PHP_URL_HOST);
if (!$host) {
return null;
}
$port = parse_url($url ?? '', PHP_URL_PORT);
if ($port) {
$host .= ':' . $port;
}
return $host;
}
* Validate user and password in URL, disallowing slashes
*
* @param string $url
* @return bool
*/
protected static function validateUserAndPass($url)
{
$parsedURL = parse_url($url ?? '');
if (!empty($parsedURL['user']) && strstr($parsedURL['user'] ?? '', '\\')) {
return false;
}
if (!empty($parsedURL['pass']) && strstr($parsedURL['pass'] ?? '', '\\')) {
return false;
}
return true;
}
* A helper to determine the current hostname used to access the site.
* The following are used to determine the host (in order)
* - Director.alternate_base_url (if it contains a domain name)
* - Trusted proxy headers
* - HTTP Host header
* - SS_BASE_URL env var
* - SERVER_NAME
* - gethostname()
*
* @param HTTPRequest $request
* @return string Host name, including port (if present)
*/
public static function host(?HTTPRequest $request = null)
{
if ($baseURL = static::config()->get('alternate_base_url')) {
$baseURL = Injector::inst()->convertServiceProperty($baseURL);
$host = static::parseHost($baseURL);
if ($host) {
return $host;
}
}
$request = static::currentRequest($request);
if ($request && ($host = $request->getHeader('Host'))) {
return $host;
}
if (isset($_SERVER['HTTP_HOST'])) {
return $_SERVER['HTTP_HOST'];
}
if ($baseURL = static::config()->uninherited('default_base_url')) {
$baseURL = Injector::inst()->convertServiceProperty($baseURL);
$host = static::parseHost($baseURL);
if ($host) {
return $host;
}
}
return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : gethostname();
}
* Return port used for the base URL.
* Note, this will be null if not specified, in which case you should assume the default
* port for the current protocol.
*
* @param HTTPRequest $request
* @return int|null
*/
public static function port(?HTTPRequest $request = null)
{
$host = static::host($request);
return (int)parse_url($host ?? '', PHP_URL_PORT) ?: null;
}
* Return host name without port
*
* @param HTTPRequest|null $request
* @return string|null
*/
public static function hostName(?HTTPRequest $request = null)
{
$host = static::host($request);
return parse_url($host ?? '', PHP_URL_HOST) ?: null;
}
* Returns the domain part of the URL 'http://www.mysite.com'. Returns FALSE is this environment
* variable isn't set.
*
* @param HTTPRequest $request
* @return bool|string
*/
public static function protocolAndHost(?HTTPRequest $request = null)
{
return static::protocol($request) . static::host($request);
}
* Return the current protocol that the site is running under.
*
* @param HTTPRequest $request
* @return string
*/
public static function protocol(?HTTPRequest $request = null)
{
return (Director::is_https($request)) ? 'https://' : 'http://';
}
* Return whether the site is running as under HTTPS.
*
* @param HTTPRequest $request
* @return bool
*/
public static function is_https(?HTTPRequest $request = null)
{
if ($baseURL = static::config()->uninherited('alternate_base_url')) {
$baseURL = Injector::inst()->convertServiceProperty($baseURL);
$protocol = parse_url($baseURL ?? '', PHP_URL_SCHEME);
if ($protocol) {
return $protocol === 'https';
}
}
$request = static::currentRequest($request);
if ($request && ($scheme = $request->getScheme())) {
return $scheme === 'https';
}
if ($baseURL = static::config()->uninherited('default_base_url')) {
$baseURL = Injector::inst()->convertServiceProperty($baseURL);
$protocol = parse_url($baseURL ?? '', PHP_URL_SCHEME);
if ($protocol) {
return $protocol === 'https';
}
}
return false;
}
* Return the root-relative url for the baseurl
*
* @return string Root-relative url with trailing slash.
*/
public static function baseURL()
{
$alternate = static::config()->get('alternate_base_url');
if ($alternate) {
$alternate = Injector::inst()->convertServiceProperty($alternate);
return rtrim(parse_url($alternate ?? '', PHP_URL_PATH) ?? '', '/') . '/';
}
$baseURL = rtrim(BASE_URL, '/') . '/';
if (defined('BASE_SCRIPT_URL')) {
return rtrim($baseURL . BASE_SCRIPT_URL, '/') . '/';
}
return $baseURL;
}
* Returns the root filesystem folder for the site. It will be automatically calculated unless
* it is overridden with {@link setBaseFolder()}.
*
* @return string
*/
public static function baseFolder()
{
$alternate = Director::config()->uninherited('alternate_base_folder');
return $alternate ?: BASE_PATH;
}
* The name of the public directory
*
* @return string
*/
public static function publicDir()
{
return PUBLIC_DIR;
}
* Gets the webroot of the project, which may be a subfolder of {@see baseFolder()}
*
* @return string
*/
public static function publicFolder()
{
$folder = Director::baseFolder();
$publicDir = Director::publicDir();
if ($publicDir) {
return Path::join($folder, $publicDir);
}
return $folder;
}
* Turns an absolute URL or folder into one that's relative to the root of the site. This is useful
* when turning a URL into a filesystem reference, or vice versa.
*
* Note: You should check {@link Director::is_site_url()} if making an untrusted url relative prior
* to calling this function.
*
* @param string $url Accepts both a URL or a filesystem path.
* @return string
*/
public static function makeRelative($url)
{
$url = preg_replace('#([^:])//#', '\\1/', trim($url ?? ''));
if (preg_match('@^(?<protocol>https?:)?//(?<hostpart>[^/?#]*)(?<url>([/?#].*)?)$@i', $url ?? '', $matches)) {
$url = $matches['url'];
}
if (trim($url ?? '', '\\/') === '') {
return '';
}
foreach ([Director::publicFolder(), Director::baseFolder(), Director::baseURL()] as $base) {
$base = rtrim($base ?? '', '\\/') ?: $base;
if (stripos($url ?? '', $base ?? '') === 0) {
return ltrim(substr($url ?? '', strlen($base ?? '')), '\\/');
}
}
return $url;
}
* Returns true if a given path is absolute. Works under both *nix and windows systems.
*
* @param string $path
*
* @return bool
*/
public static function is_absolute($path)
{
if (empty($path)) {
return false;
}
if ($path[0] == '/' || $path[0] == '\\') {
return true;
}
return preg_match('/^[a-zA-Z]:[\\\\\/]/', $path ?? '') == 1;
}
* Determine if the url is root relative (i.e. starts with /, but not with //) SilverStripe
* considers root relative urls as a subset of relative urls.
*
* @param string $url
*
* @return bool
*/
public static function is_root_relative_url($url)
{
return strpos($url ?? '', '/') === 0 && strpos($url ?? '', '//') !== 0;
}
* Checks if a given URL is absolute (e.g. starts with 'http://' etc.). URLs beginning with "//"
* are treated as absolute, as browsers take this to mean the same protocol as currently being used.
*
* Useful to check before redirecting based on a URL from user submissions through $_GET or $_POST,
* and avoid phishing attacks by redirecting to an attackers server.
*
* Note: Can't solely rely on PHP's parse_url() , since it is not intended to work with relative URLs
* or for security purposes. filter_var($url, FILTER_VALIDATE_URL) has similar problems.
*
* @param string $url
*
* @return bool
*/
public static function is_absolute_url($url)
{
if (($queryPosition = strpos($url ?? '', '?')) !== false) {
$url = substr($url ?? '', 0, $queryPosition - 1);
}
if (($hashPosition = strpos($url ?? '', '#')) !== false) {
$url = substr($url ?? '', 0, $hashPosition - 1);
}
$colonPosition = strpos($url ?? '', ':');
$slashPosition = strpos($url ?? '', '/');
return (
parse_url($url ?? '', PHP_URL_HOST)
|| preg_match('%^\s*(\\\\|/){2,}%', $url ?? '')
|| (
$colonPosition !== false
&& ($slashPosition === false || $colonPosition < $slashPosition)
)
);
}
* Checks if a given URL is relative (or root relative) by checking {@link is_absolute_url()}.
*
* @param string $url
*
* @return bool
*/
public static function is_relative_url($url)
{
return !static::is_absolute_url($url);
}
* Checks if the given URL is belonging to this "site" (not an external link). That's the case if
* the URL is relative, as defined by {@link is_relative_url()}, or if the host matches
* {@link protocolAndHost()}.
*
* Useful to check before redirecting based on a URL from user submissions through $_GET or $_POST,
* and avoid phishing attacks by redirecting to an attackers server.
*
* Provides an extension point to allow extra checks on the URL to allow some external URLs,
* e.g. links on secondary domains that point to the same CMS, or subsite domains.
*
* @param string $url
*
* @return bool
*/
public static function is_site_url($url)
{
if (!static::validateUserAndPass($url)) {
return false;
}
$urlHost = static::parseHost($url);
if ($urlHost && $urlHost === static::host()) {
return true;
}
$isSiteUrl = false;
$director = new static();
$director->extend('updateIsSiteUrl', $isSiteUrl, $url);
if ($isSiteUrl) {
return true;
}
return Director::is_relative_url($url);
}
* Given a filesystem reference relative to the site root, return the full file-system path.
*
* @param string $file
*
* @return string
*/
public static function getAbsFile($file)
{
if (Director::is_absolute($file)) {
return $file;
}
if (Director::publicDir()) {
$path = Path::join(Director::publicFolder(), $file);
if (file_exists($path ?? '')) {
return $path;
}
}
return Path::join(Director::baseFolder(), $file);
}
* Returns true if the given file exists. Filename should be relative to the site root.
*
* @param $file
*
* @return bool
*/
public static function fileExists($file)
{
$file = preg_replace('/([^\?]*)?.*/', '$1', $file ?? '');
return file_exists(Director::getAbsFile($file) ?? '');
}
* Returns the Absolute URL of the site root.
*
* @return string
*/
public static function absoluteBaseURL()
{
$baseURL = Director::absoluteURL(
Director::baseURL(),
Director::ROOT
);
return Controller::normaliseTrailingSlash($baseURL);
}
* Returns the Absolute URL of the site root, embedding the current basic-auth credentials into
* the URL.
*
* @param HTTPRequest|null $request
* @return string
*/
public static function absoluteBaseURLWithAuth(?HTTPRequest $request = null)
{
$login = '';
if ($request) {
$user = $request->getHeader('PHP_AUTH_USER');
if ($user) {
$password = $request->getHeader('PHP_AUTH_PW');
$login = sprintf("%s:%s@", $user, $password);
}
}
return Director::protocol($request) . $login . static::host($request) . Director::baseURL();
}
* Skip any further processing and immediately respond with a redirect to the passed URL.
*
* @param string $destURL
* @throws HTTPResponse_Exception
*/
protected static function force_redirect($destURL)
{
$response = new HTTPResponse();
$response->redirect($destURL, 301);
throw new HTTPResponse_Exception($response);
}
* Force the site to run on SSL.
*
* To use, call from _config.php. For example:
* <code>
* if (Director::isLive()) Director::forceSSL();
* </code>
*
* If you don't want your entire site to be on SSL, you can pass an array of PCRE regular expression
* patterns for matching relative URLs. For example:
* <code>
* if (Director::isLive()) Director::forceSSL(array('/^admin/', '/^Security/'));
* </code>
*
* If you want certain parts of your site protected under a different domain, you can specify
* the domain as an argument:
* <code>
* if (Director::isLive()) Director::forceSSL(array('/^admin/', '/^Security/'), 'secure.mysite.com');
* </code>
*
* Note that the session data will be lost when moving from HTTP to HTTPS. It is your responsibility
* to ensure that this won't cause usability problems.
*
* CAUTION: This does not respect the site environment mode. You should check this
* as per the above examples using Director::isLive() or Director::isTest() for example.
*
* @param array $patterns Array of regex patterns to match URLs that should be HTTPS.
* @param string $secureDomain Secure domain to redirect to. Defaults to the current domain.
* Can include port number.
* @param HTTPRequest|null $request Request object to check
*/
public static function forceSSL($patterns = null, $secureDomain = null, ?HTTPRequest $request = null)
{
$handler = CanonicalURLMiddleware::singleton()->setForceSSL(true);
if ($patterns) {
$handler->setForceSSLPatterns($patterns);
}
if ($secureDomain) {
$handler->setForceSSLDomain($secureDomain);
}
$handler->throwRedirectIfNeeded($request);
}
* Force a redirect to a domain starting with "www."
*
* @param HTTPRequest $request
*/
public static function forceWWW(?HTTPRequest $request = null)
{
$handler = CanonicalURLMiddleware::singleton()->setForceWWW(true);
$handler->throwRedirectIfNeeded($request);
}
* Checks if the current HTTP-Request is an "Ajax-Request" by checking for a custom header set by
* jQuery or whether a manually set request-parameter 'ajax' is present.
*
* Note that if you plan to use this to alter your HTTP response on a cached page,
* you should add X-Requested-With to the Vary header.
*
* @param HTTPRequest $request
* @return bool
*/
public static function is_ajax(?HTTPRequest $request = null)
{
$request = Director::currentRequest($request);
if ($request) {
return $request->isAjax();
}
return (
isset($_REQUEST['ajax']) ||
(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest")
);
}
* Returns true if this script is being run from the command line rather than the web server.
*
* @return bool
* @deprecated 6.4.0 Use Environment::isCli() instead.
*/
public static function is_cli()
{
Deprecation::notice('6.4.0', 'Use ' . Environment::class . '::isCli() instead.');
return Environment::isCli();
}
* Can also be checked with {@link Director::isDev()}, {@link Director::isTest()}, and
* {@link Director::isLive()}.
*
* @return string
*/
public static function get_environment_type()
{
$kernel = Injector::inst()->get(Kernel::class);
return $kernel->getEnvironment();
}
* This function will return true if the site is in a live environment. For information about
* environment types, see {@link Director::set_environment_type()}.
*
* @return bool
*/
public static function isLive()
{
return Director::get_environment_type() === 'live';
}
* This function will return true if the site is in a development environment. For information about
* environment types, see {@link Director::set_environment_type()}.
*
* @return bool
*/
public static function isDev()
{
return Director::get_environment_type() === 'dev';
}
* This function will return true if the site is in a test environment. For information about
* environment types, see {@link Director::set_environment_type()}.
*
* @return bool
*/
public static function isTest()
{
return Director::get_environment_type() === 'test';
}
* Returns an array of strings of the method names of methods on the call that should be exposed
* as global variables in the templates.
*
* @return array
*/
public static function get_template_global_variables()
{
return [
'absoluteBaseURL',
'baseURL',
'isDev',
'isTest',
'isLive',
'is_ajax',
'isAjax' => 'is_ajax',
'BaseHref' => 'absoluteBaseURL',
];
}
* Helper to validate or check the current request object
*
* @param HTTPRequest $request
* @return HTTPRequest Request object if one is both current and valid
*/
protected static function currentRequest(?HTTPRequest $request = null)
{
if (!$request && Injector::inst()->has(HTTPRequest::class)) {
$request = Injector::inst()->get(HTTPRequest::class);
}
return $request;
}
}