repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
LostPasswordHandler.redirectToSuccess
protected function redirectToSuccess(array $data) { $link = $this->link('passwordsent'); return $this->redirect($this->addBackURLParam($link)); }
php
protected function redirectToSuccess(array $data) { $link = $this->link('passwordsent'); return $this->redirect($this->addBackURLParam($link)); }
[ "protected", "function", "redirectToSuccess", "(", "array", "$", "data", ")", "{", "$", "link", "=", "$", "this", "->", "link", "(", "'passwordsent'", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "addBackURLParam", "(", "$", "link", ")", ")", ";", "}" ]
Avoid information disclosure by displaying the same status, regardless wether the email address actually exists @param array $data @return HTTPResponse
[ "Avoid", "information", "disclosure", "by", "displaying", "the", "same", "status", "regardless", "wether", "the", "email", "address", "actually", "exists" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/LostPasswordHandler.php#L254-L259
train
silverstripe/silverstripe-framework
src/ORM/Map.php
Map.unshift
public function unshift($key, $value) { $oldItems = $this->firstItems; $this->firstItems = array( $key => $value ); if ($oldItems) { $this->firstItems = $this->firstItems + $oldItems; } return $this; }
php
public function unshift($key, $value) { $oldItems = $this->firstItems; $this->firstItems = array( $key => $value ); if ($oldItems) { $this->firstItems = $this->firstItems + $oldItems; } return $this; }
[ "public", "function", "unshift", "(", "$", "key", ",", "$", "value", ")", "{", "$", "oldItems", "=", "$", "this", "->", "firstItems", ";", "$", "this", "->", "firstItems", "=", "array", "(", "$", "key", "=>", "$", "value", ")", ";", "if", "(", "$", "oldItems", ")", "{", "$", "this", "->", "firstItems", "=", "$", "this", "->", "firstItems", "+", "$", "oldItems", ";", "}", "return", "$", "this", ";", "}" ]
Unshift an item onto the start of the map. Stores the value in addition to the {@link DataQuery} for the map. @var string $key @var mixed $value @return $this
[ "Unshift", "an", "item", "onto", "the", "start", "of", "the", "map", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Map.php#L110-L122
train
silverstripe/silverstripe-framework
src/ORM/Map.php
Map.push
public function push($key, $value) { $oldItems = $this->lastItems; $this->lastItems = array( $key => $value ); if ($oldItems) { $this->lastItems = $this->lastItems + $oldItems; } return $this; }
php
public function push($key, $value) { $oldItems = $this->lastItems; $this->lastItems = array( $key => $value ); if ($oldItems) { $this->lastItems = $this->lastItems + $oldItems; } return $this; }
[ "public", "function", "push", "(", "$", "key", ",", "$", "value", ")", "{", "$", "oldItems", "=", "$", "this", "->", "lastItems", ";", "$", "this", "->", "lastItems", "=", "array", "(", "$", "key", "=>", "$", "value", ")", ";", "if", "(", "$", "oldItems", ")", "{", "$", "this", "->", "lastItems", "=", "$", "this", "->", "lastItems", "+", "$", "oldItems", ";", "}", "return", "$", "this", ";", "}" ]
Pushes an item onto the end of the map. @var string $key @var mixed $value @return $this
[ "Pushes", "an", "item", "onto", "the", "end", "of", "the", "map", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Map.php#L131-L144
train
silverstripe/silverstripe-framework
src/ORM/Map.php
Map.getIterator
public function getIterator() { return new Map_Iterator( $this->list->getIterator(), $this->keyField, $this->valueField, $this->firstItems, $this->lastItems ); }
php
public function getIterator() { return new Map_Iterator( $this->list->getIterator(), $this->keyField, $this->valueField, $this->firstItems, $this->lastItems ); }
[ "public", "function", "getIterator", "(", ")", "{", "return", "new", "Map_Iterator", "(", "$", "this", "->", "list", "->", "getIterator", "(", ")", ",", "$", "this", "->", "keyField", ",", "$", "this", "->", "valueField", ",", "$", "this", "->", "firstItems", ",", "$", "this", "->", "lastItems", ")", ";", "}" ]
Returns an Map_Iterator instance for iterating over the complete set of items in the map. Satisfies the IteratorAggreagte interface. @return Map_Iterator
[ "Returns", "an", "Map_Iterator", "instance", "for", "iterating", "over", "the", "complete", "set", "of", "items", "in", "the", "map", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Map.php#L260-L269
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridField_FormAction.php
GridField_FormAction.getNameFromParent
protected function getNameFromParent() { $base = $this->gridField; $name = array(); do { array_unshift($name, $base->getName()); $base = $base->getForm(); } while ($base && !($base instanceof Form)); return implode('.', $name); }
php
protected function getNameFromParent() { $base = $this->gridField; $name = array(); do { array_unshift($name, $base->getName()); $base = $base->getForm(); } while ($base && !($base instanceof Form)); return implode('.', $name); }
[ "protected", "function", "getNameFromParent", "(", ")", "{", "$", "base", "=", "$", "this", "->", "gridField", ";", "$", "name", "=", "array", "(", ")", ";", "do", "{", "array_unshift", "(", "$", "name", ",", "$", "base", "->", "getName", "(", ")", ")", ";", "$", "base", "=", "$", "base", "->", "getForm", "(", ")", ";", "}", "while", "(", "$", "base", "&&", "!", "(", "$", "base", "instanceof", "Form", ")", ")", ";", "return", "implode", "(", "'.'", ",", "$", "name", ")", ";", "}" ]
Calculate the name of the gridfield relative to the form. @return string
[ "Calculate", "the", "name", "of", "the", "gridfield", "relative", "to", "the", "form", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridField_FormAction.php#L127-L138
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.getAuthenticator
protected function getAuthenticator($name = 'default') { $authenticators = $this->authenticators; if (isset($authenticators[$name])) { return $authenticators[$name]; } throw new LogicException('No valid authenticator found'); }
php
protected function getAuthenticator($name = 'default') { $authenticators = $this->authenticators; if (isset($authenticators[$name])) { return $authenticators[$name]; } throw new LogicException('No valid authenticator found'); }
[ "protected", "function", "getAuthenticator", "(", "$", "name", "=", "'default'", ")", "{", "$", "authenticators", "=", "$", "this", "->", "authenticators", ";", "if", "(", "isset", "(", "$", "authenticators", "[", "$", "name", "]", ")", ")", "{", "return", "$", "authenticators", "[", "$", "name", "]", ";", "}", "throw", "new", "LogicException", "(", "'No valid authenticator found'", ")", ";", "}" ]
Get the selected authenticator for this request @param string $name The identifier of the authenticator in your config @return Authenticator Class name of Authenticator @throws LogicException
[ "Get", "the", "selected", "authenticator", "for", "this", "request" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L245-L254
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.getApplicableAuthenticators
public function getApplicableAuthenticators($service = Authenticator::LOGIN) { $authenticators = $this->getAuthenticators(); /** @var Authenticator $authenticator */ foreach ($authenticators as $name => $authenticator) { if (!($authenticator->supportedServices() & $service)) { unset($authenticators[$name]); } } if (empty($authenticators)) { throw new LogicException('No applicable authenticators found'); } return $authenticators; }
php
public function getApplicableAuthenticators($service = Authenticator::LOGIN) { $authenticators = $this->getAuthenticators(); /** @var Authenticator $authenticator */ foreach ($authenticators as $name => $authenticator) { if (!($authenticator->supportedServices() & $service)) { unset($authenticators[$name]); } } if (empty($authenticators)) { throw new LogicException('No applicable authenticators found'); } return $authenticators; }
[ "public", "function", "getApplicableAuthenticators", "(", "$", "service", "=", "Authenticator", "::", "LOGIN", ")", "{", "$", "authenticators", "=", "$", "this", "->", "getAuthenticators", "(", ")", ";", "/** @var Authenticator $authenticator */", "foreach", "(", "$", "authenticators", "as", "$", "name", "=>", "$", "authenticator", ")", "{", "if", "(", "!", "(", "$", "authenticator", "->", "supportedServices", "(", ")", "&", "$", "service", ")", ")", "{", "unset", "(", "$", "authenticators", "[", "$", "name", "]", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "authenticators", ")", ")", "{", "throw", "new", "LogicException", "(", "'No applicable authenticators found'", ")", ";", "}", "return", "$", "authenticators", ";", "}" ]
Get all registered authenticators @param int $service The type of service that is requested @return Authenticator[] Return an array of Authenticator objects
[ "Get", "all", "registered", "authenticators" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L262-L278
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.getLoginForms
public function getLoginForms() { Deprecation::notice('5.0.0', 'Now handled by delegateToMultipleHandlers'); return array_map( function (Authenticator $authenticator) { return [ $authenticator->getLoginHandler($this->Link())->loginForm() ]; }, $this->getApplicableAuthenticators() ); }
php
public function getLoginForms() { Deprecation::notice('5.0.0', 'Now handled by delegateToMultipleHandlers'); return array_map( function (Authenticator $authenticator) { return [ $authenticator->getLoginHandler($this->Link())->loginForm() ]; }, $this->getApplicableAuthenticators() ); }
[ "public", "function", "getLoginForms", "(", ")", "{", "Deprecation", "::", "notice", "(", "'5.0.0'", ",", "'Now handled by delegateToMultipleHandlers'", ")", ";", "return", "array_map", "(", "function", "(", "Authenticator", "$", "authenticator", ")", "{", "return", "[", "$", "authenticator", "->", "getLoginHandler", "(", "$", "this", "->", "Link", "(", ")", ")", "->", "loginForm", "(", ")", "]", ";", "}", ",", "$", "this", "->", "getApplicableAuthenticators", "(", ")", ")", ";", "}" ]
Get the login forms for all available authentication methods @deprecated 5.0.0 Now handled by {@link static::delegateToMultipleHandlers} @return array Returns an array of available login forms (array of Form objects).
[ "Get", "the", "login", "forms", "for", "all", "available", "authentication", "methods" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L463-L475
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.Link
public function Link($action = null) { /** @skipUpgrade */ $link = Controller::join_links(Director::baseURL(), "Security", $action); $this->extend('updateLink', $link, $action); return $link; }
php
public function Link($action = null) { /** @skipUpgrade */ $link = Controller::join_links(Director::baseURL(), "Security", $action); $this->extend('updateLink', $link, $action); return $link; }
[ "public", "function", "Link", "(", "$", "action", "=", "null", ")", "{", "/** @skipUpgrade */", "$", "link", "=", "Controller", "::", "join_links", "(", "Director", "::", "baseURL", "(", ")", ",", "\"Security\"", ",", "$", "action", ")", ";", "$", "this", "->", "extend", "(", "'updateLink'", ",", "$", "link", ",", "$", "action", ")", ";", "return", "$", "link", ";", "}" ]
Get a link to a security action @param string $action Name of the action @return string Returns the link to the given action
[ "Get", "a", "link", "to", "a", "security", "action" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L484-L490
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.preLogin
protected function preLogin() { // Event handler for pre-login, with an option to let it break you out of the login form $eventResults = $this->extend('onBeforeSecurityLogin'); // If there was a redirection, return if ($this->redirectedTo()) { return $this->getResponse(); } // If there was an HTTPResponse object returned, then return that if ($eventResults) { foreach ($eventResults as $result) { if ($result instanceof HTTPResponse) { return $result; } } } // If arriving on the login page already logged in, with no security error, and a ReturnURL then redirect // back. The login message check is neccesary to prevent infinite loops where BackURL links to // an action that triggers Security::permissionFailure. // This step is necessary in cases such as automatic redirection where a user is authenticated // upon landing on an SSL secured site and is automatically logged in, or some other case // where the user has permissions to continue but is not given the option. if (!$this->getSessionMessage() && ($member = static::getCurrentUser()) && $member->exists() && $this->getRequest()->requestVar('BackURL') ) { return $this->redirectBack(); } return null; }
php
protected function preLogin() { // Event handler for pre-login, with an option to let it break you out of the login form $eventResults = $this->extend('onBeforeSecurityLogin'); // If there was a redirection, return if ($this->redirectedTo()) { return $this->getResponse(); } // If there was an HTTPResponse object returned, then return that if ($eventResults) { foreach ($eventResults as $result) { if ($result instanceof HTTPResponse) { return $result; } } } // If arriving on the login page already logged in, with no security error, and a ReturnURL then redirect // back. The login message check is neccesary to prevent infinite loops where BackURL links to // an action that triggers Security::permissionFailure. // This step is necessary in cases such as automatic redirection where a user is authenticated // upon landing on an SSL secured site and is automatically logged in, or some other case // where the user has permissions to continue but is not given the option. if (!$this->getSessionMessage() && ($member = static::getCurrentUser()) && $member->exists() && $this->getRequest()->requestVar('BackURL') ) { return $this->redirectBack(); } return null; }
[ "protected", "function", "preLogin", "(", ")", "{", "// Event handler for pre-login, with an option to let it break you out of the login form", "$", "eventResults", "=", "$", "this", "->", "extend", "(", "'onBeforeSecurityLogin'", ")", ";", "// If there was a redirection, return", "if", "(", "$", "this", "->", "redirectedTo", "(", ")", ")", "{", "return", "$", "this", "->", "getResponse", "(", ")", ";", "}", "// If there was an HTTPResponse object returned, then return that", "if", "(", "$", "eventResults", ")", "{", "foreach", "(", "$", "eventResults", "as", "$", "result", ")", "{", "if", "(", "$", "result", "instanceof", "HTTPResponse", ")", "{", "return", "$", "result", ";", "}", "}", "}", "// If arriving on the login page already logged in, with no security error, and a ReturnURL then redirect", "// back. The login message check is neccesary to prevent infinite loops where BackURL links to", "// an action that triggers Security::permissionFailure.", "// This step is necessary in cases such as automatic redirection where a user is authenticated", "// upon landing on an SSL secured site and is automatically logged in, or some other case", "// where the user has permissions to continue but is not given the option.", "if", "(", "!", "$", "this", "->", "getSessionMessage", "(", ")", "&&", "(", "$", "member", "=", "static", "::", "getCurrentUser", "(", ")", ")", "&&", "$", "member", "->", "exists", "(", ")", "&&", "$", "this", "->", "getRequest", "(", ")", "->", "requestVar", "(", "'BackURL'", ")", ")", "{", "return", "$", "this", "->", "redirectBack", "(", ")", ";", "}", "return", "null", ";", "}" ]
Perform pre-login checking and prepare a response if available prior to login @return HTTPResponse Substitute response object if the login process should be curcumvented. Returns null if should proceed as normal.
[ "Perform", "pre", "-", "login", "checking", "and", "prepare", "a", "response", "if", "available", "prior", "to", "login" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L509-L541
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.getResponseController
protected function getResponseController($title) { // Use the default setting for which Page to use to render the security page $pageClass = $this->config()->get('page_class'); if (!$pageClass || !class_exists($pageClass)) { return $this; } // Create new instance of page holder /** @var Page $holderPage */ $holderPage = Injector::inst()->create($pageClass); $holderPage->Title = $title; /** @skipUpgrade */ $holderPage->URLSegment = 'Security'; // Disable ID-based caching of the log-in page by making it a random number $holderPage->ID = -1 * random_int(1, 10000000); $controller = ModelAsController::controller_for($holderPage); $controller->setRequest($this->getRequest()); $controller->doInit(); return $controller; }
php
protected function getResponseController($title) { // Use the default setting for which Page to use to render the security page $pageClass = $this->config()->get('page_class'); if (!$pageClass || !class_exists($pageClass)) { return $this; } // Create new instance of page holder /** @var Page $holderPage */ $holderPage = Injector::inst()->create($pageClass); $holderPage->Title = $title; /** @skipUpgrade */ $holderPage->URLSegment = 'Security'; // Disable ID-based caching of the log-in page by making it a random number $holderPage->ID = -1 * random_int(1, 10000000); $controller = ModelAsController::controller_for($holderPage); $controller->setRequest($this->getRequest()); $controller->doInit(); return $controller; }
[ "protected", "function", "getResponseController", "(", "$", "title", ")", "{", "// Use the default setting for which Page to use to render the security page", "$", "pageClass", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'page_class'", ")", ";", "if", "(", "!", "$", "pageClass", "||", "!", "class_exists", "(", "$", "pageClass", ")", ")", "{", "return", "$", "this", ";", "}", "// Create new instance of page holder", "/** @var Page $holderPage */", "$", "holderPage", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "$", "pageClass", ")", ";", "$", "holderPage", "->", "Title", "=", "$", "title", ";", "/** @skipUpgrade */", "$", "holderPage", "->", "URLSegment", "=", "'Security'", ";", "// Disable ID-based caching of the log-in page by making it a random number", "$", "holderPage", "->", "ID", "=", "-", "1", "*", "random_int", "(", "1", ",", "10000000", ")", ";", "$", "controller", "=", "ModelAsController", "::", "controller_for", "(", "$", "holderPage", ")", ";", "$", "controller", "->", "setRequest", "(", "$", "this", "->", "getRequest", "(", ")", ")", ";", "$", "controller", "->", "doInit", "(", ")", ";", "return", "$", "controller", ";", "}" ]
Prepare the controller for handling the response to this request @param string $title Title to use @return Controller
[ "Prepare", "the", "controller", "for", "handling", "the", "response", "to", "this", "request" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L564-L586
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.generateTabbedFormSet
protected function generateTabbedFormSet($forms) { if (count($forms) === 1) { return $forms; } $viewData = new ArrayData([ 'Forms' => new ArrayList($forms), ]); return $viewData->renderWith( $this->getTemplatesFor('MultiAuthenticatorTabbedForms') ); }
php
protected function generateTabbedFormSet($forms) { if (count($forms) === 1) { return $forms; } $viewData = new ArrayData([ 'Forms' => new ArrayList($forms), ]); return $viewData->renderWith( $this->getTemplatesFor('MultiAuthenticatorTabbedForms') ); }
[ "protected", "function", "generateTabbedFormSet", "(", "$", "forms", ")", "{", "if", "(", "count", "(", "$", "forms", ")", "===", "1", ")", "{", "return", "$", "forms", ";", "}", "$", "viewData", "=", "new", "ArrayData", "(", "[", "'Forms'", "=>", "new", "ArrayList", "(", "$", "forms", ")", ",", "]", ")", ";", "return", "$", "viewData", "->", "renderWith", "(", "$", "this", "->", "getTemplatesFor", "(", "'MultiAuthenticatorTabbedForms'", ")", ")", ";", "}" ]
Combine the given forms into a formset with a tabbed interface @param array|Form[] $forms @return string
[ "Combine", "the", "given", "forms", "into", "a", "formset", "with", "a", "tabbed", "interface" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L594-L607
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.setSessionMessage
public function setSessionMessage( $message, $messageType = ValidationResult::TYPE_WARNING, $messageCast = ValidationResult::CAST_TEXT ) { Controller::curr() ->getRequest() ->getSession() ->set("Security.Message.message", $message) ->set("Security.Message.type", $messageType) ->set("Security.Message.cast", $messageCast); }
php
public function setSessionMessage( $message, $messageType = ValidationResult::TYPE_WARNING, $messageCast = ValidationResult::CAST_TEXT ) { Controller::curr() ->getRequest() ->getSession() ->set("Security.Message.message", $message) ->set("Security.Message.type", $messageType) ->set("Security.Message.cast", $messageCast); }
[ "public", "function", "setSessionMessage", "(", "$", "message", ",", "$", "messageType", "=", "ValidationResult", "::", "TYPE_WARNING", ",", "$", "messageCast", "=", "ValidationResult", "::", "CAST_TEXT", ")", "{", "Controller", "::", "curr", "(", ")", "->", "getRequest", "(", ")", "->", "getSession", "(", ")", "->", "set", "(", "\"Security.Message.message\"", ",", "$", "message", ")", "->", "set", "(", "\"Security.Message.type\"", ",", "$", "messageType", ")", "->", "set", "(", "\"Security.Message.cast\"", ",", "$", "messageCast", ")", ";", "}" ]
Set the next message to display for the security login page. Defaults to warning @param string $message Message @param string $messageType Message type. One of ValidationResult::TYPE_* @param string $messageCast Message cast. One of ValidationResult::CAST_*
[ "Set", "the", "next", "message", "to", "display", "for", "the", "security", "login", "page", ".", "Defaults", "to", "warning" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L640-L651
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.logout
public function logout($request = null, $service = Authenticator::LOGOUT) { $authName = null; if (!$request) { $request = $this->getRequest(); } $handlers = $this->getServiceAuthenticatorsFromRequest($service, $request); $link = $this->Link('logout'); array_walk( $handlers, function (Authenticator &$auth, $name) use ($link) { $auth = $auth->getLogoutHandler(Controller::join_links($link, $name)); } ); return $this->delegateToMultipleHandlers( $handlers, _t(__CLASS__ . '.LOGOUT', 'Log out'), $this->getTemplatesFor('logout'), [$this, 'aggregateAuthenticatorResponses'] ); }
php
public function logout($request = null, $service = Authenticator::LOGOUT) { $authName = null; if (!$request) { $request = $this->getRequest(); } $handlers = $this->getServiceAuthenticatorsFromRequest($service, $request); $link = $this->Link('logout'); array_walk( $handlers, function (Authenticator &$auth, $name) use ($link) { $auth = $auth->getLogoutHandler(Controller::join_links($link, $name)); } ); return $this->delegateToMultipleHandlers( $handlers, _t(__CLASS__ . '.LOGOUT', 'Log out'), $this->getTemplatesFor('logout'), [$this, 'aggregateAuthenticatorResponses'] ); }
[ "public", "function", "logout", "(", "$", "request", "=", "null", ",", "$", "service", "=", "Authenticator", "::", "LOGOUT", ")", "{", "$", "authName", "=", "null", ";", "if", "(", "!", "$", "request", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "}", "$", "handlers", "=", "$", "this", "->", "getServiceAuthenticatorsFromRequest", "(", "$", "service", ",", "$", "request", ")", ";", "$", "link", "=", "$", "this", "->", "Link", "(", "'logout'", ")", ";", "array_walk", "(", "$", "handlers", ",", "function", "(", "Authenticator", "&", "$", "auth", ",", "$", "name", ")", "use", "(", "$", "link", ")", "{", "$", "auth", "=", "$", "auth", "->", "getLogoutHandler", "(", "Controller", "::", "join_links", "(", "$", "link", ",", "$", "name", ")", ")", ";", "}", ")", ";", "return", "$", "this", "->", "delegateToMultipleHandlers", "(", "$", "handlers", ",", "_t", "(", "__CLASS__", ".", "'.LOGOUT'", ",", "'Log out'", ")", ",", "$", "this", "->", "getTemplatesFor", "(", "'logout'", ")", ",", "[", "$", "this", ",", "'aggregateAuthenticatorResponses'", "]", ")", ";", "}" ]
Log the currently logged in user out Logging out without ID-parameter in the URL, will log the user out of all applicable Authenticators. Adding an ID will only log the user out of that Authentication method. @param null|HTTPRequest $request @param int $service @return HTTPResponse|string
[ "Log", "the", "currently", "logged", "in", "user", "out" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L721-L745
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.getServiceAuthenticatorsFromRequest
protected function getServiceAuthenticatorsFromRequest($service, HTTPRequest $request) { $authName = null; if ($request->param('ID')) { $authName = $request->param('ID'); } // Delegate to a single named handler - e.g. Security/login/<authname>/ if ($authName && $this->hasAuthenticator($authName)) { if ($request) { $request->shift(); } $authenticator = $this->getAuthenticator($authName); if (!$authenticator->supportedServices() & $service) { // Try to be helpful and show the service constant name, e.g. Authenticator::LOGIN $constants = array_flip((new ReflectionClass(Authenticator::class))->getConstants()); $message = 'Invalid Authenticator "' . $authName . '" for '; if (array_key_exists($service, $constants)) { $message .= 'service: Authenticator::' . $constants[$service]; } else { $message .= 'unknown authenticator service'; } throw new HTTPResponse_Exception($message, 400); } $handlers = [$authName => $authenticator]; } else { // Delegate to all of them, building a tabbed view - e.g. Security/login/ $handlers = $this->getApplicableAuthenticators($service); } return $handlers; }
php
protected function getServiceAuthenticatorsFromRequest($service, HTTPRequest $request) { $authName = null; if ($request->param('ID')) { $authName = $request->param('ID'); } // Delegate to a single named handler - e.g. Security/login/<authname>/ if ($authName && $this->hasAuthenticator($authName)) { if ($request) { $request->shift(); } $authenticator = $this->getAuthenticator($authName); if (!$authenticator->supportedServices() & $service) { // Try to be helpful and show the service constant name, e.g. Authenticator::LOGIN $constants = array_flip((new ReflectionClass(Authenticator::class))->getConstants()); $message = 'Invalid Authenticator "' . $authName . '" for '; if (array_key_exists($service, $constants)) { $message .= 'service: Authenticator::' . $constants[$service]; } else { $message .= 'unknown authenticator service'; } throw new HTTPResponse_Exception($message, 400); } $handlers = [$authName => $authenticator]; } else { // Delegate to all of them, building a tabbed view - e.g. Security/login/ $handlers = $this->getApplicableAuthenticators($service); } return $handlers; }
[ "protected", "function", "getServiceAuthenticatorsFromRequest", "(", "$", "service", ",", "HTTPRequest", "$", "request", ")", "{", "$", "authName", "=", "null", ";", "if", "(", "$", "request", "->", "param", "(", "'ID'", ")", ")", "{", "$", "authName", "=", "$", "request", "->", "param", "(", "'ID'", ")", ";", "}", "// Delegate to a single named handler - e.g. Security/login/<authname>/", "if", "(", "$", "authName", "&&", "$", "this", "->", "hasAuthenticator", "(", "$", "authName", ")", ")", "{", "if", "(", "$", "request", ")", "{", "$", "request", "->", "shift", "(", ")", ";", "}", "$", "authenticator", "=", "$", "this", "->", "getAuthenticator", "(", "$", "authName", ")", ";", "if", "(", "!", "$", "authenticator", "->", "supportedServices", "(", ")", "&", "$", "service", ")", "{", "// Try to be helpful and show the service constant name, e.g. Authenticator::LOGIN", "$", "constants", "=", "array_flip", "(", "(", "new", "ReflectionClass", "(", "Authenticator", "::", "class", ")", ")", "->", "getConstants", "(", ")", ")", ";", "$", "message", "=", "'Invalid Authenticator \"'", ".", "$", "authName", ".", "'\" for '", ";", "if", "(", "array_key_exists", "(", "$", "service", ",", "$", "constants", ")", ")", "{", "$", "message", ".=", "'service: Authenticator::'", ".", "$", "constants", "[", "$", "service", "]", ";", "}", "else", "{", "$", "message", ".=", "'unknown authenticator service'", ";", "}", "throw", "new", "HTTPResponse_Exception", "(", "$", "message", ",", "400", ")", ";", "}", "$", "handlers", "=", "[", "$", "authName", "=>", "$", "authenticator", "]", ";", "}", "else", "{", "// Delegate to all of them, building a tabbed view - e.g. Security/login/", "$", "handlers", "=", "$", "this", "->", "getApplicableAuthenticators", "(", "$", "service", ")", ";", "}", "return", "$", "handlers", ";", "}" ]
Get authenticators for the given service, optionally filtered by the ID parameter of the current request @param int $service @param HTTPRequest $request @return array|Authenticator[] @throws HTTPResponse_Exception
[ "Get", "authenticators", "for", "the", "given", "service", "optionally", "filtered", "by", "the", "ID", "parameter", "of", "the", "current", "request" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L756-L793
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.aggregateTabbedForms
protected function aggregateTabbedForms(array $results) { $forms = []; foreach ($results as $authName => $singleResult) { // The result *must* be an array with a Form key if (!is_array($singleResult) || !isset($singleResult['Form'])) { user_error('Authenticator "' . $authName . '" doesn\'t support tabbed forms', E_USER_WARNING); continue; } $forms[] = $singleResult['Form']; } if (!$forms) { throw new \LogicException('No authenticators found compatible with tabbed forms'); } return [ 'Forms' => ArrayList::create($forms), 'Form' => $this->generateTabbedFormSet($forms) ]; }
php
protected function aggregateTabbedForms(array $results) { $forms = []; foreach ($results as $authName => $singleResult) { // The result *must* be an array with a Form key if (!is_array($singleResult) || !isset($singleResult['Form'])) { user_error('Authenticator "' . $authName . '" doesn\'t support tabbed forms', E_USER_WARNING); continue; } $forms[] = $singleResult['Form']; } if (!$forms) { throw new \LogicException('No authenticators found compatible with tabbed forms'); } return [ 'Forms' => ArrayList::create($forms), 'Form' => $this->generateTabbedFormSet($forms) ]; }
[ "protected", "function", "aggregateTabbedForms", "(", "array", "$", "results", ")", "{", "$", "forms", "=", "[", "]", ";", "foreach", "(", "$", "results", "as", "$", "authName", "=>", "$", "singleResult", ")", "{", "// The result *must* be an array with a Form key", "if", "(", "!", "is_array", "(", "$", "singleResult", ")", "||", "!", "isset", "(", "$", "singleResult", "[", "'Form'", "]", ")", ")", "{", "user_error", "(", "'Authenticator \"'", ".", "$", "authName", ".", "'\" doesn\\'t support tabbed forms'", ",", "E_USER_WARNING", ")", ";", "continue", ";", "}", "$", "forms", "[", "]", "=", "$", "singleResult", "[", "'Form'", "]", ";", "}", "if", "(", "!", "$", "forms", ")", "{", "throw", "new", "\\", "LogicException", "(", "'No authenticators found compatible with tabbed forms'", ")", ";", "}", "return", "[", "'Forms'", "=>", "ArrayList", "::", "create", "(", "$", "forms", ")", ",", "'Form'", "=>", "$", "this", "->", "generateTabbedFormSet", "(", "$", "forms", ")", "]", ";", "}" ]
Aggregate tabbed forms from each handler to fragments ready to be rendered. @skipUpgrade @param array $results @return array
[ "Aggregate", "tabbed", "forms", "from", "each", "handler", "to", "fragments", "ready", "to", "be", "rendered", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L802-L823
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.delegateToMultipleHandlers
protected function delegateToMultipleHandlers(array $handlers, $title, array $templates, callable $aggregator) { // Simpler case for a single authenticator if (count($handlers) === 1) { return $this->delegateToHandler(array_values($handlers)[0], $title, $templates); } // Process each of the handlers $results = array_map( function (RequestHandler $handler) { return $handler->handleRequest($this->getRequest()); }, $handlers ); $response = call_user_func_array($aggregator, [$results]); // The return could be a HTTPResponse, in which we don't want to call the render if (is_array($response)) { return $this->renderWrappedController($title, $response, $templates); } return $response; }
php
protected function delegateToMultipleHandlers(array $handlers, $title, array $templates, callable $aggregator) { // Simpler case for a single authenticator if (count($handlers) === 1) { return $this->delegateToHandler(array_values($handlers)[0], $title, $templates); } // Process each of the handlers $results = array_map( function (RequestHandler $handler) { return $handler->handleRequest($this->getRequest()); }, $handlers ); $response = call_user_func_array($aggregator, [$results]); // The return could be a HTTPResponse, in which we don't want to call the render if (is_array($response)) { return $this->renderWrappedController($title, $response, $templates); } return $response; }
[ "protected", "function", "delegateToMultipleHandlers", "(", "array", "$", "handlers", ",", "$", "title", ",", "array", "$", "templates", ",", "callable", "$", "aggregator", ")", "{", "// Simpler case for a single authenticator", "if", "(", "count", "(", "$", "handlers", ")", "===", "1", ")", "{", "return", "$", "this", "->", "delegateToHandler", "(", "array_values", "(", "$", "handlers", ")", "[", "0", "]", ",", "$", "title", ",", "$", "templates", ")", ";", "}", "// Process each of the handlers", "$", "results", "=", "array_map", "(", "function", "(", "RequestHandler", "$", "handler", ")", "{", "return", "$", "handler", "->", "handleRequest", "(", "$", "this", "->", "getRequest", "(", ")", ")", ";", "}", ",", "$", "handlers", ")", ";", "$", "response", "=", "call_user_func_array", "(", "$", "aggregator", ",", "[", "$", "results", "]", ")", ";", "// The return could be a HTTPResponse, in which we don't want to call the render", "if", "(", "is_array", "(", "$", "response", ")", ")", "{", "return", "$", "this", "->", "renderWrappedController", "(", "$", "title", ",", "$", "response", ",", "$", "templates", ")", ";", "}", "return", "$", "response", ";", "}" ]
Delegate to a number of handlers and aggregate the results. This is used, for example, to build the log-in page where there are multiple authenticators active. If a single handler is passed, delegateToHandler() will be called instead @param array|RequestHandler[] $handlers @param string $title The title of the form @param array $templates @param callable $aggregator @return array|HTTPResponse|RequestHandler|DBHTMLText|string
[ "Delegate", "to", "a", "number", "of", "handlers", "and", "aggregate", "the", "results", ".", "This", "is", "used", "for", "example", "to", "build", "the", "log", "-", "in", "page", "where", "there", "are", "multiple", "authenticators", "active", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L871-L894
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.delegateToHandler
protected function delegateToHandler(RequestHandler $handler, $title, array $templates = []) { $result = $handler->handleRequest($this->getRequest()); // Return the customised controller - may be used to render a Form (e.g. login form) if (is_array($result)) { $result = $this->renderWrappedController($title, $result, $templates); } return $result; }
php
protected function delegateToHandler(RequestHandler $handler, $title, array $templates = []) { $result = $handler->handleRequest($this->getRequest()); // Return the customised controller - may be used to render a Form (e.g. login form) if (is_array($result)) { $result = $this->renderWrappedController($title, $result, $templates); } return $result; }
[ "protected", "function", "delegateToHandler", "(", "RequestHandler", "$", "handler", ",", "$", "title", ",", "array", "$", "templates", "=", "[", "]", ")", "{", "$", "result", "=", "$", "handler", "->", "handleRequest", "(", "$", "this", "->", "getRequest", "(", ")", ")", ";", "// Return the customised controller - may be used to render a Form (e.g. login form)", "if", "(", "is_array", "(", "$", "result", ")", ")", "{", "$", "result", "=", "$", "this", "->", "renderWrappedController", "(", "$", "title", ",", "$", "result", ",", "$", "templates", ")", ";", "}", "return", "$", "result", ";", "}" ]
Delegate to another RequestHandler, rendering any fragment arrays into an appropriate. controller. @param RequestHandler $handler @param string $title The title of the form @param array $templates @return array|HTTPResponse|RequestHandler|DBHTMLText|string
[ "Delegate", "to", "another", "RequestHandler", "rendering", "any", "fragment", "arrays", "into", "an", "appropriate", ".", "controller", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L905-L915
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.renderWrappedController
protected function renderWrappedController($title, array $fragments, array $templates) { $controller = $this->getResponseController($title); // if the controller calls Director::redirect(), this will break early if (($response = $controller->getResponse()) && $response->isFinished()) { return $response; } // Handle any form messages from validation, etc. $messageType = ''; $message = $this->getSessionMessage($messageType); // We've displayed the message in the form output, so reset it for the next run. static::clearSessionMessage(); if ($message) { $messageResult = [ 'Content' => DBField::create_field('HTMLFragment', $message), 'Message' => DBField::create_field('HTMLFragment', $message), 'MessageType' => $messageType ]; $fragments = array_merge($fragments, $messageResult); } return $controller->customise($fragments)->renderWith($templates); }
php
protected function renderWrappedController($title, array $fragments, array $templates) { $controller = $this->getResponseController($title); // if the controller calls Director::redirect(), this will break early if (($response = $controller->getResponse()) && $response->isFinished()) { return $response; } // Handle any form messages from validation, etc. $messageType = ''; $message = $this->getSessionMessage($messageType); // We've displayed the message in the form output, so reset it for the next run. static::clearSessionMessage(); if ($message) { $messageResult = [ 'Content' => DBField::create_field('HTMLFragment', $message), 'Message' => DBField::create_field('HTMLFragment', $message), 'MessageType' => $messageType ]; $fragments = array_merge($fragments, $messageResult); } return $controller->customise($fragments)->renderWith($templates); }
[ "protected", "function", "renderWrappedController", "(", "$", "title", ",", "array", "$", "fragments", ",", "array", "$", "templates", ")", "{", "$", "controller", "=", "$", "this", "->", "getResponseController", "(", "$", "title", ")", ";", "// if the controller calls Director::redirect(), this will break early", "if", "(", "(", "$", "response", "=", "$", "controller", "->", "getResponse", "(", ")", ")", "&&", "$", "response", "->", "isFinished", "(", ")", ")", "{", "return", "$", "response", ";", "}", "// Handle any form messages from validation, etc.", "$", "messageType", "=", "''", ";", "$", "message", "=", "$", "this", "->", "getSessionMessage", "(", "$", "messageType", ")", ";", "// We've displayed the message in the form output, so reset it for the next run.", "static", "::", "clearSessionMessage", "(", ")", ";", "if", "(", "$", "message", ")", "{", "$", "messageResult", "=", "[", "'Content'", "=>", "DBField", "::", "create_field", "(", "'HTMLFragment'", ",", "$", "message", ")", ",", "'Message'", "=>", "DBField", "::", "create_field", "(", "'HTMLFragment'", ",", "$", "message", ")", ",", "'MessageType'", "=>", "$", "messageType", "]", ";", "$", "fragments", "=", "array_merge", "(", "$", "fragments", ",", "$", "messageResult", ")", ";", "}", "return", "$", "controller", "->", "customise", "(", "$", "fragments", ")", "->", "renderWith", "(", "$", "templates", ")", ";", "}" ]
Render the given fragments into a security page controller with the given title. @param string $title string The title to give the security page @param array $fragments A map of objects to render into the page, e.g. "Form" @param array $templates An array of templates to use for the render @return HTTPResponse|DBHTMLText
[ "Render", "the", "given", "fragments", "into", "a", "security", "page", "controller", "with", "the", "given", "title", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L925-L951
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.lostpassword
public function lostpassword() { $handlers = []; $authenticators = $this->getApplicableAuthenticators(Authenticator::RESET_PASSWORD); /** @var Authenticator $authenticator */ foreach ($authenticators as $authenticator) { $handlers[] = $authenticator->getLostPasswordHandler( Controller::join_links($this->Link(), 'lostpassword') ); } return $this->delegateToMultipleHandlers( $handlers, _t('SilverStripe\\Security\\Security.LOSTPASSWORDHEADER', 'Lost Password'), $this->getTemplatesFor('lostpassword'), [$this, 'aggregateAuthenticatorResponses'] ); }
php
public function lostpassword() { $handlers = []; $authenticators = $this->getApplicableAuthenticators(Authenticator::RESET_PASSWORD); /** @var Authenticator $authenticator */ foreach ($authenticators as $authenticator) { $handlers[] = $authenticator->getLostPasswordHandler( Controller::join_links($this->Link(), 'lostpassword') ); } return $this->delegateToMultipleHandlers( $handlers, _t('SilverStripe\\Security\\Security.LOSTPASSWORDHEADER', 'Lost Password'), $this->getTemplatesFor('lostpassword'), [$this, 'aggregateAuthenticatorResponses'] ); }
[ "public", "function", "lostpassword", "(", ")", "{", "$", "handlers", "=", "[", "]", ";", "$", "authenticators", "=", "$", "this", "->", "getApplicableAuthenticators", "(", "Authenticator", "::", "RESET_PASSWORD", ")", ";", "/** @var Authenticator $authenticator */", "foreach", "(", "$", "authenticators", "as", "$", "authenticator", ")", "{", "$", "handlers", "[", "]", "=", "$", "authenticator", "->", "getLostPasswordHandler", "(", "Controller", "::", "join_links", "(", "$", "this", "->", "Link", "(", ")", ",", "'lostpassword'", ")", ")", ";", "}", "return", "$", "this", "->", "delegateToMultipleHandlers", "(", "$", "handlers", ",", "_t", "(", "'SilverStripe\\\\Security\\\\Security.LOSTPASSWORDHEADER'", ",", "'Lost Password'", ")", ",", "$", "this", "->", "getTemplatesFor", "(", "'lostpassword'", ")", ",", "[", "$", "this", ",", "'aggregateAuthenticatorResponses'", "]", ")", ";", "}" ]
Show the "lost password" page @return string Returns the "lost password" page as HTML code.
[ "Show", "the", "lost", "password", "page" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L964-L981
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.getTemplatesFor
public function getTemplatesFor($action) { $templates = SSViewer::get_templates_by_class(static::class, "_{$action}", __CLASS__); return array_merge( $templates, [ "Security_{$action}", "Security", $this->config()->get("template_main"), "BlankPage" ] ); }
php
public function getTemplatesFor($action) { $templates = SSViewer::get_templates_by_class(static::class, "_{$action}", __CLASS__); return array_merge( $templates, [ "Security_{$action}", "Security", $this->config()->get("template_main"), "BlankPage" ] ); }
[ "public", "function", "getTemplatesFor", "(", "$", "action", ")", "{", "$", "templates", "=", "SSViewer", "::", "get_templates_by_class", "(", "static", "::", "class", ",", "\"_{$action}\"", ",", "__CLASS__", ")", ";", "return", "array_merge", "(", "$", "templates", ",", "[", "\"Security_{$action}\"", ",", "\"Security\"", ",", "$", "this", "->", "config", "(", ")", "->", "get", "(", "\"template_main\"", ")", ",", "\"BlankPage\"", "]", ")", ";", "}" ]
Determine the list of templates to use for rendering the given action. @skipUpgrade @param string $action @return array Template list
[ "Determine", "the", "list", "of", "templates", "to", "use", "for", "rendering", "the", "given", "action", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L1037-L1050
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.setDefaultAdmin
public static function setDefaultAdmin($username, $password) { Deprecation::notice('5.0.0', 'Please use DefaultAdminService::setDefaultAdmin($username, $password)'); DefaultAdminService::setDefaultAdmin($username, $password); return true; }
php
public static function setDefaultAdmin($username, $password) { Deprecation::notice('5.0.0', 'Please use DefaultAdminService::setDefaultAdmin($username, $password)'); DefaultAdminService::setDefaultAdmin($username, $password); return true; }
[ "public", "static", "function", "setDefaultAdmin", "(", "$", "username", ",", "$", "password", ")", "{", "Deprecation", "::", "notice", "(", "'5.0.0'", ",", "'Please use DefaultAdminService::setDefaultAdmin($username, $password)'", ")", ";", "DefaultAdminService", "::", "setDefaultAdmin", "(", "$", "username", ",", "$", "password", ")", ";", "return", "true", ";", "}" ]
Set a default admin in dev-mode This will set a static default-admin which is not existing as a database-record. By this workaround we can test pages in dev-mode with a unified login. Submitted login-credentials are first checked against this static information in {@link Security::authenticate()}. @param string $username The user name @param string $password The password (in cleartext) @return bool True if successfully set @deprecated 4.0.0:5.0.0 Please use DefaultAdminService::setDefaultAdmin($username, $password)
[ "Set", "a", "default", "admin", "in", "dev", "-", "mode" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L1101-L1107
train
silverstripe/silverstripe-framework
src/Security/Security.php
Security.logout_url
public static function logout_url() { $logoutUrl = Controller::join_links(Director::baseURL(), self::config()->get('logout_url')); return SecurityToken::inst()->addToUrl($logoutUrl); }
php
public static function logout_url() { $logoutUrl = Controller::join_links(Director::baseURL(), self::config()->get('logout_url')); return SecurityToken::inst()->addToUrl($logoutUrl); }
[ "public", "static", "function", "logout_url", "(", ")", "{", "$", "logoutUrl", "=", "Controller", "::", "join_links", "(", "Director", "::", "baseURL", "(", ")", ",", "self", "::", "config", "(", ")", "->", "get", "(", "'logout_url'", ")", ")", ";", "return", "SecurityToken", "::", "inst", "(", ")", "->", "addToUrl", "(", "$", "logoutUrl", ")", ";", "}" ]
Get the URL of the logout page. To update the logout url use the "Security.logout_url" config setting. @return string
[ "Get", "the", "URL", "of", "the", "logout", "page", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Security.php#L1341-L1345
train
silverstripe/silverstripe-framework
src/Forms/MultiSelectField.php
MultiSelectField.setValue
public function setValue($value, $obj = null) { // If we're not passed a value directly, // we can look for it in a relation method on the object passed as a second arg if ($obj instanceof DataObject) { $this->loadFrom($obj); } else { parent::setValue($value); } return $this; }
php
public function setValue($value, $obj = null) { // If we're not passed a value directly, // we can look for it in a relation method on the object passed as a second arg if ($obj instanceof DataObject) { $this->loadFrom($obj); } else { parent::setValue($value); } return $this; }
[ "public", "function", "setValue", "(", "$", "value", ",", "$", "obj", "=", "null", ")", "{", "// If we're not passed a value directly,", "// we can look for it in a relation method on the object passed as a second arg", "if", "(", "$", "obj", "instanceof", "DataObject", ")", "{", "$", "this", "->", "loadFrom", "(", "$", "obj", ")", ";", "}", "else", "{", "parent", "::", "setValue", "(", "$", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
Load a value into this MultiSelectField @param mixed $value @param null|array|DataObject $obj {@see Form::loadDataFrom} @return $this
[ "Load", "a", "value", "into", "this", "MultiSelectField" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/MultiSelectField.php#L68-L78
train
silverstripe/silverstripe-framework
src/Forms/MultiSelectField.php
MultiSelectField.loadFrom
public function loadFrom(DataObjectInterface $record) { $fieldName = $this->getName(); if (empty($fieldName) || empty($record)) { return; } $relation = $record->hasMethod($fieldName) ? $record->$fieldName() : null; // Detect DB relation or field if ($relation instanceof Relation) { // Load ids from relation $value = array_values($relation->getIDList()); parent::setValue($value); } elseif ($record->hasField($fieldName)) { // Load dataValue from field... a CSV for DBMultiEnum if ($record->obj($fieldName) instanceof DBMultiEnum) { $value = $this->csvDecode($record->$fieldName); // ... JSON-encoded string for other fields } else { $value = $this->stringDecode($record->$fieldName); } parent::setValue($value); } }
php
public function loadFrom(DataObjectInterface $record) { $fieldName = $this->getName(); if (empty($fieldName) || empty($record)) { return; } $relation = $record->hasMethod($fieldName) ? $record->$fieldName() : null; // Detect DB relation or field if ($relation instanceof Relation) { // Load ids from relation $value = array_values($relation->getIDList()); parent::setValue($value); } elseif ($record->hasField($fieldName)) { // Load dataValue from field... a CSV for DBMultiEnum if ($record->obj($fieldName) instanceof DBMultiEnum) { $value = $this->csvDecode($record->$fieldName); // ... JSON-encoded string for other fields } else { $value = $this->stringDecode($record->$fieldName); } parent::setValue($value); } }
[ "public", "function", "loadFrom", "(", "DataObjectInterface", "$", "record", ")", "{", "$", "fieldName", "=", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "empty", "(", "$", "fieldName", ")", "||", "empty", "(", "$", "record", ")", ")", "{", "return", ";", "}", "$", "relation", "=", "$", "record", "->", "hasMethod", "(", "$", "fieldName", ")", "?", "$", "record", "->", "$", "fieldName", "(", ")", ":", "null", ";", "// Detect DB relation or field", "if", "(", "$", "relation", "instanceof", "Relation", ")", "{", "// Load ids from relation", "$", "value", "=", "array_values", "(", "$", "relation", "->", "getIDList", "(", ")", ")", ";", "parent", "::", "setValue", "(", "$", "value", ")", ";", "}", "elseif", "(", "$", "record", "->", "hasField", "(", "$", "fieldName", ")", ")", "{", "// Load dataValue from field... a CSV for DBMultiEnum", "if", "(", "$", "record", "->", "obj", "(", "$", "fieldName", ")", "instanceof", "DBMultiEnum", ")", "{", "$", "value", "=", "$", "this", "->", "csvDecode", "(", "$", "record", "->", "$", "fieldName", ")", ";", "// ... JSON-encoded string for other fields", "}", "else", "{", "$", "value", "=", "$", "this", "->", "stringDecode", "(", "$", "record", "->", "$", "fieldName", ")", ";", "}", "parent", "::", "setValue", "(", "$", "value", ")", ";", "}", "}" ]
Load the value from the dataobject into this field @param DataObject|DataObjectInterface $record
[ "Load", "the", "value", "from", "the", "dataobject", "into", "this", "field" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/MultiSelectField.php#L85-L113
train
silverstripe/silverstripe-framework
src/Forms/MultiSelectField.php
MultiSelectField.stringDecode
protected function stringDecode($value) { // Handle empty case if (empty($value)) { return array(); } // If json deserialisation fails, then fallover to legacy format $result = json_decode($value, true); if ($result !== false) { return $result; } throw new \InvalidArgumentException("Invalid string encoded value for multi select field"); }
php
protected function stringDecode($value) { // Handle empty case if (empty($value)) { return array(); } // If json deserialisation fails, then fallover to legacy format $result = json_decode($value, true); if ($result !== false) { return $result; } throw new \InvalidArgumentException("Invalid string encoded value for multi select field"); }
[ "protected", "function", "stringDecode", "(", "$", "value", ")", "{", "// Handle empty case", "if", "(", "empty", "(", "$", "value", ")", ")", "{", "return", "array", "(", ")", ";", "}", "// If json deserialisation fails, then fallover to legacy format", "$", "result", "=", "json_decode", "(", "$", "value", ",", "true", ")", ";", "if", "(", "$", "result", "!==", "false", ")", "{", "return", "$", "result", ";", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Invalid string encoded value for multi select field\"", ")", ";", "}" ]
Extract a string value into an array of values @param string $value @return array
[ "Extract", "a", "string", "value", "into", "an", "array", "of", "values" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/MultiSelectField.php#L171-L185
train
silverstripe/silverstripe-framework
src/Forms/MultiSelectField.php
MultiSelectField.csvEncode
protected function csvEncode($value) { if (!$value) { return null; } return implode( ',', array_map( function ($x) { return str_replace(',', '', $x); }, array_values($value) ) ); }
php
protected function csvEncode($value) { if (!$value) { return null; } return implode( ',', array_map( function ($x) { return str_replace(',', '', $x); }, array_values($value) ) ); }
[ "protected", "function", "csvEncode", "(", "$", "value", ")", "{", "if", "(", "!", "$", "value", ")", "{", "return", "null", ";", "}", "return", "implode", "(", "','", ",", "array_map", "(", "function", "(", "$", "x", ")", "{", "return", "str_replace", "(", "','", ",", "''", ",", "$", "x", ")", ";", "}", ",", "array_values", "(", "$", "value", ")", ")", ")", ";", "}" ]
Encode a list of values into a string as a comma separated list. Commas will be stripped from the items passed in @param array $value @return string|null
[ "Encode", "a", "list", "of", "values", "into", "a", "string", "as", "a", "comma", "separated", "list", ".", "Commas", "will", "be", "stripped", "from", "the", "items", "passed", "in" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/MultiSelectField.php#L194-L208
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassLoader.php
ClassLoader.getItemPath
public function getItemPath($class) { foreach (array_reverse($this->manifests) as $manifest) { /** @var ClassManifest $manifestInst */ $manifestInst = $manifest['instance']; if ($path = $manifestInst->getItemPath($class)) { return $path; } if ($manifest['exclusive']) { break; } } return false; }
php
public function getItemPath($class) { foreach (array_reverse($this->manifests) as $manifest) { /** @var ClassManifest $manifestInst */ $manifestInst = $manifest['instance']; if ($path = $manifestInst->getItemPath($class)) { return $path; } if ($manifest['exclusive']) { break; } } return false; }
[ "public", "function", "getItemPath", "(", "$", "class", ")", "{", "foreach", "(", "array_reverse", "(", "$", "this", "->", "manifests", ")", "as", "$", "manifest", ")", "{", "/** @var ClassManifest $manifestInst */", "$", "manifestInst", "=", "$", "manifest", "[", "'instance'", "]", ";", "if", "(", "$", "path", "=", "$", "manifestInst", "->", "getItemPath", "(", "$", "class", ")", ")", "{", "return", "$", "path", ";", "}", "if", "(", "$", "manifest", "[", "'exclusive'", "]", ")", "{", "break", ";", "}", "}", "return", "false", ";", "}" ]
Returns the path for a class or interface in the currently active manifest, or any previous ones if later manifests aren't set to "exclusive". @param string $class @return string|false
[ "Returns", "the", "path", "for", "a", "class", "or", "interface", "in", "the", "currently", "active", "manifest", "or", "any", "previous", "ones", "if", "later", "manifests", "aren", "t", "set", "to", "exclusive", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassLoader.php#L103-L116
train
silverstripe/silverstripe-framework
src/Core/Manifest/ClassLoader.php
ClassLoader.init
public function init($includeTests = false, $forceRegen = false) { foreach ($this->manifests as $manifest) { /** @var ClassManifest $instance */ $instance = $manifest['instance']; $instance->init($includeTests, $forceRegen); } $this->registerAutoloader(); }
php
public function init($includeTests = false, $forceRegen = false) { foreach ($this->manifests as $manifest) { /** @var ClassManifest $instance */ $instance = $manifest['instance']; $instance->init($includeTests, $forceRegen); } $this->registerAutoloader(); }
[ "public", "function", "init", "(", "$", "includeTests", "=", "false", ",", "$", "forceRegen", "=", "false", ")", "{", "foreach", "(", "$", "this", "->", "manifests", "as", "$", "manifest", ")", "{", "/** @var ClassManifest $instance */", "$", "instance", "=", "$", "manifest", "[", "'instance'", "]", ";", "$", "instance", "->", "init", "(", "$", "includeTests", ",", "$", "forceRegen", ")", ";", "}", "$", "this", "->", "registerAutoloader", "(", ")", ";", "}" ]
Initialise the class loader @param bool $includeTests @param bool $forceRegen
[ "Initialise", "the", "class", "loader" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Manifest/ClassLoader.php#L124-L133
train
silverstripe/silverstripe-framework
src/Security/Permission.php
Permission.check
public static function check($code, $arg = "any", $member = null, $strict = true) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } return self::checkMember($member, $code, $arg, $strict); }
php
public static function check($code, $arg = "any", $member = null, $strict = true) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } return self::checkMember($member, $code, $arg, $strict); }
[ "public", "static", "function", "check", "(", "$", "code", ",", "$", "arg", "=", "\"any\"", ",", "$", "member", "=", "null", ",", "$", "strict", "=", "true", ")", "{", "if", "(", "!", "$", "member", ")", "{", "if", "(", "!", "Security", "::", "getCurrentUser", "(", ")", ")", "{", "return", "false", ";", "}", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "return", "self", "::", "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", "that", "the", "current", "member", "has", "the", "given", "permission", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Permission.php#L133-L143
train
silverstripe/silverstripe-framework
src/Security/Permission.php
Permission.permissions_for_member
public static function permissions_for_member($memberID) { $groupList = self::groupList($memberID); if ($groupList) { $groupCSV = implode(", ", $groupList); $allowed = array_unique(DB::query(" SELECT \"Code\" FROM \"Permission\" WHERE \"Type\" = " . self::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\" = " . self::DENY_PERMISSION . " AND \"GroupID\" IN ($groupCSV) ")->column()); return array_diff($allowed, $denied); } return array(); }
php
public static function permissions_for_member($memberID) { $groupList = self::groupList($memberID); if ($groupList) { $groupCSV = implode(", ", $groupList); $allowed = array_unique(DB::query(" SELECT \"Code\" FROM \"Permission\" WHERE \"Type\" = " . self::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\" = " . self::DENY_PERMISSION . " AND \"GroupID\" IN ($groupCSV) ")->column()); return array_diff($allowed, $denied); } return array(); }
[ "public", "static", "function", "permissions_for_member", "(", "$", "memberID", ")", "{", "$", "groupList", "=", "self", "::", "groupList", "(", "$", "memberID", ")", ";", "if", "(", "$", "groupList", ")", "{", "$", "groupCSV", "=", "implode", "(", "\", \"", ",", "$", "groupList", ")", ";", "$", "allowed", "=", "array_unique", "(", "DB", "::", "query", "(", "\"\n\t\t\t\tSELECT \\\"Code\\\"\n\t\t\t\tFROM \\\"Permission\\\"\n\t\t\t\tWHERE \\\"Type\\\" = \"", ".", "self", "::", "GRANT_PERMISSION", ".", "\" AND \\\"GroupID\\\" IN ($groupCSV)\n\n\t\t\t\tUNION\n\n\t\t\t\tSELECT \\\"Code\\\"\n\t\t\t\tFROM \\\"PermissionRoleCode\\\" PRC\n\t\t\t\tINNER JOIN \\\"PermissionRole\\\" PR ON PRC.\\\"RoleID\\\" = PR.\\\"ID\\\"\n\t\t\t\tINNER JOIN \\\"Group_Roles\\\" GR ON GR.\\\"PermissionRoleID\\\" = PR.\\\"ID\\\"\n\t\t\t\tWHERE \\\"GroupID\\\" IN ($groupCSV)\n\t\t\t\"", ")", "->", "column", "(", ")", ")", ";", "$", "denied", "=", "array_unique", "(", "DB", "::", "query", "(", "\"\n\t\t\t\tSELECT \\\"Code\\\"\n\t\t\t\tFROM \\\"Permission\\\"\n\t\t\t\tWHERE \\\"Type\\\" = \"", ".", "self", "::", "DENY_PERMISSION", ".", "\" AND \\\"GroupID\\\" IN ($groupCSV)\n\t\t\t\"", ")", "->", "column", "(", ")", ")", ";", "return", "array_diff", "(", "$", "allowed", ",", "$", "denied", ")", ";", "}", "return", "array", "(", ")", ";", "}" ]
Get all the 'any' permission codes available to the given member. @param int $memberID @return array
[ "Get", "all", "the", "any", "permission", "codes", "available", "to", "the", "given", "member", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Permission.php#L302-L333
train
silverstripe/silverstripe-framework
src/Security/Permission.php
Permission.groupList
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 effecient; but it's called once per session so // it's a low priority to fix. $groups = $member->Groups(); $groupList = array(); 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; }
php
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 effecient; but it's called once per session so // it's a low priority to fix. $groups = $member->Groups(); $groupList = array(); 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; }
[ "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 effecient; but it's called once per session so", "// it's a low priority to fix.", "$", "groups", "=", "$", "member", "->", "Groups", "(", ")", ";", "$", "groupList", "=", "array", "(", ")", ";", "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.
[ "Get", "the", "list", "of", "groups", "that", "the", "given", "member", "belongs", "to", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Permission.php#L347-L382
train
silverstripe/silverstripe-framework
src/Security/Permission.php
Permission.get_members_by_permission
public static function get_members_by_permission($code) { $toplevelGroups = self::get_groups_by_permission($code); if (!$toplevelGroups) { return new ArrayList(); } $groupIDs = array(); foreach ($toplevelGroups as $group) { $familyIDs = $group->collateFamilyIDs(); if (is_array($familyIDs)) { $groupIDs = array_merge($groupIDs, array_values($familyIDs)); } } if (empty($groupIDs)) { return new ArrayList(); } $groupClause = DB::placeholders($groupIDs); /** @skipUpgrade */ $members = Member::get() ->where(array("\"Group\".\"ID\" IN ($groupClause)" => $groupIDs)) ->leftJoin("Group_Members", '"Member"."ID" = "Group_Members"."MemberID"') ->leftJoin("Group", '"Group_Members"."GroupID" = "Group"."ID"'); return $members; }
php
public static function get_members_by_permission($code) { $toplevelGroups = self::get_groups_by_permission($code); if (!$toplevelGroups) { return new ArrayList(); } $groupIDs = array(); foreach ($toplevelGroups as $group) { $familyIDs = $group->collateFamilyIDs(); if (is_array($familyIDs)) { $groupIDs = array_merge($groupIDs, array_values($familyIDs)); } } if (empty($groupIDs)) { return new ArrayList(); } $groupClause = DB::placeholders($groupIDs); /** @skipUpgrade */ $members = Member::get() ->where(array("\"Group\".\"ID\" IN ($groupClause)" => $groupIDs)) ->leftJoin("Group_Members", '"Member"."ID" = "Group_Members"."MemberID"') ->leftJoin("Group", '"Group_Members"."GroupID" = "Group"."ID"'); return $members; }
[ "public", "static", "function", "get_members_by_permission", "(", "$", "code", ")", "{", "$", "toplevelGroups", "=", "self", "::", "get_groups_by_permission", "(", "$", "code", ")", ";", "if", "(", "!", "$", "toplevelGroups", ")", "{", "return", "new", "ArrayList", "(", ")", ";", "}", "$", "groupIDs", "=", "array", "(", ")", ";", "foreach", "(", "$", "toplevelGroups", "as", "$", "group", ")", "{", "$", "familyIDs", "=", "$", "group", "->", "collateFamilyIDs", "(", ")", ";", "if", "(", "is_array", "(", "$", "familyIDs", ")", ")", "{", "$", "groupIDs", "=", "array_merge", "(", "$", "groupIDs", ",", "array_values", "(", "$", "familyIDs", ")", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "groupIDs", ")", ")", "{", "return", "new", "ArrayList", "(", ")", ";", "}", "$", "groupClause", "=", "DB", "::", "placeholders", "(", "$", "groupIDs", ")", ";", "/** @skipUpgrade */", "$", "members", "=", "Member", "::", "get", "(", ")", "->", "where", "(", "array", "(", "\"\\\"Group\\\".\\\"ID\\\" IN ($groupClause)\"", "=>", "$", "groupIDs", ")", ")", "->", "leftJoin", "(", "\"Group_Members\"", ",", "'\"Member\".\"ID\" = \"Group_Members\".\"MemberID\"'", ")", "->", "leftJoin", "(", "\"Group\"", ",", "'\"Group_Members\".\"GroupID\" = \"Group\".\"ID\"'", ")", ";", "return", "$", "members", ";", "}" ]
Returns all members for a specific permission. @param string|array $code Either a single permission code, or a list of permission codes @return SS_List Returns a set of member that have the specified permission.
[ "Returns", "all", "members", "for", "a", "specific", "permission", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Permission.php#L467-L494
train
silverstripe/silverstripe-framework
src/Security/Permission.php
Permission.get_groups_by_permission
public static function get_groups_by_permission($codes) { $codeParams = is_array($codes) ? $codes : array($codes); $codeClause = DB::placeholders($codeParams); // Via Roles are groups that have the permission via a role /** @skipUpgrade */ return Group::get() ->where(array( "\"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\""); }
php
public static function get_groups_by_permission($codes) { $codeParams = is_array($codes) ? $codes : array($codes); $codeClause = DB::placeholders($codeParams); // Via Roles are groups that have the permission via a role /** @skipUpgrade */ return Group::get() ->where(array( "\"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\""); }
[ "public", "static", "function", "get_groups_by_permission", "(", "$", "codes", ")", "{", "$", "codeParams", "=", "is_array", "(", "$", "codes", ")", "?", "$", "codes", ":", "array", "(", "$", "codes", ")", ";", "$", "codeClause", "=", "DB", "::", "placeholders", "(", "$", "codeParams", ")", ";", "// Via Roles are groups that have the permission via a role", "/** @skipUpgrade */", "return", "Group", "::", "get", "(", ")", "->", "where", "(", "array", "(", "\"\\\"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
[ "Return", "all", "of", "the", "groups", "that", "have", "one", "of", "the", "given", "permission", "codes" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Permission.php#L501-L517
train
silverstripe/silverstripe-framework
src/Security/Permission.php
Permission.sort_permissions
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; } }
php
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; } }
[ "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", "based", "on", "their", "sort", "value", "or", "name" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Permission.php#L640-L649
train
silverstripe/silverstripe-framework
src/Security/Permission.php
Permission.get_declared_permissions_list
public static function get_declared_permissions_list() { if (!self::$declared_permissions) { return null; } if (self::$declared_permissions_list) { return self::$declared_permissions_list; } self::$declared_permissions_list = array(); self::traverse_declared_permissions(self::$declared_permissions, self::$declared_permissions_list); return self::$declared_permissions_list; }
php
public static function get_declared_permissions_list() { if (!self::$declared_permissions) { return null; } if (self::$declared_permissions_list) { return self::$declared_permissions_list; } self::$declared_permissions_list = array(); self::traverse_declared_permissions(self::$declared_permissions, self::$declared_permissions_list); return self::$declared_permissions_list; }
[ "public", "static", "function", "get_declared_permissions_list", "(", ")", "{", "if", "(", "!", "self", "::", "$", "declared_permissions", ")", "{", "return", "null", ";", "}", "if", "(", "self", "::", "$", "declared_permissions_list", ")", "{", "return", "self", "::", "$", "declared_permissions_list", ";", "}", "self", "::", "$", "declared_permissions_list", "=", "array", "(", ")", ";", "self", "::", "traverse_declared_permissions", "(", "self", "::", "$", "declared_permissions", ",", "self", "::", "$", "declared_permissions_list", ")", ";", "return", "self", "::", "$", "declared_permissions_list", ";", "}" ]
Get a linear list of the permissions in the system. @return array Linear list of declared permissions in the system. @deprecated 4.4.0
[ "Get", "a", "linear", "list", "of", "the", "permissions", "in", "the", "system", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Permission.php#L657-L672
train
silverstripe/silverstripe-framework
src/Security/Permission.php
Permission.traverse_declared_permissions
protected static function traverse_declared_permissions($declared, &$list) { if (!is_array($declared)) { return; } foreach ($declared as $perm => $value) { if ($value instanceof Permission_Group) { $list[] = $value->getName(); self::traverse_declared_permissions($value->getPermissions(), $list); } else { $list[$perm] = $value; } } }
php
protected static function traverse_declared_permissions($declared, &$list) { if (!is_array($declared)) { return; } foreach ($declared as $perm => $value) { if ($value instanceof Permission_Group) { $list[] = $value->getName(); self::traverse_declared_permissions($value->getPermissions(), $list); } else { $list[$perm] = $value; } } }
[ "protected", "static", "function", "traverse_declared_permissions", "(", "$", "declared", ",", "&", "$", "list", ")", "{", "if", "(", "!", "is_array", "(", "$", "declared", ")", ")", "{", "return", ";", "}", "foreach", "(", "$", "declared", "as", "$", "perm", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "Permission_Group", ")", "{", "$", "list", "[", "]", "=", "$", "value", "->", "getName", "(", ")", ";", "self", "::", "traverse_declared_permissions", "(", "$", "value", "->", "getPermissions", "(", ")", ",", "$", "list", ")", ";", "}", "else", "{", "$", "list", "[", "$", "perm", "]", "=", "$", "value", ";", "}", "}", "}" ]
Recursively traverse the nested list of declared permissions and create a linear list. @param array $declared Nested structure of permissions. @param array $list List of permissions in the structure. The result will be written to this array. @deprecated 4.4.0
[ "Recursively", "traverse", "the", "nested", "list", "of", "declared", "permissions", "and", "create", "a", "linear", "list", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/Permission.php#L699-L713
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldConfig.php
GridFieldConfig.getComponentsByType
public function getComponentsByType($type) { $components = new ArrayList(); foreach ($this->components as $component) { if ($component instanceof $type) { $components->push($component); } } return $components; }
php
public function getComponentsByType($type) { $components = new ArrayList(); foreach ($this->components as $component) { if ($component instanceof $type) { $components->push($component); } } return $components; }
[ "public", "function", "getComponentsByType", "(", "$", "type", ")", "{", "$", "components", "=", "new", "ArrayList", "(", ")", ";", "foreach", "(", "$", "this", "->", "components", "as", "$", "component", ")", "{", "if", "(", "$", "component", "instanceof", "$", "type", ")", "{", "$", "components", "->", "push", "(", "$", "component", ")", ";", "}", "}", "return", "$", "components", ";", "}" ]
Returns all components extending a certain class, or implementing a certain interface. @param string $type Class name or interface @return ArrayList Of GridFieldComponent
[ "Returns", "all", "components", "extending", "a", "certain", "class", "or", "implementing", "a", "certain", "interface", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldConfig.php#L130-L139
train
silverstripe/silverstripe-framework
src/Forms/GridField/GridFieldConfig.php
GridFieldConfig.getComponentByType
public function getComponentByType($type) { foreach ($this->components as $component) { if ($component instanceof $type) { return $component; } } return null; }
php
public function getComponentByType($type) { foreach ($this->components as $component) { if ($component instanceof $type) { return $component; } } return null; }
[ "public", "function", "getComponentByType", "(", "$", "type", ")", "{", "foreach", "(", "$", "this", "->", "components", "as", "$", "component", ")", "{", "if", "(", "$", "component", "instanceof", "$", "type", ")", "{", "return", "$", "component", ";", "}", "}", "return", "null", ";", "}" ]
Returns the first available component with the given class or interface. @param string $type ClassName @return GridFieldComponent
[ "Returns", "the", "first", "available", "component", "with", "the", "given", "class", "or", "interface", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/GridField/GridFieldConfig.php#L147-L155
train
silverstripe/silverstripe-framework
src/Forms/Validator.php
Validator.validate
public function validate() { $this->resetResult(); if ($this->getEnabled()) { $this->php($this->form->getData()); } return $this->result; }
php
public function validate() { $this->resetResult(); if ($this->getEnabled()) { $this->php($this->form->getData()); } return $this->result; }
[ "public", "function", "validate", "(", ")", "{", "$", "this", "->", "resetResult", "(", ")", ";", "if", "(", "$", "this", "->", "getEnabled", "(", ")", ")", "{", "$", "this", "->", "php", "(", "$", "this", "->", "form", "->", "getData", "(", ")", ")", ";", "}", "return", "$", "this", "->", "result", ";", "}" ]
Returns any errors there may be. @return ValidationResult
[ "Returns", "any", "errors", "there", "may", "be", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/Validator.php#L56-L63
train
silverstripe/silverstripe-framework
src/View/Shortcodes/EmbedShortcodeProvider.php
EmbedShortcodeProvider.handle_shortcode
public static function handle_shortcode($arguments, $content, $parser, $shortcode, $extra = array()) { // Get service URL if (!empty($content)) { $serviceURL = $content; } elseif (!empty($arguments['url'])) { $serviceURL = $arguments['url']; } else { return ''; } // 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 EmbedResource $embed */ $embed = Injector::inst()->create(Embeddable::class, $serviceURL); if (!empty($serviceArguments)) { $embed->setOptions(array_merge($serviceArguments, (array) $embed->getOptions())); } // Allow resolver to be mocked $dispatcher = null; if (isset($extra['resolver'])) { $dispatcher = Injector::inst()->create( $extra['resolver']['class'], $serviceURL, $extra['resolver']['config'] ); } elseif (Injector::inst()->has(DispatcherInterface::class)) { $dispatcher = Injector::inst()->get(DispatcherInterface::class); } if ($dispatcher) { $embed->setDispatcher($dispatcher); } // Process embed $embed = $embed->getEmbed(); // Convert embed object into HTML if ($embed && $embed instanceof Adapter) { $result = static::embedForTemplate($embed, $arguments); if ($result) { return $result; } } // Fallback to link to service return static::linkEmbed($arguments, $serviceURL, $serviceURL); }
php
public static function handle_shortcode($arguments, $content, $parser, $shortcode, $extra = array()) { // Get service URL if (!empty($content)) { $serviceURL = $content; } elseif (!empty($arguments['url'])) { $serviceURL = $arguments['url']; } else { return ''; } // 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 EmbedResource $embed */ $embed = Injector::inst()->create(Embeddable::class, $serviceURL); if (!empty($serviceArguments)) { $embed->setOptions(array_merge($serviceArguments, (array) $embed->getOptions())); } // Allow resolver to be mocked $dispatcher = null; if (isset($extra['resolver'])) { $dispatcher = Injector::inst()->create( $extra['resolver']['class'], $serviceURL, $extra['resolver']['config'] ); } elseif (Injector::inst()->has(DispatcherInterface::class)) { $dispatcher = Injector::inst()->get(DispatcherInterface::class); } if ($dispatcher) { $embed->setDispatcher($dispatcher); } // Process embed $embed = $embed->getEmbed(); // Convert embed object into HTML if ($embed && $embed instanceof Adapter) { $result = static::embedForTemplate($embed, $arguments); if ($result) { return $result; } } // Fallback to link to service return static::linkEmbed($arguments, $serviceURL, $serviceURL); }
[ "public", "static", "function", "handle_shortcode", "(", "$", "arguments", ",", "$", "content", ",", "$", "parser", ",", "$", "shortcode", ",", "$", "extra", "=", "array", "(", ")", ")", "{", "// Get service URL", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "$", "serviceURL", "=", "$", "content", ";", "}", "elseif", "(", "!", "empty", "(", "$", "arguments", "[", "'url'", "]", ")", ")", "{", "$", "serviceURL", "=", "$", "arguments", "[", "'url'", "]", ";", "}", "else", "{", "return", "''", ";", "}", "// 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 EmbedResource $embed */", "$", "embed", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "Embeddable", "::", "class", ",", "$", "serviceURL", ")", ";", "if", "(", "!", "empty", "(", "$", "serviceArguments", ")", ")", "{", "$", "embed", "->", "setOptions", "(", "array_merge", "(", "$", "serviceArguments", ",", "(", "array", ")", "$", "embed", "->", "getOptions", "(", ")", ")", ")", ";", "}", "// Allow resolver to be mocked", "$", "dispatcher", "=", "null", ";", "if", "(", "isset", "(", "$", "extra", "[", "'resolver'", "]", ")", ")", "{", "$", "dispatcher", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "$", "extra", "[", "'resolver'", "]", "[", "'class'", "]", ",", "$", "serviceURL", ",", "$", "extra", "[", "'resolver'", "]", "[", "'config'", "]", ")", ";", "}", "elseif", "(", "Injector", "::", "inst", "(", ")", "->", "has", "(", "DispatcherInterface", "::", "class", ")", ")", "{", "$", "dispatcher", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "DispatcherInterface", "::", "class", ")", ";", "}", "if", "(", "$", "dispatcher", ")", "{", "$", "embed", "->", "setDispatcher", "(", "$", "dispatcher", ")", ";", "}", "// Process embed", "$", "embed", "=", "$", "embed", "->", "getEmbed", "(", ")", ";", "// Convert embed object into HTML", "if", "(", "$", "embed", "&&", "$", "embed", "instanceof", "Adapter", ")", "{", "$", "result", "=", "static", "::", "embedForTemplate", "(", "$", "embed", ",", "$", "arguments", ")", ";", "if", "(", "$", "result", ")", "{", "return", "$", "result", ";", "}", "}", "// Fallback to link to service", "return", "static", "::", "linkEmbed", "(", "$", "arguments", ",", "$", "serviceURL", ",", "$", "serviceURL", ")", ";", "}" ]
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
[ "Embed", "shortcode", "parser", "from", "Oembed", ".", "This", "is", "a", "temporary", "workaround", ".", "Oembed", "class", "has", "been", "replaced", "with", "the", "Embed", "external", "service", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Shortcodes/EmbedShortcodeProvider.php#L46-L101
train
silverstripe/silverstripe-framework
src/View/Shortcodes/EmbedShortcodeProvider.php
EmbedShortcodeProvider.videoEmbed
protected static function videoEmbed($arguments, $content) { // Ensure outer div has given width (but leave height auto) if (!empty($arguments['width'])) { $arguments['style'] = 'width: ' . intval($arguments['width']) . 'px;'; } // Convert caption to <p> if (!empty($arguments['caption'])) { $xmlCaption = Convert::raw2xml($arguments['caption']); $content .= "\n<p class=\"caption\">{$xmlCaption}</p>"; } unset($arguments['width']); unset($arguments['height']); unset($arguments['url']); unset($arguments['caption']); return HTML::createTag('div', $arguments, $content); }
php
protected static function videoEmbed($arguments, $content) { // Ensure outer div has given width (but leave height auto) if (!empty($arguments['width'])) { $arguments['style'] = 'width: ' . intval($arguments['width']) . 'px;'; } // Convert caption to <p> if (!empty($arguments['caption'])) { $xmlCaption = Convert::raw2xml($arguments['caption']); $content .= "\n<p class=\"caption\">{$xmlCaption}</p>"; } unset($arguments['width']); unset($arguments['height']); unset($arguments['url']); unset($arguments['caption']); return HTML::createTag('div', $arguments, $content); }
[ "protected", "static", "function", "videoEmbed", "(", "$", "arguments", ",", "$", "content", ")", "{", "// Ensure outer div has given width (but leave height auto)", "if", "(", "!", "empty", "(", "$", "arguments", "[", "'width'", "]", ")", ")", "{", "$", "arguments", "[", "'style'", "]", "=", "'width: '", ".", "intval", "(", "$", "arguments", "[", "'width'", "]", ")", ".", "'px;'", ";", "}", "// Convert caption to <p>", "if", "(", "!", "empty", "(", "$", "arguments", "[", "'caption'", "]", ")", ")", "{", "$", "xmlCaption", "=", "Convert", "::", "raw2xml", "(", "$", "arguments", "[", "'caption'", "]", ")", ";", "$", "content", ".=", "\"\\n<p class=\\\"caption\\\">{$xmlCaption}</p>\"", ";", "}", "unset", "(", "$", "arguments", "[", "'width'", "]", ")", ";", "unset", "(", "$", "arguments", "[", "'height'", "]", ")", ";", "unset", "(", "$", "arguments", "[", "'url'", "]", ")", ";", "unset", "(", "$", "arguments", "[", "'caption'", "]", ")", ";", "return", "HTML", "::", "createTag", "(", "'div'", ",", "$", "arguments", ",", "$", "content", ")", ";", "}" ]
Build video embed tag @param array $arguments @param string $content Raw HTML content @return string
[ "Build", "video", "embed", "tag" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/View/Shortcodes/EmbedShortcodeProvider.php#L134-L151
train
silverstripe/silverstripe-framework
src/Forms/CompositeField.php
CompositeField.getSchemaDataDefaults
public function getSchemaDataDefaults() { $defaults = parent::getSchemaDataDefaults(); $children = $this->getChildren(); if ($children && $children->count()) { $childSchema = []; /** @var FormField $child */ foreach ($children as $child) { $childSchema[] = $child->getSchemaData(); } $defaults['children'] = $childSchema; } $defaults['data']['tag'] = $this->getTag(); $defaults['data']['legend'] = $this->getLegend(); // Scaffolded children will inherit this data $defaults['data']['inherited'] = [ 'data' => [ 'fieldholder' => 'small' ], ]; return $defaults; }
php
public function getSchemaDataDefaults() { $defaults = parent::getSchemaDataDefaults(); $children = $this->getChildren(); if ($children && $children->count()) { $childSchema = []; /** @var FormField $child */ foreach ($children as $child) { $childSchema[] = $child->getSchemaData(); } $defaults['children'] = $childSchema; } $defaults['data']['tag'] = $this->getTag(); $defaults['data']['legend'] = $this->getLegend(); // Scaffolded children will inherit this data $defaults['data']['inherited'] = [ 'data' => [ 'fieldholder' => 'small' ], ]; return $defaults; }
[ "public", "function", "getSchemaDataDefaults", "(", ")", "{", "$", "defaults", "=", "parent", "::", "getSchemaDataDefaults", "(", ")", ";", "$", "children", "=", "$", "this", "->", "getChildren", "(", ")", ";", "if", "(", "$", "children", "&&", "$", "children", "->", "count", "(", ")", ")", "{", "$", "childSchema", "=", "[", "]", ";", "/** @var FormField $child */", "foreach", "(", "$", "children", "as", "$", "child", ")", "{", "$", "childSchema", "[", "]", "=", "$", "child", "->", "getSchemaData", "(", ")", ";", "}", "$", "defaults", "[", "'children'", "]", "=", "$", "childSchema", ";", "}", "$", "defaults", "[", "'data'", "]", "[", "'tag'", "]", "=", "$", "this", "->", "getTag", "(", ")", ";", "$", "defaults", "[", "'data'", "]", "[", "'legend'", "]", "=", "$", "this", "->", "getLegend", "(", ")", ";", "// Scaffolded children will inherit this data", "$", "defaults", "[", "'data'", "]", "[", "'inherited'", "]", "=", "[", "'data'", "=>", "[", "'fieldholder'", "=>", "'small'", "]", ",", "]", ";", "return", "$", "defaults", ";", "}" ]
Merge child field data into this form
[ "Merge", "child", "field", "data", "into", "this", "form" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/CompositeField.php#L74-L98
train
silverstripe/silverstripe-framework
src/Forms/CompositeField.php
CompositeField.collateDataFields
public function collateDataFields(&$list, $saveableOnly = false) { foreach ($this->children as $field) { if (! $field instanceof FormField) { continue; } if ($field instanceof CompositeField) { $field->collateDataFields($list, $saveableOnly); } if ($saveableOnly) { $isIncluded = ($field->hasData() && !$field->isReadonly() && !$field->isDisabled()); } else { $isIncluded = ($field->hasData()); } if ($isIncluded) { $name = $field->getName(); if ($name) { $formName = (isset($this->form)) ? $this->form->FormName() : '(unknown form)'; if (isset($list[$name])) { $fieldClass = get_class($field); $otherFieldClass = get_class($list[$name]); user_error( "collateDataFields() I noticed that a field called '$name' appears twice in" . " your form: '{$formName}'. One is a '{$fieldClass}' and the other is a" . " '{$otherFieldClass}'", E_USER_ERROR ); } $list[$name] = $field; } } } }
php
public function collateDataFields(&$list, $saveableOnly = false) { foreach ($this->children as $field) { if (! $field instanceof FormField) { continue; } if ($field instanceof CompositeField) { $field->collateDataFields($list, $saveableOnly); } if ($saveableOnly) { $isIncluded = ($field->hasData() && !$field->isReadonly() && !$field->isDisabled()); } else { $isIncluded = ($field->hasData()); } if ($isIncluded) { $name = $field->getName(); if ($name) { $formName = (isset($this->form)) ? $this->form->FormName() : '(unknown form)'; if (isset($list[$name])) { $fieldClass = get_class($field); $otherFieldClass = get_class($list[$name]); user_error( "collateDataFields() I noticed that a field called '$name' appears twice in" . " your form: '{$formName}'. One is a '{$fieldClass}' and the other is a" . " '{$otherFieldClass}'", E_USER_ERROR ); } $list[$name] = $field; } } } }
[ "public", "function", "collateDataFields", "(", "&", "$", "list", ",", "$", "saveableOnly", "=", "false", ")", "{", "foreach", "(", "$", "this", "->", "children", "as", "$", "field", ")", "{", "if", "(", "!", "$", "field", "instanceof", "FormField", ")", "{", "continue", ";", "}", "if", "(", "$", "field", "instanceof", "CompositeField", ")", "{", "$", "field", "->", "collateDataFields", "(", "$", "list", ",", "$", "saveableOnly", ")", ";", "}", "if", "(", "$", "saveableOnly", ")", "{", "$", "isIncluded", "=", "(", "$", "field", "->", "hasData", "(", ")", "&&", "!", "$", "field", "->", "isReadonly", "(", ")", "&&", "!", "$", "field", "->", "isDisabled", "(", ")", ")", ";", "}", "else", "{", "$", "isIncluded", "=", "(", "$", "field", "->", "hasData", "(", ")", ")", ";", "}", "if", "(", "$", "isIncluded", ")", "{", "$", "name", "=", "$", "field", "->", "getName", "(", ")", ";", "if", "(", "$", "name", ")", "{", "$", "formName", "=", "(", "isset", "(", "$", "this", "->", "form", ")", ")", "?", "$", "this", "->", "form", "->", "FormName", "(", ")", ":", "'(unknown form)'", ";", "if", "(", "isset", "(", "$", "list", "[", "$", "name", "]", ")", ")", "{", "$", "fieldClass", "=", "get_class", "(", "$", "field", ")", ";", "$", "otherFieldClass", "=", "get_class", "(", "$", "list", "[", "$", "name", "]", ")", ";", "user_error", "(", "\"collateDataFields() I noticed that a field called '$name' appears twice in\"", ".", "\" your form: '{$formName}'. One is a '{$fieldClass}' and the other is a\"", ".", "\" '{$otherFieldClass}'\"", ",", "E_USER_ERROR", ")", ";", "}", "$", "list", "[", "$", "name", "]", "=", "$", "field", ";", "}", "}", "}", "}" ]
Add all of the non-composite fields contained within this field to the list. Sequentialisation is used when connecting the form to its data source @param array $list @param bool $saveableOnly
[ "Add", "all", "of", "the", "non", "-", "composite", "fields", "contained", "within", "this", "field", "to", "the", "list", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/CompositeField.php#L233-L265
train
silverstripe/silverstripe-framework
src/Forms/CompositeField.php
CompositeField.makeFieldReadonly
public function makeFieldReadonly($field) { $fieldName = ($field instanceof FormField) ? $field->getName() : $field; // Iterate on items, looking for the applicable field foreach ($this->children as $i => $item) { if ($item instanceof CompositeField) { if ($item->makeFieldReadonly($fieldName)) { return true; }; } elseif ($item instanceof FormField && $item->getName() == $fieldName) { // Once it's found, use FormField::transform to turn the field into a readonly version of itself. $this->children->replaceField($fieldName, $item->transform(new ReadonlyTransformation())); // A true results indicates that the field was found return true; } } return false; }
php
public function makeFieldReadonly($field) { $fieldName = ($field instanceof FormField) ? $field->getName() : $field; // Iterate on items, looking for the applicable field foreach ($this->children as $i => $item) { if ($item instanceof CompositeField) { if ($item->makeFieldReadonly($fieldName)) { return true; }; } elseif ($item instanceof FormField && $item->getName() == $fieldName) { // Once it's found, use FormField::transform to turn the field into a readonly version of itself. $this->children->replaceField($fieldName, $item->transform(new ReadonlyTransformation())); // A true results indicates that the field was found return true; } } return false; }
[ "public", "function", "makeFieldReadonly", "(", "$", "field", ")", "{", "$", "fieldName", "=", "(", "$", "field", "instanceof", "FormField", ")", "?", "$", "field", "->", "getName", "(", ")", ":", "$", "field", ";", "// Iterate on items, looking for the applicable field", "foreach", "(", "$", "this", "->", "children", "as", "$", "i", "=>", "$", "item", ")", "{", "if", "(", "$", "item", "instanceof", "CompositeField", ")", "{", "if", "(", "$", "item", "->", "makeFieldReadonly", "(", "$", "fieldName", ")", ")", "{", "return", "true", ";", "}", ";", "}", "elseif", "(", "$", "item", "instanceof", "FormField", "&&", "$", "item", "->", "getName", "(", ")", "==", "$", "fieldName", ")", "{", "// Once it's found, use FormField::transform to turn the field into a readonly version of itself.", "$", "this", "->", "children", "->", "replaceField", "(", "$", "fieldName", ",", "$", "item", "->", "transform", "(", "new", "ReadonlyTransformation", "(", ")", ")", ")", ";", "// A true results indicates that the field was found", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Transform the named field into a readonly feld. @param string|FormField @return bool
[ "Transform", "the", "named", "field", "into", "a", "readonly", "feld", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/CompositeField.php#L505-L524
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLExpression.php
SQLExpression.renameTable
public function renameTable($old, $new) { $this->replaceText("`$old`", "`$new`"); $this->replaceText("\"$old\"", "\"$new\""); $this->replaceText(Convert::symbol2sql($old), Convert::symbol2sql($new)); }
php
public function renameTable($old, $new) { $this->replaceText("`$old`", "`$new`"); $this->replaceText("\"$old\"", "\"$new\""); $this->replaceText(Convert::symbol2sql($old), Convert::symbol2sql($new)); }
[ "public", "function", "renameTable", "(", "$", "old", ",", "$", "new", ")", "{", "$", "this", "->", "replaceText", "(", "\"`$old`\"", ",", "\"`$new`\"", ")", ";", "$", "this", "->", "replaceText", "(", "\"\\\"$old\\\"\"", ",", "\"\\\"$new\\\"\"", ")", ";", "$", "this", "->", "replaceText", "(", "Convert", "::", "symbol2sql", "(", "$", "old", ")", ",", "Convert", "::", "symbol2sql", "(", "$", "new", ")", ")", ";", "}" ]
Swap the use of one table with another. @param string $old Name of the old table (unquoted, escaped) @param string $new Name of the new table (unquoted, escaped)
[ "Swap", "the", "use", "of", "one", "table", "with", "another", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLExpression.php#L71-L76
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLExpression.php
SQLExpression.sql
public function sql(&$parameters = array()) { // Build each component as needed $sql = DB::build_sql($this, $parameters); if (empty($sql)) { return null; } if ($this->replacementsOld) { $sql = str_replace($this->replacementsOld, $this->replacementsNew, $sql); } return $sql; }
php
public function sql(&$parameters = array()) { // Build each component as needed $sql = DB::build_sql($this, $parameters); if (empty($sql)) { return null; } if ($this->replacementsOld) { $sql = str_replace($this->replacementsOld, $this->replacementsNew, $sql); } return $sql; }
[ "public", "function", "sql", "(", "&", "$", "parameters", "=", "array", "(", ")", ")", "{", "// Build each component as needed", "$", "sql", "=", "DB", "::", "build_sql", "(", "$", "this", ",", "$", "parameters", ")", ";", "if", "(", "empty", "(", "$", "sql", ")", ")", "{", "return", "null", ";", "}", "if", "(", "$", "this", "->", "replacementsOld", ")", "{", "$", "sql", "=", "str_replace", "(", "$", "this", "->", "replacementsOld", ",", "$", "this", "->", "replacementsNew", ",", "$", "sql", ")", ";", "}", "return", "$", "sql", ";", "}" ]
Generate the SQL statement for this query. @param array $parameters Out variable for parameters required for this query @return string The completed SQL query
[ "Generate", "the", "SQL", "statement", "for", "this", "query", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLExpression.php#L91-L105
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLExpression.php
SQLExpression.copyTo
protected function copyTo(SQLExpression $object) { $target = array_keys(get_object_vars($object)); foreach (get_object_vars($this) as $variable => $value) { if (in_array($variable, $target)) { $object->$variable = $value; } } }
php
protected function copyTo(SQLExpression $object) { $target = array_keys(get_object_vars($object)); foreach (get_object_vars($this) as $variable => $value) { if (in_array($variable, $target)) { $object->$variable = $value; } } }
[ "protected", "function", "copyTo", "(", "SQLExpression", "$", "object", ")", "{", "$", "target", "=", "array_keys", "(", "get_object_vars", "(", "$", "object", ")", ")", ";", "foreach", "(", "get_object_vars", "(", "$", "this", ")", "as", "$", "variable", "=>", "$", "value", ")", "{", "if", "(", "in_array", "(", "$", "variable", ",", "$", "target", ")", ")", "{", "$", "object", "->", "$", "variable", "=", "$", "value", ";", "}", "}", "}" ]
Copies the query parameters contained in this object to another SQLExpression @param SQLExpression $object The object to copy properties to
[ "Copies", "the", "query", "parameters", "contained", "in", "this", "object", "to", "another", "SQLExpression" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLExpression.php#L124-L132
train
silverstripe/silverstripe-framework
src/Security/CMSSecurity.php
CMSSecurity.getTargetMember
public function getTargetMember() { $tempid = $this->getRequest()->requestVar('tempid'); if ($tempid) { return Member::member_from_tempid($tempid); } return null; }
php
public function getTargetMember() { $tempid = $this->getRequest()->requestVar('tempid'); if ($tempid) { return Member::member_from_tempid($tempid); } return null; }
[ "public", "function", "getTargetMember", "(", ")", "{", "$", "tempid", "=", "$", "this", "->", "getRequest", "(", ")", "->", "requestVar", "(", "'tempid'", ")", ";", "if", "(", "$", "tempid", ")", "{", "return", "Member", "::", "member_from_tempid", "(", "$", "tempid", ")", ";", "}", "return", "null", ";", "}" ]
Get known logged out member @return Member
[ "Get", "known", "logged", "out", "member" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/CMSSecurity.php#L73-L81
train
silverstripe/silverstripe-framework
src/Security/CMSSecurity.php
CMSSecurity.redirectToExternalLogin
protected function redirectToExternalLogin() { $loginURL = Security::create()->Link('login'); $loginURLATT = Convert::raw2att($loginURL); $loginURLJS = Convert::raw2js($loginURL); $message = _t( __CLASS__ . '.INVALIDUSER', '<p>Invalid user. <a target="_top" href="{link}">Please re-authenticate here</a> to continue.</p>', 'Message displayed to user if their session cannot be restored', array('link' => $loginURLATT) ); $response = $this->getResponse(); $response->setStatusCode(200); $response->setBody(<<<PHP <!DOCTYPE html> <html><body> $message <script type="application/javascript"> setTimeout(function(){top.location.href = "$loginURLJS";}, 0); </script> </body></html> PHP ); $this->setResponse($response); return $response; }
php
protected function redirectToExternalLogin() { $loginURL = Security::create()->Link('login'); $loginURLATT = Convert::raw2att($loginURL); $loginURLJS = Convert::raw2js($loginURL); $message = _t( __CLASS__ . '.INVALIDUSER', '<p>Invalid user. <a target="_top" href="{link}">Please re-authenticate here</a> to continue.</p>', 'Message displayed to user if their session cannot be restored', array('link' => $loginURLATT) ); $response = $this->getResponse(); $response->setStatusCode(200); $response->setBody(<<<PHP <!DOCTYPE html> <html><body> $message <script type="application/javascript"> setTimeout(function(){top.location.href = "$loginURLJS";}, 0); </script> </body></html> PHP ); $this->setResponse($response); return $response; }
[ "protected", "function", "redirectToExternalLogin", "(", ")", "{", "$", "loginURL", "=", "Security", "::", "create", "(", ")", "->", "Link", "(", "'login'", ")", ";", "$", "loginURLATT", "=", "Convert", "::", "raw2att", "(", "$", "loginURL", ")", ";", "$", "loginURLJS", "=", "Convert", "::", "raw2js", "(", "$", "loginURL", ")", ";", "$", "message", "=", "_t", "(", "__CLASS__", ".", "'.INVALIDUSER'", ",", "'<p>Invalid user. <a target=\"_top\" href=\"{link}\">Please re-authenticate here</a> to continue.</p>'", ",", "'Message displayed to user if their session cannot be restored'", ",", "array", "(", "'link'", "=>", "$", "loginURLATT", ")", ")", ";", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", ";", "$", "response", "->", "setStatusCode", "(", "200", ")", ";", "$", "response", "->", "setBody", "(", "<<<PHP\n<!DOCTYPE html>\n<html><body>\n$message\n<script type=\"application/javascript\">\nsetTimeout(function(){top.location.href = \"$loginURLJS\";}, 0);\n</script>\n</body></html>\nPHP", ")", ";", "$", "this", "->", "setResponse", "(", "$", "response", ")", ";", "return", "$", "response", ";", "}" ]
Redirects the user to the external login page @return HTTPResponse
[ "Redirects", "the", "user", "to", "the", "external", "login", "page" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/CMSSecurity.php#L118-L144
train
silverstripe/silverstripe-framework
src/Security/CMSSecurity.php
CMSSecurity.success
public function success() { // Ensure member is properly logged in if (!Security::getCurrentUser() || !class_exists(AdminRootController::class)) { return $this->redirectToExternalLogin(); } // Get redirect url $controller = $this->getResponseController(_t(__CLASS__ . '.SUCCESS', 'Success')); $backURLs = array( $this->getRequest()->requestVar('BackURL'), $this->getRequest()->getSession()->get('BackURL'), Director::absoluteURL(AdminRootController::config()->get('url_base'), true), ); $backURL = null; foreach ($backURLs as $backURL) { if ($backURL && Director::is_site_url($backURL)) { break; } } // Show login $controller = $controller->customise(array( 'Content' => DBField::create_field(DBHTMLText::class, _t( __CLASS__ . '.SUCCESSCONTENT', '<p>Login success. If you are not automatically redirected ' . '<a target="_top" href="{link}">click here</a></p>', 'Login message displayed in the cms popup once a user has re-authenticated themselves', array('link' => Convert::raw2att($backURL)) )) )); return $controller->renderWith($this->getTemplatesFor('success')); }
php
public function success() { // Ensure member is properly logged in if (!Security::getCurrentUser() || !class_exists(AdminRootController::class)) { return $this->redirectToExternalLogin(); } // Get redirect url $controller = $this->getResponseController(_t(__CLASS__ . '.SUCCESS', 'Success')); $backURLs = array( $this->getRequest()->requestVar('BackURL'), $this->getRequest()->getSession()->get('BackURL'), Director::absoluteURL(AdminRootController::config()->get('url_base'), true), ); $backURL = null; foreach ($backURLs as $backURL) { if ($backURL && Director::is_site_url($backURL)) { break; } } // Show login $controller = $controller->customise(array( 'Content' => DBField::create_field(DBHTMLText::class, _t( __CLASS__ . '.SUCCESSCONTENT', '<p>Login success. If you are not automatically redirected ' . '<a target="_top" href="{link}">click here</a></p>', 'Login message displayed in the cms popup once a user has re-authenticated themselves', array('link' => Convert::raw2att($backURL)) )) )); return $controller->renderWith($this->getTemplatesFor('success')); }
[ "public", "function", "success", "(", ")", "{", "// Ensure member is properly logged in", "if", "(", "!", "Security", "::", "getCurrentUser", "(", ")", "||", "!", "class_exists", "(", "AdminRootController", "::", "class", ")", ")", "{", "return", "$", "this", "->", "redirectToExternalLogin", "(", ")", ";", "}", "// Get redirect url", "$", "controller", "=", "$", "this", "->", "getResponseController", "(", "_t", "(", "__CLASS__", ".", "'.SUCCESS'", ",", "'Success'", ")", ")", ";", "$", "backURLs", "=", "array", "(", "$", "this", "->", "getRequest", "(", ")", "->", "requestVar", "(", "'BackURL'", ")", ",", "$", "this", "->", "getRequest", "(", ")", "->", "getSession", "(", ")", "->", "get", "(", "'BackURL'", ")", ",", "Director", "::", "absoluteURL", "(", "AdminRootController", "::", "config", "(", ")", "->", "get", "(", "'url_base'", ")", ",", "true", ")", ",", ")", ";", "$", "backURL", "=", "null", ";", "foreach", "(", "$", "backURLs", "as", "$", "backURL", ")", "{", "if", "(", "$", "backURL", "&&", "Director", "::", "is_site_url", "(", "$", "backURL", ")", ")", "{", "break", ";", "}", "}", "// Show login", "$", "controller", "=", "$", "controller", "->", "customise", "(", "array", "(", "'Content'", "=>", "DBField", "::", "create_field", "(", "DBHTMLText", "::", "class", ",", "_t", "(", "__CLASS__", ".", "'.SUCCESSCONTENT'", ",", "'<p>Login success. If you are not automatically redirected '", ".", "'<a target=\"_top\" href=\"{link}\">click here</a></p>'", ",", "'Login message displayed in the cms popup once a user has re-authenticated themselves'", ",", "array", "(", "'link'", "=>", "Convert", "::", "raw2att", "(", "$", "backURL", ")", ")", ")", ")", ")", ")", ";", "return", "$", "controller", "->", "renderWith", "(", "$", "this", "->", "getTemplatesFor", "(", "'success'", ")", ")", ";", "}" ]
Given a successful login, tell the parent frame to close the dialog @return HTTPResponse|DBField
[ "Given", "a", "successful", "login", "tell", "the", "parent", "frame", "to", "close", "the", "dialog" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/CMSSecurity.php#L176-L208
train
silverstripe/silverstripe-framework
src/Control/Middleware/ChangeDetectionMiddleware.php
ChangeDetectionMiddleware.sendNotModified
protected function sendNotModified(HTTPRequest $request, HTTPResponse $response) { // 304 is invalid for destructive requests if (in_array($request->httpMethod(), ['POST', 'DELETE', 'PUT'])) { $response->setStatusCode(412); } else { $response->setStatusCode(304); } $response->setBody(''); return $response; }
php
protected function sendNotModified(HTTPRequest $request, HTTPResponse $response) { // 304 is invalid for destructive requests if (in_array($request->httpMethod(), ['POST', 'DELETE', 'PUT'])) { $response->setStatusCode(412); } else { $response->setStatusCode(304); } $response->setBody(''); return $response; }
[ "protected", "function", "sendNotModified", "(", "HTTPRequest", "$", "request", ",", "HTTPResponse", "$", "response", ")", "{", "// 304 is invalid for destructive requests", "if", "(", "in_array", "(", "$", "request", "->", "httpMethod", "(", ")", ",", "[", "'POST'", ",", "'DELETE'", ",", "'PUT'", "]", ")", ")", "{", "$", "response", "->", "setStatusCode", "(", "412", ")", ";", "}", "else", "{", "$", "response", "->", "setStatusCode", "(", "304", ")", ";", "}", "$", "response", "->", "setBody", "(", "''", ")", ";", "return", "$", "response", ";", "}" ]
Sent not-modified response @param HTTPRequest $request @param HTTPResponse $response @return mixed
[ "Sent", "not", "-", "modified", "response" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/ChangeDetectionMiddleware.php#L83-L93
train
silverstripe/silverstripe-framework
src/Forms/MoneyField.php
MoneyField.buildCurrencyField
protected function buildCurrencyField() { $name = $this->getName(); // Validate allowed currencies $currencyValue = $this->fieldCurrency ? $this->fieldCurrency->dataValue() : null; $allowedCurrencies = $this->getAllowedCurrencies(); if (count($allowedCurrencies) === 1) { // Hidden field for single currency $field = HiddenField::create("{$name}[Currency]"); reset($allowedCurrencies); $currencyValue = key($allowedCurrencies); } elseif ($allowedCurrencies) { // Dropdown field for multiple currencies $field = DropdownField::create( "{$name}[Currency]", _t('SilverStripe\\Forms\\MoneyField.FIELDLABELCURRENCY', 'Currency'), $allowedCurrencies ); } else { // Free-text entry for currency value $field = TextField::create( "{$name}[Currency]", _t('SilverStripe\\Forms\\MoneyField.FIELDLABELCURRENCY', 'Currency') ); } $field->setReadonly($this->isReadonly()); $field->setDisabled($this->isDisabled()); if ($currencyValue) { $field->setValue($currencyValue); } $this->fieldCurrency = $field; return $field; }
php
protected function buildCurrencyField() { $name = $this->getName(); // Validate allowed currencies $currencyValue = $this->fieldCurrency ? $this->fieldCurrency->dataValue() : null; $allowedCurrencies = $this->getAllowedCurrencies(); if (count($allowedCurrencies) === 1) { // Hidden field for single currency $field = HiddenField::create("{$name}[Currency]"); reset($allowedCurrencies); $currencyValue = key($allowedCurrencies); } elseif ($allowedCurrencies) { // Dropdown field for multiple currencies $field = DropdownField::create( "{$name}[Currency]", _t('SilverStripe\\Forms\\MoneyField.FIELDLABELCURRENCY', 'Currency'), $allowedCurrencies ); } else { // Free-text entry for currency value $field = TextField::create( "{$name}[Currency]", _t('SilverStripe\\Forms\\MoneyField.FIELDLABELCURRENCY', 'Currency') ); } $field->setReadonly($this->isReadonly()); $field->setDisabled($this->isDisabled()); if ($currencyValue) { $field->setValue($currencyValue); } $this->fieldCurrency = $field; return $field; }
[ "protected", "function", "buildCurrencyField", "(", ")", "{", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "// Validate allowed currencies", "$", "currencyValue", "=", "$", "this", "->", "fieldCurrency", "?", "$", "this", "->", "fieldCurrency", "->", "dataValue", "(", ")", ":", "null", ";", "$", "allowedCurrencies", "=", "$", "this", "->", "getAllowedCurrencies", "(", ")", ";", "if", "(", "count", "(", "$", "allowedCurrencies", ")", "===", "1", ")", "{", "// Hidden field for single currency", "$", "field", "=", "HiddenField", "::", "create", "(", "\"{$name}[Currency]\"", ")", ";", "reset", "(", "$", "allowedCurrencies", ")", ";", "$", "currencyValue", "=", "key", "(", "$", "allowedCurrencies", ")", ";", "}", "elseif", "(", "$", "allowedCurrencies", ")", "{", "// Dropdown field for multiple currencies", "$", "field", "=", "DropdownField", "::", "create", "(", "\"{$name}[Currency]\"", ",", "_t", "(", "'SilverStripe\\\\Forms\\\\MoneyField.FIELDLABELCURRENCY'", ",", "'Currency'", ")", ",", "$", "allowedCurrencies", ")", ";", "}", "else", "{", "// Free-text entry for currency value", "$", "field", "=", "TextField", "::", "create", "(", "\"{$name}[Currency]\"", ",", "_t", "(", "'SilverStripe\\\\Forms\\\\MoneyField.FIELDLABELCURRENCY'", ",", "'Currency'", ")", ")", ";", "}", "$", "field", "->", "setReadonly", "(", "$", "this", "->", "isReadonly", "(", ")", ")", ";", "$", "field", "->", "setDisabled", "(", "$", "this", "->", "isDisabled", "(", ")", ")", ";", "if", "(", "$", "currencyValue", ")", "{", "$", "field", "->", "setValue", "(", "$", "currencyValue", ")", ";", "}", "$", "this", "->", "fieldCurrency", "=", "$", "field", ";", "return", "$", "field", ";", "}" ]
Builds a new currency field based on the allowed currencies configured @return FormField
[ "Builds", "a", "new", "currency", "field", "based", "on", "the", "allowed", "currencies", "configured" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/MoneyField.php#L85-L119
train
silverstripe/silverstripe-framework
src/Forms/MoneyField.php
MoneyField.getDBMoney
protected function getDBMoney() { return DBMoney::create_field('Money', [ 'Currency' => $this->fieldCurrency->dataValue(), 'Amount' => $this->fieldAmount->dataValue() ]) ->setLocale($this->getLocale()); }
php
protected function getDBMoney() { return DBMoney::create_field('Money', [ 'Currency' => $this->fieldCurrency->dataValue(), 'Amount' => $this->fieldAmount->dataValue() ]) ->setLocale($this->getLocale()); }
[ "protected", "function", "getDBMoney", "(", ")", "{", "return", "DBMoney", "::", "create_field", "(", "'Money'", ",", "[", "'Currency'", "=>", "$", "this", "->", "fieldCurrency", "->", "dataValue", "(", ")", ",", "'Amount'", "=>", "$", "this", "->", "fieldAmount", "->", "dataValue", "(", ")", "]", ")", "->", "setLocale", "(", "$", "this", "->", "getLocale", "(", ")", ")", ";", "}" ]
Get value as DBMoney object useful for formatting the number @return DBMoney
[ "Get", "value", "as", "DBMoney", "object", "useful", "for", "formatting", "the", "number" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/MoneyField.php#L184-L191
train
silverstripe/silverstripe-framework
src/Forms/MoneyField.php
MoneyField.setAllowedCurrencies
public function setAllowedCurrencies($currencies) { if (empty($currencies)) { $currencies = []; } elseif (is_string($currencies)) { $currencies = [ $currencies => $currencies ]; } elseif (!is_array($currencies)) { throw new InvalidArgumentException("Invalid currency list"); } elseif (!ArrayLib::is_associative($currencies)) { $currencies = array_combine($currencies, $currencies); } $this->allowedCurrencies = $currencies; // Rebuild currency field $this->buildCurrencyField(); return $this; }
php
public function setAllowedCurrencies($currencies) { if (empty($currencies)) { $currencies = []; } elseif (is_string($currencies)) { $currencies = [ $currencies => $currencies ]; } elseif (!is_array($currencies)) { throw new InvalidArgumentException("Invalid currency list"); } elseif (!ArrayLib::is_associative($currencies)) { $currencies = array_combine($currencies, $currencies); } $this->allowedCurrencies = $currencies; // Rebuild currency field $this->buildCurrencyField(); return $this; }
[ "public", "function", "setAllowedCurrencies", "(", "$", "currencies", ")", "{", "if", "(", "empty", "(", "$", "currencies", ")", ")", "{", "$", "currencies", "=", "[", "]", ";", "}", "elseif", "(", "is_string", "(", "$", "currencies", ")", ")", "{", "$", "currencies", "=", "[", "$", "currencies", "=>", "$", "currencies", "]", ";", "}", "elseif", "(", "!", "is_array", "(", "$", "currencies", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid currency list\"", ")", ";", "}", "elseif", "(", "!", "ArrayLib", "::", "is_associative", "(", "$", "currencies", ")", ")", "{", "$", "currencies", "=", "array_combine", "(", "$", "currencies", ",", "$", "currencies", ")", ";", "}", "$", "this", "->", "allowedCurrencies", "=", "$", "currencies", ";", "// Rebuild currency field", "$", "this", "->", "buildCurrencyField", "(", ")", ";", "return", "$", "this", ";", "}" ]
Set list of currencies. Currencies should be in the 3-letter ISO 4217 currency code. @param array $currencies @return $this
[ "Set", "list", "of", "currencies", ".", "Currencies", "should", "be", "in", "the", "3", "-", "letter", "ISO", "4217", "currency", "code", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/MoneyField.php#L266-L285
train
silverstripe/silverstripe-framework
src/Dev/DebugView.php
DebugView.Breadcrumbs
public function Breadcrumbs() { $basePath = str_replace(Director::protocolAndHost(), '', Director::absoluteBaseURL()); $relPath = parse_url( substr($_SERVER['REQUEST_URI'], strlen($basePath), strlen($_SERVER['REQUEST_URI'])), PHP_URL_PATH ); $parts = explode('/', $relPath); $base = Director::absoluteBaseURL(); $pathPart = ""; $pathLinks = array(); foreach ($parts as $part) { if ($part != '') { $pathPart .= "$part/"; $pathLinks[] = "<a href=\"$base$pathPart\">$part</a>"; } } return implode('&nbsp;&rarr;&nbsp;', $pathLinks); }
php
public function Breadcrumbs() { $basePath = str_replace(Director::protocolAndHost(), '', Director::absoluteBaseURL()); $relPath = parse_url( substr($_SERVER['REQUEST_URI'], strlen($basePath), strlen($_SERVER['REQUEST_URI'])), PHP_URL_PATH ); $parts = explode('/', $relPath); $base = Director::absoluteBaseURL(); $pathPart = ""; $pathLinks = array(); foreach ($parts as $part) { if ($part != '') { $pathPart .= "$part/"; $pathLinks[] = "<a href=\"$base$pathPart\">$part</a>"; } } return implode('&nbsp;&rarr;&nbsp;', $pathLinks); }
[ "public", "function", "Breadcrumbs", "(", ")", "{", "$", "basePath", "=", "str_replace", "(", "Director", "::", "protocolAndHost", "(", ")", ",", "''", ",", "Director", "::", "absoluteBaseURL", "(", ")", ")", ";", "$", "relPath", "=", "parse_url", "(", "substr", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ",", "strlen", "(", "$", "basePath", ")", ",", "strlen", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ")", ",", "PHP_URL_PATH", ")", ";", "$", "parts", "=", "explode", "(", "'/'", ",", "$", "relPath", ")", ";", "$", "base", "=", "Director", "::", "absoluteBaseURL", "(", ")", ";", "$", "pathPart", "=", "\"\"", ";", "$", "pathLinks", "=", "array", "(", ")", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "if", "(", "$", "part", "!=", "''", ")", "{", "$", "pathPart", ".=", "\"$part/\"", ";", "$", "pathLinks", "[", "]", "=", "\"<a href=\\\"$base$pathPart\\\">$part</a>\"", ";", "}", "}", "return", "implode", "(", "'&nbsp;&rarr;&nbsp;'", ",", "$", "pathLinks", ")", ";", "}" ]
Generate breadcrumb links to the URL path being displayed @return string
[ "Generate", "breadcrumb", "links", "to", "the", "URL", "path", "being", "displayed" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/DebugView.php#L125-L143
train
silverstripe/silverstripe-framework
src/Dev/DebugView.php
DebugView.renderHeader
public function renderHeader($httpRequest = null) { $url = htmlentities( $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'], ENT_COMPAT, 'UTF-8' ); $debugCSS = ModuleResourceLoader::singleton() ->resolveURL('silverstripe/framework:client/styles/debug.css'); $output = '<!DOCTYPE html><html><head><title>' . $url . '</title>'; $output .= '<link rel="stylesheet" type="text/css" href="' . $debugCSS . '" />'; $output .= '</head>'; $output .= '<body>'; return $output; }
php
public function renderHeader($httpRequest = null) { $url = htmlentities( $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'], ENT_COMPAT, 'UTF-8' ); $debugCSS = ModuleResourceLoader::singleton() ->resolveURL('silverstripe/framework:client/styles/debug.css'); $output = '<!DOCTYPE html><html><head><title>' . $url . '</title>'; $output .= '<link rel="stylesheet" type="text/css" href="' . $debugCSS . '" />'; $output .= '</head>'; $output .= '<body>'; return $output; }
[ "public", "function", "renderHeader", "(", "$", "httpRequest", "=", "null", ")", "{", "$", "url", "=", "htmlentities", "(", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ".", "' '", ".", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ",", "ENT_COMPAT", ",", "'UTF-8'", ")", ";", "$", "debugCSS", "=", "ModuleResourceLoader", "::", "singleton", "(", ")", "->", "resolveURL", "(", "'silverstripe/framework:client/styles/debug.css'", ")", ";", "$", "output", "=", "'<!DOCTYPE html><html><head><title>'", ".", "$", "url", ".", "'</title>'", ";", "$", "output", ".=", "'<link rel=\"stylesheet\" type=\"text/css\" href=\"'", ".", "$", "debugCSS", ".", "'\" />'", ";", "$", "output", ".=", "'</head>'", ";", "$", "output", ".=", "'<body>'", ";", "return", "$", "output", ";", "}" ]
Render HTML header for development views @param HTTPRequest $httpRequest @return string
[ "Render", "HTML", "header", "for", "development", "views" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/DebugView.php#L214-L230
train
silverstripe/silverstripe-framework
src/Dev/DebugView.php
DebugView.renderError
public function renderError($httpRequest, $errno, $errstr, $errfile, $errline) { $errorType = isset(self::$error_types[$errno]) ? self::$error_types[$errno] : self::$unknown_error; $httpRequestEnt = htmlentities($httpRequest, ENT_COMPAT, 'UTF-8'); if (ini_get('html_errors')) { $errstr = strip_tags($errstr); } else { $errstr = Convert::raw2xml($errstr); } $output = '<div class="header info ' . $errorType['class'] . '">'; $output .= "<h1>[" . $errorType['title'] . '] ' . $errstr . "</h1>"; $output .= "<h3>$httpRequestEnt</h3>"; $output .= "<p>Line <strong>$errline</strong> in <strong>$errfile</strong></p>"; $output .= '</div>'; return $output; }
php
public function renderError($httpRequest, $errno, $errstr, $errfile, $errline) { $errorType = isset(self::$error_types[$errno]) ? self::$error_types[$errno] : self::$unknown_error; $httpRequestEnt = htmlentities($httpRequest, ENT_COMPAT, 'UTF-8'); if (ini_get('html_errors')) { $errstr = strip_tags($errstr); } else { $errstr = Convert::raw2xml($errstr); } $output = '<div class="header info ' . $errorType['class'] . '">'; $output .= "<h1>[" . $errorType['title'] . '] ' . $errstr . "</h1>"; $output .= "<h3>$httpRequestEnt</h3>"; $output .= "<p>Line <strong>$errline</strong> in <strong>$errfile</strong></p>"; $output .= '</div>'; return $output; }
[ "public", "function", "renderError", "(", "$", "httpRequest", ",", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ")", "{", "$", "errorType", "=", "isset", "(", "self", "::", "$", "error_types", "[", "$", "errno", "]", ")", "?", "self", "::", "$", "error_types", "[", "$", "errno", "]", ":", "self", "::", "$", "unknown_error", ";", "$", "httpRequestEnt", "=", "htmlentities", "(", "$", "httpRequest", ",", "ENT_COMPAT", ",", "'UTF-8'", ")", ";", "if", "(", "ini_get", "(", "'html_errors'", ")", ")", "{", "$", "errstr", "=", "strip_tags", "(", "$", "errstr", ")", ";", "}", "else", "{", "$", "errstr", "=", "Convert", "::", "raw2xml", "(", "$", "errstr", ")", ";", "}", "$", "output", "=", "'<div class=\"header info '", ".", "$", "errorType", "[", "'class'", "]", ".", "'\">'", ";", "$", "output", ".=", "\"<h1>[\"", ".", "$", "errorType", "[", "'title'", "]", ".", "'] '", ".", "$", "errstr", ".", "\"</h1>\"", ";", "$", "output", ".=", "\"<h3>$httpRequestEnt</h3>\"", ";", "$", "output", ".=", "\"<p>Line <strong>$errline</strong> in <strong>$errfile</strong></p>\"", ";", "$", "output", ".=", "'</div>'", ";", "return", "$", "output", ";", "}" ]
Render an error. @param string $httpRequest the kind of request @param int $errno Codenumber of the error @param string $errstr The error message @param string $errfile The name of the soruce code file where the error occurred @param int $errline The line number on which the error occured @return string
[ "Render", "an", "error", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/DebugView.php#L276-L292
train
silverstripe/silverstripe-framework
src/Dev/DebugView.php
DebugView.renderSourceFragment
public function renderSourceFragment($lines, $errline) { $output = '<div class="info"><h3>Source</h3>'; $output .= '<pre>'; foreach ($lines as $offset => $line) { $line = htmlentities($line, ENT_COMPAT, 'UTF-8'); if ($offset == $errline) { $output .= "<span>$offset</span> <span class=\"error\">$line</span>"; } else { $output .= "<span>$offset</span> $line"; } } $output .= '</pre></div>'; return $output; }
php
public function renderSourceFragment($lines, $errline) { $output = '<div class="info"><h3>Source</h3>'; $output .= '<pre>'; foreach ($lines as $offset => $line) { $line = htmlentities($line, ENT_COMPAT, 'UTF-8'); if ($offset == $errline) { $output .= "<span>$offset</span> <span class=\"error\">$line</span>"; } else { $output .= "<span>$offset</span> $line"; } } $output .= '</pre></div>'; return $output; }
[ "public", "function", "renderSourceFragment", "(", "$", "lines", ",", "$", "errline", ")", "{", "$", "output", "=", "'<div class=\"info\"><h3>Source</h3>'", ";", "$", "output", ".=", "'<pre>'", ";", "foreach", "(", "$", "lines", "as", "$", "offset", "=>", "$", "line", ")", "{", "$", "line", "=", "htmlentities", "(", "$", "line", ",", "ENT_COMPAT", ",", "'UTF-8'", ")", ";", "if", "(", "$", "offset", "==", "$", "errline", ")", "{", "$", "output", ".=", "\"<span>$offset</span> <span class=\\\"error\\\">$line</span>\"", ";", "}", "else", "{", "$", "output", ".=", "\"<span>$offset</span> $line\"", ";", "}", "}", "$", "output", ".=", "'</pre></div>'", ";", "return", "$", "output", ";", "}" ]
Render a fragment of the a source file @param array $lines An array of file lines; the keys should be the original line numbers @param int $errline The line of the error @return string
[ "Render", "a", "fragment", "of", "the", "a", "source", "file" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/DebugView.php#L301-L316
train
silverstripe/silverstripe-framework
src/Dev/DebugView.php
DebugView.renderTrace
public function renderTrace($trace) { $output = '<div class="info">'; $output .= '<h3>Trace</h3>'; $output .= Backtrace::get_rendered_backtrace($trace); $output .= '</div>'; return $output; }
php
public function renderTrace($trace) { $output = '<div class="info">'; $output .= '<h3>Trace</h3>'; $output .= Backtrace::get_rendered_backtrace($trace); $output .= '</div>'; return $output; }
[ "public", "function", "renderTrace", "(", "$", "trace", ")", "{", "$", "output", "=", "'<div class=\"info\">'", ";", "$", "output", ".=", "'<h3>Trace</h3>'", ";", "$", "output", ".=", "Backtrace", "::", "get_rendered_backtrace", "(", "$", "trace", ")", ";", "$", "output", ".=", "'</div>'", ";", "return", "$", "output", ";", "}" ]
Render a call track @param array $trace The debug_backtrace() array @return string
[ "Render", "a", "call", "track" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/DebugView.php#L324-L332
train
silverstripe/silverstripe-framework
src/Dev/DebugView.php
DebugView.renderVariable
public function renderVariable($val, $caller) { $output = '<pre style="background-color:#ccc;padding:5px;font-size:14px;line-height:18px;">'; $output .= "<span style=\"font-size: 12px;color:#666;\">" . $this->formatCaller($caller) . " - </span>\n"; if (is_string($val)) { $output .= wordwrap($val, self::config()->columns); } else { $output .= var_export($val, true); } $output .= '</pre>'; return $output; }
php
public function renderVariable($val, $caller) { $output = '<pre style="background-color:#ccc;padding:5px;font-size:14px;line-height:18px;">'; $output .= "<span style=\"font-size: 12px;color:#666;\">" . $this->formatCaller($caller) . " - </span>\n"; if (is_string($val)) { $output .= wordwrap($val, self::config()->columns); } else { $output .= var_export($val, true); } $output .= '</pre>'; return $output; }
[ "public", "function", "renderVariable", "(", "$", "val", ",", "$", "caller", ")", "{", "$", "output", "=", "'<pre style=\"background-color:#ccc;padding:5px;font-size:14px;line-height:18px;\">'", ";", "$", "output", ".=", "\"<span style=\\\"font-size: 12px;color:#666;\\\">\"", ".", "$", "this", "->", "formatCaller", "(", "$", "caller", ")", ".", "\" - </span>\\n\"", ";", "if", "(", "is_string", "(", "$", "val", ")", ")", "{", "$", "output", ".=", "wordwrap", "(", "$", "val", ",", "self", "::", "config", "(", ")", "->", "columns", ")", ";", "}", "else", "{", "$", "output", ".=", "var_export", "(", "$", "val", ",", "true", ")", ";", "}", "$", "output", ".=", "'</pre>'", ";", "return", "$", "output", ";", "}" ]
Outputs a variable in a user presentable way @param object $val @param array $caller Caller information @return string
[ "Outputs", "a", "variable", "in", "a", "user", "presentable", "way" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Dev/DebugView.php#L367-L379
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
SQLConditionalExpression.addFrom
public function addFrom($from) { if (is_array($from)) { $this->from = array_merge($this->from, $from); } elseif (!empty($from)) { $this->from[str_replace(array('"','`'), '', $from)] = $from; } return $this; }
php
public function addFrom($from) { if (is_array($from)) { $this->from = array_merge($this->from, $from); } elseif (!empty($from)) { $this->from[str_replace(array('"','`'), '', $from)] = $from; } return $this; }
[ "public", "function", "addFrom", "(", "$", "from", ")", "{", "if", "(", "is_array", "(", "$", "from", ")", ")", "{", "$", "this", "->", "from", "=", "array_merge", "(", "$", "this", "->", "from", ",", "$", "from", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "from", ")", ")", "{", "$", "this", "->", "from", "[", "str_replace", "(", "array", "(", "'\"'", ",", "'`'", ")", ",", "''", ",", "$", "from", ")", "]", "=", "$", "from", ";", "}", "return", "$", "this", ";", "}" ]
Add a table to include in the query or update @example $query->addFrom('"MyTable"'); // SELECT * FROM "MyTable" @param string|array $from Single, or list of, ANSI quoted table names @return $this Self reference
[ "Add", "a", "table", "to", "include", "in", "the", "query", "or", "update" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLConditionalExpression.php#L79-L88
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
SQLConditionalExpression.addLeftJoin
public function addLeftJoin($table, $onPredicate, $tableAlias = '', $order = 20, $parameters = array()) { if (!$tableAlias) { $tableAlias = $table; } $this->from[$tableAlias] = array( 'type' => 'LEFT', 'table' => $table, 'filter' => array($onPredicate), 'order' => $order, 'parameters' => $parameters ); return $this; }
php
public function addLeftJoin($table, $onPredicate, $tableAlias = '', $order = 20, $parameters = array()) { if (!$tableAlias) { $tableAlias = $table; } $this->from[$tableAlias] = array( 'type' => 'LEFT', 'table' => $table, 'filter' => array($onPredicate), 'order' => $order, 'parameters' => $parameters ); return $this; }
[ "public", "function", "addLeftJoin", "(", "$", "table", ",", "$", "onPredicate", ",", "$", "tableAlias", "=", "''", ",", "$", "order", "=", "20", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "if", "(", "!", "$", "tableAlias", ")", "{", "$", "tableAlias", "=", "$", "table", ";", "}", "$", "this", "->", "from", "[", "$", "tableAlias", "]", "=", "array", "(", "'type'", "=>", "'LEFT'", ",", "'table'", "=>", "$", "table", ",", "'filter'", "=>", "array", "(", "$", "onPredicate", ")", ",", "'order'", "=>", "$", "order", ",", "'parameters'", "=>", "$", "parameters", ")", ";", "return", "$", "this", ";", "}" ]
Add a LEFT JOIN criteria to the tables list. @param string $table Unquoted table name @param string $onPredicate The "ON" SQL fragment in a "LEFT JOIN ... AS ... ON ..." statement, Needs to be valid (quoted) SQL. @param string $tableAlias Optional alias which makes it easier to identify and replace joins later on @param int $order A numerical index to control the order that joins are added to the query; lower order values will cause the query to appear first. The default is 20, and joins created automatically by the ORM have a value of 10. @param array $parameters Any additional parameters if the join is a parameterised subquery @return $this Self reference
[ "Add", "a", "LEFT", "JOIN", "criteria", "to", "the", "tables", "list", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLConditionalExpression.php#L139-L152
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
SQLConditionalExpression.addInnerJoin
public function addInnerJoin($table, $onPredicate, $tableAlias = null, $order = 20, $parameters = array()) { if (!$tableAlias) { $tableAlias = $table; } $this->from[$tableAlias] = array( 'type' => 'INNER', 'table' => $table, 'filter' => array($onPredicate), 'order' => $order, 'parameters' => $parameters ); return $this; }
php
public function addInnerJoin($table, $onPredicate, $tableAlias = null, $order = 20, $parameters = array()) { if (!$tableAlias) { $tableAlias = $table; } $this->from[$tableAlias] = array( 'type' => 'INNER', 'table' => $table, 'filter' => array($onPredicate), 'order' => $order, 'parameters' => $parameters ); return $this; }
[ "public", "function", "addInnerJoin", "(", "$", "table", ",", "$", "onPredicate", ",", "$", "tableAlias", "=", "null", ",", "$", "order", "=", "20", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "if", "(", "!", "$", "tableAlias", ")", "{", "$", "tableAlias", "=", "$", "table", ";", "}", "$", "this", "->", "from", "[", "$", "tableAlias", "]", "=", "array", "(", "'type'", "=>", "'INNER'", ",", "'table'", "=>", "$", "table", ",", "'filter'", "=>", "array", "(", "$", "onPredicate", ")", ",", "'order'", "=>", "$", "order", ",", "'parameters'", "=>", "$", "parameters", ")", ";", "return", "$", "this", ";", "}" ]
Add an INNER JOIN criteria @param string $table Unquoted table name @param string $onPredicate The "ON" SQL fragment in an "INNER JOIN ... AS ... ON ..." statement. Needs to be valid (quoted) SQL. @param string $tableAlias Optional alias which makes it easier to identify and replace joins later on @param int $order A numerical index to control the order that joins are added to the query; lower order values will cause the query to appear first. The default is 20, and joins created automatically by the ORM have a value of 10. @param array $parameters Any additional parameters if the join is a parameterised subquery @return $this Self reference
[ "Add", "an", "INNER", "JOIN", "criteria" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLConditionalExpression.php#L167-L180
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
SQLConditionalExpression.queriedTables
public function queriedTables() { $tables = array(); foreach ($this->from as $key => $tableClause) { if (is_array($tableClause)) { $table = '"' . $tableClause['table'] . '"'; } elseif (is_string($tableClause) && preg_match('/JOIN +("[^"]+") +(AS|ON) +/i', $tableClause, $matches)) { $table = $matches[1]; } else { $table = $tableClause; } // Handle string replacements if ($this->replacementsOld) { $table = str_replace($this->replacementsOld, $this->replacementsNew, $table); } $tables[] = preg_replace('/^"|"$/', '', $table); } return $tables; }
php
public function queriedTables() { $tables = array(); foreach ($this->from as $key => $tableClause) { if (is_array($tableClause)) { $table = '"' . $tableClause['table'] . '"'; } elseif (is_string($tableClause) && preg_match('/JOIN +("[^"]+") +(AS|ON) +/i', $tableClause, $matches)) { $table = $matches[1]; } else { $table = $tableClause; } // Handle string replacements if ($this->replacementsOld) { $table = str_replace($this->replacementsOld, $this->replacementsNew, $table); } $tables[] = preg_replace('/^"|"$/', '', $table); } return $tables; }
[ "public", "function", "queriedTables", "(", ")", "{", "$", "tables", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "from", "as", "$", "key", "=>", "$", "tableClause", ")", "{", "if", "(", "is_array", "(", "$", "tableClause", ")", ")", "{", "$", "table", "=", "'\"'", ".", "$", "tableClause", "[", "'table'", "]", ".", "'\"'", ";", "}", "elseif", "(", "is_string", "(", "$", "tableClause", ")", "&&", "preg_match", "(", "'/JOIN +(\"[^\"]+\") +(AS|ON) +/i'", ",", "$", "tableClause", ",", "$", "matches", ")", ")", "{", "$", "table", "=", "$", "matches", "[", "1", "]", ";", "}", "else", "{", "$", "table", "=", "$", "tableClause", ";", "}", "// Handle string replacements", "if", "(", "$", "this", "->", "replacementsOld", ")", "{", "$", "table", "=", "str_replace", "(", "$", "this", "->", "replacementsOld", ",", "$", "this", "->", "replacementsNew", ",", "$", "table", ")", ";", "}", "$", "tables", "[", "]", "=", "preg_replace", "(", "'/^\"|\"$/'", ",", "''", ",", "$", "table", ")", ";", "}", "return", "$", "tables", ";", "}" ]
Return a list of tables that this query is selecting from. @return array Unquoted table names
[ "Return", "a", "list", "of", "tables", "that", "this", "query", "is", "selecting", "from", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLConditionalExpression.php#L224-L246
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
SQLConditionalExpression.getJoins
public function getJoins(&$parameters = array()) { if (func_num_args() == 0) { Deprecation::notice( '4.0', 'SQLConditionalExpression::getJoins() now may produce parameters which are necessary to execute this query' ); } // Sort the joins $parameters = array(); $joins = $this->getOrderedJoins($this->from); // Build from clauses foreach ($joins as $alias => $join) { // $join can be something like this array structure // array('type' => 'inner', 'table' => 'SiteTree', 'filter' => array("SiteTree.ID = 1", // "Status = 'approved'", 'order' => 20)) if (!is_array($join)) { if (empty($alias) || is_numeric($alias)) { continue; } if (preg_match('/AS\s+(?:"[^"]+"|[A-Z0-9_]+)\s*$/i', $join)) { // custom aliases override the ones defined through array keys // this is only meant to keep backward compatibility with SS <= 4.3, // to be removed in SS5 continue; } $trimmedAlias = trim($alias, '"'); if ($trimmedAlias !== trim($join, '"')) { $joins[$alias] = "{$join} AS \"{$trimmedAlias}\""; } continue; } if (is_string($join['filter'])) { $filter = $join['filter']; } elseif (sizeof($join['filter']) == 1) { $filter = $join['filter'][0]; } else { $filter = "(" . implode(") AND (", $join['filter']) . ")"; } // Ensure tables are quoted, unless the table is actually a sub-select $table = preg_match('/\bSELECT\b/i', $join['table']) ? $join['table'] : "\"{$join['table']}\""; $aliasClause = ($alias != $join['table']) ? " AS \"{$alias}\"" : ""; $joins[$alias] = strtoupper($join['type']) . " JOIN " . $table . "$aliasClause ON $filter"; if (!empty($join['parameters'])) { $parameters = array_merge($parameters, $join['parameters']); } } return $joins; }
php
public function getJoins(&$parameters = array()) { if (func_num_args() == 0) { Deprecation::notice( '4.0', 'SQLConditionalExpression::getJoins() now may produce parameters which are necessary to execute this query' ); } // Sort the joins $parameters = array(); $joins = $this->getOrderedJoins($this->from); // Build from clauses foreach ($joins as $alias => $join) { // $join can be something like this array structure // array('type' => 'inner', 'table' => 'SiteTree', 'filter' => array("SiteTree.ID = 1", // "Status = 'approved'", 'order' => 20)) if (!is_array($join)) { if (empty($alias) || is_numeric($alias)) { continue; } if (preg_match('/AS\s+(?:"[^"]+"|[A-Z0-9_]+)\s*$/i', $join)) { // custom aliases override the ones defined through array keys // this is only meant to keep backward compatibility with SS <= 4.3, // to be removed in SS5 continue; } $trimmedAlias = trim($alias, '"'); if ($trimmedAlias !== trim($join, '"')) { $joins[$alias] = "{$join} AS \"{$trimmedAlias}\""; } continue; } if (is_string($join['filter'])) { $filter = $join['filter']; } elseif (sizeof($join['filter']) == 1) { $filter = $join['filter'][0]; } else { $filter = "(" . implode(") AND (", $join['filter']) . ")"; } // Ensure tables are quoted, unless the table is actually a sub-select $table = preg_match('/\bSELECT\b/i', $join['table']) ? $join['table'] : "\"{$join['table']}\""; $aliasClause = ($alias != $join['table']) ? " AS \"{$alias}\"" : ""; $joins[$alias] = strtoupper($join['type']) . " JOIN " . $table . "$aliasClause ON $filter"; if (!empty($join['parameters'])) { $parameters = array_merge($parameters, $join['parameters']); } } return $joins; }
[ "public", "function", "getJoins", "(", "&", "$", "parameters", "=", "array", "(", ")", ")", "{", "if", "(", "func_num_args", "(", ")", "==", "0", ")", "{", "Deprecation", "::", "notice", "(", "'4.0'", ",", "'SQLConditionalExpression::getJoins() now may produce parameters which are necessary to\n\t\t\t\texecute this query'", ")", ";", "}", "// Sort the joins", "$", "parameters", "=", "array", "(", ")", ";", "$", "joins", "=", "$", "this", "->", "getOrderedJoins", "(", "$", "this", "->", "from", ")", ";", "// Build from clauses", "foreach", "(", "$", "joins", "as", "$", "alias", "=>", "$", "join", ")", "{", "// $join can be something like this array structure", "// array('type' => 'inner', 'table' => 'SiteTree', 'filter' => array(\"SiteTree.ID = 1\",", "// \"Status = 'approved'\", 'order' => 20))", "if", "(", "!", "is_array", "(", "$", "join", ")", ")", "{", "if", "(", "empty", "(", "$", "alias", ")", "||", "is_numeric", "(", "$", "alias", ")", ")", "{", "continue", ";", "}", "if", "(", "preg_match", "(", "'/AS\\s+(?:\"[^\"]+\"|[A-Z0-9_]+)\\s*$/i'", ",", "$", "join", ")", ")", "{", "// custom aliases override the ones defined through array keys", "// this is only meant to keep backward compatibility with SS <= 4.3,", "// to be removed in SS5", "continue", ";", "}", "$", "trimmedAlias", "=", "trim", "(", "$", "alias", ",", "'\"'", ")", ";", "if", "(", "$", "trimmedAlias", "!==", "trim", "(", "$", "join", ",", "'\"'", ")", ")", "{", "$", "joins", "[", "$", "alias", "]", "=", "\"{$join} AS \\\"{$trimmedAlias}\\\"\"", ";", "}", "continue", ";", "}", "if", "(", "is_string", "(", "$", "join", "[", "'filter'", "]", ")", ")", "{", "$", "filter", "=", "$", "join", "[", "'filter'", "]", ";", "}", "elseif", "(", "sizeof", "(", "$", "join", "[", "'filter'", "]", ")", "==", "1", ")", "{", "$", "filter", "=", "$", "join", "[", "'filter'", "]", "[", "0", "]", ";", "}", "else", "{", "$", "filter", "=", "\"(\"", ".", "implode", "(", "\") AND (\"", ",", "$", "join", "[", "'filter'", "]", ")", ".", "\")\"", ";", "}", "// Ensure tables are quoted, unless the table is actually a sub-select", "$", "table", "=", "preg_match", "(", "'/\\bSELECT\\b/i'", ",", "$", "join", "[", "'table'", "]", ")", "?", "$", "join", "[", "'table'", "]", ":", "\"\\\"{$join['table']}\\\"\"", ";", "$", "aliasClause", "=", "(", "$", "alias", "!=", "$", "join", "[", "'table'", "]", ")", "?", "\" AS \\\"{$alias}\\\"\"", ":", "\"\"", ";", "$", "joins", "[", "$", "alias", "]", "=", "strtoupper", "(", "$", "join", "[", "'type'", "]", ")", ".", "\" JOIN \"", ".", "$", "table", ".", "\"$aliasClause ON $filter\"", ";", "if", "(", "!", "empty", "(", "$", "join", "[", "'parameters'", "]", ")", ")", "{", "$", "parameters", "=", "array_merge", "(", "$", "parameters", ",", "$", "join", "[", "'parameters'", "]", ")", ";", "}", "}", "return", "$", "joins", ";", "}" ]
Retrieves the finalised list of joins @todo This part of the code could be simplified @param array $parameters Out variable for parameters required for this query @return array List of joins as a mapping from array('Alias' => 'Join Expression')
[ "Retrieves", "the", "finalised", "list", "of", "joins" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLConditionalExpression.php#L266-L328
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
SQLConditionalExpression.setWhere
public function setWhere($where) { $where = func_num_args() > 1 ? func_get_args() : $where; $this->where = array(); return $this->addWhere($where); }
php
public function setWhere($where) { $where = func_num_args() > 1 ? func_get_args() : $where; $this->where = array(); return $this->addWhere($where); }
[ "public", "function", "setWhere", "(", "$", "where", ")", "{", "$", "where", "=", "func_num_args", "(", ")", ">", "1", "?", "func_get_args", "(", ")", ":", "$", "where", ";", "$", "this", "->", "where", "=", "array", "(", ")", ";", "return", "$", "this", "->", "addWhere", "(", "$", "where", ")", ";", "}" ]
Set a WHERE clause. @see SQLConditionalExpression::addWhere() for syntax examples @param mixed $where Predicate(s) to set, as escaped SQL statements or paramaterised queries @param mixed $where,... Unlimited additional predicates @return $this Self reference
[ "Set", "a", "WHERE", "clause", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLConditionalExpression.php#L433-L438
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLConditionalExpression.php
SQLConditionalExpression.filtersOnID
public function filtersOnID() { $regexp = '/^(.*\.)?("|`)?ID("|`)?\s?(=|IN)/'; foreach ($this->getWhereParameterised($parameters) as $predicate) { if (preg_match($regexp, $predicate)) { return true; } } return false; }
php
public function filtersOnID() { $regexp = '/^(.*\.)?("|`)?ID("|`)?\s?(=|IN)/'; foreach ($this->getWhereParameterised($parameters) as $predicate) { if (preg_match($regexp, $predicate)) { return true; } } return false; }
[ "public", "function", "filtersOnID", "(", ")", "{", "$", "regexp", "=", "'/^(.*\\.)?(\"|`)?ID(\"|`)?\\s?(=|IN)/'", ";", "foreach", "(", "$", "this", "->", "getWhereParameterised", "(", "$", "parameters", ")", "as", "$", "predicate", ")", "{", "if", "(", "preg_match", "(", "$", "regexp", ",", "$", "predicate", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether this query is for a specific ID in a table @todo Doesn't work with combined statements (e.g. "Foo='bar' AND ID=5") @return boolean
[ "Checks", "whether", "this", "query", "is", "for", "a", "specific", "ID", "in", "a", "table" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLConditionalExpression.php#L720-L731
train
silverstripe/silverstripe-framework
src/Core/Cache/DefaultCacheFactory.php
DefaultCacheFactory.isAPCUSupported
protected function isAPCUSupported() { static $apcuSupported = null; if (null === $apcuSupported) { // Need to check for CLI because Symfony won't: https://github.com/symfony/symfony/pull/25080 $apcuSupported = Director::is_cli() ? ini_get('apc.enable_cli') && ApcuAdapter::isSupported() : ApcuAdapter::isSupported(); } return $apcuSupported; }
php
protected function isAPCUSupported() { static $apcuSupported = null; if (null === $apcuSupported) { // Need to check for CLI because Symfony won't: https://github.com/symfony/symfony/pull/25080 $apcuSupported = Director::is_cli() ? ini_get('apc.enable_cli') && ApcuAdapter::isSupported() : ApcuAdapter::isSupported(); } return $apcuSupported; }
[ "protected", "function", "isAPCUSupported", "(", ")", "{", "static", "$", "apcuSupported", "=", "null", ";", "if", "(", "null", "===", "$", "apcuSupported", ")", "{", "// Need to check for CLI because Symfony won't: https://github.com/symfony/symfony/pull/25080", "$", "apcuSupported", "=", "Director", "::", "is_cli", "(", ")", "?", "ini_get", "(", "'apc.enable_cli'", ")", "&&", "ApcuAdapter", "::", "isSupported", "(", ")", ":", "ApcuAdapter", "::", "isSupported", "(", ")", ";", "}", "return", "$", "apcuSupported", ";", "}" ]
Determine if apcu is supported @return bool
[ "Determine", "if", "apcu", "is", "supported" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Core/Cache/DefaultCacheFactory.php#L85-L93
train
silverstripe/silverstripe-framework
src/Forms/NumericField.php
NumericField.getFormatter
protected function getFormatter() { if ($this->getHTML5()) { // Locale-independent html5 number formatter $formatter = NumberFormatter::create( i18n::config()->uninherited('default_locale'), NumberFormatter::DECIMAL ); $formatter->setAttribute(NumberFormatter::GROUPING_USED, false); $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, '.'); } else { // Locale-specific number formatter $formatter = NumberFormatter::create($this->getLocale(), NumberFormatter::DECIMAL); } // Set decimal precision $scale = $this->getScale(); if ($scale === 0) { $formatter->setAttribute(NumberFormatter::DECIMAL_ALWAYS_SHOWN, false); $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 0); } else { $formatter->setAttribute(NumberFormatter::DECIMAL_ALWAYS_SHOWN, true); if ($scale === null) { // At least one digit to distinguish floating point from integer $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 1); } else { $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $scale); } } return $formatter; }
php
protected function getFormatter() { if ($this->getHTML5()) { // Locale-independent html5 number formatter $formatter = NumberFormatter::create( i18n::config()->uninherited('default_locale'), NumberFormatter::DECIMAL ); $formatter->setAttribute(NumberFormatter::GROUPING_USED, false); $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, '.'); } else { // Locale-specific number formatter $formatter = NumberFormatter::create($this->getLocale(), NumberFormatter::DECIMAL); } // Set decimal precision $scale = $this->getScale(); if ($scale === 0) { $formatter->setAttribute(NumberFormatter::DECIMAL_ALWAYS_SHOWN, false); $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 0); } else { $formatter->setAttribute(NumberFormatter::DECIMAL_ALWAYS_SHOWN, true); if ($scale === null) { // At least one digit to distinguish floating point from integer $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 1); } else { $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $scale); } } return $formatter; }
[ "protected", "function", "getFormatter", "(", ")", "{", "if", "(", "$", "this", "->", "getHTML5", "(", ")", ")", "{", "// Locale-independent html5 number formatter", "$", "formatter", "=", "NumberFormatter", "::", "create", "(", "i18n", "::", "config", "(", ")", "->", "uninherited", "(", "'default_locale'", ")", ",", "NumberFormatter", "::", "DECIMAL", ")", ";", "$", "formatter", "->", "setAttribute", "(", "NumberFormatter", "::", "GROUPING_USED", ",", "false", ")", ";", "$", "formatter", "->", "setSymbol", "(", "NumberFormatter", "::", "DECIMAL_SEPARATOR_SYMBOL", ",", "'.'", ")", ";", "}", "else", "{", "// Locale-specific number formatter", "$", "formatter", "=", "NumberFormatter", "::", "create", "(", "$", "this", "->", "getLocale", "(", ")", ",", "NumberFormatter", "::", "DECIMAL", ")", ";", "}", "// Set decimal precision", "$", "scale", "=", "$", "this", "->", "getScale", "(", ")", ";", "if", "(", "$", "scale", "===", "0", ")", "{", "$", "formatter", "->", "setAttribute", "(", "NumberFormatter", "::", "DECIMAL_ALWAYS_SHOWN", ",", "false", ")", ";", "$", "formatter", "->", "setAttribute", "(", "NumberFormatter", "::", "FRACTION_DIGITS", ",", "0", ")", ";", "}", "else", "{", "$", "formatter", "->", "setAttribute", "(", "NumberFormatter", "::", "DECIMAL_ALWAYS_SHOWN", ",", "true", ")", ";", "if", "(", "$", "scale", "===", "null", ")", "{", "// At least one digit to distinguish floating point from integer", "$", "formatter", "->", "setAttribute", "(", "NumberFormatter", "::", "MIN_FRACTION_DIGITS", ",", "1", ")", ";", "}", "else", "{", "$", "formatter", "->", "setAttribute", "(", "NumberFormatter", "::", "FRACTION_DIGITS", ",", "$", "scale", ")", ";", "}", "}", "return", "$", "formatter", ";", "}" ]
Get number formatter for localising this field @return NumberFormatter
[ "Get", "number", "formatter", "for", "localising", "this", "field" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/NumericField.php#L56-L86
train
silverstripe/silverstripe-framework
src/Forms/NumericField.php
NumericField.Value
public function Value() { // Show invalid value back to user in case of error if ($this->value === null || $this->value === false) { return $this->originalValue; } $formatter = $this->getFormatter(); return $formatter->format($this->value, $this->getNumberType()); }
php
public function Value() { // Show invalid value back to user in case of error if ($this->value === null || $this->value === false) { return $this->originalValue; } $formatter = $this->getFormatter(); return $formatter->format($this->value, $this->getNumberType()); }
[ "public", "function", "Value", "(", ")", "{", "// Show invalid value back to user in case of error", "if", "(", "$", "this", "->", "value", "===", "null", "||", "$", "this", "->", "value", "===", "false", ")", "{", "return", "$", "this", "->", "originalValue", ";", "}", "$", "formatter", "=", "$", "this", "->", "getFormatter", "(", ")", ";", "return", "$", "formatter", "->", "format", "(", "$", "this", "->", "value", ",", "$", "this", "->", "getNumberType", "(", ")", ")", ";", "}" ]
Format value for output @return string
[ "Format", "value", "for", "output" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/NumericField.php#L132-L140
train
silverstripe/silverstripe-framework
src/Forms/NumericField.php
NumericField.cast
protected function cast($value) { if (strlen($value) === 0) { return null; } if ($this->getScale() === 0) { return (int)$value; } return (float)$value; }
php
protected function cast($value) { if (strlen($value) === 0) { return null; } if ($this->getScale() === 0) { return (int)$value; } return (float)$value; }
[ "protected", "function", "cast", "(", "$", "value", ")", "{", "if", "(", "strlen", "(", "$", "value", ")", "===", "0", ")", "{", "return", "null", ";", "}", "if", "(", "$", "this", "->", "getScale", "(", ")", "===", "0", ")", "{", "return", "(", "int", ")", "$", "value", ";", "}", "return", "(", "float", ")", "$", "value", ";", "}" ]
Helper to cast non-localised strings to their native type @param string $value @return float|int
[ "Helper", "to", "cast", "non", "-", "localised", "strings", "to", "their", "native", "type" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/NumericField.php#L155-L164
train
silverstripe/silverstripe-framework
src/Forms/FormMessage.php
FormMessage.setMessage
public function setMessage( $message, $messageType = ValidationResult::TYPE_ERROR, $messageCast = ValidationResult::CAST_TEXT ) { if (!in_array($messageCast, [ValidationResult::CAST_TEXT, ValidationResult::CAST_HTML])) { throw new InvalidArgumentException("Invalid message cast type"); } $this->message = $message; $this->messageType = $messageType; $this->messageCast = $messageCast; return $this; }
php
public function setMessage( $message, $messageType = ValidationResult::TYPE_ERROR, $messageCast = ValidationResult::CAST_TEXT ) { if (!in_array($messageCast, [ValidationResult::CAST_TEXT, ValidationResult::CAST_HTML])) { throw new InvalidArgumentException("Invalid message cast type"); } $this->message = $message; $this->messageType = $messageType; $this->messageCast = $messageCast; return $this; }
[ "public", "function", "setMessage", "(", "$", "message", ",", "$", "messageType", "=", "ValidationResult", "::", "TYPE_ERROR", ",", "$", "messageCast", "=", "ValidationResult", "::", "CAST_TEXT", ")", "{", "if", "(", "!", "in_array", "(", "$", "messageCast", ",", "[", "ValidationResult", "::", "CAST_TEXT", ",", "ValidationResult", "::", "CAST_HTML", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid message cast type\"", ")", ";", "}", "$", "this", "->", "message", "=", "$", "message", ";", "$", "this", "->", "messageType", "=", "$", "messageType", ";", "$", "this", "->", "messageCast", "=", "$", "messageCast", ";", "return", "$", "this", ";", "}" ]
Sets the error message to be displayed on the form field. Allows HTML content, so remember to use Convert::raw2xml(). @param string $message Message string @param string $messageType Message type @param string $messageCast @return $this
[ "Sets", "the", "error", "message", "to", "be", "displayed", "on", "the", "form", "field", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormMessage.php#L81-L93
train
silverstripe/silverstripe-framework
src/Forms/FormMessage.php
FormMessage.getSchemaMessage
public function getSchemaMessage() { $message = $this->getMessage(); if (!$message) { return null; } // Form schema messages treat simple strings as plain text, so nest for html messages if ($this->getMessageCast() === ValidationResult::CAST_HTML) { $message = ['html' => $message]; } return [ 'value' => $message, 'type' => $this->getMessageType(), ]; }
php
public function getSchemaMessage() { $message = $this->getMessage(); if (!$message) { return null; } // Form schema messages treat simple strings as plain text, so nest for html messages if ($this->getMessageCast() === ValidationResult::CAST_HTML) { $message = ['html' => $message]; } return [ 'value' => $message, 'type' => $this->getMessageType(), ]; }
[ "public", "function", "getSchemaMessage", "(", ")", "{", "$", "message", "=", "$", "this", "->", "getMessage", "(", ")", ";", "if", "(", "!", "$", "message", ")", "{", "return", "null", ";", "}", "// Form schema messages treat simple strings as plain text, so nest for html messages", "if", "(", "$", "this", "->", "getMessageCast", "(", ")", "===", "ValidationResult", "::", "CAST_HTML", ")", "{", "$", "message", "=", "[", "'html'", "=>", "$", "message", "]", ";", "}", "return", "[", "'value'", "=>", "$", "message", ",", "'type'", "=>", "$", "this", "->", "getMessageType", "(", ")", ",", "]", ";", "}" ]
Get form schema encoded message @return array|null Message in array format, or null if no message
[ "Get", "form", "schema", "encoded", "message" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/FormMessage.php#L117-L131
train
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
TrustedProxyMiddleware.isTrustedProxy
protected function isTrustedProxy(HTTPRequest $request) { $trustedIPs = $this->getTrustedProxyIPs(); // Disabled if (empty($trustedIPs) || $trustedIPs === 'none') { return false; } // Allow all if ($trustedIPs === '*') { return true; } // Validate IP address $ip = $request->getIP(); if ($ip) { return IPUtils::checkIP($ip, preg_split('/\s*,\s*/', $trustedIPs)); } return false; }
php
protected function isTrustedProxy(HTTPRequest $request) { $trustedIPs = $this->getTrustedProxyIPs(); // Disabled if (empty($trustedIPs) || $trustedIPs === 'none') { return false; } // Allow all if ($trustedIPs === '*') { return true; } // Validate IP address $ip = $request->getIP(); if ($ip) { return IPUtils::checkIP($ip, preg_split('/\s*,\s*/', $trustedIPs)); } return false; }
[ "protected", "function", "isTrustedProxy", "(", "HTTPRequest", "$", "request", ")", "{", "$", "trustedIPs", "=", "$", "this", "->", "getTrustedProxyIPs", "(", ")", ";", "// Disabled", "if", "(", "empty", "(", "$", "trustedIPs", ")", "||", "$", "trustedIPs", "===", "'none'", ")", "{", "return", "false", ";", "}", "// Allow all", "if", "(", "$", "trustedIPs", "===", "'*'", ")", "{", "return", "true", ";", "}", "// Validate IP address", "$", "ip", "=", "$", "request", "->", "getIP", "(", ")", ";", "if", "(", "$", "ip", ")", "{", "return", "IPUtils", "::", "checkIP", "(", "$", "ip", ",", "preg_split", "(", "'/\\s*,\\s*/'", ",", "$", "trustedIPs", ")", ")", ";", "}", "return", "false", ";", "}" ]
Determine if the current request is coming from a trusted proxy @param HTTPRequest $request @return bool True if the request's source IP is a trusted proxy
[ "Determine", "if", "the", "current", "request", "is", "coming", "from", "a", "trusted", "proxy" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/TrustedProxyMiddleware.php#L185-L206
train
silverstripe/silverstripe-framework
src/Control/Middleware/TrustedProxyMiddleware.php
TrustedProxyMiddleware.getIPFromHeaderValue
protected function getIPFromHeaderValue($headerValue) { // Sometimes the IP from a load balancer could be "x.x.x.x, y.y.y.y, z.z.z.z" // so we need to find the most likely candidate $ips = preg_split('/\s*,\s*/', $headerValue); // Prioritise filters $filters = [ FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE, FILTER_FLAG_NO_PRIV_RANGE, null ]; foreach ($filters as $filter) { // Find best IP foreach ($ips as $ip) { if (filter_var($ip, FILTER_VALIDATE_IP, $filter)) { return $ip; } } } return null; }
php
protected function getIPFromHeaderValue($headerValue) { // Sometimes the IP from a load balancer could be "x.x.x.x, y.y.y.y, z.z.z.z" // so we need to find the most likely candidate $ips = preg_split('/\s*,\s*/', $headerValue); // Prioritise filters $filters = [ FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE, FILTER_FLAG_NO_PRIV_RANGE, null ]; foreach ($filters as $filter) { // Find best IP foreach ($ips as $ip) { if (filter_var($ip, FILTER_VALIDATE_IP, $filter)) { return $ip; } } } return null; }
[ "protected", "function", "getIPFromHeaderValue", "(", "$", "headerValue", ")", "{", "// Sometimes the IP from a load balancer could be \"x.x.x.x, y.y.y.y, z.z.z.z\"", "// so we need to find the most likely candidate", "$", "ips", "=", "preg_split", "(", "'/\\s*,\\s*/'", ",", "$", "headerValue", ")", ";", "// Prioritise filters", "$", "filters", "=", "[", "FILTER_FLAG_NO_PRIV_RANGE", "|", "FILTER_FLAG_NO_RES_RANGE", ",", "FILTER_FLAG_NO_PRIV_RANGE", ",", "null", "]", ";", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "// Find best IP", "foreach", "(", "$", "ips", "as", "$", "ip", ")", "{", "if", "(", "filter_var", "(", "$", "ip", ",", "FILTER_VALIDATE_IP", ",", "$", "filter", ")", ")", "{", "return", "$", "ip", ";", "}", "}", "}", "return", "null", ";", "}" ]
Extract an IP address from a header value that has been obtained. Accepts single IP or comma separated string of IPs @param string $headerValue The value from a trusted header @return string The IP address
[ "Extract", "an", "IP", "address", "from", "a", "header", "value", "that", "has", "been", "obtained", ".", "Accepts", "single", "IP", "or", "comma", "separated", "string", "of", "IPs" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Middleware/TrustedProxyMiddleware.php#L215-L236
train
silverstripe/silverstripe-framework
src/i18n/Messages/Symfony/ModuleYamlLoader.php
ModuleYamlLoader.normaliseMessages
protected function normaliseMessages($messages, $locale) { foreach ($messages as $key => $value) { $messages[$key] = $this->normaliseMessage($key, $value, $locale); } return $messages; }
php
protected function normaliseMessages($messages, $locale) { foreach ($messages as $key => $value) { $messages[$key] = $this->normaliseMessage($key, $value, $locale); } return $messages; }
[ "protected", "function", "normaliseMessages", "(", "$", "messages", ",", "$", "locale", ")", "{", "foreach", "(", "$", "messages", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "messages", "[", "$", "key", "]", "=", "$", "this", "->", "normaliseMessage", "(", "$", "key", ",", "$", "value", ",", "$", "locale", ")", ";", "}", "return", "$", "messages", ";", "}" ]
Normalises plurals in messages from rails-yaml format to symfony. @param array $messages List of messages @param string $locale @return array Normalised messages
[ "Normalises", "plurals", "in", "messages", "from", "rails", "-", "yaml", "format", "to", "symfony", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/Messages/Symfony/ModuleYamlLoader.php#L84-L90
train
silverstripe/silverstripe-framework
src/i18n/Messages/Symfony/ModuleYamlLoader.php
ModuleYamlLoader.normaliseMessage
protected function normaliseMessage($key, $value, $locale) { if (!is_array($value)) { return $value; } if (isset($value['default'])) { return $value['default']; } // Plurals $pluralised = i18n::encode_plurals($value); if ($pluralised) { return $pluralised; } // Warn if mismatched plural forms trigger_error("Localisation entity {$locale}.{$key} is invalid", E_USER_WARNING); return null; }
php
protected function normaliseMessage($key, $value, $locale) { if (!is_array($value)) { return $value; } if (isset($value['default'])) { return $value['default']; } // Plurals $pluralised = i18n::encode_plurals($value); if ($pluralised) { return $pluralised; } // Warn if mismatched plural forms trigger_error("Localisation entity {$locale}.{$key} is invalid", E_USER_WARNING); return null; }
[ "protected", "function", "normaliseMessage", "(", "$", "key", ",", "$", "value", ",", "$", "locale", ")", "{", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "if", "(", "isset", "(", "$", "value", "[", "'default'", "]", ")", ")", "{", "return", "$", "value", "[", "'default'", "]", ";", "}", "// Plurals", "$", "pluralised", "=", "i18n", "::", "encode_plurals", "(", "$", "value", ")", ";", "if", "(", "$", "pluralised", ")", "{", "return", "$", "pluralised", ";", "}", "// Warn if mismatched plural forms", "trigger_error", "(", "\"Localisation entity {$locale}.{$key} is invalid\"", ",", "E_USER_WARNING", ")", ";", "return", "null", ";", "}" ]
Normalise rails-yaml plurals into pipe-separated rules @link http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html @link http://guides.rubyonrails.org/i18n.html#pluralization @link http://symfony.com/doc/current/components/translation/usage.html#component-translation-pluralization @param string $key @param mixed $value Input value @param string $locale @return string
[ "Normalise", "rails", "-", "yaml", "plurals", "into", "pipe", "-", "separated", "rules" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/i18n/Messages/Symfony/ModuleYamlLoader.php#L104-L121
train
silverstripe/silverstripe-framework
src/ORM/RelationList.php
RelationList.forForeignID
public function forForeignID($id) { // Turn a 1-element array into a simple value if (is_array($id) && sizeof($id) == 1) { $id = reset($id); } // Calculate the new filter $filter = $this->foreignIDFilter($id); $list = $this->alterDataQuery(function (DataQuery $query) use ($id, $filter) { // Check if there is an existing filter, remove if there is $currentFilter = $query->getQueryParam('Foreign.Filter'); if ($currentFilter) { try { $query->removeFilterOn($currentFilter); } catch (Exception $e) { /* NOP */ } } // Add the new filter $query->setQueryParam('Foreign.ID', $id); $query->setQueryParam('Foreign.Filter', $filter); $query->where($filter); }); return $list; }
php
public function forForeignID($id) { // Turn a 1-element array into a simple value if (is_array($id) && sizeof($id) == 1) { $id = reset($id); } // Calculate the new filter $filter = $this->foreignIDFilter($id); $list = $this->alterDataQuery(function (DataQuery $query) use ($id, $filter) { // Check if there is an existing filter, remove if there is $currentFilter = $query->getQueryParam('Foreign.Filter'); if ($currentFilter) { try { $query->removeFilterOn($currentFilter); } catch (Exception $e) { /* NOP */ } } // Add the new filter $query->setQueryParam('Foreign.ID', $id); $query->setQueryParam('Foreign.Filter', $filter); $query->where($filter); }); return $list; }
[ "public", "function", "forForeignID", "(", "$", "id", ")", "{", "// Turn a 1-element array into a simple value", "if", "(", "is_array", "(", "$", "id", ")", "&&", "sizeof", "(", "$", "id", ")", "==", "1", ")", "{", "$", "id", "=", "reset", "(", "$", "id", ")", ";", "}", "// Calculate the new filter", "$", "filter", "=", "$", "this", "->", "foreignIDFilter", "(", "$", "id", ")", ";", "$", "list", "=", "$", "this", "->", "alterDataQuery", "(", "function", "(", "DataQuery", "$", "query", ")", "use", "(", "$", "id", ",", "$", "filter", ")", "{", "// Check if there is an existing filter, remove if there is", "$", "currentFilter", "=", "$", "query", "->", "getQueryParam", "(", "'Foreign.Filter'", ")", ";", "if", "(", "$", "currentFilter", ")", "{", "try", "{", "$", "query", "->", "removeFilterOn", "(", "$", "currentFilter", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "/* NOP */", "}", "}", "// Add the new filter", "$", "query", "->", "setQueryParam", "(", "'Foreign.ID'", ",", "$", "id", ")", ";", "$", "query", "->", "setQueryParam", "(", "'Foreign.Filter'", ",", "$", "filter", ")", ";", "$", "query", "->", "where", "(", "$", "filter", ")", ";", "}", ")", ";", "return", "$", "list", ";", "}" ]
Returns a copy of this list with the ManyMany relationship linked to the given foreign ID. @param int|array $id An ID or an array of IDs. @return static
[ "Returns", "a", "copy", "of", "this", "list", "with", "the", "ManyMany", "relationship", "linked", "to", "the", "given", "foreign", "ID", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/RelationList.php#L48-L76
train
silverstripe/silverstripe-framework
src/Security/BasicAuthMiddleware.php
BasicAuthMiddleware.checkMatchingURL
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; }
php
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; }
[ "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.
[ "Check", "if", "global", "basic", "auth", "is", "enabled", "for", "the", "given", "request" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/BasicAuthMiddleware.php#L99-L117
train
silverstripe/silverstripe-framework
src/Forms/SelectField.php
SelectField.getListMap
protected function getListMap($source) { // Extract source as an array if ($source instanceof SS_List) { $source = $source->map(); } if ($source instanceof Map) { $source = $source->toArray(); } if (!is_array($source) && !($source instanceof ArrayAccess)) { user_error('$source passed in as invalid type', E_USER_ERROR); } return $source; }
php
protected function getListMap($source) { // Extract source as an array if ($source instanceof SS_List) { $source = $source->map(); } if ($source instanceof Map) { $source = $source->toArray(); } if (!is_array($source) && !($source instanceof ArrayAccess)) { user_error('$source passed in as invalid type', E_USER_ERROR); } return $source; }
[ "protected", "function", "getListMap", "(", "$", "source", ")", "{", "// Extract source as an array", "if", "(", "$", "source", "instanceof", "SS_List", ")", "{", "$", "source", "=", "$", "source", "->", "map", "(", ")", ";", "}", "if", "(", "$", "source", "instanceof", "Map", ")", "{", "$", "source", "=", "$", "source", "->", "toArray", "(", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "source", ")", "&&", "!", "(", "$", "source", "instanceof", "ArrayAccess", ")", ")", "{", "user_error", "(", "'$source passed in as invalid type'", ",", "E_USER_ERROR", ")", ";", "}", "return", "$", "source", ";", "}" ]
Given a list of values, extract the associative map of id => title @param mixed $source @return array Associative array of ids and titles
[ "Given", "a", "list", "of", "values", "extract", "the", "associative", "map", "of", "id", "=", ">", "title" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/SelectField.php#L166-L180
train
silverstripe/silverstripe-framework
src/Forms/SelectField.php
SelectField.isSelectedValue
public function isSelectedValue($dataValue, $userValue) { if ($dataValue === $userValue) { return true; } // Allow null to match empty strings if ($dataValue === '' && $userValue === null) { return true; } // Safety check against casting arrays as strings in PHP>5.4 if (is_array($dataValue) || is_array($userValue)) { return false; } // For non-falsey values do loose comparison if ($dataValue) { return $dataValue == $userValue; } // For empty values, use string comparison to perform visible value match return ((string) $dataValue) === ((string) $userValue); }
php
public function isSelectedValue($dataValue, $userValue) { if ($dataValue === $userValue) { return true; } // Allow null to match empty strings if ($dataValue === '' && $userValue === null) { return true; } // Safety check against casting arrays as strings in PHP>5.4 if (is_array($dataValue) || is_array($userValue)) { return false; } // For non-falsey values do loose comparison if ($dataValue) { return $dataValue == $userValue; } // For empty values, use string comparison to perform visible value match return ((string) $dataValue) === ((string) $userValue); }
[ "public", "function", "isSelectedValue", "(", "$", "dataValue", ",", "$", "userValue", ")", "{", "if", "(", "$", "dataValue", "===", "$", "userValue", ")", "{", "return", "true", ";", "}", "// Allow null to match empty strings", "if", "(", "$", "dataValue", "===", "''", "&&", "$", "userValue", "===", "null", ")", "{", "return", "true", ";", "}", "// Safety check against casting arrays as strings in PHP>5.4", "if", "(", "is_array", "(", "$", "dataValue", ")", "||", "is_array", "(", "$", "userValue", ")", ")", "{", "return", "false", ";", "}", "// For non-falsey values do loose comparison", "if", "(", "$", "dataValue", ")", "{", "return", "$", "dataValue", "==", "$", "userValue", ";", "}", "// For empty values, use string comparison to perform visible value match", "return", "(", "(", "string", ")", "$", "dataValue", ")", "===", "(", "(", "string", ")", "$", "userValue", ")", ";", "}" ]
Determine if the current value of this field matches the given option value @param mixed $dataValue The value as extracted from the source of this field (or empty value if available) @param mixed $userValue The value as submitted by the user @return boolean True if the selected value matches the given option value
[ "Determine", "if", "the", "current", "value", "of", "this", "field", "matches", "the", "given", "option", "value" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/SelectField.php#L216-L239
train
silverstripe/silverstripe-framework
src/Forms/SelectField.php
SelectField.castedCopy
public function castedCopy($classOrCopy) { $field = parent::castedCopy($classOrCopy); if ($field instanceof SelectField) { $field->setSource($this->getSource()); } return $field; }
php
public function castedCopy($classOrCopy) { $field = parent::castedCopy($classOrCopy); if ($field instanceof SelectField) { $field->setSource($this->getSource()); } return $field; }
[ "public", "function", "castedCopy", "(", "$", "classOrCopy", ")", "{", "$", "field", "=", "parent", "::", "castedCopy", "(", "$", "classOrCopy", ")", ";", "if", "(", "$", "field", "instanceof", "SelectField", ")", "{", "$", "field", "->", "setSource", "(", "$", "this", "->", "getSource", "(", ")", ")", ";", "}", "return", "$", "field", ";", "}" ]
Returns another instance of this field, but "cast" to a different class. @see FormField::castedCopy() @param String $classOrCopy @return FormField
[ "Returns", "another", "instance", "of", "this", "field", "but", "cast", "to", "a", "different", "class", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Forms/SelectField.php#L266-L273
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/ChangePasswordHandler.php
ChangePasswordHandler.redirectBackToForm
public function redirectBackToForm() { // Redirect back to form $url = $this->addBackURLParam(Security::singleton()->Link('changepassword')); return $this->redirect($url); }
php
public function redirectBackToForm() { // Redirect back to form $url = $this->addBackURLParam(Security::singleton()->Link('changepassword')); return $this->redirect($url); }
[ "public", "function", "redirectBackToForm", "(", ")", "{", "// Redirect back to form", "$", "url", "=", "$", "this", "->", "addBackURLParam", "(", "Security", "::", "singleton", "(", ")", "->", "Link", "(", "'changepassword'", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "url", ")", ";", "}" ]
Something went wrong, go back to the changepassword @return HTTPResponse
[ "Something", "went", "wrong", "go", "back", "to", "the", "changepassword" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/ChangePasswordHandler.php#L310-L316
train
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/ChangePasswordHandler.php
ChangePasswordHandler.checkPassword
protected function checkPassword($member, $password) { if (empty($password)) { return false; } // With a valid user and password, check the password is correct $authenticators = Security::singleton()->getApplicableAuthenticators(Authenticator::CHECK_PASSWORD); foreach ($authenticators as $authenticator) { if (!$authenticator->checkPassword($member, $password)->isValid()) { return false; } } return true; }
php
protected function checkPassword($member, $password) { if (empty($password)) { return false; } // With a valid user and password, check the password is correct $authenticators = Security::singleton()->getApplicableAuthenticators(Authenticator::CHECK_PASSWORD); foreach ($authenticators as $authenticator) { if (!$authenticator->checkPassword($member, $password)->isValid()) { return false; } } return true; }
[ "protected", "function", "checkPassword", "(", "$", "member", ",", "$", "password", ")", "{", "if", "(", "empty", "(", "$", "password", ")", ")", "{", "return", "false", ";", "}", "// With a valid user and password, check the password is correct", "$", "authenticators", "=", "Security", "::", "singleton", "(", ")", "->", "getApplicableAuthenticators", "(", "Authenticator", "::", "CHECK_PASSWORD", ")", ";", "foreach", "(", "$", "authenticators", "as", "$", "authenticator", ")", "{", "if", "(", "!", "$", "authenticator", "->", "checkPassword", "(", "$", "member", ",", "$", "password", ")", "->", "isValid", "(", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Check if password is ok @param Member $member @param string $password @return bool
[ "Check", "if", "password", "is", "ok" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Security/MemberAuthenticator/ChangePasswordHandler.php#L325-L338
train
silverstripe/silverstripe-framework
src/ORM/Queries/SQLAssignmentRow.php
SQLAssignmentRow.addAssignments
public function addAssignments(array $assignments) { $assignments = $this->normaliseAssignments($assignments); $this->assignments = array_merge($this->assignments, $assignments); return $this; }
php
public function addAssignments(array $assignments) { $assignments = $this->normaliseAssignments($assignments); $this->assignments = array_merge($this->assignments, $assignments); return $this; }
[ "public", "function", "addAssignments", "(", "array", "$", "assignments", ")", "{", "$", "assignments", "=", "$", "this", "->", "normaliseAssignments", "(", "$", "assignments", ")", ";", "$", "this", "->", "assignments", "=", "array_merge", "(", "$", "this", "->", "assignments", ",", "$", "assignments", ")", ";", "return", "$", "this", ";", "}" ]
Adds assignments for a list of several fields Note that field values must not be escaped, as these will be internally parameterised by the database engine. <code> // Basic assignments $query->addAssignments(array( '"Object"."Title"' => 'Bob', '"Object"."Description"' => 'Bob was here' )) // Parameterised assignments $query->addAssignments(array( '"Object"."Title"' => array('?' => 'Bob')), '"Object"."Description"' => array('?' => null)) )) // Complex parameters $query->addAssignments(array( '"Object"."Score"' => array('MAX(?,?)' => array(1, 3)) )); // Assigment of literal SQL for a field. The empty array is // important to denote the zero-number paramater list $query->addAssignments(array( '"Object"."Score"' => array('NOW()' => array()) )); </code> @param array $assignments The list of fields to assign @return $this The self reference to this row
[ "Adds", "assignments", "for", "a", "list", "of", "several", "fields" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/ORM/Queries/SQLAssignmentRow.php#L137-L142
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.handleRequest
public function handleRequest(HTTPRequest $request) { Injector::inst()->registerService($request, HTTPRequest::class); $rules = Director::config()->uninherited('rules'); $this->extend('updateRules', $rules); // Default handler - mo URL rules matched, so return a 404 error. $handler = function () { return new HTTPResponse('No URL rule was matched', 404); }; foreach ($rules as $pattern => $controllerOptions) { // Match pattern $arguments = $request->match($pattern, true); if ($arguments == false) { continue; } // Normalise route rule if (is_string($controllerOptions)) { if (substr($controllerOptions, 0, 2) == '->') { $controllerOptions = array('Redirect' => substr($controllerOptions, 2)); } else { $controllerOptions = array('Controller' => $controllerOptions); } } $request->setRouteParams($controllerOptions); // controllerOptions provide some default arguments $arguments = array_merge($controllerOptions, $arguments); // Pop additional tokens from the tokenizer if necessary if (isset($controllerOptions['_PopTokeniser'])) { $request->shift($controllerOptions['_PopTokeniser']); } // Handler for redirection if (isset($arguments['Redirect'])) { $handler = function () use ($arguments) { // Redirection $response = new HTTPResponse(); $response->redirect(static::absoluteURL($arguments['Redirect'])); return $response; }; break; } // Handler for constructing and calling a controller $handler = function (HTTPRequest $request) use ($arguments) { try { /** @var RequestHandler $controllerObj */ $controllerObj = Injector::inst()->create($arguments['Controller']); return $controllerObj->handleRequest($request); } catch (HTTPResponse_Exception $responseException) { return $responseException->getResponse(); } }; break; } // Call the handler with the configured middlewares $response = $this->callMiddleware($request, $handler); // Note that if a different request was previously registered, this will now be lost // In these cases it's better to use Kernel::nest() prior to kicking off a nested request Injector::inst()->unregisterNamedObject(HTTPRequest::class); return $response; }
php
public function handleRequest(HTTPRequest $request) { Injector::inst()->registerService($request, HTTPRequest::class); $rules = Director::config()->uninherited('rules'); $this->extend('updateRules', $rules); // Default handler - mo URL rules matched, so return a 404 error. $handler = function () { return new HTTPResponse('No URL rule was matched', 404); }; foreach ($rules as $pattern => $controllerOptions) { // Match pattern $arguments = $request->match($pattern, true); if ($arguments == false) { continue; } // Normalise route rule if (is_string($controllerOptions)) { if (substr($controllerOptions, 0, 2) == '->') { $controllerOptions = array('Redirect' => substr($controllerOptions, 2)); } else { $controllerOptions = array('Controller' => $controllerOptions); } } $request->setRouteParams($controllerOptions); // controllerOptions provide some default arguments $arguments = array_merge($controllerOptions, $arguments); // Pop additional tokens from the tokenizer if necessary if (isset($controllerOptions['_PopTokeniser'])) { $request->shift($controllerOptions['_PopTokeniser']); } // Handler for redirection if (isset($arguments['Redirect'])) { $handler = function () use ($arguments) { // Redirection $response = new HTTPResponse(); $response->redirect(static::absoluteURL($arguments['Redirect'])); return $response; }; break; } // Handler for constructing and calling a controller $handler = function (HTTPRequest $request) use ($arguments) { try { /** @var RequestHandler $controllerObj */ $controllerObj = Injector::inst()->create($arguments['Controller']); return $controllerObj->handleRequest($request); } catch (HTTPResponse_Exception $responseException) { return $responseException->getResponse(); } }; break; } // Call the handler with the configured middlewares $response = $this->callMiddleware($request, $handler); // Note that if a different request was previously registered, this will now be lost // In these cases it's better to use Kernel::nest() prior to kicking off a nested request Injector::inst()->unregisterNamedObject(HTTPRequest::class); return $response; }
[ "public", "function", "handleRequest", "(", "HTTPRequest", "$", "request", ")", "{", "Injector", "::", "inst", "(", ")", "->", "registerService", "(", "$", "request", ",", "HTTPRequest", "::", "class", ")", ";", "$", "rules", "=", "Director", "::", "config", "(", ")", "->", "uninherited", "(", "'rules'", ")", ";", "$", "this", "->", "extend", "(", "'updateRules'", ",", "$", "rules", ")", ";", "// Default handler - mo URL rules matched, so return a 404 error.", "$", "handler", "=", "function", "(", ")", "{", "return", "new", "HTTPResponse", "(", "'No URL rule was matched'", ",", "404", ")", ";", "}", ";", "foreach", "(", "$", "rules", "as", "$", "pattern", "=>", "$", "controllerOptions", ")", "{", "// Match pattern", "$", "arguments", "=", "$", "request", "->", "match", "(", "$", "pattern", ",", "true", ")", ";", "if", "(", "$", "arguments", "==", "false", ")", "{", "continue", ";", "}", "// Normalise route rule", "if", "(", "is_string", "(", "$", "controllerOptions", ")", ")", "{", "if", "(", "substr", "(", "$", "controllerOptions", ",", "0", ",", "2", ")", "==", "'->'", ")", "{", "$", "controllerOptions", "=", "array", "(", "'Redirect'", "=>", "substr", "(", "$", "controllerOptions", ",", "2", ")", ")", ";", "}", "else", "{", "$", "controllerOptions", "=", "array", "(", "'Controller'", "=>", "$", "controllerOptions", ")", ";", "}", "}", "$", "request", "->", "setRouteParams", "(", "$", "controllerOptions", ")", ";", "// controllerOptions provide some default arguments", "$", "arguments", "=", "array_merge", "(", "$", "controllerOptions", ",", "$", "arguments", ")", ";", "// Pop additional tokens from the tokenizer if necessary", "if", "(", "isset", "(", "$", "controllerOptions", "[", "'_PopTokeniser'", "]", ")", ")", "{", "$", "request", "->", "shift", "(", "$", "controllerOptions", "[", "'_PopTokeniser'", "]", ")", ";", "}", "// Handler for redirection", "if", "(", "isset", "(", "$", "arguments", "[", "'Redirect'", "]", ")", ")", "{", "$", "handler", "=", "function", "(", ")", "use", "(", "$", "arguments", ")", "{", "// Redirection", "$", "response", "=", "new", "HTTPResponse", "(", ")", ";", "$", "response", "->", "redirect", "(", "static", "::", "absoluteURL", "(", "$", "arguments", "[", "'Redirect'", "]", ")", ")", ";", "return", "$", "response", ";", "}", ";", "break", ";", "}", "// Handler for constructing and calling a controller", "$", "handler", "=", "function", "(", "HTTPRequest", "$", "request", ")", "use", "(", "$", "arguments", ")", "{", "try", "{", "/** @var RequestHandler $controllerObj */", "$", "controllerObj", "=", "Injector", "::", "inst", "(", ")", "->", "create", "(", "$", "arguments", "[", "'Controller'", "]", ")", ";", "return", "$", "controllerObj", "->", "handleRequest", "(", "$", "request", ")", ";", "}", "catch", "(", "HTTPResponse_Exception", "$", "responseException", ")", "{", "return", "$", "responseException", "->", "getResponse", "(", ")", ";", "}", "}", ";", "break", ";", "}", "// Call the handler with the configured middlewares", "$", "response", "=", "$", "this", "->", "callMiddleware", "(", "$", "request", ",", "$", "handler", ")", ";", "// Note that if a different request was previously registered, this will now be lost", "// In these cases it's better to use Kernel::nest() prior to kicking off a nested request", "Injector", "::", "inst", "(", ")", "->", "unregisterNamedObject", "(", "HTTPRequest", "::", "class", ")", ";", "return", "$", "response", ";", "}" ]
Process the given URL, creating the appropriate controller and executing it. Request processing is handled as follows: - Director::handleRequest($request) checks each of the Director rules and identifies a controller to handle this request. - Controller::handleRequest($request) is then called. This will find a rule to handle the URL, and call the rule handling method. - RequestHandler::handleRequest($request) is recursively called whenever a rule handling method returns a RequestHandler object. In addition to request processing, Director will manage the session, and perform the output of the actual response to the browser. @param HTTPRequest $request @return HTTPResponse @throws HTTPResponse_Exception
[ "Process", "the", "given", "URL", "creating", "the", "appropriate", "controller", "and", "executing", "it", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L306-L376
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.absoluteURL
public static function absoluteURL($url, $relativeParent = self::BASE) { if (is_bool($relativeParent)) { // Deprecate old boolean second parameter Deprecation::notice('5.0', 'Director::absoluteURL takes an explicit parent for relative url'); $relativeParent = $relativeParent ? self::BASE : self::REQUEST; } // Check if there is already a protocol given if (preg_match('/^http(s?):\/\//', $url)) { return $url; } // Absolute urls without protocol are added // E.g. //google.com -> http://google.com if (strpos($url, '//') === 0) { return self::protocol() . substr($url, 2); } // Determine method for mapping the parent to this relative url if ($relativeParent === self::ROOT || self::is_root_relative_url($url)) { // Root relative urls always should be evaluated relative to the root $parent = self::protocolAndHost(); } elseif ($relativeParent === self::REQUEST) { // Request relative urls rely on the REQUEST_URI param (old default behaviour) if (!isset($_SERVER['REQUEST_URI'])) { return false; } $parent = dirname($_SERVER['REQUEST_URI'] . 'x'); } else { // Default to respecting site base_url $parent = self::absoluteBaseURL(); } // Map empty urls to relative slash and join to base if (empty($url) || $url === '.' || $url === './') { $url = '/'; } return Controller::join_links($parent, $url); }
php
public static function absoluteURL($url, $relativeParent = self::BASE) { if (is_bool($relativeParent)) { // Deprecate old boolean second parameter Deprecation::notice('5.0', 'Director::absoluteURL takes an explicit parent for relative url'); $relativeParent = $relativeParent ? self::BASE : self::REQUEST; } // Check if there is already a protocol given if (preg_match('/^http(s?):\/\//', $url)) { return $url; } // Absolute urls without protocol are added // E.g. //google.com -> http://google.com if (strpos($url, '//') === 0) { return self::protocol() . substr($url, 2); } // Determine method for mapping the parent to this relative url if ($relativeParent === self::ROOT || self::is_root_relative_url($url)) { // Root relative urls always should be evaluated relative to the root $parent = self::protocolAndHost(); } elseif ($relativeParent === self::REQUEST) { // Request relative urls rely on the REQUEST_URI param (old default behaviour) if (!isset($_SERVER['REQUEST_URI'])) { return false; } $parent = dirname($_SERVER['REQUEST_URI'] . 'x'); } else { // Default to respecting site base_url $parent = self::absoluteBaseURL(); } // Map empty urls to relative slash and join to base if (empty($url) || $url === '.' || $url === './') { $url = '/'; } return Controller::join_links($parent, $url); }
[ "public", "static", "function", "absoluteURL", "(", "$", "url", ",", "$", "relativeParent", "=", "self", "::", "BASE", ")", "{", "if", "(", "is_bool", "(", "$", "relativeParent", ")", ")", "{", "// Deprecate old boolean second parameter", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'Director::absoluteURL takes an explicit parent for relative url'", ")", ";", "$", "relativeParent", "=", "$", "relativeParent", "?", "self", "::", "BASE", ":", "self", "::", "REQUEST", ";", "}", "// Check if there is already a protocol given", "if", "(", "preg_match", "(", "'/^http(s?):\\/\\//'", ",", "$", "url", ")", ")", "{", "return", "$", "url", ";", "}", "// Absolute urls without protocol are added", "// E.g. //google.com -> http://google.com", "if", "(", "strpos", "(", "$", "url", ",", "'//'", ")", "===", "0", ")", "{", "return", "self", "::", "protocol", "(", ")", ".", "substr", "(", "$", "url", ",", "2", ")", ";", "}", "// Determine method for mapping the parent to this relative url", "if", "(", "$", "relativeParent", "===", "self", "::", "ROOT", "||", "self", "::", "is_root_relative_url", "(", "$", "url", ")", ")", "{", "// Root relative urls always should be evaluated relative to the root", "$", "parent", "=", "self", "::", "protocolAndHost", "(", ")", ";", "}", "elseif", "(", "$", "relativeParent", "===", "self", "::", "REQUEST", ")", "{", "// Request relative urls rely on the REQUEST_URI param (old default behaviour)", "if", "(", "!", "isset", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ")", ")", "{", "return", "false", ";", "}", "$", "parent", "=", "dirname", "(", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ".", "'x'", ")", ";", "}", "else", "{", "// Default to respecting site base_url", "$", "parent", "=", "self", "::", "absoluteBaseURL", "(", ")", ";", "}", "// Map empty urls to relative slash and join to base", "if", "(", "empty", "(", "$", "url", ")", "||", "$", "url", "===", "'.'", "||", "$", "url", "===", "'./'", ")", "{", "$", "url", "=", "'/'", ";", "}", "return", "Controller", "::", "join_links", "(", "$", "parent", ",", "$", "url", ")", ";", "}" ]
Turns the given URL into an absolute URL. By default non-site root relative urls will be evaluated relative to the current base_url. @param string $url URL To transform to absolute. @param string $relativeParent Method to use for evaluating relative urls. Either one of BASE (baseurl), ROOT (site root), or REQUEST (requested page). Defaults to BASE, which is the same behaviour as template url resolution. Ignored if the url is absolute or site root. @return string
[ "Turns", "the", "given", "URL", "into", "an", "absolute", "URL", ".", "By", "default", "non", "-", "site", "root", "relative", "urls", "will", "be", "evaluated", "relative", "to", "the", "current", "base_url", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L411-L450
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.validateUserAndPass
protected static function validateUserAndPass($url) { $parsedURL = parse_url($url); // Validate user (disallow slashes) if (!empty($parsedURL['user']) && strstr($parsedURL['user'], '\\')) { return false; } if (!empty($parsedURL['pass']) && strstr($parsedURL['pass'], '\\')) { return false; } return true; }
php
protected static function validateUserAndPass($url) { $parsedURL = parse_url($url); // Validate user (disallow slashes) if (!empty($parsedURL['user']) && strstr($parsedURL['user'], '\\')) { return false; } if (!empty($parsedURL['pass']) && strstr($parsedURL['pass'], '\\')) { return false; } return true; }
[ "protected", "static", "function", "validateUserAndPass", "(", "$", "url", ")", "{", "$", "parsedURL", "=", "parse_url", "(", "$", "url", ")", ";", "// Validate user (disallow slashes)", "if", "(", "!", "empty", "(", "$", "parsedURL", "[", "'user'", "]", ")", "&&", "strstr", "(", "$", "parsedURL", "[", "'user'", "]", ",", "'\\\\'", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "empty", "(", "$", "parsedURL", "[", "'pass'", "]", ")", "&&", "strstr", "(", "$", "parsedURL", "[", "'pass'", "]", ",", "'\\\\'", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Validate user and password in URL, disallowing slashes @param string $url @return bool
[ "Validate", "user", "and", "password", "in", "URL", "disallowing", "slashes" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L481-L494
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.port
public static function port(HTTPRequest $request = null) { $host = static::host($request); return (int)parse_url($host, PHP_URL_PORT) ?: null; }
php
public static function port(HTTPRequest $request = null) { $host = static::host($request); return (int)parse_url($host, PHP_URL_PORT) ?: null; }
[ "public", "static", "function", "port", "(", "HTTPRequest", "$", "request", "=", "null", ")", "{", "$", "host", "=", "static", "::", "host", "(", "$", "request", ")", ";", "return", "(", "int", ")", "parse_url", "(", "$", "host", ",", "PHP_URL_PORT", ")", "?", ":", "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. @param HTTPRequest $request @return int|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", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L551-L555
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.hostName
public static function hostName(HTTPRequest $request = null) { $host = static::host($request); return parse_url($host, PHP_URL_HOST) ?: null; }
php
public static function hostName(HTTPRequest $request = null) { $host = static::host($request); return parse_url($host, PHP_URL_HOST) ?: null; }
[ "public", "static", "function", "hostName", "(", "HTTPRequest", "$", "request", "=", "null", ")", "{", "$", "host", "=", "static", "::", "host", "(", "$", "request", ")", ";", "return", "parse_url", "(", "$", "host", ",", "PHP_URL_HOST", ")", "?", ":", "null", ";", "}" ]
Return host name without port @param HTTPRequest|null $request @return string|null
[ "Return", "host", "name", "without", "port" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L563-L567
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.is_https
public static function is_https(HTTPRequest $request = null) { // Check override from alternate_base_url if ($baseURL = self::config()->uninherited('alternate_base_url')) { $baseURL = Injector::inst()->convertServiceProperty($baseURL); $protocol = parse_url($baseURL, PHP_URL_SCHEME); if ($protocol) { return $protocol === 'https'; } } // Check the current request $request = static::currentRequest($request); if ($request && ($scheme = $request->getScheme())) { return $scheme === 'https'; } // Check default_base_url if ($baseURL = self::config()->uninherited('default_base_url')) { $baseURL = Injector::inst()->convertServiceProperty($baseURL); $protocol = parse_url($baseURL, PHP_URL_SCHEME); if ($protocol) { return $protocol === 'https'; } } return false; }
php
public static function is_https(HTTPRequest $request = null) { // Check override from alternate_base_url if ($baseURL = self::config()->uninherited('alternate_base_url')) { $baseURL = Injector::inst()->convertServiceProperty($baseURL); $protocol = parse_url($baseURL, PHP_URL_SCHEME); if ($protocol) { return $protocol === 'https'; } } // Check the current request $request = static::currentRequest($request); if ($request && ($scheme = $request->getScheme())) { return $scheme === 'https'; } // Check default_base_url if ($baseURL = self::config()->uninherited('default_base_url')) { $baseURL = Injector::inst()->convertServiceProperty($baseURL); $protocol = parse_url($baseURL, PHP_URL_SCHEME); if ($protocol) { return $protocol === 'https'; } } return false; }
[ "public", "static", "function", "is_https", "(", "HTTPRequest", "$", "request", "=", "null", ")", "{", "// Check override from alternate_base_url", "if", "(", "$", "baseURL", "=", "self", "::", "config", "(", ")", "->", "uninherited", "(", "'alternate_base_url'", ")", ")", "{", "$", "baseURL", "=", "Injector", "::", "inst", "(", ")", "->", "convertServiceProperty", "(", "$", "baseURL", ")", ";", "$", "protocol", "=", "parse_url", "(", "$", "baseURL", ",", "PHP_URL_SCHEME", ")", ";", "if", "(", "$", "protocol", ")", "{", "return", "$", "protocol", "===", "'https'", ";", "}", "}", "// Check the current request", "$", "request", "=", "static", "::", "currentRequest", "(", "$", "request", ")", ";", "if", "(", "$", "request", "&&", "(", "$", "scheme", "=", "$", "request", "->", "getScheme", "(", ")", ")", ")", "{", "return", "$", "scheme", "===", "'https'", ";", "}", "// Check default_base_url", "if", "(", "$", "baseURL", "=", "self", "::", "config", "(", ")", "->", "uninherited", "(", "'default_base_url'", ")", ")", "{", "$", "baseURL", "=", "Injector", "::", "inst", "(", ")", "->", "convertServiceProperty", "(", "$", "baseURL", ")", ";", "$", "protocol", "=", "parse_url", "(", "$", "baseURL", ",", "PHP_URL_SCHEME", ")", ";", "if", "(", "$", "protocol", ")", "{", "return", "$", "protocol", "===", "'https'", ";", "}", "}", "return", "false", ";", "}" ]
Return whether the site is running as under HTTPS. @param HTTPRequest $request @return bool
[ "Return", "whether", "the", "site", "is", "running", "as", "under", "HTTPS", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L598-L625
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.baseURL
public static function baseURL() { // Check override base_url $alternate = self::config()->get('alternate_base_url'); if ($alternate) { $alternate = Injector::inst()->convertServiceProperty($alternate); return rtrim(parse_url($alternate, PHP_URL_PATH), '/') . '/'; } // Get env base url $baseURL = rtrim(BASE_URL, '/') . '/'; // Check if BASE_SCRIPT_URL is defined // e.g. `index.php/` if (defined('BASE_SCRIPT_URL')) { return $baseURL . BASE_SCRIPT_URL; } return $baseURL; }
php
public static function baseURL() { // Check override base_url $alternate = self::config()->get('alternate_base_url'); if ($alternate) { $alternate = Injector::inst()->convertServiceProperty($alternate); return rtrim(parse_url($alternate, PHP_URL_PATH), '/') . '/'; } // Get env base url $baseURL = rtrim(BASE_URL, '/') . '/'; // Check if BASE_SCRIPT_URL is defined // e.g. `index.php/` if (defined('BASE_SCRIPT_URL')) { return $baseURL . BASE_SCRIPT_URL; } return $baseURL; }
[ "public", "static", "function", "baseURL", "(", ")", "{", "// Check override base_url", "$", "alternate", "=", "self", "::", "config", "(", ")", "->", "get", "(", "'alternate_base_url'", ")", ";", "if", "(", "$", "alternate", ")", "{", "$", "alternate", "=", "Injector", "::", "inst", "(", ")", "->", "convertServiceProperty", "(", "$", "alternate", ")", ";", "return", "rtrim", "(", "parse_url", "(", "$", "alternate", ",", "PHP_URL_PATH", ")", ",", "'/'", ")", ".", "'/'", ";", "}", "// Get env base url", "$", "baseURL", "=", "rtrim", "(", "BASE_URL", ",", "'/'", ")", ".", "'/'", ";", "// Check if BASE_SCRIPT_URL is defined", "// e.g. `index.php/`", "if", "(", "defined", "(", "'BASE_SCRIPT_URL'", ")", ")", "{", "return", "$", "baseURL", ".", "BASE_SCRIPT_URL", ";", "}", "return", "$", "baseURL", ";", "}" ]
Return the root-relative url for the baseurl @return string Root-relative url with trailing slash.
[ "Return", "the", "root", "-", "relative", "url", "for", "the", "baseurl" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L632-L651
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.makeRelative
public static function makeRelative($url) { // Allow for the accidental inclusion whitespace and // in the URL $url = preg_replace('#([^:])//#', '\\1/', trim($url)); // If using a real url, remove protocol / hostname / auth / port if (preg_match('#^(?<protocol>https?:)?//(?<hostpart>[^/]*)(?<url>(/.*)?)$#i', $url, $matches)) { $url = $matches['url']; } // Empty case if (trim($url, '\\/') === '') { return ''; } // Remove base folder or url foreach ([self::publicFolder(), self::baseFolder(), self::baseURL()] as $base) { // Ensure single / doesn't break comparison (unless it would make base empty) $base = rtrim($base, '\\/') ?: $base; if (stripos($url, $base) === 0) { return ltrim(substr($url, strlen($base)), '\\/'); } } // Nothing matched, fall back to returning the original URL return $url; }
php
public static function makeRelative($url) { // Allow for the accidental inclusion whitespace and // in the URL $url = preg_replace('#([^:])//#', '\\1/', trim($url)); // If using a real url, remove protocol / hostname / auth / port if (preg_match('#^(?<protocol>https?:)?//(?<hostpart>[^/]*)(?<url>(/.*)?)$#i', $url, $matches)) { $url = $matches['url']; } // Empty case if (trim($url, '\\/') === '') { return ''; } // Remove base folder or url foreach ([self::publicFolder(), self::baseFolder(), self::baseURL()] as $base) { // Ensure single / doesn't break comparison (unless it would make base empty) $base = rtrim($base, '\\/') ?: $base; if (stripos($url, $base) === 0) { return ltrim(substr($url, strlen($base)), '\\/'); } } // Nothing matched, fall back to returning the original URL return $url; }
[ "public", "static", "function", "makeRelative", "(", "$", "url", ")", "{", "// Allow for the accidental inclusion whitespace and // in the URL", "$", "url", "=", "preg_replace", "(", "'#([^:])//#'", ",", "'\\\\1/'", ",", "trim", "(", "$", "url", ")", ")", ";", "// If using a real url, remove protocol / hostname / auth / port", "if", "(", "preg_match", "(", "'#^(?<protocol>https?:)?//(?<hostpart>[^/]*)(?<url>(/.*)?)$#i'", ",", "$", "url", ",", "$", "matches", ")", ")", "{", "$", "url", "=", "$", "matches", "[", "'url'", "]", ";", "}", "// Empty case", "if", "(", "trim", "(", "$", "url", ",", "'\\\\/'", ")", "===", "''", ")", "{", "return", "''", ";", "}", "// Remove base folder or url", "foreach", "(", "[", "self", "::", "publicFolder", "(", ")", ",", "self", "::", "baseFolder", "(", ")", ",", "self", "::", "baseURL", "(", ")", "]", "as", "$", "base", ")", "{", "// Ensure single / doesn't break comparison (unless it would make base empty)", "$", "base", "=", "rtrim", "(", "$", "base", ",", "'\\\\/'", ")", "?", ":", "$", "base", ";", "if", "(", "stripos", "(", "$", "url", ",", "$", "base", ")", "===", "0", ")", "{", "return", "ltrim", "(", "substr", "(", "$", "url", ",", "strlen", "(", "$", "base", ")", ")", ",", "'\\\\/'", ")", ";", "}", "}", "// Nothing matched, fall back to returning the original URL", "return", "$", "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 {@link Director::is_site_url()} if making an untrusted url relative prior to calling this function. @param string $url Accepts both a URL or a filesystem path. @return string
[ "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", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L708-L734
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.getAbsFile
public static function getAbsFile($file) { // If already absolute if (self::is_absolute($file)) { return $file; } // If path is relative to public folder search there first if (self::publicDir()) { $path = Path::join(self::publicFolder(), $file); if (file_exists($path)) { return $path; } } // Default to base folder return Path::join(self::baseFolder(), $file); }
php
public static function getAbsFile($file) { // If already absolute if (self::is_absolute($file)) { return $file; } // If path is relative to public folder search there first if (self::publicDir()) { $path = Path::join(self::publicFolder(), $file); if (file_exists($path)) { return $path; } } // Default to base folder return Path::join(self::baseFolder(), $file); }
[ "public", "static", "function", "getAbsFile", "(", "$", "file", ")", "{", "// If already absolute", "if", "(", "self", "::", "is_absolute", "(", "$", "file", ")", ")", "{", "return", "$", "file", ";", "}", "// If path is relative to public folder search there first", "if", "(", "self", "::", "publicDir", "(", ")", ")", "{", "$", "path", "=", "Path", "::", "join", "(", "self", "::", "publicFolder", "(", ")", ",", "$", "file", ")", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "return", "$", "path", ";", "}", "}", "// Default to base folder", "return", "Path", "::", "join", "(", "self", "::", "baseFolder", "(", ")", ",", "$", "file", ")", ";", "}" ]
Given a filesystem reference relative to the site root, return the full file-system path. @param string $file @return string
[ "Given", "a", "filesystem", "reference", "relative", "to", "the", "site", "root", "return", "the", "full", "file", "-", "system", "path", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L856-L873
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.absoluteBaseURLWithAuth
public static function absoluteBaseURLWithAuth(HTTPRequest $request = null) { // Detect basic auth $user = $request->getHeader('PHP_AUTH_USER'); if ($user) { $password = $request->getHeader('PHP_AUTH_PW'); $login = sprintf("%s:%s@", $user, $password) ; } else { $login = ''; } return Director::protocol($request) . $login . static::host($request) . Director::baseURL(); }
php
public static function absoluteBaseURLWithAuth(HTTPRequest $request = null) { // Detect basic auth $user = $request->getHeader('PHP_AUTH_USER'); if ($user) { $password = $request->getHeader('PHP_AUTH_PW'); $login = sprintf("%s:%s@", $user, $password) ; } else { $login = ''; } return Director::protocol($request) . $login . static::host($request) . Director::baseURL(); }
[ "public", "static", "function", "absoluteBaseURLWithAuth", "(", "HTTPRequest", "$", "request", "=", "null", ")", "{", "// Detect basic auth", "$", "user", "=", "$", "request", "->", "getHeader", "(", "'PHP_AUTH_USER'", ")", ";", "if", "(", "$", "user", ")", "{", "$", "password", "=", "$", "request", "->", "getHeader", "(", "'PHP_AUTH_PW'", ")", ";", "$", "login", "=", "sprintf", "(", "\"%s:%s@\"", ",", "$", "user", ",", "$", "password", ")", ";", "}", "else", "{", "$", "login", "=", "''", ";", "}", "return", "Director", "::", "protocol", "(", "$", "request", ")", ".", "$", "login", ".", "static", "::", "host", "(", "$", "request", ")", ".", "Director", "::", "baseURL", "(", ")", ";", "}" ]
Returns the Absolute URL of the site root, embedding the current basic-auth credentials into the URL. @param HTTPRequest|null $request @return string
[ "Returns", "the", "Absolute", "URL", "of", "the", "site", "root", "embedding", "the", "current", "basic", "-", "auth", "credentials", "into", "the", "URL", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L909-L921
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.forceSSL
public static function forceSSL($patterns = null, $secureDomain = null, HTTPRequest $request = null) { $handler = CanonicalURLMiddleware::singleton()->setForceSSL(true); if ($patterns) { $handler->setForceSSLPatterns($patterns); } if ($secureDomain) { $handler->setForceSSLDomain($secureDomain); } $handler->throwRedirectIfNeeded($request); }
php
public static function forceSSL($patterns = null, $secureDomain = null, HTTPRequest $request = null) { $handler = CanonicalURLMiddleware::singleton()->setForceSSL(true); if ($patterns) { $handler->setForceSSLPatterns($patterns); } if ($secureDomain) { $handler->setForceSSLDomain($secureDomain); } $handler->throwRedirectIfNeeded($request); }
[ "public", "static", "function", "forceSSL", "(", "$", "patterns", "=", "null", ",", "$", "secureDomain", "=", "null", ",", "HTTPRequest", "$", "request", "=", "null", ")", "{", "$", "handler", "=", "CanonicalURLMiddleware", "::", "singleton", "(", ")", "->", "setForceSSL", "(", "true", ")", ";", "if", "(", "$", "patterns", ")", "{", "$", "handler", "->", "setForceSSLPatterns", "(", "$", "patterns", ")", ";", "}", "if", "(", "$", "secureDomain", ")", "{", "$", "handler", "->", "setForceSSLDomain", "(", "$", "secureDomain", ")", ";", "}", "$", "handler", "->", "throwRedirectIfNeeded", "(", "$", "request", ")", ";", "}" ]
Force the site to run on SSL. To use, call from _config.php. For example: <code> if (Director::isLive()) Director::forceSSL(); </code> If you don't want your entire site to be on SSL, you can pass an array of PCRE regular expression patterns for matching relative URLs. For example: <code> if (Director::isLive()) Director::forceSSL(array('/^admin/', '/^Security/')); </code> If you want certain parts of your site protected under a different domain, you can specify the domain as an argument: <code> if (Director::isLive()) Director::forceSSL(array('/^admin/', '/^Security/'), 'secure.mysite.com'); </code> Note that the session data will be lost when moving from HTTP to HTTPS. It is your responsibility to ensure that this won't cause usability problems. CAUTION: This does not respect the site environment mode. You should check this as per the above examples using Director::isLive() or Director::isTest() for example. @param array $patterns Array of regex patterns to match URLs that should be HTTPS. @param string $secureDomain Secure domain to redirect to. Defaults to the current domain. Can include port number. @param HTTPRequest|null $request Request object to check
[ "Force", "the", "site", "to", "run", "on", "SSL", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L968-L978
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.forceWWW
public static function forceWWW(HTTPRequest $request = null) { $handler = CanonicalURLMiddleware::singleton()->setForceWWW(true); $handler->throwRedirectIfNeeded($request); }
php
public static function forceWWW(HTTPRequest $request = null) { $handler = CanonicalURLMiddleware::singleton()->setForceWWW(true); $handler->throwRedirectIfNeeded($request); }
[ "public", "static", "function", "forceWWW", "(", "HTTPRequest", "$", "request", "=", "null", ")", "{", "$", "handler", "=", "CanonicalURLMiddleware", "::", "singleton", "(", ")", "->", "setForceWWW", "(", "true", ")", ";", "$", "handler", "->", "throwRedirectIfNeeded", "(", "$", "request", ")", ";", "}" ]
Force a redirect to a domain starting with "www." @param HTTPRequest $request
[ "Force", "a", "redirect", "to", "a", "domain", "starting", "with", "www", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L985-L989
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.is_ajax
public static function is_ajax(HTTPRequest $request = null) { $request = self::currentRequest($request); if ($request) { return $request->isAjax(); } return ( isset($_REQUEST['ajax']) || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest") ); }
php
public static function is_ajax(HTTPRequest $request = null) { $request = self::currentRequest($request); if ($request) { return $request->isAjax(); } return ( isset($_REQUEST['ajax']) || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest") ); }
[ "public", "static", "function", "is_ajax", "(", "HTTPRequest", "$", "request", "=", "null", ")", "{", "$", "request", "=", "self", "::", "currentRequest", "(", "$", "request", ")", ";", "if", "(", "$", "request", ")", "{", "return", "$", "request", "->", "isAjax", "(", ")", ";", "}", "return", "(", "isset", "(", "$", "_REQUEST", "[", "'ajax'", "]", ")", "||", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_X_REQUESTED_WITH'", "]", ")", "&&", "$", "_SERVER", "[", "'HTTP_X_REQUESTED_WITH'", "]", "==", "\"XMLHttpRequest\"", ")", ")", ";", "}" ]
Checks if the current HTTP-Request is an "Ajax-Request" by checking for a custom header set by jQuery or whether a manually set request-parameter 'ajax' is present. Note that if you plan to use this to alter your HTTP response on a cached page, you should add X-Requested-With to the Vary header. @param HTTPRequest $request @return bool
[ "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", "." ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L1001-L1012
train
silverstripe/silverstripe-framework
src/Control/Director.php
Director.currentRequest
protected static function currentRequest(HTTPRequest $request = null) { // Ensure we only use a registered HTTPRequest and don't // incidentally construct a singleton if (!$request && Injector::inst()->has(HTTPRequest::class)) { $request = Injector::inst()->get(HTTPRequest::class); } return $request; }
php
protected static function currentRequest(HTTPRequest $request = null) { // Ensure we only use a registered HTTPRequest and don't // incidentally construct a singleton if (!$request && Injector::inst()->has(HTTPRequest::class)) { $request = Injector::inst()->get(HTTPRequest::class); } return $request; }
[ "protected", "static", "function", "currentRequest", "(", "HTTPRequest", "$", "request", "=", "null", ")", "{", "// Ensure we only use a registered HTTPRequest and don't", "// incidentally construct a singleton", "if", "(", "!", "$", "request", "&&", "Injector", "::", "inst", "(", ")", "->", "has", "(", "HTTPRequest", "::", "class", ")", ")", "{", "$", "request", "=", "Injector", "::", "inst", "(", ")", "->", "get", "(", "HTTPRequest", "::", "class", ")", ";", "}", "return", "$", "request", ";", "}" ]
Helper to validate or check the current request object @param HTTPRequest $request @return HTTPRequest Request object if one is both current and valid
[ "Helper", "to", "validate", "or", "check", "the", "current", "request", "object" ]
ed7aaff7da61eefa172fe213ec25e35d2568bc20
https://github.com/silverstripe/silverstripe-framework/blob/ed7aaff7da61eefa172fe213ec25e35d2568bc20/src/Control/Director.php#L1093-L1101
train