code
stringlengths
17
296k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
protected function getMemberFromData(array $data) { if (!empty($data['Email'])) { $uniqueIdentifier = Member::config()->get('unique_identifier_field'); return Member::get()->filter([$uniqueIdentifier => $data['Email']])->first(); } }
Load an existing Member from the provided data @param array $data @return Member|null
getMemberFromData
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php
BSD-3-Clause
protected function sendEmail($member, $token) { try { $email = Email::create() ->setHTMLTemplate('SilverStripe\\Control\\Email\\ForgotPasswordEmail') ->setData($member) ->setSubject(_t( 'SilverStripe\\Security\\Member.SUBJECTPASSWORDRESET', "Your password reset link", 'Email subject' )) ->addData('PasswordResetLink', Security::getPasswordResetLink($member, $token)) ->setTo($member->Email); $member->extend('updateForgotPasswordEmail', $email); $email->send(); return true; } catch (TransportExceptionInterface | RfcComplianceException $e) { /** @var LoggerInterface $logger */ $logger = Injector::inst()->get(LoggerInterface::class); $logger->error('Error sending email in ' . __FILE__ . ' line ' . __LINE__ . ": {$e->getMessage()}"); return false; } }
Send the email to the member that requested a reset link @param Member $member @param string $token @return bool
sendEmail
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php
BSD-3-Clause
protected function redirectToSuccess(array $data) { $link = $this->link('passwordsent'); return $this->redirect($this->addBackURLParam($link)); }
Avoid information disclosure by displaying the same status, regardless whether the email address actually exists @param array $data @return HTTPResponse
redirectToSuccess
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LostPasswordHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LostPasswordHandler.php
BSD-3-Clause
public function getDeviceCookieName() { return $this->deviceCookieName; }
Get the name of the cookie used to track this device @return string
getDeviceCookieName
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
public function setDeviceCookieName($deviceCookieName) { $this->deviceCookieName = $deviceCookieName; return $this; }
Set the name of the cookie used to track this device @param string $deviceCookieName @return $this
setDeviceCookieName
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
public function getTokenCookieName() { return $this->tokenCookieName; }
Get the name of the cookie used to store an login token @return string
getTokenCookieName
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
public function setTokenCookieName($tokenCookieName) { $this->tokenCookieName = $tokenCookieName; return $this; }
Set the name of the cookie used to store an login token @param string $tokenCookieName @return $this
setTokenCookieName
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
public function getTokenCookieSecure() { return $this->tokenCookieSecure; }
Get the name of the cookie used to store an login token @return string
getTokenCookieSecure
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
public function setTokenCookieSecure($tokenCookieSecure) { $this->tokenCookieSecure = $tokenCookieSecure; return $this; }
Set cookie with HTTPS only flag @param string $tokenCookieSecure @return $this
setTokenCookieSecure
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
public function getCascadeInTo() { return $this->cascadeInTo; }
Once a member is found by authenticateRequest() pass it to this identity store @return IdentityStore
getCascadeInTo
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
public function setCascadeInTo(IdentityStore $cascadeInTo) { $this->cascadeInTo = $cascadeInTo; return $this; }
Set the name of the cookie used to store an login token @param IdentityStore $cascadeInTo @return $this
setCascadeInTo
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
protected function clearCookies() { $secure = $this->getTokenCookieSecure(); Cookie::set($this->getTokenCookieName(), null, null, null, null, $secure); Cookie::set($this->getDeviceCookieName(), null, null, null, null, $secure); Cookie::force_expiry($this->getTokenCookieName(), null, null, null, null, $secure); Cookie::force_expiry($this->getDeviceCookieName(), null, null, null, null, $secure); }
Clear the cookies set for the user
clearCookies
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CookieAuthenticationHandler.php
BSD-3-Clause
public function Link($action = null) { $link = Controller::join_links($this->link, $action); $this->extend('updateLink', $link, $action); return $link; }
Return a link to this request handler. The link returned is supplied in the constructor @param null|string $action @return string
Link
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LoginHandler.php
BSD-3-Clause
public function login() { return [ 'Form' => $this->loginForm(), ]; }
URL handler for the log-in screen @return array
login
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LoginHandler.php
BSD-3-Clause
public function loginForm() { return MemberLoginForm::create( $this, get_class($this->authenticator), 'LoginForm' ); }
Return the MemberLoginForm form @return MemberLoginForm
loginForm
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LoginHandler.php
BSD-3-Clause
public function doLogin($data, MemberLoginForm $form, HTTPRequest $request) { $failureMessage = null; $this->extend('beforeLogin'); // Successful login if ($member = $this->checkLogin($data, $request, $result)) { $this->performLogin($member, $data, $request); // Allow operations on the member after successful login $this->extend('afterLogin', $member); return $this->redirectAfterSuccessfulLogin(); } $this->extend('failedLogin'); $message = implode("; ", array_map( function ($message) { return $message['message']; }, $result->getMessages() ?? [] )); $form->sessionMessage($message, 'bad'); // Failed login if (array_key_exists('Email', $data ?? [])) { $rememberMe = (isset($data['Remember']) && Security::config()->get('autologin_enabled') === true); $this ->getRequest() ->getSession() ->set('SessionForms.MemberLoginForm.Email', $data['Email']) ->set('SessionForms.MemberLoginForm.Remember', $rememberMe); } // Fail to login redirects back to form return $form->getRequestHandler()->redirectBackToForm(); }
Login form handler method This method is called when the user finishes the login flow @param array $data Submitted data @param MemberLoginForm $form @param HTTPRequest $request @return HTTPResponse
doLogin
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LoginHandler.php
BSD-3-Clause
protected function redirectAfterSuccessfulLogin() { $this ->getRequest() ->getSession() ->clear('SessionForms.MemberLoginForm.Email') ->clear('SessionForms.MemberLoginForm.Remember'); $member = Security::getCurrentUser(); if ($member->isPasswordExpired()) { return $this->redirectToChangePassword(); } // Absolute redirection URLs may cause spoofing $backURL = $this->getBackURL(); if ($backURL) { return $this->redirect($backURL); } // If a default login dest has been set, redirect to that. $defaultLoginDest = Security::config()->get('default_login_dest'); if ($defaultLoginDest) { return $this->redirect($defaultLoginDest); } // Redirect the user to the page where they came from if ($member) { // Welcome message $message = _t( 'SilverStripe\\Security\\Member.WELCOMEBACK', 'Welcome back, {firstname}', ['firstname' => $member->FirstName] ); Security::singleton()->setSessionMessage($message, ValidationResult::TYPE_GOOD); } // Redirect back return $this->redirectBack(); }
Login in the user and figure out where to redirect the browser. The $data has this format array( 'AuthenticationMethod' => 'MemberAuthenticator', 'Email' => '[email protected]', 'Password' => '1nitialPassword', 'BackURL' => 'test/link', [Optional: 'Remember' => 1 ] ) @return HTTPResponse
redirectAfterSuccessfulLogin
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LoginHandler.php
BSD-3-Clause
public function checkLogin($data, HTTPRequest $request, ValidationResult &$result = null) { $member = $this->authenticator->authenticate($data, $request, $result); if ($member instanceof Member) { return $member; } return null; }
Try to authenticate the user @param array $data Submitted data @param HTTPRequest $request @param ValidationResult $result @return Member Returns the member object on successful authentication or NULL on failure.
checkLogin
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LoginHandler.php
BSD-3-Clause
public function performLogin($member, $data, HTTPRequest $request) { /** IdentityStore */ $rememberMe = (isset($data['Remember']) && Security::config()->get('autologin_enabled')); $identityStore = Injector::inst()->get(IdentityStore::class); $identityStore->logIn($member, $rememberMe, $request); return $member; }
Try to authenticate the user @param Member $member @param array $data Submitted data @param HTTPRequest $request @return Member Returns the member object on successful authentication or NULL on failure.
performLogin
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LoginHandler.php
BSD-3-Clause
protected function redirectToChangePassword() { $cp = ChangePasswordForm::create($this, 'ChangePasswordForm'); $cp->sessionMessage( _t('SilverStripe\\Security\\Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good' ); $changedPasswordLink = Security::singleton()->Link('changepassword'); $changePasswordUrl = $this->addBackURLParam($changedPasswordLink); return $this->redirect($changePasswordUrl); }
Invoked if password is expired and must be changed @return HTTPResponse
redirectToChangePassword
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/LoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/LoginHandler.php
BSD-3-Clause
public function __construct(RequestHandler $controller, $authenticatorClass, $name) { $this->controller = $controller; $this->setAuthenticatorClass($authenticatorClass); $fields = $this->getFormFields(); $actions = $this->getFormActions(); parent::__construct($controller, $authenticatorClass, $name, $fields, $actions); $this->addExtraClass('form--no-dividers'); }
CMSMemberLoginForm constructor. @param RequestHandler $controller @param string $authenticatorClass @param FieldList $name
__construct
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CMSMemberLoginForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CMSMemberLoginForm.php
BSD-3-Clause
public function getExternalLink($action = null) { return Security::singleton()->Link($action); }
Get link to use for external security actions @param string $action Action @return string
getExternalLink
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CMSMemberLoginForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CMSMemberLoginForm.php
BSD-3-Clause
protected function getFormFields() { $request = $this->getRequest(); if ($request->getVar('BackURL')) { $backURL = $request->getVar('BackURL'); } else { $backURL = $request->getSession()->get('BackURL'); } $label = Member::singleton()->fieldLabel(Member::config()->get('unique_identifier_field')); $fields = FieldList::create( HiddenField::create("AuthenticationMethod", null, $this->getAuthenticatorClass(), $this), // Regardless of what the unique identifier field is (usually 'Email'), it will be held in the // 'Email' value, below: $emailField = TextField::create("Email", $label, null, null, $this), PasswordField::create("Password", _t('SilverStripe\\Security\\Member.PASSWORD', 'Password')) ); $emailField->setAttribute('autofocus', 'true'); if (Security::config()->get('remember_username')) { $emailField->setValue($this->getSession()->get('SessionForms.MemberLoginForm.Email')); } else { // Some browsers won't respect this attribute unless it's added to the form $this->setAttribute('autocomplete', 'off'); $emailField->setAttribute('autocomplete', 'off'); } if (Security::config()->get('autologin_enabled')) { $fields->push( CheckboxField::create( "Remember", _t( 'SilverStripe\\Security\\Member.KEEP_ME_SIGNED_IN', 'Keep me signed in for {count} days', [ 'count' => RememberLoginHash::config()->uninherited('token_expiry_days') ] ) ) ->setAttribute( 'title', _t( 'SilverStripe\\Security\\Member.KEEP_ME_SIGNED_IN_TOOLTIP', 'You will remain authenticated on this device for {count} days. Only use this feature if you trust the device you are using.', ['count' => RememberLoginHash::config()->uninherited('token_expiry_days')] ) ) ); } if (isset($backURL)) { $fields->push(HiddenField::create('BackURL', 'BackURL', $backURL)); } return $fields; }
Build the FieldList for the login form @return FieldList
getFormFields
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/MemberLoginForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/MemberLoginForm.php
BSD-3-Clause
protected function getFormActions() { $actions = FieldList::create( FormAction::create('doLogin', _t('SilverStripe\\Security\\Member.BUTTONLOGIN', "Log in")), LiteralField::create( 'forgotPassword', '<p id="ForgotPassword"><a href="' . Security::lost_password_url() . '">' . _t('SilverStripe\\Security\\Member.BUTTONLOSTPASSWORD', "I've lost my password") . '</a></p>' ) ); return $actions; }
Build default login form action FieldList @return FieldList
getFormActions
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/MemberLoginForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/MemberLoginForm.php
BSD-3-Clause
public function getAuthenticatorName() { return _t(MemberLoginForm::class . '.AUTHENTICATORNAME', "E-mail & Password"); }
The name of this login form, to display in the frontend Replaces Authenticator::get_name() @return string
getAuthenticatorName
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/MemberLoginForm.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/MemberLoginForm.php
BSD-3-Clause
public function loginForm() { return CMSMemberLoginForm::create( $this, get_class($this->authenticator), 'LoginForm' ); }
Return the CMSMemberLoginForm form @return CMSMemberLoginForm
loginForm
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CMSLoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CMSLoginHandler.php
BSD-3-Clause
protected function redirectToChangePassword() { // Since this form is loaded via an iframe, this redirect must be performed via javascript $changePasswordForm = ChangePasswordForm::create($this, 'ChangePasswordForm'); $changePasswordForm->sessionMessage( _t('SilverStripe\\Security\\Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good' ); // Get redirect url $changedPasswordLink = Security::singleton()->Link('changepassword'); $changePasswordURL = $this->addBackURLParam($changedPasswordLink); if (Injector::inst()->has(PasswordExpirationMiddleware::class)) { $session = $this->getRequest()->getSession(); $passwordExpirationMiddleware = Injector::inst()->get(PasswordExpirationMiddleware::class); $passwordExpirationMiddleware->allowCurrentRequest($session); } $changePasswordURLATT = Convert::raw2att($changePasswordURL); $changePasswordURLJS = Convert::raw2js($changePasswordURL); $message = _t( 'SilverStripe\\Security\\CMSMemberLoginForm.PASSWORDEXPIRED', '<p>Your password has expired. <a target="_top" href="{link}">Please choose a new one.</a></p>', 'Message displayed to user if their session cannot be restored', ['link' => $changePasswordURLATT] ); // Redirect to change password page $response = HTTPResponse::create() ->setBody(<<<PHP <!DOCTYPE html> <html><body> $message <script type="application/javascript"> setTimeout(function(){top.location.href = "$changePasswordURLJS";}, 0); </script> </body></html> PHP ); return $response; }
Redirect the user to the change password form. @return HTTPResponse
redirectToChangePassword
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CMSLoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CMSLoginHandler.php
BSD-3-Clause
protected function redirectAfterSuccessfulLogin() { // Check password expiry if (Security::getCurrentUser()->isPasswordExpired()) { // Redirect the user to the external password change form if necessary return $this->redirectToChangePassword(); } // Link to success template $url = CMSSecurity::singleton()->Link('success'); return $this->redirect($url); }
Send user to the right location after login @return HTTPResponse
redirectAfterSuccessfulLogin
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/CMSLoginHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/CMSLoginHandler.php
BSD-3-Clause
public function changepassword() { $request = $this->getRequest(); // Extract the member from the URL. $member = null; if ($request->getVar('m') !== null) { $member = Member::get()->filter(['ID' => (int)$request->getVar('m')])->first(); } $token = $request->getVar('t'); // Check whether we are merely changing password, or resetting. if ($token !== null && $member && $member->validateAutoLoginToken($token)) { $this->setSessionToken($member, $token); // Redirect to myself, but without the hash in the URL return $this->redirect($this->link); } $session = $this->getRequest()->getSession(); if ($session->get('AutoLoginHash')) { $message = DBField::create_field( 'HTMLFragment', '<p>' . _t( 'SilverStripe\\Security\\Security.ENTERNEWPASSWORD', 'Please enter a new password.' ) . '</p>' ); // Subsequent request after the "first load with hash" (see previous if clause). return [ 'Content' => $message, 'Form' => $this->changePasswordForm() ]; } if (Security::getCurrentUser()) { // Logged in user requested a password change form. $message = DBField::create_field( 'HTMLFragment', '<p>' . _t( 'SilverStripe\\Security\\Security.CHANGEPASSWORDBELOW', 'You can change your password below.' ) . '</p>' ); return [ 'Content' => $message, 'Form' => $this->changePasswordForm() ]; } // Show a friendly message saying the login token has expired if ($token !== null && $member && !$member->validateAutoLoginToken($token)) { $message = DBField::create_field( 'HTMLFragment', _t( 'SilverStripe\\Security\\Security.NOTERESETLINKINVALID', '<p>The password reset link is invalid or expired.</p>' . '<p>You can request a new one <a href="{link1}">here</a> or change your password after' . ' you <a href="{link2}">log in</a>.</p>', [ 'link1' => Security::lost_password_url(), 'link2' => Security::login_url(), ] ) ); return [ 'Content' => $message, ]; } // Someone attempted to go to changepassword without token or being logged in return Security::permissionFailure( Controller::curr(), _t( 'SilverStripe\\Security\\Security.ERRORPASSWORDPERMISSION', 'You must be logged in in order to change your password!' ) ); }
Handle the change password request @return array|HTTPResponse
changepassword
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/ChangePasswordHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/ChangePasswordHandler.php
BSD-3-Clause
public function Link($action = null) { $link = Controller::join_links($this->link, $action); $this->extend('updateLink', $link, $action); return $link; }
Return a link to this request handler. The link returned is supplied in the constructor @param string|null $action @return string
Link
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/ChangePasswordHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/ChangePasswordHandler.php
BSD-3-Clause
public function changePasswordForm() { return ChangePasswordForm::create( $this, 'ChangePasswordForm' ); }
Factory method for the lost password form @return ChangePasswordForm Returns the lost password form
changePasswordForm
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/ChangePasswordHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/ChangePasswordHandler.php
BSD-3-Clause
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
redirectBackToForm
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/ChangePasswordHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/ChangePasswordHandler.php
BSD-3-Clause
public function getSessionVariable() { return $this->sessionVariable; }
Get the session variable name used to track member ID @return string
getSessionVariable
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/SessionAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/SessionAuthenticationHandler.php
BSD-3-Clause
public function setSessionVariable($sessionVariable) { $this->sessionVariable = $sessionVariable; }
Set the session variable name used to track member ID @param string $sessionVariable
setSessionVariable
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/SessionAuthenticationHandler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/SessionAuthenticationHandler.php
BSD-3-Clause
public function checkPassword(Member $member, $password, ValidationResult &$result = null) { // Check if allowed to login $result = $member->validateCanLogin($result); if (!$result->isValid()) { return $result; } // Allow default admin to login as self if (DefaultAdminService::isDefaultAdminCredentials($member->Email, $password)) { return $result; } // Check a password is set on this member if (empty($member->Password) && $member->exists()) { $result->addError(_t(__CLASS__ . '.NoPassword', 'There is no password on this member.')); } $encryptor = PasswordEncryptor::create_for_algorithm($member->PasswordEncryption); if (!$encryptor->check($member->Password, $password, $member->Salt, $member)) { $result->addError(_t( __CLASS__ . '.ERRORWRONGCRED', 'The provided details don\'t seem to be correct. Please try again.' )); } return $result; }
Check if the passed password matches the stored one (if the member is not locked out). Note, we don't return early, to prevent differences in timings to give away if a member password is invalid. @param Member $member @param string $password @param ValidationResult $result @return ValidationResult
checkPassword
php
silverstripe/silverstripe-framework
src/Security/MemberAuthenticator/MemberAuthenticator.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/MemberAuthenticator/MemberAuthenticator.php
BSD-3-Clause
public function doRefuse() { $url = $this->storage->getFailureUrl(); $this->storage->cleanup(); return $this->controller->redirect($url); }
The form refusal handler. Cleans up the confirmation storage and returns the failure redirection (kept in the storage) @return HTTPResponse redirect
doRefuse
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Form.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Form.php
BSD-3-Clause
public function doConfirm() { $storage = $this->storage; $data = $this->getData(); if (!$storage->confirm($data)) { throw new ValidationException('Sorry, we could not verify the parameters'); } $url = $storage->getSuccessUrl(); return $this->controller->redirect($url); }
The form confirmation handler. Checks all the items in the storage has been confirmed and marks them as such. Returns a redirect when all the storage items has been verified and marked as confirmed. @return HTTPResponse success url @throws ValidationException when the confirmation storage has an item missing on the form
doConfirm
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Form.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Form.php
BSD-3-Clause
protected function buildEmptyFieldList() { return FieldList::create( HeaderField::create(null, _t(__CLASS__ . '.EMPTY_TITLE', 'Nothing to confirm')) ); }
Builds the fields showing the form is empty and there's nothing to confirm @return FieldList
buildEmptyFieldList
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Form.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Form.php
BSD-3-Clause
public function cleanup() { Cookie::force_expiry($this->getCookieKey()); $this->session->clear($this->getNamespace()); }
Remove all the data from the storage Cleans up Session and Cookie related to this storage
cleanup
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getTokenHash(Item $item) { $token = $item->getToken(); $salt = $this->getSessionSalt(); $salted = $salt . $token; return hash(static::HASH_ALGO ?? '', $salted ?? '', true); }
Returns salted and hashed version of the item token @param Item $item @return string
getTokenHash
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getCookieKey() { $salt = $this->getSessionSalt(); return bin2hex(hash(static::HASH_ALGO ?? '', $salt . 'cookie key', true)); }
Returns the unique cookie key generated from the session salt @return string
getCookieKey
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getCsrfToken() { $salt = $this->getSessionSalt(); return base64_encode(hash(static::HASH_ALGO ?? '', $salt . 'csrf token', true)); }
Returns a unique token to use as a CSRF token @return string
getCsrfToken
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getSessionSalt() { $key = $this->getNamespace('salt'); if (!$salt = $this->session->get($key)) { $salt = $this->generateSalt(); $this->session->set($key, $salt); } return $salt; }
Returns the salt generated for the current session @return string
getSessionSalt
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
protected function generateSalt() { return random_bytes(64); }
Returns randomly generated salt @return string
generateSalt
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function putItem(Item $item) { $key = $this->getNamespace('items'); $items = $this->session->get($key) ?: []; $token = $this->getTokenHash($item); $items[$token] = $item; $this->session->set($key, $items); return $this; }
Adds a new object to the list of confirmation items Replaces the item if there is already one with the same token @param Item $item Item requiring confirmation @return $this
putItem
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getItems() { return $this->session->get($this->getNamespace('items')) ?: []; }
Returns the list of registered confirmation items @return Item[]
getItems
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getItem($key) { foreach ($this->getItems() as $item) { if ($item->getToken() === $key) { return $item; } } }
Look up an item by its token key @param string $key Item token key @return null|Item
getItem
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function setSuccessRequest(HTTPRequest $request) { $url = Controller::join_links(Director::baseURL(), $request->getURL(true)); $this->setSuccessUrl($url); $httpMethod = $request->httpMethod(); $this->session->set($this->getNamespace('httpMethod'), $httpMethod); if ($httpMethod === 'POST') { $checksum = $this->setSuccessPostVars($request->postVars()); $this->session->set($this->getNamespace('postChecksum'), $checksum); } }
This request should be performed on success Usually the original request which triggered the confirmation @param HTTPRequest $request @return $this
setSuccessRequest
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getHttpMethod() { return $this->session->get($this->getNamespace('httpMethod')); }
Returns HTTP method of the success request @return string
getHttpMethod
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function setSuccessUrl($url) { $this->session->set($this->getNamespace('successUrl'), $url); return $this; }
The URL the form should redirect to on success @param string $url Success URL @return $this
setSuccessUrl
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getSuccessUrl() { return $this->session->get($this->getNamespace('successUrl')); }
Returns the URL registered by {@see Storage::setSuccessUrl} as a success redirect target @return string
getSuccessUrl
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function setFailureUrl($url) { $this->session->set($this->getNamespace('failureUrl'), $url); return $this; }
The URL the form should redirect to on failure @param string $url Failure URL @return $this
setFailureUrl
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function getFailureUrl() { return $this->session->get($this->getNamespace('failureUrl')); }
Returns the URL registered by {@see Storage::setFailureUrl} as a success redirect target @return string
getFailureUrl
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
protected function getNamespace($key = null) { return sprintf( '%s.%s%s', str_replace('\\', '.', __CLASS__), $this->id, $key ? '.' . $key : '' ); }
Returns the namespace of the storage in the session @param string|null $key Optional key within the storage @return string
getNamespace
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Storage.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Storage.php
BSD-3-Clause
public function index() { return [ 'Title' => _t(__CLASS__ . '.FORM_TITLE', 'Confirm potentially dangerous action'), 'Form' => $this->Form() ]; }
URL handler for the log-in screen @return array
index
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Handler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Handler.php
BSD-3-Clause
public function securityTokenEnabled() { return false; }
This method is being used by Form to check whether it needs to use SecurityToken We always return false here as the confirmation form should decide this on its own depending on the Storage data. If we had the original request to be POST with its own SecurityID, we don't want to interfre with it. If it's been GET request, then it will generate a new SecurityToken @return bool
securityTokenEnabled
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Handler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Handler.php
BSD-3-Clause
public function Form() { $storageId = $this->request->param('StorageID'); if (!strlen(trim($storageId ?? ''))) { $this->httpError(404, "Undefined StorageID"); } return Form::create($storageId, $this, __FUNCTION__); }
Returns an instance of Confirmation\Form initialized with the proper storage id taken from URL @return Form
Form
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Handler.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Handler.php
BSD-3-Clause
public function getName() { return $this->name; }
Returns the item name (human readable) @return string
getName
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Item.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Item.php
BSD-3-Clause
public function getDescription() { return $this->description; }
Returns the human readable description of the item @return string
getDescription
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Item.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Item.php
BSD-3-Clause
public function isConfirmed() { return $this->confirmed; }
Returns whether the item has been confirmed @return bool
isConfirmed
php
silverstripe/silverstripe-framework
src/Security/Confirmation/Item.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/Security/Confirmation/Item.php
BSD-3-Clause
public function getForeignKey() { return $this->foreignKey; }
Gets the field name which holds the related object ID. @return string
getForeignKey
php
silverstripe/silverstripe-framework
src/ORM/HasManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/HasManyList.php
BSD-3-Clause
public function removeByID($itemID) { $item = $this->byID($itemID); return $this->remove($item); }
Remove an item from this relation. Doesn't actually remove the item, it just clears the foreign key value. @param int $itemID The ID of the item to be removed.
removeByID
php
silverstripe/silverstripe-framework
src/ORM/HasManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/HasManyList.php
BSD-3-Clause
public function remove($item) { if (!($item instanceof $this->dataClass)) { throw new InvalidArgumentException("HasManyList::remove() expecting a $this->dataClass object, or ID"); } // Don't remove item which doesn't belong to this list $foreignID = $this->getForeignID(); $foreignKey = $this->getForeignKey(); if (empty($foreignID) || (is_array($foreignID) && in_array($item->$foreignKey, $foreignID ?? [])) || $foreignID == $item->$foreignKey ) { $item->$foreignKey = null; $item->write(); } if ($this->removeCallbacks) { $this->removeCallbacks->call($this, [$item->ID]); } }
Remove an item from this relation. Doesn't actually remove the item, it just clears the foreign key value. @param DataObject $item The DataObject to be removed
remove
php
silverstripe/silverstripe-framework
src/ORM/HasManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/HasManyList.php
BSD-3-Clause
public function sqlColumnForField($class, $field, $tablePrefix = null) { $table = $this->tableForField($class, $field); if (!$table) { throw new InvalidArgumentException("\"{$field}\" is not a field on class \"{$class}\""); } return "\"{$tablePrefix}{$table}\".\"{$field}\""; }
Given a DataObject class and a field on that class, determine the appropriate SQL for selecting / filtering on in a SQL string. Note that $class must be a valid class, not an arbitrary table. The result will be a standard ANSI-sql quoted string in "Table"."Column" format. @param string $class Class name (not a table). @param string $field Name of field that belongs to this class (or a parent class) @param string $tablePrefix Optional prefix for table (alias) @return string The SQL identifier string for the corresponding column for this field
sqlColumnForField
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function tableName($class) { $tables = $this->getTableNames(); $class = ClassInfo::class_name($class); if (isset($tables[$class])) { return Convert::raw2sql($tables[$class]); } return null; }
Get table name for the given class. Note that this does not confirm a table actually exists (or should exist), but returns the name that would be used if this table did exist. @param string $class @return string Returns the table name, or null if there is no table
tableName
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function baseDataClass($class) { $current = $class; while ($next = get_parent_class($current ?? '')) { if ($next === DataObject::class) { // Only use ClassInfo::class_name() to format the class if we've not used get_parent_class() return ($current === $class) ? ClassInfo::class_name($current) : $current; } $current = $next; } throw new InvalidArgumentException("$class is not a subclass of DataObject"); }
Returns the root class (the first to extend from DataObject) for the passed class. @param string|object $class @return class-string<DataObject> @throws InvalidArgumentException
baseDataClass
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function fieldSpec($classOrInstance, $fieldName, $options = 0) { $specs = $this->fieldSpecs($classOrInstance, $options); return isset($specs[$fieldName]) ? $specs[$fieldName] : null; }
Get specifications for a single class field @param string|DataObject $classOrInstance Name or instance of class @param string $fieldName Name of field to retrieve @param int $options Bitmask of options - UNINHERITED Limit to only this table - DB_ONLY Exclude virtual fields (such as composite fields), and only include fields with a db column. - INCLUDE_CLASS Prefix the field specification with the class name in RecordClass.Column(spec) format. @return string|null Field will be a string in FieldClass(args) format, or RecordClass.FieldClass(args) format if using INCLUDE_CLASS. Will be null if no field is found.
fieldSpec
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function tableClass($table) { $tables = $this->getTableNames(); $class = array_search($table, $tables ?? [], true); if ($class) { return $class; } // If there is no class for this table, strip table modifiers (e.g. _Live / _Versions) // from the end and re-attempt a search. if (preg_match('/^(?<class>.+)(_[^_]+)$/i', $table ?? '', $matches)) { $table = $matches['class']; $class = array_search($table, $tables ?? [], true); if ($class) { return $class; } } return null; }
Find the class for the given table @param string $table @return class-string<DataObject>|null The FQN of the class, or null if not found
tableClass
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
protected function buildTableName($class) { $table = Config::inst()->get($class, 'table_name', Config::UNINHERITED); // Generate default table name if ($table) { return $table; } if (strpos($class ?? '', '\\') === false) { return $class; } $separator = DataObjectSchema::config()->uninherited('table_namespace_separator'); $table = str_replace('\\', $separator ?? '', trim($class ?? '', '\\')); if (!ClassInfo::classImplements($class, TestOnly::class) && $this->classHasTable($class)) { DBSchemaManager::showTableNameWarning($table, $class); } return $table; }
Generate table name for a class. Note: some DB schema have a hard limit on table name length. This is not enforced by this method. See dev/build errors for details in case of table name violation. @param string $class @return string
buildTableName
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function databaseFields($class, $aggregated = true) { $class = ClassInfo::class_name($class); if ($class === DataObject::class) { return []; } $this->cacheDatabaseFields($class); $fields = $this->databaseFields[$class]; if (!$aggregated) { return $fields; } // Recursively merge $parentFields = $this->databaseFields(get_parent_class($class ?? '')); return array_merge($fields, array_diff_key($parentFields ?? [], $fields)); }
Return the complete map of fields to specification on this object, including fixed_fields. "ID" will be included on every table. @param string $class Class name to query from @param bool $aggregated Include fields in entire hierarchy, rather than just on this table @return array Map of fieldname to specification, similar to {@link DataObject::$db}.
databaseFields
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function classHasTable($class) { if (!is_subclass_of($class, DataObject::class)) { return false; } $fields = $this->databaseFields($class, false); return !empty($fields); }
Check if the given class has a table @param string $class @return bool
classHasTable
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function compositeFields($class, $aggregated = true) { $class = ClassInfo::class_name($class); if ($class === DataObject::class) { return []; } $this->cacheDatabaseFields($class); // Get fields for this class $compositeFields = $this->compositeFields[$class]; if (!$aggregated) { return $compositeFields; } // Recursively merge $parentFields = $this->compositeFields(get_parent_class($class ?? '')); return array_merge($compositeFields, array_diff_key($parentFields ?? [], $compositeFields)); }
Returns a list of all the composite if the given db field on the class is a composite field. Will check all applicable ancestor classes and aggregate results. Can be called directly on an object. E.g. Member::composite_fields(), or Member::composite_fields(null, true) to aggregate. Includes composite has_one (Polymorphic) fields @param string $class Name of class to check @param bool $aggregated Include fields in entire hierarchy, rather than just on this table @return array List of composite fields and their class spec
compositeFields
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function compositeField($class, $field, $aggregated = true) { $fields = $this->compositeFields($class, $aggregated); return isset($fields[$field]) ? $fields[$field] : null; }
Get a composite field for a class @param string $class Class name to query from @param string $field Field name @param bool $aggregated Include fields in entire hierarchy, rather than just on this table @return string|null Field specification, or null if not a field
compositeField
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
protected function cacheDatabaseIndexes($class) { if (!array_key_exists($class, $this->databaseIndexes ?? [])) { $this->databaseIndexes[$class] = array_merge( $this->buildSortDatabaseIndexes($class), $this->cacheDefaultDatabaseIndexes($class), $this->buildCustomDatabaseIndexes($class) ); } }
Cache all indexes for the given class. Will do nothing if already cached. @param $class
cacheDatabaseIndexes
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
protected function parseSortColumn($column) { // Parse column specification, considering possible ansi sql quoting // Note that table prefix is allowed, but discarded if (preg_match('/^("?(?<table>[^"\s]+)"?\\.)?"?(?<column>[^"\s]+)"?(\s+(?<direction>((asc)|(desc))(ending)?))?$/i', $column ?? '', $match)) { $table = $match['table']; $column = $match['column']; } else { throw new InvalidArgumentException("Invalid sort() column"); } return [$table, $column]; }
Parses a specified column into a sort field and direction @param string $column String to parse containing the column name @return array Resolved table and column.
parseSortColumn
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function tableForField($candidateClass, $fieldName) { $class = $this->classForField($candidateClass, $fieldName); if ($class) { return $this->tableName($class); } return null; }
Returns the table name in the class hierarchy which contains a given field column for a {@link DataObject}. If the field does not exist, this will return null. @param string $candidateClass @param string $fieldName @return string
tableForField
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function classForField($candidateClass, $fieldName) { // normalise class name $candidateClass = ClassInfo::class_name($candidateClass); if ($candidateClass === DataObject::class) { return null; } // Short circuit for fixed fields $fixed = DataObject::config()->uninherited('fixed_fields'); if (isset($fixed[$fieldName])) { return $this->baseDataClass($candidateClass); } // Find regular field while ($candidateClass && $candidateClass !== DataObject::class) { $fields = $this->databaseFields($candidateClass, false); if (isset($fields[$fieldName])) { return $candidateClass; } $candidateClass = get_parent_class($candidateClass ?? ''); } return null; }
Returns the class name in the class hierarchy which contains a given field column for a {@link DataObject}. If the field does not exist, this will return null. @param string $candidateClass @param string $fieldName @return class-string<DataObject>|null
classForField
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
protected function parseBelongsManyManyComponent($parentClass, $component, $specification) { $childClass = $specification; $relationName = null; if (strpos($specification ?? '', '.') !== false) { list($childClass, $relationName) = explode('.', $specification ?? '', 2); } // Check child class exists if (!class_exists($childClass ?? '')) { throw new LogicException( "belongs_many_many relation {$parentClass}.{$component} points to " . "{$childClass} which does not exist" ); } // We need to find the inverse component name, if not explicitly given if (!$relationName) { $relationName = $this->getManyManyInverseRelationship($childClass, $parentClass); } // Check valid relation found if (!$relationName) { throw new LogicException( "belongs_many_many relation {$parentClass}.{$component} points to " . "{$specification} without matching many_many" ); } // Return relatios return [ 'childClass' => $childClass, 'relationName' => $relationName, ]; }
Parse a belongs_many_many component to extract class and relationship name @param string $parentClass Name of class @param string $component Name of relation on class @param string $specification specification for this belongs_many_many @return array Array with child class and relation name
parseBelongsManyManyComponent
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function manyManyExtraFieldsForComponent($class, $component) { // Get directly declared many_many_extraFields $extraFields = Config::inst()->get($class, 'many_many_extraFields'); if (isset($extraFields[$component])) { return $extraFields[$component]; } // If not belongs_many_many then there are no components while ($class && ($class !== DataObject::class)) { $belongsManyMany = Config::inst()->get($class, 'belongs_many_many', Config::UNINHERITED); if (isset($belongsManyMany[$component])) { // Reverse relationship and find extrafields from child class $belongs = $this->parseBelongsManyManyComponent( $class, $component, $belongsManyMany[$component] ); return $this->manyManyExtraFieldsForComponent($belongs['childClass'], $belongs['relationName']); } $class = get_parent_class($class ?? ''); } return null; }
Return the many-to-many extra fields specification for a specific component. @param string $class @param string $component @return array|null
manyManyExtraFieldsForComponent
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function hasManyComponent($class, $component, $classOnly = true) { $hasMany = (array)Config::inst()->get($class, 'has_many'); if (!isset($hasMany[$component])) { return null; } // Remove has_one specifier if given $hasMany = $hasMany[$component]; $hasManyClass = strtok($hasMany ?? '', '.'); // Validate $this->checkRelationClass($class, $component, $hasManyClass, 'has_many'); return $classOnly ? $hasManyClass : $hasMany; }
Return data for a specific has_many component. @param string $class Parent class @param string $component @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have the field data stripped off. It defaults to TRUE. @return string|null
hasManyComponent
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function hasOneComponent($class, $component) { $hasOnes = Config::forClass($class)->get('has_one'); if (!isset($hasOnes[$component])) { return null; } $spec = $hasOnes[$component]; // Validate if (is_array($spec)) { $this->checkHasOneArraySpec($class, $component, $spec); } $relationClass = is_array($spec) ? $spec['class'] : $spec; $this->checkRelationClass($class, $component, $relationClass, 'has_one'); return $relationClass; }
Return data for a specific has_one component. @param string $class @param string $component @return string|null
hasOneComponent
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function belongsToComponent($class, $component, $classOnly = true) { $belongsTo = (array)Config::forClass($class)->get('belongs_to'); if (!isset($belongsTo[$component])) { return null; } // Remove has_one specifier if given $belongsTo = $belongsTo[$component]; $belongsToClass = strtok($belongsTo ?? '', '.'); // Validate $this->checkRelationClass($class, $component, $belongsToClass, 'belongs_to'); return $classOnly ? $belongsToClass : $belongsTo; }
Return data for a specific belongs_to component. @param string $class @param string $component @param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have the field data stripped off. It defaults to TRUE. @return string|null
belongsToComponent
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function unaryComponent($class, $component) { return $this->hasOneComponent($class, $component) ?: $this->belongsToComponent($class, $component); }
Check class for any unary component Alias for hasOneComponent() ?: belongsToComponent() @param string $class @param string $component @return string|null
unaryComponent
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
protected function getManyManyInverseRelationship($childClass, $parentClass) { $otherManyMany = Config::inst()->get($childClass, 'many_many', Config::UNINHERITED); if (!$otherManyMany) { return null; } foreach ($otherManyMany as $inverseComponentName => $manyManySpec) { // Normal many-many if ($manyManySpec === $parentClass) { return $inverseComponentName; } // many-many through, inspect 'to' for the many_many if (is_array($manyManySpec)) { $toClass = $this->hasOneComponent($manyManySpec['through'], $manyManySpec['to']); if ($toClass === $parentClass) { return $inverseComponentName; } } } return null; }
Find a many_many on the child class that points back to this many_many @param string $childClass @param string $parentClass @return string|null
getManyManyInverseRelationship
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
public function getRemoteJoinField($class, $component, $type = 'has_many', &$polymorphic = false) { return $this->getBelongsToAndHasManyDetails($class, $component, $type, $polymorphic)['joinField']; }
Tries to find the database key on another object that is used to store a relationship to this class. If no join field can be found it defaults to 'ParentID'. If the remote field is polymorphic then $polymorphic is set to true, and the return value is in the form 'Relation' instead of 'RelationID', referencing the composite DBField. @param string $class @param string $component Name of the relation on the current object pointing to the remote object. @param string $type the join type - either 'has_many' or 'belongs_to' @param boolean $polymorphic Flag set to true if the remote join field is polymorphic. @return string @throws Exception
getRemoteJoinField
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
protected function checkManyManyFieldClass($parentClass, $component, $joinClass, $specification, $key) { // Ensure value for this key exists if (empty($specification[$key])) { throw new InvalidArgumentException( "many_many relation {$parentClass}.{$component} has missing {$key} which " . "should be a has_one on class {$joinClass}" ); } // Check that the field exists on the given object $relation = $specification[$key]; $relationClass = $this->hasOneComponent($joinClass, $relation); if (empty($relationClass)) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a field name " . "{$joinClass}::{$relation} which is not a has_one" ); } // Check for polymorphic /** @internal Polymorphic many_many is experimental */ if ($relationClass === DataObject::class) { // Currently polymorphic 'from' is supported. if ($key === 'from') { return $relationClass; } throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a polymorphic field " . "{$joinClass}::{$relation} which is not supported" ); } // Validate the join class isn't also the name of a field or relation on either side // of the relation $field = $this->fieldSpec($relationClass, $joinClass); if ($field) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} class {$relationClass} " . " cannot have a db field of the same name of the join class {$joinClass}" ); } // Validate bad types on parent relation if ($key === 'from' && $relationClass !== $parentClass && !is_subclass_of($parentClass, $relationClass)) { throw new InvalidArgumentException( "many_many through relation {$parentClass}.{$component} {$key} references a field name " . "{$joinClass}::{$relation} of type {$relationClass}; {$parentClass} expected" ); } return $relationClass; }
Validate the to or from field on a has_many mapping class @param string $parentClass Name of parent class @param string $component Name of many_many component @param string $joinClass Class for the joined table @param array $specification Complete many_many specification @param string $key Name of key to check ('from' or 'to') @return string Class that matches the given relation @throws InvalidArgumentException
checkManyManyFieldClass
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
protected function checkRelationClass($class, $component, $relationClass, $type) { if (!is_string($component) || is_numeric($component)) { throw new InvalidArgumentException( "{$class} has invalid {$type} relation name" ); } if (!is_string($relationClass)) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} is not a class name" ); } if (!class_exists($relationClass ?? '')) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} references class {$relationClass} which doesn't exist" ); } // Support polymorphic has_one if ($type === 'has_one') { $valid = is_a($relationClass, DataObject::class, true); } else { $valid = is_subclass_of($relationClass, DataObject::class, true); } if (!$valid) { throw new InvalidArgumentException( "{$type} relation {$class}.{$component} references class {$relationClass} " . " which is not a subclass of " . DataObject::class ); } }
Validate a given class is valid for a relation @param string $class Parent class @param string $component Component name @param string $relationClass Candidate class to check @param string $type Relation type (e.g. has_one)
checkRelationClass
php
silverstripe/silverstripe-framework
src/ORM/DataObjectSchema.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObjectSchema.php
BSD-3-Clause
protected function linkJoinTable() { // Join to the many-many join table $dataClassIDColumn = DataObject::getSchema()->sqlColumnForField($this->dataClass(), 'ID'); $this->dataQuery->innerJoin( $this->joinTable, "\"{$this->joinTable}\".\"{$this->localKey}\" = {$dataClassIDColumn}" ); // Add the extra fields to the query if ($this->extraFields) { $this->appendExtraFieldsToQuery(); } }
Setup the join between this dataobject and the necessary mapping table
linkJoinTable
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
protected function foreignIDFilter($id = null) { if ($id === null) { $id = $this->getForeignID(); } // Apply relation filter $key = "\"{$this->joinTable}\".\"{$this->foreignKey}\""; if (is_array($id)) { $in = $this->prepareForeignIDsForWhereInClause($id); $vals = str_contains($in, '?') ? $id : []; return ["$key IN ($in)" => $vals]; } if ($id !== null) { return [$key => $id]; } return null; }
Return a filter expression for when getting the contents of the relationship for some foreign ID @param int|null|string|array $id
foreignIDFilter
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
protected function foreignIDWriteFilter($id = null) { return $this->foreignIDFilter($id); }
Return a filter expression for the join table when writing to the join table When writing (add, remove, removeByID), we need to filter the join table to just the relevant entries. However some subclasses of ManyManyList (Member_GroupSet) modify foreignIDFilter to include additional calculated entries, so we need different filters when reading and when writing @param array|int|null $id (optional) An ID or an array of IDs - if not provided, will use the current ids as per getForeignID @return array Condition In array(SQL => parameters format)
foreignIDWriteFilter
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function remove($item) { if (!($item instanceof $this->dataClass)) { throw new InvalidArgumentException("ManyManyList::remove() expecting a $this->dataClass object"); } $result = $this->removeByID($item->ID); return $result; }
Remove the given item from this list. Note that for a ManyManyList, the item is never actually deleted, only the join table is affected. @param DataObject $item
remove
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function removeByID($itemID) { if (!is_numeric($itemID)) { throw new InvalidArgumentException("ManyManyList::removeById() expecting an ID"); } $query = SQLDelete::create("\"{$this->joinTable}\""); if ($filter = $this->foreignIDWriteFilter($this->getForeignID())) { $query->setWhere($filter); } else { user_error("Can't call ManyManyList::remove() until a foreign ID is set"); } $query->addWhere([ "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID ]); // Perform the deletion $query->execute(); if ($this->removeCallbacks) { $this->removeCallbacks->call($this, [$itemID]); } }
Remove the given item from this list. Note that for a ManyManyList, the item is never actually deleted, only the join table is affected @param int $itemID The item ID
removeByID
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function removeAll() { // Remove the join to the join table to avoid MySQL row locking issues. $query = $this->dataQuery(); $foreignFilter = $query->getQueryParam('Foreign.Filter'); $query->removeFilterOn($foreignFilter); // Select ID column $selectQuery = $query->query(); $dataClassIDColumn = DataObject::getSchema()->sqlColumnForField($this->dataClass(), 'ID'); $selectQuery->setSelect($dataClassIDColumn); $from = $selectQuery->getFrom(); unset($from[$this->joinTable]); $selectQuery->setFrom($from); $selectQuery->setOrderBy(); // ORDER BY in subselects breaks MS SQL Server and is not necessary here $selectQuery->setLimit(null); // LIMIT in subselects breaks MariaDB (https://mariadb.com/kb/en/subquery-limitations/#limit) and is not necessary here $selectQuery->setDistinct(false); // Use a sub-query as SQLite does not support setting delete targets in // joined queries. $delete = SQLDelete::create(); $delete->setFrom("\"{$this->joinTable}\""); $delete->addWhere($this->foreignIDFilter()); $subSelect = $selectQuery->sql($parameters); $delete->addWhere([ "\"{$this->joinTable}\".\"{$this->localKey}\" IN ($subSelect)" => $parameters ]); $affectedIds = []; if ($this->removeCallbacks) { $affectedIds = $delete ->toSelect() ->setSelect("\"{$this->joinTable}\".\"{$this->localKey}\"") ->execute() ->column(); } // Perform the deletion $delete->execute(); if ($this->removeCallbacks && $affectedIds) { $this->removeCallbacks->call($this, $affectedIds); } }
Remove all items from this many-many join. To remove a subset of items, filter it first. @return void
removeAll
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function getExtraData($componentName, $itemID) { $result = []; // Skip if no extrafields or unsaved record if (empty($this->extraFields) || empty($itemID)) { return $result; } if (!is_numeric($itemID)) { throw new InvalidArgumentException('ManyManyList::getExtraData() passed a non-numeric child ID'); } $cleanExtraFields = []; foreach ($this->extraFields as $fieldName => $dbFieldSpec) { $cleanExtraFields[] = "\"{$fieldName}\""; } $query = SQLSelect::create($cleanExtraFields, "\"{$this->joinTable}\""); $filter = $this->foreignIDWriteFilter($this->getForeignID()); if ($filter) { $query->setWhere($filter); } else { throw new BadMethodCallException("Can't call ManyManyList::getExtraData() until a foreign ID is set"); } $query->addWhere([ "\"{$this->joinTable}\".\"{$this->localKey}\"" => $itemID ]); $queryResult = $query->execute()->record(); if ($queryResult) { foreach ($queryResult as $fieldName => $value) { $result[$fieldName] = $value; } } return $result; }
Find the extra field data for a single row of the relationship join table, given the known child ID. @param string $componentName The name of the component @param int $itemID The ID of the child for the relationship @return array Map of fieldName => fieldValue
getExtraData
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function getJoinTable() { return $this->joinTable; }
Gets the join table used for the relationship. @return string the name of the table
getJoinTable
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function getLocalKey() { return $this->localKey; }
Gets the key used to store the ID of the local/parent object. @return string the field name
getLocalKey
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function getForeignKey() { return $this->foreignKey; }
Gets the key used to store the ID of the foreign/child object. @return string the field name
getForeignKey
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function getExtraFields() { return $this->extraFields; }
Gets the extra fields included in the relationship. @return array a map of field names to types
getExtraFields
php
silverstripe/silverstripe-framework
src/ORM/ManyManyList.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/ManyManyList.php
BSD-3-Clause
public function __construct(SS_List $list, $keyField = "ID", $valueField = "Title") { Deprecation::withSuppressedNotice(function () { Deprecation::notice('5.4.0', 'Will be renamed to SilverStripe\Model\List\Map', Deprecation::SCOPE_CLASS); }); $this->list = $list; $this->keyField = $keyField; $this->valueField = $valueField; }
Construct a new map around an SS_list. @param SS_List $list The list to build a map from @param string $keyField The field to use as the key of each map entry @param string $valueField The field to use as the value of each map entry
__construct
php
silverstripe/silverstripe-framework
src/ORM/Map.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Map.php
BSD-3-Clause
public function setKeyField($keyField) { $this->keyField = $keyField; }
Set the key field for this map. @var string $keyField
setKeyField
php
silverstripe/silverstripe-framework
src/ORM/Map.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Map.php
BSD-3-Clause