class Director implements TemplateGlobalProvider (View source)

Director is responsible for processing URLs, and providing environment information.

The most important part of director is Director::handleRequest(), which is passed an HTTPRequest and will execute the appropriate controller.

Traits

Provides extensions to this object to integrate it with standard config API methods.

Allows an object to have extensions applied to it.

A class that can be instantiated or replaced via DI

Adds middleware support to an object.

Allows an object to declare a set of custom methods

Constants

BASE

Specifies this url is relative to the base.

ROOT

Specifies this url is relative to the site root.

REQUEST

specifies this url is relative to the current request.

Config options

extensions array

An array of extension names and parameters to be applied to this object upon construction.

from  Extensible
unextendable_classes array

Classes that cannot be extended

from  Extensible
rules array
alternate_base_folder string
alternate_public_dir bool|null

Override PUBLIC_DIR. Set to a non-null value to override.

default_base_url string

Base url to populate if cannot be determined otherwise.

Properties

protected static array $extra_methods

Custom method sources

from  CustomMethods
protected array $extra_method_registers

Name of methods to invoke by defineMethods for this instance

from  CustomMethods
protected static array $built_in_methods

Non-custom methods

from  CustomMethods
protected Extension[] $extension_instances from  Extensible
protected callable[][] $beforeExtendCallbacks

List of callbacks to call prior to extensions having extend called on them, each grouped by methodName.

from  Extensible
protected callable[][] $afterExtendCallbacks

List of callbacks to call after extensions having extend called on them, each grouped by methodName.

from  Extensible
protected HTTPMiddleware[] $middlewares from  HTTPMiddlewareAware

Methods

public static 
config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).

public
mixed
stat(string $name) deprecated

Get inherited config value

public
mixed
uninherited(string $name)

Gets the uninherited value for the given config option

public
$this
set_stat(string $name, mixed $value) deprecated

Update the config value for a given property

public
mixed
__call(string $method, array $arguments)

Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located

protected
defineMethods()

Adds any methods from Extension instances attached to this object.

protected
registerExtraMethodCallback(string $name, callable $callback)

Register an callback to invoke that defines extra methods

public
bool
hasMethod(string $method)

Return TRUE if a method exists on this object

protected
array
getExtraMethodConfig(string $method)

Get meta-data details on a named method

public
array
allMethodNames(bool $custom = false)

Return the names of all the methods available on this object

protected
array
findMethodsFromExtension(object $extension) deprecated

No description

protected
addMethodsFrom(string $property, string|int $index = null)

Add all the methods from an object property (which is an Extension) to this object.

protected
removeMethodsFrom(string $property, string|int $index = null)

Add all the methods from an object property (which is an Extension) to this object.

protected
addWrapperMethod(string $method, string $wrap)

Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)

protected
addCallbackMethod(string $method, callable $callback)

Add callback as a method.

protected
beforeExtending(string $method, callable $callback)

Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.

protected
afterExtending(string $method, callable $callback)

Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.

protected
constructExtensions() deprecated

No description

protected
defineExtensionMethods()

Adds any methods from Extension instances attached to this object.

public static 
bool
add_extension(string $classOrExtension, string $extension = null)

Add an extension to a specific class.

public static 
remove_extension(string $extension)

Remove an extension from a class.

public static 
array
get_extensions(string $class = null, bool $includeArgumentString = false)

No description

public static 
array|null
get_extra_config_sources(string $class = null)

Get extra config sources for this class

public static 
bool
has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)

Return TRUE if a class has a specified extension.

public
array
invokeWithExtensions(string $method, mixed $a1 = null, mixed $a2 = null, mixed $a3 = null, mixed $a4 = null, mixed $a5 = null, mixed $a6 = null, mixed $a7 = null)

Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array

public
array
extend(string $method, mixed $a1 = null, mixed $a2 = null, mixed $a3 = null, mixed $a4 = null, mixed $a5 = null, mixed $a6 = null, mixed $a7 = null)

Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed

public
Extension|null
getExtensionInstance(string $extension)

Get an extension instance attached to this object by name.

public
bool
hasExtension(string $extension)

Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.

public
getExtensionInstances()

Get all extension instances for this specific object instance.

public static 
create(mixed ...$args)

An implementation of the factory method, allows you to create an instance of a class

public static 
singleton(string $class = null)

Creates a class instance by the "singleton" design pattern.

public
getMiddlewares()

No description

public
$this
setMiddlewares(HTTPMiddleware[] $middlewares)

No description

public
$this
addMiddleware(HTTPMiddleware $middleware)

No description

protected
callMiddleware(HTTPRequest $request, callable $last)

Call middleware

public
__construct()

No description

public static 
test(string $url, array $postVars = [], array|Session $session = [], string $httpMethod = null, string $body = null, array $headers = [], array|Cookie_Backend $cookies = [], HTTPRequest $request = null)

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.

public static 
mixed
mockRequest(callable $callback, string $url, array $postVars = [], array|Session $session = [], string $httpMethod = null, string $body = null, array $headers = [], array|Cookie_Backend $cookies = [], HTTPRequest $request = null)

Mock a request, passing this to the given callback, before resetting.

public
handleRequest(HTTPRequest $request)

Process the given URL, creating the appropriate controller and executing it.

public static 
bool
isManifestFlushed() deprecated

Returns indication whether the manifest cache has been flushed in the beginning of the current request.

public static 
get_current_page()

Return the SiteTree object that is currently being viewed. If there is no SiteTree object to return, then this will return the current controller.

public static 
set_current_page(SiteTree $page)

Set the currently active SiteTree object that is being used to respond to the request.

public static 
string
absoluteURL(string $url, string $relativeParent = self::BASE)

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.

protected static 
string|null
parseHost(string $url)

Return only host (and optional port) part of a url

protected static 
bool
validateUserAndPass(string $url)

Validate user and password in URL, disallowing slashes

public static 
string
host(HTTPRequest $request = null)

A helper to determine the current hostname used to access the site.

public static 
int|null
port(HTTPRequest $request = null)

Return port used for the base URL.

public static 
string|null
hostName(HTTPRequest $request = null)

Return host name without port

public static 
bool|string
protocolAndHost(HTTPRequest $request = null)

Returns the domain part of the URL 'http://www.mysite.com'. Returns FALSE is this environment variable isn't set.

public static 
string
protocol(HTTPRequest $request = null)

Return the current protocol that the site is running under.

public static 
bool
is_https(HTTPRequest $request = null)

Return whether the site is running as under HTTPS.

public static 
string
baseURL()

Return the root-relative url for the baseurl

public static 
string
baseFolder()

Returns the root filesystem folder for the site. It will be automatically calculated unless it is overridden with setBaseFolder().

public static 
string
publicDir()

Check if using a separate public dir, and if so return this directory name.

public static 
string
publicFolder()

Gets the webroot of the project, which may be a subfolder of {baseFolder()}

public static 
string
makeRelative(string $url)

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.

public static 
bool
is_absolute(string $path)

Returns true if a given path is absolute. Works under both *nix and windows systems.

public static 
bool
is_root_relative_url(string $url)

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.

public static 
bool
is_absolute_url(string $url)

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.

public static 
bool
is_relative_url(string $url)

Checks if a given URL is relative (or root relative) by checking is_absolute_url().

public static 
bool
is_site_url(string $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 is_relative_url(), or if the host matches protocolAndHost().

public static 
string
getAbsFile(string $file)

Given a filesystem reference relative to the site root, return the full file-system path.

public static 
bool
fileExists($file)

Returns true if the given file exists. Filename should be relative to the site root.

public static 
string
absoluteBaseURL()

Returns the Absolute URL of the site root.

public static 
string
absoluteBaseURLWithAuth(HTTPRequest $request = null)

Returns the Absolute URL of the site root, embedding the current basic-auth credentials into the URL.

protected static 
force_redirect(string $destURL)

Skip any further processing and immediately respond with a redirect to the passed URL.

public static 
forceSSL(array $patterns = null, string $secureDomain = null, HTTPRequest $request = null)

Force the site to run on SSL.

public static 
forceWWW(HTTPRequest $request = null)

Force a redirect to a domain starting with "www."

public static 
bool
is_ajax(HTTPRequest $request = null)

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.

public static 
bool
is_cli()

Returns true if this script is being run from the command line rather than the web server.

public static 
string
get_environment_type()

Can also be checked with Director::isDev()}, {@link Director::isTest(), and Director::isLive().

public static 
bool
isLive()

This function will return true if the site is in a live environment. For information about environment types, see Director::set_environment_type().

public static 
bool
isDev()

This function will return true if the site is in a development environment. For information about environment types, see Director::set_environment_type().

public static 
bool
isTest()

This function will return true if the site is in a test environment. For information about environment types, see Director::set_environment_type().

public static 
array
get_template_global_variables()

Returns an array of strings of the method names of methods on the call that should be exposed as global variables in the templates.

protected static 
currentRequest(HTTPRequest $request = null)

Helper to validate or check the current request object

Details

static Config_ForClass config()

Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).

Return Value

Config_ForClass

mixed stat(string $name) deprecated

deprecated 5.0 Use ->config()->get() instead

Get inherited config value

Parameters

string $name

Return Value

mixed

mixed uninherited(string $name)

Gets the uninherited value for the given config option

Parameters

string $name

Return Value

mixed

$this set_stat(string $name, mixed $value) deprecated

deprecated 5.0 Use ->config()->set() instead

Update the config value for a given property

Parameters

string $name
mixed $value

Return Value

$this

mixed __call(string $method, array $arguments)

Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located

You can add extra methods to a class using Extensions}, {@link Object::createMethod() or Object::addWrapperMethod()

Parameters

string $method
array $arguments

Return Value

mixed

Exceptions

BadMethodCallException

protected defineMethods()

Adds any methods from Extension instances attached to this object.

All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().

protected registerExtraMethodCallback(string $name, callable $callback)

Register an callback to invoke that defines extra methods

Parameters

string $name
callable $callback

bool hasMethod(string $method)

Return TRUE if a method exists on this object

This should be used rather than PHP's inbuild method_exists() as it takes into account methods added via extensions

Parameters

string $method

Return Value

bool

protected array getExtraMethodConfig(string $method)

Get meta-data details on a named method

Parameters

string $method

Return Value

array

List of custom method details, if defined for this method

array allMethodNames(bool $custom = false)

Return the names of all the methods available on this object

Parameters

bool $custom

include methods added dynamically at runtime

Return Value

array

protected array findMethodsFromExtension(object $extension) deprecated

deprecated 4.13.0 Will be replaced by findMethodsFrom() in CMS 5

No description

Parameters

object $extension

Return Value

array

protected addMethodsFrom(string $property, string|int $index = null)

Add all the methods from an object property (which is an Extension) to this object.

Parameters

string $property

the property name

string|int $index

an index to use if the property is an array

Exceptions

InvalidArgumentException

protected removeMethodsFrom(string $property, string|int $index = null)

Add all the methods from an object property (which is an Extension) to this object.

Parameters

string $property

the property name

string|int $index

an index to use if the property is an array

protected addWrapperMethod(string $method, string $wrap)

Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)

Parameters

string $method

the method name to wrap

string $wrap

the method name to wrap to

protected addCallbackMethod(string $method, callable $callback)

Add callback as a method.

Parameters

string $method

Name of method

callable $callback

Callback to invoke. Note: $this is passed as first parameter to this callback and then $args as array

protected beforeExtending(string $method, callable $callback)

Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.

Parameters

string $method

The name of the method to hook into

callable $callback

The callback to execute

protected afterExtending(string $method, callable $callback)

Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.

Parameters

string $method

The name of the method to hook into

callable $callback

The callback to execute

protected constructExtensions() deprecated

deprecated 4.0.0:5.0.0 Extensions and methods are now lazy-loaded

No description

protected defineExtensionMethods()

Adds any methods from Extension instances attached to this object.

All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().

static bool add_extension(string $classOrExtension, string $extension = null)

Add an extension to a specific class.

The preferred method for adding extensions is through YAML config, since it avoids autoloading the class, and is easier to override in more specific configurations.

As an alternative, extensions can be added to a specific class directly in the Object::$extensions array. See SiteTree::$extensions for examples. Keep in mind that the extension will only be applied to new instances, not existing ones (including all instances created through singleton()).

Parameters

string $classOrExtension

Class that should be extended - has to be a subclass of Object

string $extension

Subclass of Extension with optional parameters as a string, e.g. "Versioned" or "Translatable('Param')"

Return Value

bool

Flag if the extension was added

See also

http://doc.silverstripe.org/framework/en/trunk/reference/dataextension

static remove_extension(string $extension)

Remove an extension from a class.

Note: This will not remove extensions from parent classes, and must be called directly on the class assigned the extension.

Keep in mind that this won't revert any datamodel additions of the extension at runtime, unless its used before the schema building kicks in (in your _config.php). Doesn't remove the extension from any Object instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through singleton() to avoid side-effects from stale extension information.

Add support for removing extensions with parameters

Parameters

string $extension

class name of an Extension subclass, without parameters

static array get_extensions(string $class = null, bool $includeArgumentString = false)

No description

Parameters

string $class

If omitted, will get extensions for the current class

bool $includeArgumentString

Include the argument string in the return array, FALSE would return array("Versioned"), TRUE returns array("Versioned('Stage','Live')").

Return Value

array

Numeric array of either DataExtension class names, or eval'ed class name strings with constructor arguments.

static array|null get_extra_config_sources(string $class = null)

Get extra config sources for this class

Parameters

string $class

Name of class. If left null will return for the current class

Return Value

array|null

static bool has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)

Return TRUE if a class has a specified extension.

This supports backwards-compatible format (static Object::has_extension($requiredExtension)) and new format ($object->has_extension($class, $requiredExtension))

Parameters

string $classOrExtension

Class to check extension for, or the extension name to check if the second argument is null.

string $requiredExtension

If the first argument is the parent class, this is the extension to check. If left null, the first parameter will be treated as the extension.

bool $strict

if the extension has to match the required extension and not be a subclass

Return Value

bool

Flag if the extension exists

array invokeWithExtensions(string $method, mixed $a1 = null, mixed $a2 = null, mixed $a3 = null, mixed $a4 = null, mixed $a5 = null, mixed $a6 = null, mixed $a7 = null)

Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array

Parameters

string $method

the method name to call

mixed $a1
mixed $a2
mixed $a3
mixed $a4
mixed $a5
mixed $a6
mixed $a7

Return Value

array

List of results with nulls filtered out

array extend(string $method, mixed $a1 = null, mixed $a2 = null, mixed $a3 = null, mixed $a4 = null, mixed $a5 = null, mixed $a6 = null, mixed $a7 = null)

Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed

Currently returns an array, with an index resulting every time the function is called. Only adds returns if they're not NULL, to avoid bogus results from methods just defined on the parent extension. This is important for permission-checks through extend, as they use min() to determine if any of the returns is FALSE. As min() doesn't do type checking, an included NULL return would fail the permission checks.

The extension methods are defined during __construct()} in {@link defineMethods().

Parameters

string $method

the name of the method to call on each extension

mixed $a1
mixed $a2
mixed $a3
mixed $a4
mixed $a5
mixed $a6
mixed $a7

Return Value

array

Extension|null getExtensionInstance(string $extension)

Get an extension instance attached to this object by name.

Parameters

string $extension

Return Value

Extension|null

bool hasExtension(string $extension)

Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.

Caution: Don't use singleton()->hasExtension() as it will give you inconsistent results based on when the singleton was first accessed.

Parameters

string $extension

Classname of an Extension subclass without parameters

Return Value

bool

Extension[] getExtensionInstances()

Get all extension instances for this specific object instance.

See get_extensions() to get all applied extension classes for this class (not the instance).

This method also provides lazy-population of the extension_instances property.

Return Value

Extension[]

Map of DataExtension instances, keyed by classname.

static Injectable create(mixed ...$args)

An implementation of the factory method, allows you to create an instance of a class

This method will defer class substitution to the Injector API, which can be customised via the Config API to declare substitution classes.

This can be called in one of two ways - either calling via the class directly, or calling on Object and passing the class name as the first parameter. The following are equivalent: $list = DataList::create(SiteTree::class); $list = SiteTree::get();

Parameters

mixed ...$args

Return Value

Injectable

static Injectable singleton(string $class = null)

Creates a class instance by the "singleton" design pattern.

It will always return the same instance for this class, which can be used for performance reasons and as a simple way to access instance methods which don't rely on instance data (e.g. the custom SilverStripe static handling).

Parameters

string $class

Optional classname to create, if the called class should not be used

Return Value

Injectable

The singleton instance

HTTPMiddleware[] getMiddlewares()

No description

Return Value

HTTPMiddleware[]

$this setMiddlewares(HTTPMiddleware[] $middlewares)

No description

Parameters

HTTPMiddleware[] $middlewares

Return Value

$this

$this addMiddleware(HTTPMiddleware $middleware)

No description

Parameters

HTTPMiddleware $middleware

Return Value

$this

protected HTTPResponse callMiddleware(HTTPRequest $request, callable $last)

Call middleware

Parameters

HTTPRequest $request

The request to pass to the middlewares and callback

callable $last

The callback to call after all middlewares

Return Value

HTTPResponse

__construct()

No description

static HTTPResponse test(string $url, array $postVars = [], array|Session $session = [], string $httpMethod = null, string $body = null, array $headers = [], array|Cookie_Backend $cookies = [], HTTPRequest $request = null)

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.

Parameters

string $url

The URL to visit.

array $postVars

The $_POST & $_FILES variables.

array|Session $session

The Session object representing the current session. By passing the same object to multiple calls of Director::test(), you can simulate a persisted session.

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.

string $body

The HTTP body.

array $headers

HTTP headers with key-value pairs.

array|Cookie_Backend $cookies

to populate $_COOKIE.

HTTPRequest $request

The {\SilverStripe\Control\SS_HTTP_Request} object generated as a part of this request.

Return Value

HTTPResponse

Exceptions

HTTPResponse_Exception

static mixed mockRequest(callable $callback, string $url, array $postVars = [], array|Session $session = [], string $httpMethod = null, string $body = null, array $headers = [], array|Cookie_Backend $cookies = [], HTTPRequest $request = null)

Mock a request, passing this to the given callback, before resetting.

Parameters

callable $callback

Action to pass the HTTPRequst object

string $url

The URL to build

array $postVars

The $_POST & $_FILES variables.

array|Session $session

The Session object representing the current session. By passing the same object to multiple calls of Director::test(), you can simulate a persisted session.

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.

string $body

The HTTP body.

array $headers

HTTP headers with key-value pairs.

array|Cookie_Backend $cookies

to populate $_COOKIE.

HTTPRequest $request

The {\SilverStripe\Control\SS_HTTP_Request} object generated as a part of this request.

Return Value

mixed

Result of callback

HTTPResponse handleRequest(HTTPRequest $request)

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.

Parameters

HTTPRequest $request

Return Value

HTTPResponse

Exceptions

HTTPResponse_Exception

static bool isManifestFlushed() deprecated

deprecated 4.12.0 Use Kernel::isFlushed instead

Returns indication whether the manifest cache has been flushed in the beginning of the current request.

That could mean the current active request has ?flush parameter. Another possibility is a race condition when the current request hits the server in between another request ?flush authorisation and a redirect to the actual flush.

Return Value

bool

static SiteTree|Controller get_current_page()

Return the SiteTree object that is currently being viewed. If there is no SiteTree object to return, then this will return the current controller.

Return Value

SiteTree|Controller

static set_current_page(SiteTree $page)

Set the currently active SiteTree object that is being used to respond to the request.

Parameters

SiteTree $page

static string absoluteURL(string $url, string $relativeParent = self::BASE)

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.

Parameters

string $url

The url or path to resolve to absolute url.

string $relativeParent

Disambiguation method to use for evaluating relative paths

Return Value

string

The absolute url

static protected string|null parseHost(string $url)

Return only host (and optional port) part of a url

Parameters

string $url

Return Value

string|null

Hostname, and optional port, or null if not a valid host

static protected bool validateUserAndPass(string $url)

Validate user and password in URL, disallowing slashes

Parameters

string $url

Return Value

bool

static string host(HTTPRequest $request = null)

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()

Parameters

HTTPRequest $request

Return Value

string

Host name, including port (if present)

static int|null port(HTTPRequest $request = null)

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.

Parameters

HTTPRequest $request

Return Value

int|null

static string|null hostName(HTTPRequest $request = null)

Return host name without port

Parameters

HTTPRequest $request

Return Value

string|null

static bool|string protocolAndHost(HTTPRequest $request = null)

Returns the domain part of the URL 'http://www.mysite.com'. Returns FALSE is this environment variable isn't set.

Parameters

HTTPRequest $request

Return Value

bool|string

static string protocol(HTTPRequest $request = null)

Return the current protocol that the site is running under.

Parameters

HTTPRequest $request

Return Value

string

static bool is_https(HTTPRequest $request = null)

Return whether the site is running as under HTTPS.

Parameters

HTTPRequest $request

Return Value

bool

static string baseURL()

Return the root-relative url for the baseurl

Return Value

string

Root-relative url with trailing slash.

static string baseFolder()

Returns the root filesystem folder for the site. It will be automatically calculated unless it is overridden with setBaseFolder().

Return Value

string

static string publicDir()

Check if using a separate public dir, and if so return this directory name.

This will be removed in 5.0 and fixed to 'public'

Return Value

string

static string publicFolder()

Gets the webroot of the project, which may be a subfolder of {baseFolder()}

Return Value

string

static string makeRelative(string $url)

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 Director::is_site_url() if making an untrusted url relative prior to calling this function.

Parameters

string $url

Accepts both a URL or a filesystem path.

Return Value

string

static bool is_absolute(string $path)

Returns true if a given path is absolute. Works under both *nix and windows systems.

Parameters

string $path

Return Value

bool

static bool is_root_relative_url(string $url)

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.

Parameters

string $url

Return Value

bool

static bool is_absolute_url(string $url)

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.

Parameters

string $url

Return Value

bool

static bool is_relative_url(string $url)

Checks if a given URL is relative (or root relative) by checking is_absolute_url().

Parameters

string $url

Return Value

bool

static bool is_site_url(string $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 is_relative_url(), or if the host matches 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.

Parameters

string $url

Return Value

bool

static string getAbsFile(string $file)

Given a filesystem reference relative to the site root, return the full file-system path.

Parameters

string $file

Return Value

string

static bool fileExists($file)

Returns true if the given file exists. Filename should be relative to the site root.

Parameters

$file

Return Value

bool

static string absoluteBaseURL()

Returns the Absolute URL of the site root.

Return Value

string

static string absoluteBaseURLWithAuth(HTTPRequest $request = null)

Returns the Absolute URL of the site root, embedding the current basic-auth credentials into the URL.

Parameters

HTTPRequest $request

Return Value

string

static protected force_redirect(string $destURL)

Skip any further processing and immediately respond with a redirect to the passed URL.

Parameters

string $destURL

Exceptions

HTTPResponse_Exception

static forceSSL(array $patterns = null, string $secureDomain = null, HTTPRequest $request = null)

Force the site to run on SSL.

To use, call from _config.php. For example:

if (Director::isLive()) Director::forceSSL();

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:

if (Director::isLive()) Director::forceSSL(array('/^admin/', '/^Security/'));

If you want certain parts of your site protected under a different domain, you can specify the domain as an argument:

if (Director::isLive()) Director::forceSSL(array('/^admin/', '/^Security/'), 'secure.mysite.com');

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.

Parameters

array $patterns

Array of regex patterns to match URLs that should be HTTPS.

string $secureDomain

Secure domain to redirect to. Defaults to the current domain. Can include port number.

HTTPRequest $request

Request object to check

static forceWWW(HTTPRequest $request = null)

Force a redirect to a domain starting with "www."

Parameters

HTTPRequest $request

static bool is_ajax(HTTPRequest $request = null)

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.

Parameters

HTTPRequest $request

Return Value

bool

static bool is_cli()

Returns true if this script is being run from the command line rather than the web server.

Return Value

bool

static string get_environment_type()

Can also be checked with Director::isDev()}, {@link Director::isTest(), and Director::isLive().

Return Value

string

static bool isLive()

This function will return true if the site is in a live environment. For information about environment types, see Director::set_environment_type().

Return Value

bool

static bool isDev()

This function will return true if the site is in a development environment. For information about environment types, see Director::set_environment_type().

Return Value

bool

static bool isTest()

This function will return true if the site is in a test environment. For information about environment types, see Director::set_environment_type().

Return Value

bool

static array get_template_global_variables()

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 Value

array

Returns an array of items. Each key => value pair is one of three forms:

  • template name (no key)
  • template name => method name
  • template name => [], where the array can contain these key => value pairs
    • "method" => method name
    • "casting" => casting class to use (i.e., Varchar, HTMLFragment, etc)

static protected HTTPRequest currentRequest(HTTPRequest $request = null)

Helper to validate or check the current request object

Parameters

HTTPRequest $request

Return Value

HTTPRequest

Request object if one is both current and valid