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 function setFailover(ViewableData $failover) { // Ensure cached methods from previous failover are removed if ($this->failover) { $this->removeMethodsFrom('failover'); } $this->failover = $failover; $this->defineMethods(); }
Set a failover object to attempt to get data from if it is not present on this object. @param ViewableData $failover
setFailover
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function getFailover() { return $this->failover; }
Get the current failover object if set @return ViewableData|null
getFailover
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function hasField($field) { return property_exists($this, $field) || $this->hasDynamicData($field); }
Check if a field exists on this object. This should be overloaded in child classes. @param string $field @return bool
hasField
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function getField($field) { if ($this->isAccessibleProperty($field)) { return $this->$field; } return $this->getDynamicData($field); }
Get the value of a field on this object. This should be overloaded in child classes. @param string $field @return mixed
getField
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function setField($field, $value) { $this->objCacheClear(); // prior to PHP 8.2 support ViewableData::setField() simply used `$this->field = $value;` // so the following logic essentially mimics this behaviour, though without the use // of now deprecated dynamic properties if ($this->isAccessibleProperty($field)) { $this->$field = $value; } return $this->setDynamicData($field, $value); }
Set a field on this object. This should be overloaded in child classes. @param string $field @param mixed $value @return $this
setField
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function customise($data) { if (is_array($data) && (empty($data) || ArrayLib::is_associative($data))) { $data = new ArrayData($data); } if ($data instanceof ViewableData) { return new ViewableData_Customised($this, $data); } throw new InvalidArgumentException( 'ViewableData->customise(): $data must be an associative array or a ViewableData instance' ); }
Merge some arbitrary data in with this object. This method returns a {@link ViewableData_Customised} instance with references to both this and the new custom data. Note that any fields you specify will take precedence over the fields on this object. @param array|ViewableData $data @return ViewableData_Customised
customise
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function exists() { return true; }
Return true if this object "exists" i.e. has a sensible value This method should be overridden in subclasses to provide more context about the classes state. For example, a {@link DataObject} class could return false when it is deleted from the database @return bool
exists
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function castingHelper($field) { // Get casting if it has been configured. // DB fields and PHP methods are all case insensitive so we normalise casing before checking. $specs = array_change_key_case(static::config()->get('casting'), CASE_LOWER); $fieldLower = strtolower($field); if (isset($specs[$fieldLower])) { return $specs[$fieldLower]; } // If no specific cast is declared, fall back to failover. // Note that if there is a failover, the default_cast will always // be drawn from this object instead of the top level object. $failover = $this->getFailover(); if ($failover) { $cast = $failover->castingHelper($field); if ($cast) { return $cast; } } // Fall back to default_cast $default = $this->config()->get('default_cast'); if (empty($default)) { throw new Exception("No default_cast"); } return $default; }
Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field on this object. This helper will be a subclass of DBField. @param string $field @return string Casting helper As a constructor pattern, and may include arguments. @throws Exception
castingHelper
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function castingClass($field) { Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it.'); // Strip arguments $spec = $this->castingHelper($field); return trim(strtok($spec ?? '', '(') ?? ''); }
Get the class name a field on this object will be casted to. @param string $field @return string @deprecated 5.4.0 Will be removed without equivalent functionality to replace it.
castingClass
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function escapeTypeForField($field) { Deprecation::noticeWithNoReplacment('5.4.0', 'Will be removed without equivalent functionality to replace it.'); $class = $this->castingClass($field) ?: $this->config()->get('default_cast'); /** @var DBField $type */ $type = Injector::inst()->get($class, true); return $type->config()->get('escape_type'); }
Return the string-format type for the given field. @param string $field @return string 'xml'|'raw' @deprecated 5.4.0 Will be removed without equivalent functionality to replace it.
escapeTypeForField
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function renderWith($template, $customFields = null) { if (!is_object($template)) { $template = SSViewer::create($template); } $data = $this->getCustomisedObj() ?: $this; if ($customFields instanceof ViewableData) { $data = $data->customise($customFields); } if ($template instanceof SSViewer) { return $template->process($data, is_array($customFields) ? $customFields : null); } throw new UnexpectedValueException( "ViewableData::renderWith(): unexpected " . get_class($template) . " object, expected an SSViewer instance" ); }
Render this object into the template, and get the result as a string. You can pass one of the following as the $template parameter: - a template name (e.g. Page) - an array of possible template names - the first valid one will be used - an SSViewer instance @param string|array|SSViewer $template the template to render into @param array $customFields fields to customise() the object with before rendering @return DBHTMLText
renderWith
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
protected function objCacheName($fieldName, $arguments) { Deprecation::noticeWithNoReplacment('5.4.0', 'Will be made private'); return $arguments ? $fieldName . ":" . var_export($arguments, true) : $fieldName; }
Generate the cache name for a field @param string $fieldName Name of field @param array $arguments List of optional arguments given @return string @deprecated 5.4.0 Will be made private
objCacheName
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
protected function objCacheGet($key) { if (isset($this->objCache[$key])) { return $this->objCache[$key]; } return null; }
Get a cached value from the field cache @param string $key Cache key @return mixed
objCacheGet
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
protected function objCacheSet($key, $value) { $this->objCache[$key] = $value; return $this; }
Store a value in the field cache @param string $key Cache key @param mixed $value @return $this
objCacheSet
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function obj($fieldName, $arguments = [], $cache = false, $cacheName = null) { if ($cacheName !== null) { Deprecation::noticeWithNoReplacment('5.4.0', 'The $cacheName parameter has been deprecated and will be removed'); } if (!$cacheName && $cache) { $cacheName = $this->objCacheName($fieldName, $arguments); } // Check pre-cached value $value = $cache ? $this->objCacheGet($cacheName) : null; if ($value !== null) { return $value; } // Load value from record if ($this->hasMethod($fieldName)) { $value = call_user_func_array([$this, $fieldName], $arguments ?: []); } else { $value = $this->$fieldName; } // Cast object if (!is_object($value)) { // Force cast $castingHelper = $this->castingHelper($fieldName); $valueObject = Injector::inst()->create($castingHelper, $fieldName); $valueObject->setValue($value, $this); $value = $valueObject; } // Record in cache if ($cache) { $this->objCacheSet($cacheName, $value); } return $value; }
Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified. @param string $fieldName @param array $arguments @param bool $cache Cache this object @param string $cacheName a custom cache name @return Object|DBField
obj
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function cachedCall($fieldName, $arguments = [], $identifier = null) { Deprecation::notice('5.4.0', 'Use obj() instead'); return $this->obj($fieldName, $arguments, true, $identifier); }
A simple wrapper around {@link ViewableData::obj()} that automatically caches the result so it can be used again without re-running the method. @param string $fieldName @param array $arguments @param string $identifier an optional custom cache identifier @return Object|DBField @deprecated 5.4.0 use obj() instead
cachedCall
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function hasValue($field, $arguments = [], $cache = true) { $result = $this->obj($field, $arguments, $cache); return $result->exists(); }
Checks if a given method/field has a valid value. If the result is an object, this will return the result of the exists method, otherwise will check if the result is not just an empty paragraph tag. @param string $field @param array $arguments @param bool $cache @return bool
hasValue
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function XML_val($field, $arguments = [], $cache = false) { Deprecation::noticeWithNoReplacment('5.4.0'); $result = $this->obj($field, $arguments, $cache); // Might contain additional formatting over ->XML(). E.g. parse shortcodes, nl2br() return $result->forTemplate(); }
Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template. @param string $field @param array $arguments @param bool $cache @return string @deprecated 5.4.0 Will be removed without equivalent functionality to replace it
XML_val
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function getViewerTemplates($suffix = '') { return SSViewer::get_templates_by_class(static::class, $suffix, ViewableData::class); }
Find appropriate templates for SSViewer to use to render this object @param string $suffix @return array
getViewerTemplates
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function Me() { return $this; }
When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself. @return ViewableData
Me
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function CSSClasses($stopAtClass = ViewableData::class) { $classes = []; $classAncestry = array_reverse(ClassInfo::ancestry(static::class) ?? []); $stopClasses = ClassInfo::ancestry($stopAtClass); foreach ($classAncestry as $class) { if (in_array($class, $stopClasses ?? [])) { break; } $classes[] = $class; } // optionally add template identifier if (isset($this->template) && !in_array($this->template, $classes ?? [])) { $classes[] = $this->template; } // Strip out namespaces $classes = preg_replace('#.*\\\\#', '', $classes ?? ''); return Convert::raw2att(implode(' ', $classes)); }
Get part of the current classes ancestry to be used as a CSS class. This method returns an escaped string of CSS classes representing the current classes ancestry until it hits a stop point - e.g. "Page DataObject ViewableData". @param string $stopAtClass the class to stop at (default: ViewableData) @return string @uses ClassInfo
CSSClasses
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function Debug() { return new ViewableData_Debugger($this); }
Return debug information about this object that can be rendered into a template @return ViewableData_Debugger
Debug
php
silverstripe/silverstripe-framework
src/View/ViewableData.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/ViewableData.php
BSD-3-Clause
public function toASCII($source) { if (function_exists('iconv') && $this->config()->use_iconv) { return $this->useIconv($source); } else { return $this->useStrTr($source); } }
Convert the given utf8 string to a safe ASCII source @param string $source @return string
toASCII
php
silverstripe/silverstripe-framework
src/View/Parsers/Transliterator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/Transliterator.php
BSD-3-Clause
public function register($shortcode, $callback) { if (is_callable($callback)) { $this->shortcodes[$shortcode] = $callback; } else { throw new InvalidArgumentException("Callback is not callable"); } return $this; }
Register a shortcode, and attach it to a PHP callback. The callback for a shortcode will have the following arguments passed to it: - Any parameters attached to the shortcode as an associative array (keys are lower-case). - Any content enclosed within the shortcode (if it is an enclosing shortcode). Note that any content within this will not have been parsed, and can optionally be fed back into the parser. - The {@link ShortcodeParser} instance used to parse the content. - The shortcode tag name that was matched within the parsed content. - An associative array of extra information about the shortcode being parsed. @param string $shortcode The shortcode tag to map to the callback - normally in lowercase_underscore format. @param callable $callback The callback to replace the shortcode with. @return $this
register
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
public function registered($shortcode) { return array_key_exists($shortcode, $this->shortcodes ?? []); }
Check if a shortcode has been registered. @param string $shortcode @return bool
registered
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
public function unregister($shortcode) { if ($this->registered($shortcode)) { unset($this->shortcodes[$shortcode]); } }
Remove a specific registered shortcode. @param string $shortcode
unregister
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
public function getRegisteredShortcodes() { return $this->shortcodes; }
Get an array containing information about registered shortcodes @return array
getRegisteredShortcodes
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
public function clear() { $this->shortcodes = []; }
Remove all registered shortcodes.
clear
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
public function callShortcode($tag, $attributes, $content, $extra = []) { if (!$tag || !isset($this->shortcodes[$tag])) { return false; } return call_user_func($this->shortcodes[$tag], $attributes, $content, $this, $tag, $extra); }
Call a shortcode and return its replacement text Returns false if the shortcode isn't registered @param string $tag @param array $attributes @param string $content @param array $extra @return mixed
callShortcode
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
public function getShortcodeReplacementText($tag, $extra = [], $isHTMLAllowed = true) { $content = $this->callShortcode($tag['open'], $tag['attrs'], $tag['content'], $extra); // Missing tag if ($content === false) { if (ShortcodeParser::$error_behavior == ShortcodeParser::ERROR) { throw new \InvalidArgumentException('Unknown shortcode tag ' . $tag['open']); } elseif (ShortcodeParser::$error_behavior == ShortcodeParser::WARN && $isHTMLAllowed) { $content = '<strong class="warning">' . $tag['text'] . '</strong>'; } elseif (ShortcodeParser::$error_behavior == ShortcodeParser::STRIP) { return ''; } else { return $tag['text']; } } return $content; }
Return the text to insert in place of a shoprtcode. Behaviour in the case of missing shortcodes depends on the setting of ShortcodeParser::$error_behavior. @param array $tag A map containing the the following keys: - 'open': The name of the tag - 'attrs': Attributes of the tag - 'content': Content of the tag @param array $extra Extra-meta data @param boolean $isHTMLAllowed A boolean indicating whether it's okay to insert HTML tags into the result @return bool|mixed|string
getShortcodeReplacementText
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
protected function replaceTagsWithText($content, $tags, $generator) { // The string with tags replaced with markers $str = ''; // The start index of the next tag, remembered as we step backwards through the list $li = null; $i = count($tags ?? []); while ($i--) { if ($li === null) { $tail = substr($content ?? '', $tags[$i]['e'] ?? 0); } else { $tail = substr($content ?? '', $tags[$i]['e'] ?? 0, $li - $tags[$i]['e']); } if ($tags[$i]['escaped']) { $str = substr($content ?? '', $tags[$i]['s']+1, $tags[$i]['e'] - $tags[$i]['s'] - 2) . $tail . $str; } else { $str = $generator($i, $tags[$i]) . $tail . $str; } $li = $tags[$i]['s']; } return substr($content ?? '', 0, $tags[0]['s']) . $str; }
Replaces the shortcode tags extracted by extractTags with HTML element "markers", so that we can parse the resulting string as HTML and easily mutate the shortcodes in the DOM @param string $content The HTML string with [tag] style shortcodes embedded @param array $tags The tags extracted by extractTags @param callable $generator @return string The HTML string with [tag] style shortcodes replaced by markers
replaceTagsWithText
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
protected function replaceMarkerWithContent($node, $tag) { $content = $this->getShortcodeReplacementText($tag); if ($content) { $parsed = HTMLValue::create($content); $body = $parsed->getBody(); if ($body) { $this->insertListAfter($body->childNodes, $node); } } $this->removeNode($node); }
Given a node with represents a shortcode marker and some information about the shortcode, call the shortcode handler & replace the marker with the actual content @param DOMElement $node @param array $tag
replaceMarkerWithContent
php
silverstripe/silverstripe-framework
src/View/Parsers/ShortcodeParser.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/ShortcodeParser.php
BSD-3-Clause
public function getDocument() { if (!$this->valid) { return false; } elseif ($this->document) { return $this->document; } else { $this->document = new DOMDocument('1.0', 'UTF-8'); $this->document->strictErrorChecking = false; $this->document->formatOutput = false; return $this->document; } }
Get the DOMDocument for the passed content @return DOMDocument | false - Return false if HTML not valid, the DOMDocument instance otherwise
getDocument
php
silverstripe/silverstripe-framework
src/View/Parsers/HTMLValue.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/HTMLValue.php
BSD-3-Clause
public function isValid() { return $this->valid; }
Is this HTMLValue in an errored state? @return bool
isValid
php
silverstripe/silverstripe-framework
src/View/Parsers/HTMLValue.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/HTMLValue.php
BSD-3-Clause
public function __call($method, $arguments) { $doc = $this->getDocument(); if ($doc && method_exists($doc, $method ?? '')) { return call_user_func_array([$doc, $method], $arguments ?? []); } else { return parent::__call($method, $arguments); } }
Pass through any missed method calls to DOMDocument (if they exist) so that HTMLValue can be treated mostly like an instance of DOMDocument @param string $method @param array $arguments @return mixed
__call
php
silverstripe/silverstripe-framework
src/View/Parsers/HTMLValue.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/HTMLValue.php
BSD-3-Clause
public function getBody() { $doc = $this->getDocument(); if (!$doc) { return false; } $body = $doc->getElementsByTagName('body'); if (!$body->length) { return false; } return $body->item(0); }
Get the body element, or false if there isn't one (we haven't loaded any content or this instance is in an invalid state)
getBody
php
silverstripe/silverstripe-framework
src/View/Parsers/HTMLValue.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/HTMLValue.php
BSD-3-Clause
public function query($query) { $xp = new DOMXPath($this->getDocument()); return $xp->query($query); }
Make an xpath query against this HTML @param string $query The xpath query string @return DOMNodeList
query
php
silverstripe/silverstripe-framework
src/View/Parsers/HTMLValue.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Parsers/HTMLValue.php
BSD-3-Clause
public static function get_shortcodes() { return ['embed']; }
Gets the list of shortcodes provided by this handler @return mixed
get_shortcodes
php
silverstripe/silverstripe-framework
src/View/Shortcodes/EmbedShortcodeProvider.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Shortcodes/EmbedShortcodeProvider.php
BSD-3-Clause
public static function handle_shortcode($arguments, $content, $parser, $shortcode, $extra = []) { // Get service URL if (!empty($content)) { $serviceURL = $content; } elseif (!empty($arguments['url'])) { $serviceURL = $arguments['url']; } else { return ''; } $class = $arguments['class'] ?? ''; $width = $arguments['width'] ?? ''; $height = $arguments['height'] ?? ''; // Try to use cached result $cache = static::getCache(); $key = static::deriveCacheKey($serviceURL, $class, $width, $height); try { if ($cache->has($key)) { return $cache->get($key); } } catch (InvalidArgumentException $e) { } // See https://github.com/oscarotero/Embed#example-with-all-options for service arguments $serviceArguments = []; if (!empty($arguments['width'])) { $serviceArguments['min_image_width'] = $arguments['width']; } if (!empty($arguments['height'])) { $serviceArguments['min_image_height'] = $arguments['height']; } /** @var EmbedContainer $embeddable */ $embeddable = Injector::inst()->create(Embeddable::class, $serviceURL); // Only EmbedContainer is currently supported if (!($embeddable instanceof EmbedContainer)) { throw new \RuntimeException('Emeddable must extend EmbedContainer'); } if (!empty($serviceArguments)) { $embeddable->setOptions(array_merge($serviceArguments, (array) $embeddable->getOptions())); } // Process embed try { // this will trigger a request/response which will then be cached within $embeddable $embeddable->getExtractor(); } catch (NetworkException | RequestException $e) { $message = (Director::isDev()) ? $e->getMessage() : _t(__CLASS__ . '.INVALID_URL', 'There was a problem loading the media.'); $attr = [ 'class' => 'ss-media-exception embed' ]; $result = HTML::createTag( 'div', $attr, HTML::createTag('p', [], $message) ); return $result; } // Convert embed object into HTML $html = static::embeddableToHtml($embeddable, $arguments); // Fallback to link to service if (!$html) { $result = static::linkEmbed($arguments, $serviceURL, $serviceURL); } // Cache result if ($html) { try { $cache->set($key, $html); } catch (InvalidArgumentException $e) { } } return $html; }
Embed shortcode parser from Oembed. This is a temporary workaround. Oembed class has been replaced with the Embed external service. @param array $arguments @param string $content @param ShortcodeParser $parser @param string $shortcode @param array $extra @return string
handle_shortcode
php
silverstripe/silverstripe-framework
src/View/Shortcodes/EmbedShortcodeProvider.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Shortcodes/EmbedShortcodeProvider.php
BSD-3-Clause
private static function sandboxHtml(string $html, array $arguments) { // Do not sandbox if the domain is excluded if (EmbedShortcodeProvider::domainIsExcludedFromSandboxing()) { return $html; } // Do not sandbox if the html is already an iframe if (preg_match('#^<iframe[^>]*>#', $html) && preg_match('#</iframe\s*>$#', $html)) { // Prevent things like <iframe><script>alert(1)</script></iframe> // and <iframe></iframe><unsafe stuff here/><iframe></iframe> // If there's more than 2 HTML tags then sandbox it if (substr_count($html, '<') <= 2) { return $html; } } // Sandbox the html in an iframe $style = ''; if (!empty($arguments['width'])) { $style .= 'width:' . intval($arguments['width']) . 'px;'; } if (!empty($arguments['height'])) { $style .= 'height:' . intval($arguments['height']) . 'px;'; } $attrs = array_merge([ 'frameborder' => '0', ], static::config()->get('sandboxed_iframe_attributes')); $attrs['src'] = 'data:text/html;charset=utf-8,' . rawurlencode($html); if (array_key_exists('style', $attrs)) { $attrs['style'] .= ";$style"; $attrs['style'] = ltrim($attrs['style'], ';'); } else { $attrs['style'] = $style; } $html = HTML::createTag('iframe', $attrs); return $html; }
Wrap potentially dangerous html embeds in an iframe to sandbox them Potentially dangerous html embeds would could be those that contain <script> or <style> tags or html that contains an on*= attribute
sandboxHtml
php
silverstripe/silverstripe-framework
src/View/Shortcodes/EmbedShortcodeProvider.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/View/Shortcodes/EmbedShortcodeProvider.php
BSD-3-Clause
protected function getFormFields() { $fields = FieldList::create(); $controller = $this->getController(); $backURL = $controller->getBackURL() ?: $controller->getReturnReferer(); // Protect against infinite redirection back to the logout URL after logging out if (!$backURL || Director::makeRelative($backURL) === $controller->getRequest()->getURL()) { $backURL = Director::baseURL(); } $fields->push(HiddenField::create('BackURL', 'BackURL', $backURL)); return $fields; }
Build the FieldList for the logout form @return FieldList
getFormFields
php
silverstripe/silverstripe-framework
src/Security/LogoutForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/LogoutForm.php
BSD-3-Clause
protected function getFormActions() { $actions = FieldList::create( FormAction::create('doLogout', _t('SilverStripe\\Security\\Member.BUTTONLOGOUT', "Log out")) ); return $actions; }
Build default logout form action FieldList @return FieldList
getFormActions
php
silverstripe/silverstripe-framework
src/Security/LogoutForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/LogoutForm.php
BSD-3-Clause
public function setEmail($email) { // Store hashed email only $this->EmailHashed = sha1($email ?? ''); return $this; }
Set email used for this attempt @param string $email @return $this
setEmail
php
silverstripe/silverstripe-framework
src/Security/LoginAttempt.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/LoginAttempt.php
BSD-3-Clause
public static function getByEmail($email) { return static::get()->filterAny([ 'EmailHashed' => sha1($email ?? ''), ]); }
Get all login attempts for the given email address @param string $email @return DataList<LoginAttempt>
getByEmail
php
silverstripe/silverstripe-framework
src/Security/LoginAttempt.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/LoginAttempt.php
BSD-3-Clause
public static function inst() { if (!SecurityToken::$inst) { SecurityToken::$inst = new SecurityToken(); } return SecurityToken::$inst; }
Gets a global token (or creates one if it doesnt exist already). @return SecurityToken
inst
php
silverstripe/silverstripe-framework
src/Security/SecurityToken.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/SecurityToken.php
BSD-3-Clause
public static function disable() { SecurityToken::$enabled = false; SecurityToken::$inst = new NullSecurityToken(); }
Globally disable the token (override with {@link NullSecurityToken}) implementation. Note: Does not apply for
disable
php
silverstripe/silverstripe-framework
src/Security/SecurityToken.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/SecurityToken.php
BSD-3-Clause
public static function getSecurityID() { $token = SecurityToken::inst(); return $token->getValue(); }
Returns the value of an the global SecurityToken in the current session @return int
getSecurityID
php
silverstripe/silverstripe-framework
src/Security/SecurityToken.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/SecurityToken.php
BSD-3-Clause
public function reset() { $this->setValue($this->generate()); }
Reset the token to a new value.
reset
php
silverstripe/silverstripe-framework
src/Security/SecurityToken.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/SecurityToken.php
BSD-3-Clause
protected function getRequestToken($request) { $name = $this->getName(); $header = 'X-' . ucwords(strtolower($name ?? '')); if ($token = $request->getHeader($header)) { return $token; } // Get from request var return $request->requestVar($name); }
Get security token from request @param HTTPRequest $request @return string
getRequestToken
php
silverstripe/silverstripe-framework
src/Security/SecurityToken.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/SecurityToken.php
BSD-3-Clause
public function foreignIDFilter($id = null) { if ($id === null) { $id = $this->getForeignID(); } // Find directly applied groups $manyManyFilter = parent::foreignIDFilter($id); $query = SQLSelect::create('"Group_Members"."GroupID"', '"Group_Members"', $manyManyFilter); $groupIDs = $query->execute()->column(); // Get all ancestors, iteratively merging these into the master set $allGroupIDs = []; while ($groupIDs) { $allGroupIDs = array_merge($allGroupIDs, $groupIDs); $groupIDs = DataObject::get(Group::class)->byIDs($groupIDs)->column("ParentID"); $groupIDs = array_filter($groupIDs ?? []); } // Add a filter to this DataList if (!empty($allGroupIDs)) { $in = $this->prepareForeignIDsForWhereInClause($allGroupIDs); $vals = str_contains($in, '?') ? $allGroupIDs : []; return ["\"Group\".\"ID\" IN ($in)" => $vals]; } return ['"Group"."ID"' => 0]; }
Link this group set to a specific member. Recursively selects all groups applied to this member, as well as any parent groups of any applied groups @param array|int|string|null $id (optional) An ID or an array of IDs - if not provided, will use the current ids as per getForeignID @return array Condition In array(SQL => parameters format)
foreignIDFilter
php
silverstripe/silverstripe-framework
src/Security/Member_GroupSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member_GroupSet.php
BSD-3-Clause
protected function canAddGroups($itemIDs) { if (empty($itemIDs)) { return true; } $member = $this->getMember(); return empty($member) || $member->onChangeGroups($itemIDs); }
Determine if the following groups IDs can be added @param array $itemIDs @return boolean
canAddGroups
php
silverstripe/silverstripe-framework
src/Security/Member_GroupSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member_GroupSet.php
BSD-3-Clause
protected function getMember() { $id = $this->getForeignID(); if ($id) { return DataObject::get_by_id(Member::class, $id); } }
Get foreign member record for this relation @return Member
getMember
php
silverstripe/silverstripe-framework
src/Security/Member_GroupSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Member_GroupSet.php
BSD-3-Clause
public function Members($filter = '') { // First get direct members as a base result $result = $this->DirectMembers(); // Unsaved group cannot have child groups because its ID is still 0. if (!$this->exists()) { return $result; } // Remove the default foreign key filter in prep for re-applying a filter containing all children groups. // Filters are conjunctive in DataQuery by default, so this filter would otherwise overrule any less specific // ones. if (!($result instanceof UnsavedRelationList)) { $result = $result->alterDataQuery(function ($query) { /** @var DataQuery $query */ $query->removeFilterOn('Group_Members'); }); } // Now set all children groups as a new foreign key $familyIDs = $this->collateFamilyIDs(); $result = $result->forForeignID($familyIDs); return $result->where($filter); }
Get many-many relation to {@link Member}, including all members which are "inherited" from children groups of this record. See {@link DirectMembers()} for retrieving members without any inheritance. @param string $filter @return ManyManyList<Member>
Members
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function DirectMembers() { return $this->getManyManyComponents('Members'); }
Return only the members directly added to this group @return ManyManyList<Member>
DirectMembers
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function collateFamilyIDs() { if (!$this->exists()) { throw new \InvalidArgumentException("Cannot call collateFamilyIDs on unsaved Group."); } $familyIDs = []; $chunkToAdd = [$this->ID]; while ($chunkToAdd) { $familyIDs = array_merge($familyIDs, $chunkToAdd); // Get the children of *all* the groups identified in the previous chunk. // This minimises the number of SQL queries necessary $chunkToAdd = Group::get()->filter("ParentID", $chunkToAdd)->column('ID'); } return $familyIDs; }
Return a set of this record's "family" of IDs - the IDs of this record and all its descendants. @return array
collateFamilyIDs
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function collateAncestorIDs() { $parent = $this; $items = []; while ($parent instanceof Group) { $items[] = $parent->ID; $parent = $parent->getParent(); } return $items; }
Returns an array of the IDs of this group and all its parents @return array
collateAncestorIDs
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function inGroup($group) { return in_array($this->identifierToGroupID($group), $this->collateAncestorIDs() ?? []); }
Check if the group is a child of the given group or any parent groups @param string|int|Group $group Group instance, Group Code or ID @return bool Returns TRUE if the Group is a child of the given group, otherwise FALSE
inGroup
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
protected function identifierToGroupID($groupID) { if (is_numeric($groupID) && Group::get()->byID($groupID)) { return $groupID; } elseif (is_string($groupID) && $groupByCode = Group::get()->filter(['Code' => $groupID])->first()) { return $groupByCode->ID; } elseif ($groupID instanceof Group && $groupID->exists()) { return $groupID->ID; } return null; }
Turn a string|int|Group into a GroupID @param string|int|Group $groupID Group instance, Group Code or ID @return int|null the Group ID or NULL if not found
identifierToGroupID
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function stageChildren() { return Group::get() ->filter("ParentID", $this->ID) ->exclude("ID", $this->ID) ->sort('"Sort"'); }
Override this so groups are ordered in the CMS
stageChildren
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function setCode($val) { $this->setField('Code', Convert::raw2url($val)); }
Overloaded to ensure the code is always descent. @param string $val
setCode
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function canView($member = null) { if (!$member) { $member = Security::getCurrentUser(); } // check for extensions, we do this first as they can overrule everything $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } // user needs access to CMS_ACCESS_SecurityAdmin if (Permission::checkMember($member, "CMS_ACCESS_SecurityAdmin")) { return true; } // if user can grant access for specific groups, they need to be able to see the groups if (Permission::checkMember($member, "SITETREE_GRANT_ACCESS")) { return true; } return false; }
Checks for permission-code CMS_ACCESS_SecurityAdmin. @param Member $member @return boolean
canView
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function AllChildrenIncludingDeleted() { $children = parent::AllChildrenIncludingDeleted(); $filteredChildren = new ArrayList(); if ($children) { foreach ($children as $child) { /** @var DataObject $child */ if ($child->canView()) { $filteredChildren->push($child); } } } return $filteredChildren; }
Returns all of the children for the CMS Tree. Filters to only those groups that the current user can edit @return ArrayList<DataObject>
AllChildrenIncludingDeleted
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function requireDefaultRecords() { parent::requireDefaultRecords(); // Add default author group if no other group exists $allGroups = Group::get(); if (!$allGroups->count()) { $authorGroup = new Group(); $authorGroup->Code = 'content-authors'; $authorGroup->Title = _t(__CLASS__ . '.DefaultGroupTitleContentAuthors', 'Content Authors'); $authorGroup->Sort = 1; $authorGroup->write(); Permission::grant($authorGroup->ID, 'CMS_ACCESS_CMSMain'); Permission::grant($authorGroup->ID, 'CMS_ACCESS_AssetAdmin'); Permission::grant($authorGroup->ID, 'CMS_ACCESS_ReportAdmin'); Permission::grant($authorGroup->ID, 'SITETREE_REORGANISE'); } // Add default admin group if none with permission code ADMIN exists $adminGroups = Permission::get_groups_by_permission('ADMIN'); if (!$adminGroups->count()) { $adminGroup = new Group(); $adminGroup->Code = 'administrators'; $adminGroup->Title = _t(__CLASS__ . '.DefaultGroupTitleAdministrators', 'Administrators'); $adminGroup->Sort = 0; $adminGroup->write(); Permission::grant($adminGroup->ID, 'ADMIN'); } // Members are populated through Member->requireDefaultRecords() }
Add default records to database. This function is called whenever the database is built, after the database tables have all been created.
requireDefaultRecords
php
silverstripe/silverstripe-framework
src/Security/Group.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Group.php
BSD-3-Clause
public function getTestNames() { if ($this->testNames !== null) { return $this->testNames; } return array_keys(array_filter($this->getTests() ?? [])); }
Gets the list of tests to use for this validator @return string[]
getTestNames
php
silverstripe/silverstripe-framework
src/Security/PasswordValidator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/PasswordValidator.php
BSD-3-Clause
public function setTestNames($testNames) { $this->testNames = $testNames; return $this; }
Set list of tests to use for this validator @param string[] $testNames @return $this
setTestNames
php
silverstripe/silverstripe-framework
src/Security/PasswordValidator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/PasswordValidator.php
BSD-3-Clause
protected function getHandlers() { return $this->handlers; }
This method currently uses a fallback as loading the handlers via YML has proven unstable @return AuthenticationHandler[]
getHandlers
php
silverstripe/silverstripe-framework
src/Security/RequestAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RequestAuthenticationHandler.php
BSD-3-Clause
public function setHandlers(array $handlers) { $this->handlers = $handlers; return $this; }
Set an associative array of handlers @param AuthenticationHandler[] $handlers @return $this
setHandlers
php
silverstripe/silverstripe-framework
src/Security/RequestAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RequestAuthenticationHandler.php
BSD-3-Clause
public static function setRedirect(Session $session, $url) { $session->set(static::SESSION_KEY_REDIRECT, $url); }
Preserve the password change URL in the session That URL is to be redirected to to force users change expired passwords @param Session $session Session where we persist the redirect URL @param string $url change password form address
setRedirect
php
silverstripe/silverstripe-framework
src/Security/PasswordExpirationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/PasswordExpirationMiddleware.php
BSD-3-Clause
public static function allowCurrentRequest(Session $session) { $session->set(static::SESSION_KEY_ALLOW_CURRENT_REQUEST, true); }
Allow the current request to be finished without password expiration check @param Session $session Session where we persist the redirect URL
allowCurrentRequest
php
silverstripe/silverstripe-framework
src/Security/PasswordExpirationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/PasswordExpirationMiddleware.php
BSD-3-Clause
public static function log($member) { $record = new MemberPassword(); $record->MemberID = $member->ID; $record->Password = $member->Password; $record->PasswordEncryption = $member->PasswordEncryption; $record->Salt = $member->Salt; $record->write(); }
Log a password change from the given member. Call MemberPassword::log($this) from within Member whenever the password is changed. @param Member $member
log
php
silverstripe/silverstripe-framework
src/Security/MemberPassword.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberPassword.php
BSD-3-Clause
public function checkPassword($password) { $encryptor = PasswordEncryptor::create_for_algorithm($this->PasswordEncryption); return $encryptor->check($this->Password ?? '', $password, $this->Salt, $this->Member()); }
Check if the given password is the same as the one stored in this record. @param string $password Cleartext password @return bool
checkPassword
php
silverstripe/silverstripe-framework
src/Security/MemberPassword.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberPassword.php
BSD-3-Clause
public function setAuthenticatorClass($class) { $this->authenticatorClass = $class; $fields = $this->Fields(); if (!$fields) { return $this; } $authenticatorField = $fields->dataFieldByName('AuthenticationMethod'); if ($authenticatorField) { $authenticatorField->setValue($class); } return $this; }
Set the authenticator class name to use @param string $class @return $this
setAuthenticatorClass
php
silverstripe/silverstripe-framework
src/Security/LoginForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/LoginForm.php
BSD-3-Clause
public function getAuthenticatorClass() { return $this->authenticatorClass; }
Returns the authenticator class name to use @return string
getAuthenticatorClass
php
silverstripe/silverstripe-framework
src/Security/LoginForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/LoginForm.php
BSD-3-Clause
protected function checkMatchingURL(HTTPRequest $request) { // Null if no permissions enabled $patterns = $this->getURLPatterns(); if (!$patterns) { return null; } // Filter redirect based on url $relativeURL = $request->getURL(true); foreach ($patterns as $pattern => $result) { if (preg_match($pattern ?? '', $relativeURL ?? '')) { return $result; } } // No patterns match return null; }
Check if global basic auth is enabled for the given request @param HTTPRequest $request @return bool|string|array|null boolean value if enabled/disabled explicitly for this request, or null if should fall back to config value. Can also provide an explicit string / array of permission codes to require for this requset.
checkMatchingURL
php
silverstripe/silverstripe-framework
src/Security/BasicAuthMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/BasicAuthMiddleware.php
BSD-3-Clause
public function randomToken($algorithm = 'whirlpool') { return hash($algorithm ?? '', random_bytes(64)); }
Generates a random token that can be used for session IDs, CSRF tokens etc., based on hash algorithms. If you are using it as a password equivalent (e.g. autologin token) do NOT store it in the database as a plain text but encrypt it with Member::encryptWithUserSettings. @param string $algorithm Any identifier listed in hash_algos() (Default: whirlpool) @return string Returned length will depend on the used $algorithm @throws Exception When there is no valid source of CSPRNG
randomToken
php
silverstripe/silverstripe-framework
src/Security/RandomGenerator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RandomGenerator.php
BSD-3-Clause
public static function check($code, $arg = "any", $member = null, $strict = true) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } return Permission::checkMember($member, $code, $arg, $strict); }
Check that the current member has the given permission. @param string|array $code Code of the permission to check (case-sensitive) @param string $arg Optional argument (e.g. a permissions for a specific page) @param int|Member $member Optional member instance or ID. If set to NULL, the permssion will be checked for the current user @param bool $strict Use "strict" checking (which means a permission will be granted if the key does not exist at all)? @return int|bool The ID of the permission record if the permission exists; FALSE otherwise. If "strict" checking is disabled, TRUE will be returned if the permission does not exist at all.
check
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function reset() { Permission::$cache_permissions = []; }
Flush the permission cache, for example if you have edited group membership or a permission record.
reset
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function permissions_for_member($memberID) { $groupList = Permission::groupList($memberID); if ($groupList) { $groupCSV = implode(", ", $groupList); $allowed = array_unique(DB::query(" SELECT \"Code\" FROM \"Permission\" WHERE \"Type\" = " . Permission::GRANT_PERMISSION . " AND \"GroupID\" IN ($groupCSV) UNION SELECT \"Code\" FROM \"PermissionRoleCode\" PRC INNER JOIN \"PermissionRole\" PR ON PRC.\"RoleID\" = PR.\"ID\" INNER JOIN \"Group_Roles\" GR ON GR.\"PermissionRoleID\" = PR.\"ID\" WHERE \"GroupID\" IN ($groupCSV) ")->column() ?? []); $denied = array_unique(DB::query(" SELECT \"Code\" FROM \"Permission\" WHERE \"Type\" = " . Permission::DENY_PERMISSION . " AND \"GroupID\" IN ($groupCSV) ")->column() ?? []); return array_diff($allowed ?? [], $denied); } return []; }
Get all the 'any' permission codes available to the given member. @param int $memberID @return array
permissions_for_member
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function groupList($memberID = null) { // Default to current member, with session-caching if (!$memberID) { $member = Security::getCurrentUser(); if ($member && isset($_SESSION['Permission_groupList'][$member->ID])) { return $_SESSION['Permission_groupList'][$member->ID]; } } else { $member = DataObject::get_by_id("SilverStripe\\Security\\Member", $memberID); } if ($member) { // Build a list of the IDs of the groups. Most of the heavy lifting // is done by Member::Groups // NOTE: This isn't efficient; but it's called once per session so // it's a low priority to fix. $groups = $member->Groups(); $groupList = []; if ($groups) { foreach ($groups as $group) { $groupList[] = $group->ID; } } // Session caching if (!$memberID) { $_SESSION['Permission_groupList'][$member->ID] = $groupList; } return isset($groupList) ? $groupList : null; } return null; }
Get the list of groups that the given member belongs to. Call without an argument to get the groups that the current member belongs to. In this case, the results will be session-cached. @param int $memberID The ID of the member. Leave blank for the current member. @return array Returns a list of group IDs to which the member belongs to or NULL.
groupList
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function get_groups_by_permission($codes) { $codeParams = is_array($codes) ? $codes : [$codes]; $codeClause = DB::placeholders($codeParams); // Via Roles are groups that have the permission via a role return Group::get() ->where([ "\"PermissionRoleCode\".\"Code\" IN ($codeClause) OR \"Permission\".\"Code\" IN ($codeClause)" => array_merge($codeParams, $codeParams) ]) ->leftJoin('Permission', "\"Permission\".\"GroupID\" = \"Group\".\"ID\"") ->leftJoin('Group_Roles', "\"Group_Roles\".\"GroupID\" = \"Group\".\"ID\"") ->leftJoin('PermissionRole', "\"Group_Roles\".\"PermissionRoleID\" = \"PermissionRole\".\"ID\"") ->leftJoin('PermissionRoleCode', "\"PermissionRoleCode\".\"RoleID\" = \"PermissionRole\".\"ID\""); }
Return all of the groups that have one of the given permission codes @param array|string $codes Either a single permission code, or an array of permission codes @return SS_List The matching group objects
get_groups_by_permission
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function sort_permissions($a, $b) { if ($a['sort'] == $b['sort']) { // Same sort value, do alpha instead return strcmp($a['name'] ?? '', $b['name'] ?? ''); } else { // Just numeric. return $a['sort'] < $b['sort'] ? -1 : 1; } }
Sort permissions based on their sort value, or name @param array $a @param array $b @return int
sort_permissions
php
silverstripe/silverstripe-framework
src/Security/Permission.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Permission.php
BSD-3-Clause
public static function protect_entire_site($protect = true, $code = BasicAuth::AUTH_PERMISSION, $message = null) { static::config() ->set('entire_site_protected', $protect) ->set('entire_site_protected_code', $code); if ($message) { static::config()->set('entire_site_protected_message', $message); } }
Enable protection of all requests handed by SilverStripe with basic authentication. This log-in uses the Member database for authentication, but doesn't interfere with the regular log-in form. This can be useful for test sites, where you want to hide the site away from prying eyes, but still be able to test the regular log-in features of the site. You can also enable this feature by adding this line to your .env. Set this to a permission code you wish to require: `SS_USE_BASIC_AUTH=ADMIN` CAUTION: Basic Auth is an oudated security measure which passes credentials without encryption over the network. It is considered insecure unless this connection itself is secured (via HTTPS). It also doesn't prevent access to web requests which aren't handled via SilverStripe (e.g. published assets). Consider using additional authentication and authorisation measures to secure access (e.g. IP whitelists). @param boolean $protect Set this to false to disable protection. @param string $code {@link Permission} code that is required from the user. Defaults to "ADMIN". Set to NULL to just require a valid login, regardless of the permission codes a user has. @param string $message
protect_entire_site
php
silverstripe/silverstripe-framework
src/Security/BasicAuth.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/BasicAuth.php
BSD-3-Clause
public static function setDefaultAdmin($username, $password) { // don't overwrite if already set if (static::hasDefaultAdmin()) { throw new BadMethodCallException( "Default admin already exists. Use clearDefaultAdmin() first." ); } if (empty($username) || empty($password)) { throw new InvalidArgumentException("Default admin username / password cannot be empty"); } static::$default_username = $username; static::$default_password = $password; static::$has_default_admin = true; }
Set the default admin credentials @param string $username @param string $password
setDefaultAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public static function hasDefaultAdmin() { // Check environment if not explicitly set if (!isset(static::$has_default_admin)) { return !empty(Environment::getEnv('SS_DEFAULT_ADMIN_USERNAME')) && !empty(Environment::getEnv('SS_DEFAULT_ADMIN_PASSWORD')); } return static::$has_default_admin; }
Check if there is a default admin @return bool
hasDefaultAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public static function clearDefaultAdmin() { static::$has_default_admin = false; static::$default_username = null; static::$default_password = null; }
Flush the default admin credentials.
clearDefaultAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public function findOrCreateAdmin($email, $name = null) { $this->extend('beforeFindOrCreateAdmin', $email, $name); // Find member $admin = Member::get() ->filter('Email', $email) ->first(); // Find or create admin group $adminGroup = $this->findOrCreateAdminGroup(); // If no admin is found, create one if ($admin) { $inGroup = $admin->inGroup($adminGroup); } else { // Note: This user won't be able to login until a password is set // Set 'Email' to identify this as the default admin $inGroup = false; $admin = Member::create(); $admin->FirstName = $name ?: $email; $admin->Email = $email; $admin->PasswordEncryption = Security::config()->get('password_encryption_algorithm'); $admin->write(); } // Ensure this user is in an admin group if (!$inGroup) { // Add member to group instead of adding group to member // This bypasses the privilege escallation code in Member_GroupSet $adminGroup ->DirectMembers() ->add($admin); } $this->extend('afterFindOrCreateAdmin', $admin); return $admin; }
Find or create a Member with admin permissions @param string $email @param string $name @return Member
findOrCreateAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
protected function findOrCreateAdminGroup() { // Check pre-existing group $adminGroup = Permission::get_groups_by_permission('ADMIN')->first(); if ($adminGroup) { return $adminGroup; } // Check if default records create the group Group::singleton()->requireDefaultRecords(); $adminGroup = Permission::get_groups_by_permission('ADMIN')->first(); if ($adminGroup) { return $adminGroup; } // Create new admin group directly $adminGroup = Group::create(); $adminGroup->Code = 'administrators'; $adminGroup->Title = _t('SilverStripe\\Security\\Group.DefaultGroupTitleAdministrators', 'Administrators'); $adminGroup->Sort = 0; $adminGroup->write(); Permission::grant($adminGroup->ID, 'ADMIN'); return $adminGroup; }
Ensure a Group exists with admin permission @return Group
findOrCreateAdminGroup
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public static function isDefaultAdmin($username) { return static::hasDefaultAdmin() && $username && $username === static::getDefaultAdminUsername(); }
Check if the user is a default admin. Returns false if there is no default admin. @param string $username @return bool
isDefaultAdmin
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public static function isDefaultAdminCredentials($username, $password) { return static::isDefaultAdmin($username) && $password && $password === static::getDefaultAdminPassword(); }
Check if the user credentials match the default admin. Returns false if there is no default admin. @param string $username @param string $password @return bool
isDefaultAdminCredentials
php
silverstripe/silverstripe-framework
src/Security/DefaultAdminService.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/DefaultAdminService.php
BSD-3-Clause
public function process(HTTPRequest $request, callable $delegate) { try { $this ->getAuthenticationHandler() ->authenticateRequest($request); } catch (ValidationException $e) { return new HTTPResponse( "Bad log-in details: " . $e->getMessage(), 400 ); } catch (DatabaseException $e) { // Database isn't ready, carry on. } return $delegate($request); }
Identify the current user from the request @param HTTPRequest $request @param callable $delegate @return HTTPResponse
process
php
silverstripe/silverstripe-framework
src/Security/AuthenticationMiddleware.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/AuthenticationMiddleware.php
BSD-3-Clause
protected function getNewDeviceID() { $generator = new RandomGenerator(); return $generator->randomToken('sha1'); }
Randomly generates a new ID used for the device @return string A device ID
getNewDeviceID
php
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RememberLoginHash.php
BSD-3-Clause
public function getNewHash(Member $member) { $generator = new RandomGenerator(); $this->setToken($generator->randomToken('sha1')); return $member->encryptWithUserSettings($this->token); }
Creates a new random token and hashes it using the member information @param Member $member The logged in user @return string The hash to be stored in the database
getNewHash
php
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RememberLoginHash.php
BSD-3-Clause
public static function generate(Member $member) { if (!$member->exists()) { return null; } if (static::config()->force_single_token) { RememberLoginHash::get()->filter('MemberID', $member->ID)->removeAll(); } $rememberLoginHash = RememberLoginHash::create(); do { $deviceID = $rememberLoginHash->getNewDeviceID(); } while (RememberLoginHash::get()->filter('DeviceID', $deviceID)->count()); $rememberLoginHash->DeviceID = $deviceID; $rememberLoginHash->Hash = $rememberLoginHash->getNewHash($member); $rememberLoginHash->MemberID = $member->ID; $now = DBDatetime::now(); $expiryDate = new DateTime($now->Rfc2822()); $tokenExpiryDays = static::config()->token_expiry_days; $expiryDate->add(new DateInterval('P' . $tokenExpiryDays . 'D')); $rememberLoginHash->ExpiryDate = $expiryDate->format('Y-m-d H:i:s'); $rememberLoginHash->extend('onAfterGenerateToken'); $rememberLoginHash->write(); return $rememberLoginHash; }
Generates a new login hash associated with a device The device is assigned a globally unique device ID The returned login hash stores the hashed token in the database, for this device and this member @param Member $member The logged in user @return RememberLoginHash The generated login hash
generate
php
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RememberLoginHash.php
BSD-3-Clause
public function renew() { // Only regenerate token if configured to do so Deprecation::notice('5.3.0', 'Will be removed without equivalent functionality'); $replaceToken = RememberLoginHash::config()->get('replace_token_during_session_renewal'); if ($replaceToken) { $hash = $this->getNewHash($this->Member()); $this->Hash = $hash; } $this->extend('onAfterRenewToken', $replaceToken); $this->write(); return $this; }
Generates a new hash for this member but keeps the device ID intact @deprecated 5.3.0 Will be removed without equivalent functionality @return RememberLoginHash
renew
php
silverstripe/silverstripe-framework
src/Security/RememberLoginHash.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/RememberLoginHash.php
BSD-3-Clause
public function __construct($baseClass, CacheInterface $cache = null) { if (!is_a($baseClass, DataObject::class, true)) { throw new InvalidArgumentException('Invalid DataObject class: ' . $baseClass); } $this->baseClass = $baseClass; $this->cacheService = $cache; return $this; }
Construct new permissions object @param string $baseClass Base class @param CacheInterface $cache
__construct
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
public function flushMemberCache($memberIDs = null) { if (!$this->cacheService) { return; } // Hard flush, e.g. flush=1 if (!$memberIDs) { $this->cacheService->clear(); } if ($memberIDs && is_array($memberIDs)) { foreach ([InheritedPermissions::VIEW, InheritedPermissions::EDIT, InheritedPermissions::DELETE] as $type) { foreach ($memberIDs as $memberID) { $key = $this->generateCacheKey($type, $memberID); $this->cacheService->delete($key); } } } }
Clear the cache for this instance only @param array $memberIDs A list of member IDs
flushMemberCache
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
public function setGlobalEditPermissions($permissions) { $this->globalEditPermissions = $permissions; return $this; }
Global permissions required to edit @param array $permissions @return $this
setGlobalEditPermissions
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
public function getDefaultPermissions() { return $this->defaultPermissions; }
Get root permissions handler, or null if no handler @return DefaultPermissionChecker|null
getDefaultPermissions
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
public function prePopulatePermissionCache($permission = 'edit', $ids = []) { switch ($permission) { case InheritedPermissions::EDIT: $this->canEditMultiple($ids, Security::getCurrentUser(), false); break; case InheritedPermissions::VIEW: $this->canViewMultiple($ids, Security::getCurrentUser(), false); break; case InheritedPermissions::DELETE: $this->canDeleteMultiple($ids, Security::getCurrentUser(), false); break; default: throw new InvalidArgumentException("Invalid permission type $permission"); } }
Force pre-calculation of a list of permissions for optimisation @param string $permission @param array $ids
prePopulatePermissionCache
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause
protected function getPermissionField($type) { switch ($type) { case InheritedPermissions::DELETE: // Delete uses edit type - Drop through case InheritedPermissions::EDIT: return 'CanEditType'; case InheritedPermissions::VIEW: return 'CanViewType'; default: throw new InvalidArgumentException("Invalid argument type $type"); } }
Get field to check for permission type for the given check. Defaults to those provided by {@see InheritedPermissionsExtension) @param string $type @return string
getPermissionField
php
silverstripe/silverstripe-framework
src/Security/InheritedPermissions.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/InheritedPermissions.php
BSD-3-Clause