idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
4,300
protected function buildSelectQuery ( SQLSelect $ query , array & $ parameters ) { $ sql = $ this -> buildSelectFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildFromFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildWhereFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildGroupByFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildHavingFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildOrderByFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildLimitFragment ( $ query , $ parameters ) ; return $ sql ; }
Builds a query from a SQLSelect expression
4,301
protected function buildDeleteQuery ( SQLDelete $ query , array & $ parameters ) { $ sql = $ this -> buildDeleteFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildFromFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildWhereFragment ( $ query , $ parameters ) ; return $ sql ; }
Builds a query from a SQLDelete expression
4,302
protected function buildInsertQuery ( SQLInsert $ query , array & $ parameters ) { $ nl = $ this -> getSeparator ( ) ; $ into = $ query -> getInto ( ) ; $ columns = $ query -> getColumns ( ) ; $ sql = "INSERT INTO {$into}{$nl}(" . implode ( ', ' , $ columns ) . ")" ; $ sql .= "{$nl}VALUES" ; $ rowParts = array ( ) ; foreach ( $ query -> getRows ( ) as $ row ) { $ assignments = $ row -> getAssignments ( ) ; $ parts = array ( ) ; foreach ( $ columns as $ column ) { if ( isset ( $ assignments [ $ column ] ) ) { foreach ( $ assignments [ $ column ] as $ assignmentSQL => $ assignmentParameters ) { $ parts [ ] = $ assignmentSQL ; $ parameters = array_merge ( $ parameters , $ assignmentParameters ) ; break ; } } else { $ parts [ ] = '?' ; $ parameters [ ] = null ; } } $ rowParts [ ] = '(' . implode ( ', ' , $ parts ) . ')' ; } $ sql .= $ nl . implode ( ",$nl" , $ rowParts ) ; return $ sql ; }
Builds a query from a SQLInsert expression
4,303
protected function buildUpdateQuery ( SQLUpdate $ query , array & $ parameters ) { $ sql = $ this -> buildUpdateFragment ( $ query , $ parameters ) ; $ sql .= $ this -> buildWhereFragment ( $ query , $ parameters ) ; return $ sql ; }
Builds a query from a SQLUpdate expression
4,304
protected function buildSelectFragment ( SQLSelect $ query , array & $ parameters ) { $ distinct = $ query -> getDistinct ( ) ; $ select = $ query -> getSelect ( ) ; $ clauses = array ( ) ; foreach ( $ select as $ alias => $ field ) { $ fieldAlias = "\"{$alias}\"" ; if ( $ alias === $ field || substr ( $ field , - strlen ( $ fieldAlias ) ) === $ fieldAlias ) { $ clauses [ ] = $ field ; } else { $ clauses [ ] = "$field AS $fieldAlias" ; } } $ text = 'SELECT ' ; if ( $ distinct ) { $ text .= 'DISTINCT ' ; } return $ text . implode ( ', ' , $ clauses ) ; }
Returns the SELECT clauses ready for inserting into a query .
4,305
public function buildDeleteFragment ( SQLDelete $ query , array & $ parameters ) { $ text = 'DELETE' ; $ delete = $ query -> getDelete ( ) ; if ( ! empty ( $ delete ) ) { $ text .= ' ' . implode ( ', ' , $ delete ) ; } return $ text ; }
Return the DELETE clause ready for inserting into a query .
4,306
public function buildUpdateFragment ( SQLUpdate $ query , array & $ parameters ) { $ table = $ query -> getTable ( ) ; $ text = "UPDATE $table" ; $ parts = array ( ) ; foreach ( $ query -> getAssignments ( ) as $ column => $ assignment ) { foreach ( $ assignment as $ assignmentSQL => $ assignmentParameters ) { $ parts [ ] = "$column = $assignmentSQL" ; $ parameters = array_merge ( $ parameters , $ assignmentParameters ) ; break ; } } $ nl = $ this -> getSeparator ( ) ; $ text .= "{$nl}SET " . implode ( ', ' , $ parts ) ; return $ text ; }
Return the UPDATE clause ready for inserting into a query .
4,307
public function buildFromFragment ( SQLConditionalExpression $ query , array & $ parameters ) { $ from = $ query -> getJoins ( $ joinParameters ) ; $ parameters = array_merge ( $ parameters , $ joinParameters ) ; $ nl = $ this -> getSeparator ( ) ; return "{$nl}FROM " . implode ( ' ' , $ from ) ; }
Return the FROM clause ready for inserting into a query .
4,308
public function buildWhereFragment ( SQLConditionalExpression $ query , array & $ parameters ) { $ where = $ query -> getWhereParameterised ( $ whereParameters ) ; if ( empty ( $ where ) ) { return '' ; } $ connective = $ query -> getConnective ( ) ; $ parameters = array_merge ( $ parameters , $ whereParameters ) ; $ nl = $ this -> getSeparator ( ) ; return "{$nl}WHERE (" . implode ( "){$nl}{$connective} (" , $ where ) . ")" ; }
Returns the WHERE clauses ready for inserting into a query .
4,309
public function buildOrderByFragment ( SQLSelect $ query , array & $ parameters ) { $ orderBy = $ query -> getOrderBy ( ) ; if ( empty ( $ orderBy ) ) { return '' ; } $ statements = array ( ) ; foreach ( $ orderBy as $ clause => $ dir ) { $ statements [ ] = trim ( "$clause $dir" ) ; } $ nl = $ this -> getSeparator ( ) ; return "{$nl}ORDER BY " . implode ( ', ' , $ statements ) ; }
Returns the ORDER BY clauses ready for inserting into a query .
4,310
public function buildGroupByFragment ( SQLSelect $ query , array & $ parameters ) { $ groupBy = $ query -> getGroupBy ( ) ; if ( empty ( $ groupBy ) ) { return '' ; } $ nl = $ this -> getSeparator ( ) ; return "{$nl}GROUP BY " . implode ( ', ' , $ groupBy ) ; }
Returns the GROUP BY clauses ready for inserting into a query .
4,311
public function buildHavingFragment ( SQLSelect $ query , array & $ parameters ) { $ having = $ query -> getHavingParameterised ( $ havingParameters ) ; if ( empty ( $ having ) ) { return '' ; } $ connective = $ query -> getConnective ( ) ; $ parameters = array_merge ( $ parameters , $ havingParameters ) ; $ nl = $ this -> getSeparator ( ) ; return "{$nl}HAVING (" . implode ( "){$nl}{$connective} (" , $ having ) . ")" ; }
Returns the HAVING clauses ready for inserting into a query .
4,312
public function buildLimitFragment ( SQLSelect $ query , array & $ parameters ) { $ nl = $ this -> getSeparator ( ) ; $ limit = $ query -> getLimit ( ) ; if ( empty ( $ limit ) ) { return '' ; } if ( ! is_array ( $ limit ) ) { return "{$nl}LIMIT $limit" ; } if ( ! isset ( $ limit [ 'limit' ] ) || ! is_numeric ( $ limit [ 'limit' ] ) ) { throw new InvalidArgumentException ( 'DBQueryBuilder::buildLimitSQL(): Wrong format for $limit: ' . var_export ( $ limit , true ) ) ; } $ clause = "{$nl}LIMIT {$limit['limit']}" ; if ( isset ( $ limit [ 'start' ] ) && is_numeric ( $ limit [ 'start' ] ) && $ limit [ 'start' ] !== 0 ) { $ clause .= " OFFSET {$limit['start']}" ; } return $ clause ; }
Return the LIMIT clause ready for inserting into a query .
4,313
public function logIn ( Member $ member , $ persistent = false , HTTPRequest $ request = null ) { $ member -> beforeMemberLoggedIn ( ) ; foreach ( $ this -> getHandlers ( ) as $ handler ) { $ handler -> logIn ( $ member , $ persistent , $ request ) ; } Security :: setCurrentUser ( $ member ) ; $ member -> afterMemberLoggedIn ( ) ; }
Log into the identity - store handlers attached to this request filter
4,314
public function logOut ( HTTPRequest $ request = null ) { $ member = Security :: getCurrentUser ( ) ; if ( $ member ) { $ member -> beforeMemberLoggedOut ( $ request ) ; } foreach ( $ this -> getHandlers ( ) as $ handler ) { $ handler -> logOut ( $ request ) ; } Security :: setCurrentUser ( null ) ; if ( $ member ) { $ member -> afterMemberLoggedOut ( $ request ) ; } }
Log out of all the identity - store handlers attached to this request filter
4,315
public function renderError ( $ httpRequest , $ errno , $ errstr , $ errfile , $ errline ) { if ( ! isset ( self :: $ error_types [ $ errno ] ) ) { $ errorTypeTitle = "UNKNOWN TYPE, ERRNO $errno" ; } else { $ errorTypeTitle = self :: $ error_types [ $ errno ] [ 'title' ] ; } $ output = CLI :: text ( "ERROR [" . $ errorTypeTitle . "]: $errstr\nIN $httpRequest\n" , "red" , null , true ) ; $ output .= CLI :: text ( "Line $errline in $errfile\n\n" , "red" ) ; return $ output ; }
Write information about the error to the screen
4,316
public function renderSourceFragment ( $ lines , $ errline ) { $ output = "Source\n======\n" ; foreach ( $ lines as $ offset => $ line ) { $ output .= ( $ offset == $ errline ) ? "* " : " " ; $ output .= str_pad ( "$offset:" , 5 ) ; $ output .= wordwrap ( $ line , self :: config ( ) -> columns , "\n " ) ; } $ output .= "\n" ; return $ output ; }
Write a fragment of the a source file
4,317
public function renderTrace ( $ trace = null ) { $ output = "Trace\n=====\n" ; $ output .= Backtrace :: get_rendered_backtrace ( $ trace ? $ trace : debug_backtrace ( ) , true ) ; return $ output ; }
Write a backtrace
4,318
public function getVersion ( ) { $ modules = $ this -> getModules ( ) ; $ lockModules = $ this -> getModuleVersionFromComposer ( array_keys ( $ modules ) ) ; $ output = [ ] ; foreach ( $ modules as $ module => $ title ) { $ version = isset ( $ lockModules [ $ module ] ) ? $ lockModules [ $ module ] : _t ( __CLASS__ . '.VERSIONUNKNOWN' , 'Unknown' ) ; $ output [ ] = $ title . ': ' . $ version ; } return implode ( ', ' , $ output ) ; }
Gets a comma delimited string of package titles and versions
4,319
public function getModuleVersionFromComposer ( $ modules = [ ] ) { $ versions = [ ] ; $ lockData = $ this -> getComposerLock ( ) ; if ( $ lockData && ! empty ( $ lockData [ 'packages' ] ) ) { foreach ( $ lockData [ 'packages' ] as $ package ) { if ( in_array ( $ package [ 'name' ] , $ modules ) && isset ( $ package [ 'version' ] ) ) { $ versions [ $ package [ 'name' ] ] = $ package [ 'version' ] ; } } } return $ versions ; }
Tries to obtain version number from composer . lock if it exists
4,320
protected function getComposerLock ( $ cache = true ) { $ composerLockPath = BASE_PATH . '/composer.lock' ; if ( ! file_exists ( $ composerLockPath ) ) { return [ ] ; } $ lockData = [ ] ; $ jsonData = file_get_contents ( $ composerLockPath ) ; if ( $ cache ) { $ cache = Injector :: inst ( ) -> get ( CacheInterface :: class . '.VersionProvider_composerlock' ) ; $ cacheKey = md5 ( $ jsonData ) ; if ( $ versions = $ cache -> get ( $ cacheKey ) ) { $ lockData = json_decode ( $ versions , true ) ; } } if ( empty ( $ lockData ) && $ jsonData ) { $ lockData = json_decode ( $ jsonData , true ) ; if ( $ cache ) { $ cache -> set ( $ cacheKey , $ jsonData ) ; } } return $ lockData ; }
Load composer . lock s contents and return it
4,321
public function toASCII ( $ source ) { if ( function_exists ( 'iconv' ) && $ this -> config ( ) -> use_iconv ) { return $ this -> useIconv ( $ source ) ; } else { return $ this -> useStrTr ( $ source ) ; } }
Convert the given utf8 string to a safe ASCII source
4,322
public function getRelationAutosetClass ( $ default = File :: class ) { if ( ! $ this -> getRelationAutoSetting ( ) ) { return $ default ; } $ name = $ this -> getName ( ) ; $ record = $ this -> getRecord ( ) ; if ( empty ( $ name ) || empty ( $ record ) ) { return $ default ; } else { $ class = $ record -> getRelationClass ( $ name ) ; return empty ( $ class ) ? $ default : $ class ; } }
Gets the foreign class that needs to be created or File as default if there is no relationship or it cannot be determined .
4,323
protected function extractUploadedFileData ( $ postVars ) { $ tmpFiles = array ( ) ; if ( ! empty ( $ postVars [ 'tmp_name' ] ) && is_array ( $ postVars [ 'tmp_name' ] ) && ! empty ( $ postVars [ 'tmp_name' ] [ 'Uploads' ] ) ) { for ( $ i = 0 ; $ i < count ( $ postVars [ 'tmp_name' ] [ 'Uploads' ] ) ; $ i ++ ) { if ( empty ( $ postVars [ 'tmp_name' ] [ 'Uploads' ] [ $ i ] ) ) { continue ; } $ tmpFile = array ( ) ; foreach ( array ( 'name' , 'type' , 'tmp_name' , 'error' , 'size' ) as $ field ) { $ tmpFile [ $ field ] = $ postVars [ $ field ] [ 'Uploads' ] [ $ i ] ; } $ tmpFiles [ ] = $ tmpFile ; } } elseif ( ! empty ( $ postVars [ 'tmp_name' ] ) ) { $ tmpFiles [ ] = $ postVars ; } return $ tmpFiles ; }
Given an array of post variables extract all temporary file data into an array
4,324
protected function prepareColumns ( $ columns ) { $ prefix = DataQuery :: applyRelationPrefix ( $ this -> relation ) ; $ table = DataObject :: getSchema ( ) -> tableForField ( $ this -> model , current ( $ columns ) ) ; $ fullTable = $ prefix . $ table ; $ columns = array_map ( function ( $ col ) use ( $ fullTable ) { return "\"{$fullTable}\".\"{$col}\"" ; } , $ columns ) ; return implode ( ',' , $ columns ) ; }
Adds table identifier to the every column . Columns must have table identifier to prevent duplicate column name error .
4,325
public function getItems ( ) { $ items = new ArrayList ( ) ; if ( $ this -> value != 'unchanged' ) { $ sourceObject = $ this -> getSourceObject ( ) ; if ( is_array ( $ sourceObject ) ) { $ values = is_array ( $ this -> value ) ? $ this -> value : preg_split ( '/ *, */' , trim ( $ this -> value ) ) ; foreach ( $ values as $ value ) { $ item = new stdClass ; $ item -> ID = $ value ; $ item -> Title = $ sourceObject [ $ value ] ; $ items -> push ( $ item ) ; } return $ items ; } if ( is_string ( $ this -> value ) ) { $ ids = explode ( ',' , $ this -> value ) ; foreach ( $ ids as $ id ) { if ( ! is_numeric ( $ id ) ) { continue ; } $ item = DataObject :: get_by_id ( $ sourceObject , $ id ) ; if ( $ item ) { $ items -> push ( $ item ) ; } } return $ items ; } } if ( $ this -> form ) { $ fieldName = $ this -> name ; $ record = $ this -> form -> getRecord ( ) ; if ( is_object ( $ record ) && $ record -> hasMethod ( $ fieldName ) ) { return $ record -> $ fieldName ( ) ; } } return $ items ; }
Return this field s linked items
4,326
public function Field ( $ properties = array ( ) ) { $ value = '' ; $ titleArray = array ( ) ; $ idArray = array ( ) ; $ items = $ this -> getItems ( ) ; $ emptyTitle = _t ( 'SilverStripe\\Forms\\DropdownField.CHOOSE' , '(Choose)' , 'start value of a dropdown' ) ; if ( $ items && count ( $ items ) ) { foreach ( $ items as $ item ) { $ idArray [ ] = $ item -> ID ; $ titleArray [ ] = ( $ item instanceof ViewableData ) ? $ item -> obj ( $ this -> getLabelField ( ) ) -> forTemplate ( ) : Convert :: raw2xml ( $ item -> { $ this -> getLabelField ( ) } ) ; } $ title = implode ( ", " , $ titleArray ) ; sort ( $ idArray ) ; $ value = implode ( "," , $ idArray ) ; } else { $ title = $ emptyTitle ; } $ dataUrlTree = '' ; if ( $ this -> form ) { $ dataUrlTree = $ this -> Link ( 'tree' ) ; if ( ! empty ( $ idArray ) ) { $ dataUrlTree = Controller :: join_links ( $ dataUrlTree , '?forceValue=' . implode ( ',' , $ idArray ) ) ; } } $ properties = array_merge ( $ properties , array ( 'Title' => $ title , 'EmptyTitle' => $ emptyTitle , 'Link' => $ dataUrlTree , 'Value' => $ value ) ) ; return FormField :: Field ( $ properties ) ; }
We overwrite the field attribute to add our hidden fields as this formfield can contain multiple values .
4,327
public function performReadonlyTransformation ( ) { $ copy = $ this -> castedCopy ( TreeMultiselectField_Readonly :: class ) ; $ copy -> setKeyField ( $ this -> getKeyField ( ) ) ; $ copy -> setLabelField ( $ this -> getLabelField ( ) ) ; $ copy -> setSourceObject ( $ this -> getSourceObject ( ) ) ; $ copy -> setTitleField ( $ this -> getTitleField ( ) ) ; return $ copy ; }
Changes this field to the readonly field .
4,328
public function setList ( $ list ) { $ this -> list = $ list ; $ this -> failover = $ this -> list ; return $ this ; }
Set the list this decorator wraps around .
4,329
public function getFormatter ( ) { $ locale = $ this -> getLocale ( ) ; $ currency = $ this -> getCurrency ( ) ; if ( $ currency ) { $ locale .= '@currency=' . $ currency ; } return NumberFormatter :: create ( $ locale , NumberFormatter :: CURRENCY ) ; }
Get currency formatter
4,330
public function getQuery ( $ searchParams , $ sort = false , $ limit = false , $ existingQuery = null ) { $ query = null ; if ( $ existingQuery ) { if ( ! ( $ existingQuery instanceof DataList ) ) { throw new InvalidArgumentException ( "existingQuery must be DataList" ) ; } if ( $ existingQuery -> dataClass ( ) != $ this -> modelClass ) { throw new InvalidArgumentException ( "existingQuery's dataClass is " . $ existingQuery -> dataClass ( ) . ", $this->modelClass expected." ) ; } $ query = $ existingQuery ; } else { $ query = DataList :: create ( $ this -> modelClass ) ; } if ( is_array ( $ limit ) ) { $ query = $ query -> limit ( isset ( $ limit [ 'limit' ] ) ? $ limit [ 'limit' ] : null , isset ( $ limit [ 'start' ] ) ? $ limit [ 'start' ] : null ) ; } else { $ query = $ query -> limit ( $ limit ) ; } $ query = $ query -> sort ( $ sort ) ; $ this -> setSearchParams ( $ searchParams ) ; foreach ( $ this -> searchParams as $ key => $ value ) { $ key = str_replace ( '__' , '.' , $ key ) ; if ( $ filter = $ this -> getFilter ( $ key ) ) { $ filter -> setModel ( $ this -> modelClass ) ; $ filter -> setValue ( $ value ) ; if ( ! $ filter -> isEmpty ( ) ) { $ query = $ query -> alterDataQuery ( array ( $ filter , 'apply' ) ) ; } } } if ( $ this -> connective != "AND" ) { throw new Exception ( "SearchContext connective '$this->connective' not supported after ORM-rewrite." ) ; } return $ query ; }
Returns a SQL object representing the search context for the given list of query parameters .
4,331
public function getResults ( $ searchParams , $ sort = false , $ limit = false ) { $ searchParams = array_filter ( ( array ) $ searchParams , array ( $ this , 'clearEmptySearchFields' ) ) ; return $ this -> getQuery ( $ searchParams , $ sort , $ limit ) ; }
Returns a result set from the given search parameters .
4,332
public function getFilter ( $ name ) { if ( isset ( $ this -> filters [ $ name ] ) ) { return $ this -> filters [ $ name ] ; } else { return null ; } }
Accessor for the filter attached to a named field .
4,333
public function setSearchParams ( $ searchParams ) { if ( $ searchParams instanceof HTTPRequest ) { $ this -> searchParams = $ searchParams -> getVars ( ) ; } else { $ this -> searchParams = $ searchParams ; } return $ this ; }
Set search param values
4,334
public function getSummary ( ) { $ list = ArrayList :: create ( ) ; foreach ( $ this -> searchParams as $ searchField => $ searchValue ) { if ( empty ( $ searchValue ) ) { continue ; } $ filter = $ this -> getFilter ( $ searchField ) ; if ( ! $ filter ) { continue ; } $ field = $ this -> fields -> fieldByName ( $ filter -> getFullName ( ) ) ; if ( ! $ field ) { continue ; } if ( $ field instanceof SelectField ) { $ source = $ field -> getSource ( ) ; if ( isset ( $ source [ $ searchValue ] ) ) { $ searchValue = $ source [ $ searchValue ] ; } } else { if ( $ field instanceof CheckboxField ) { $ searchValue = null ; } } $ list -> push ( ArrayData :: create ( [ 'Field' => $ field -> Title ( ) , 'Value' => $ searchValue , ] ) ) ; } return $ list ; }
Gets a list of what fields were searched and the values provided for each field . Returns an ArrayList of ArrayData suitable for rendering on a template .
4,335
public static function requireLogin ( HTTPRequest $ request , $ realm , $ permissionCode = null , $ tryUsingSessionLogin = true ) { if ( ( Director :: is_cli ( ) && static :: config ( ) -> get ( 'ignore_cli' ) ) ) { return true ; } $ member = null ; try { if ( $ request -> getHeader ( 'PHP_AUTH_USER' ) && $ request -> getHeader ( 'PHP_AUTH_PW' ) ) { $ authenticators = Security :: singleton ( ) -> getApplicableAuthenticators ( Authenticator :: LOGIN ) ; foreach ( $ authenticators as $ name => $ authenticator ) { $ member = $ authenticator -> authenticate ( [ 'Email' => $ request -> getHeader ( 'PHP_AUTH_USER' ) , 'Password' => $ request -> getHeader ( 'PHP_AUTH_PW' ) , ] , $ request ) ; if ( $ member instanceof Member ) { break ; } } } } catch ( DatabaseException $ e ) { return true ; } if ( ! $ member && $ tryUsingSessionLogin ) { $ member = Security :: getCurrentUser ( ) ; } if ( ! $ member ) { $ response = new HTTPResponse ( null , 401 ) ; $ response -> addHeader ( 'WWW-Authenticate' , "Basic realm=\"$realm\"" ) ; if ( $ request -> getHeader ( 'PHP_AUTH_USER' ) ) { $ response -> setBody ( _t ( 'SilverStripe\\Security\\BasicAuth.ERRORNOTREC' , "That username / password isn't recognised" ) ) ; } else { $ response -> setBody ( _t ( 'SilverStripe\\Security\\BasicAuth.ENTERINFO' , 'Please enter a username and password.' ) ) ; } $ e = new HTTPResponse_Exception ( null , 401 ) ; $ e -> setResponse ( $ response ) ; throw $ e ; } if ( $ permissionCode && ! Permission :: checkMember ( $ member -> ID , $ permissionCode ) ) { $ response = new HTTPResponse ( null , 401 ) ; $ response -> addHeader ( 'WWW-Authenticate' , "Basic realm=\"$realm\"" ) ; if ( $ request -> getHeader ( 'PHP_AUTH_USER' ) ) { $ response -> setBody ( _t ( 'SilverStripe\\Security\\BasicAuth.ERRORNOTADMIN' , 'That user is not an administrator.' ) ) ; } $ e = new HTTPResponse_Exception ( null , 401 ) ; $ e -> setResponse ( $ response ) ; throw $ e ; } return $ member ; }
Require basic authentication . Will request a username and password if none is given .
4,336
public static function protect_entire_site ( $ protect = true , $ code = self :: AUTH_PERMISSION , $ message = null ) { static :: config ( ) -> set ( 'entire_site_protected' , $ protect ) -> set ( 'entire_site_protected_code' , $ code ) ; if ( $ message ) { static :: config ( ) -> set ( 'entire_site_protected_message' , $ message ) ; } }
Enable protection of the entire site with basic authentication .
4,337
public function setWhitelist ( $ whitelist ) { if ( ! is_array ( $ whitelist ) ) { $ whitelist = preg_split ( '/\s*,\s*/' , $ whitelist ) ; } $ this -> whitelist = $ whitelist ; return $ this ; }
Set list of html properties to whitelist
4,338
public function Plain ( ) { $ text = preg_replace ( '/\<br(\s*)?\/?\>/i' , "\n" , $ this -> RAW ( ) ) ; $ text = preg_replace ( '/\<\/p\>/i' , "\n\n" , $ text ) ; $ text = strip_tags ( $ text ) ; $ text = preg_replace ( '~(\R){2,}~' , "\n\n" , $ text ) ; return trim ( Convert :: xml2raw ( $ text ) ) ; }
Get plain - text version
4,339
protected function getTransactionManager ( ) { if ( ! $ this -> transactionManager ) { if ( $ this -> connector instanceof TransactionManager ) { $ this -> transactionManager = new NestedTransactionManager ( $ this -> connector ) ; } else { $ this -> transactionManager = new NestedTransactionManager ( new MySQLTransactionManager ( $ this ) ) ; } } return $ this -> transactionManager ; }
Returns the TransactionManager to handle transactions for this database .
4,340
protected function resetTransactionNesting ( ) { if ( $ this -> connector instanceof TransactionalDBConnector ) { if ( $ this -> transactionNesting > 0 ) { $ this -> connector -> transactionRollback ( ) ; } } $ this -> transactionNesting = 0 ; }
In error condition set transactionNesting to zero
4,341
protected function inspectQuery ( $ sql ) { $ isDDL = $ this -> getConnector ( ) -> isQueryDDL ( $ sql ) ; if ( $ isDDL ) { $ this -> resetTransactionNesting ( ) ; } }
Inspect a SQL query prior to execution
4,342
public function clearTable ( $ table ) { $ this -> query ( "DELETE FROM \"$table\"" ) ; $ autoIncrement = $ this -> preparedQuery ( 'SELECT "AUTO_INCREMENT" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?' , [ $ this -> getSelectedDatabase ( ) , $ table ] ) -> value ( ) ; if ( $ autoIncrement > 1 ) { $ this -> query ( "ALTER TABLE \"$table\" AUTO_INCREMENT = 1" ) ; } }
Clear all data in a given table
4,343
public function resolveURL ( $ resource ) { if ( empty ( $ resource ) ) { return null ; } $ resource = $ this -> resolveResource ( $ resource ) ; $ generator = Injector :: inst ( ) -> get ( ResourceURLGenerator :: class ) ; return $ generator -> urlForResource ( $ resource ) ; }
Resolves resource specifier to the given url .
4,344
public function resolveResource ( $ resource ) { if ( ! preg_match ( '#^ *(?<module>[^/: ]+/[^/: ]+) *: *(?<resource>[^ ]*)$#' , $ resource , $ matches ) ) { return $ resource ; } $ module = $ matches [ 'module' ] ; $ resource = $ matches [ 'resource' ] ; $ moduleObj = ModuleLoader :: getModule ( $ module ) ; if ( ! $ moduleObj ) { throw new InvalidArgumentException ( "Can't find module '$module', the composer.json file may be missing from the modules installation directory" ) ; } $ resourceObj = $ moduleObj -> getResource ( $ resource ) ; return $ resourceObj ; }
Return module resource for the given path if specified as one . Returns the original resource otherwise .
4,345
public static function create ( $ select = "*" , $ from = array ( ) , $ where = array ( ) , $ orderby = array ( ) , $ groupby = array ( ) , $ having = array ( ) , $ limit = array ( ) ) { return Injector :: inst ( ) -> createWithArgs ( __CLASS__ , func_get_args ( ) ) ; }
Construct a new SQLSelect .
4,346
public function setSelect ( $ fields ) { $ this -> select = array ( ) ; if ( func_num_args ( ) > 1 ) { $ fields = func_get_args ( ) ; } elseif ( ! is_array ( $ fields ) ) { $ fields = array ( $ fields ) ; } return $ this -> addSelect ( $ fields ) ; }
Set the list of columns to be selected by the query .
4,347
public function addSelect ( $ fields ) { if ( func_num_args ( ) > 1 ) { $ fields = func_get_args ( ) ; } elseif ( ! is_array ( $ fields ) ) { $ fields = array ( $ fields ) ; } foreach ( $ fields as $ idx => $ field ) { $ this -> selectField ( $ field , is_numeric ( $ idx ) ? null : $ idx ) ; } return $ this ; }
Add to the list of columns to be selected by the query .
4,348
public function selectField ( $ field , $ alias = null ) { if ( ! $ alias ) { if ( preg_match ( '/"([^"]+)"$/' , $ field , $ matches ) ) { $ alias = $ matches [ 1 ] ; } else { $ alias = $ field ; } } $ this -> select [ $ alias ] = $ field ; return $ this ; }
Select an additional field .
4,349
public function setLimit ( $ limit , $ offset = 0 ) { if ( ( is_numeric ( $ limit ) && $ limit < 0 ) || ( is_numeric ( $ offset ) && $ offset < 0 ) ) { throw new InvalidArgumentException ( "SQLSelect::setLimit() only takes positive values" ) ; } if ( $ limit === 0 ) { Deprecation :: notice ( '4.3' , "setLimit(0) is deprecated in SS4. To clear limit, call setLimit(null). " . "In SS5 a limit of 0 will instead return no records." ) ; } if ( is_numeric ( $ limit ) && ( $ limit || $ offset ) ) { $ this -> limit = array ( 'start' => ( int ) $ offset , 'limit' => ( int ) $ limit , ) ; } elseif ( $ limit && is_string ( $ limit ) ) { if ( strpos ( $ limit , ',' ) !== false ) { list ( $ start , $ innerLimit ) = explode ( ',' , $ limit , 2 ) ; } else { list ( $ innerLimit , $ start ) = explode ( ' OFFSET ' , strtoupper ( $ limit ) , 2 ) ; } $ this -> limit = array ( 'start' => ( int ) $ start , 'limit' => ( int ) $ innerLimit , ) ; } elseif ( $ limit === null && $ offset ) { $ this -> limit = array ( 'start' => ( int ) $ offset , 'limit' => $ limit ) ; } else { $ this -> limit = $ limit ; } return $ this ; }
Pass LIMIT clause either as SQL snippet or in array format . Internally limit will always be stored as a map containing the keys start and limit
4,350
public function setOrderBy ( $ clauses = null , $ direction = null ) { $ this -> orderby = array ( ) ; return $ this -> addOrderBy ( $ clauses , $ direction ) ; }
Set ORDER BY clause either as SQL snippet or in array format .
4,351
public function addOrderBy ( $ clauses = null , $ direction = null ) { if ( empty ( $ clauses ) ) { return $ this ; } if ( is_string ( $ clauses ) ) { if ( strpos ( $ clauses , "(" ) !== false ) { $ sort = preg_split ( "/,(?![^()]*+\\))/" , $ clauses ) ; } else { $ sort = explode ( "," , $ clauses ) ; } $ clauses = array ( ) ; foreach ( $ sort as $ clause ) { list ( $ column , $ direction ) = $ this -> getDirectionFromString ( $ clause , $ direction ) ; $ clauses [ $ column ] = $ direction ; } } if ( is_array ( $ clauses ) ) { foreach ( $ clauses as $ key => $ value ) { if ( ! is_numeric ( $ key ) ) { $ column = trim ( $ key ) ; $ columnDir = strtoupper ( trim ( $ value ) ) ; } else { list ( $ column , $ columnDir ) = $ this -> getDirectionFromString ( $ value ) ; } $ this -> orderby [ $ column ] = $ columnDir ; } } else { user_error ( 'SQLSelect::orderby() incorrect format for $orderby' , E_USER_WARNING ) ; } if ( $ this -> orderby ) { $ i = 0 ; $ orderby = array ( ) ; foreach ( $ this -> orderby as $ clause => $ dir ) { if ( strpos ( $ clause , '(' ) !== false || strpos ( $ clause , " " ) !== false ) { $ clause = trim ( $ clause ) ; do { $ column = "_SortColumn{$i}" ; ++ $ i ; } while ( array_key_exists ( '"' . $ column . '"' , $ this -> orderby ) ) ; $ this -> selectField ( $ clause , $ column ) ; $ clause = '"' . $ column . '"' ; } $ orderby [ $ clause ] = $ dir ; } $ this -> orderby = $ orderby ; } return $ this ; }
Add ORDER BY clause either as SQL snippet or in array format .
4,352
private function getDirectionFromString ( $ value , $ defaultDirection = null ) { if ( preg_match ( '/^(.*)(asc|desc)$/i' , $ value , $ matches ) ) { $ column = trim ( $ matches [ 1 ] ) ; $ direction = strtoupper ( $ matches [ 2 ] ) ; } else { $ column = $ value ; $ direction = $ defaultDirection ? $ defaultDirection : "ASC" ; } return array ( $ column , $ direction ) ; }
Extract the direction part of a single - column order by clause .
4,353
public function getOrderBy ( ) { $ orderby = $ this -> orderby ; if ( ! $ orderby ) { $ orderby = array ( ) ; } if ( ! is_array ( $ orderby ) ) { $ orderby = preg_split ( '/,(?![^()]*+\\))/' , $ orderby ) ; } foreach ( $ orderby as $ k => $ v ) { if ( strpos ( $ v , ' ' ) !== false ) { unset ( $ orderby [ $ k ] ) ; $ rule = explode ( ' ' , trim ( $ v ) ) ; $ clause = $ rule [ 0 ] ; $ dir = ( isset ( $ rule [ 1 ] ) ) ? $ rule [ 1 ] : 'ASC' ; $ orderby [ $ clause ] = $ dir ; } } return $ orderby ; }
Returns the current order by as array if not already . To handle legacy statements which are stored as strings . Without clauses and directions convert the orderby clause to something readable .
4,354
public function reverseOrderBy ( ) { $ order = $ this -> getOrderBy ( ) ; $ this -> orderby = array ( ) ; foreach ( $ order as $ clause => $ dir ) { $ dir = ( strtoupper ( $ dir ) == 'DESC' ) ? 'ASC' : 'DESC' ; $ this -> addOrderBy ( $ clause , $ dir ) ; } return $ this ; }
Reverses the order by clause by replacing ASC or DESC references in the current order by with it s corollary .
4,355
public function addGroupBy ( $ groupby ) { if ( is_array ( $ groupby ) ) { $ this -> groupby = array_merge ( $ this -> groupby , $ groupby ) ; } elseif ( ! empty ( $ groupby ) ) { $ this -> groupby [ ] = $ groupby ; } return $ this ; }
Add a GROUP BY clause .
4,356
public function setHaving ( $ having ) { $ having = func_num_args ( ) > 1 ? func_get_args ( ) : $ having ; $ this -> having = array ( ) ; return $ this -> addHaving ( $ having ) ; }
Set a HAVING clause .
4,357
public function addHaving ( $ having ) { $ having = $ this -> normalisePredicates ( func_get_args ( ) ) ; $ this -> having = array_merge ( $ this -> having , $ having ) ; return $ this ; }
Add a HAVING clause
4,358
public function unlimitedRowCount ( $ column = null ) { if ( count ( $ this -> having ) ) { $ records = $ this -> execute ( ) ; return $ records -> numRecords ( ) ; } $ clone = clone $ this ; $ clone -> limit = null ; $ clone -> orderby = null ; if ( $ column == null ) { if ( $ this -> groupby ) { $ countQuery = new SQLSelect ( ) ; $ countQuery -> setSelect ( "count(*)" ) ; $ countQuery -> setFrom ( array ( '(' . $ clone -> sql ( $ innerParameters ) . ') all_distinct' ) ) ; $ sql = $ countQuery -> sql ( $ parameters ) ; $ result = DB :: prepared_query ( $ sql , $ innerParameters ) ; return ( int ) $ result -> value ( ) ; } else { $ clone -> setSelect ( array ( "count(*)" ) ) ; } } else { $ clone -> setSelect ( array ( "count($column)" ) ) ; } $ clone -> setGroupBy ( array ( ) ) ; return ( int ) $ clone -> execute ( ) -> value ( ) ; }
Return the number of rows in this query if the limit were removed . Useful in paged data sets .
4,359
public function count ( $ column = null ) { if ( ! empty ( $ this -> having ) ) { $ records = $ this -> execute ( ) ; return $ records -> numRecords ( ) ; } elseif ( $ column == null ) { if ( $ this -> groupby ) { $ column = 'DISTINCT ' . implode ( ", " , $ this -> groupby ) ; } else { $ column = '*' ; } } $ clone = clone $ this ; $ clone -> select = array ( 'Count' => "count($column)" ) ; $ clone -> limit = null ; $ clone -> orderby = null ; $ clone -> groupby = null ; $ count = ( int ) $ clone -> execute ( ) -> value ( ) ; if ( $ this -> limit ) { if ( $ this -> limit [ 'limit' ] !== null && $ count >= ( $ this -> limit [ 'start' ] + $ this -> limit [ 'limit' ] ) ) { return $ this -> limit [ 'limit' ] ; } else { return max ( 0 , $ count - $ this -> limit [ 'start' ] ) ; } } else { return $ count ; } }
Return the number of rows in this query respecting limit and offset .
4,360
public function aggregate ( $ column , $ alias = null ) { $ clone = clone $ this ; if ( $ this -> limit ) { $ clone -> setLimit ( $ this -> limit ) ; $ clone -> setOrderBy ( $ this -> orderby ) ; } else { $ clone -> setOrderBy ( array ( ) ) ; } $ clone -> setGroupBy ( $ this -> groupby ) ; if ( $ alias ) { $ clone -> setSelect ( array ( ) ) ; $ clone -> selectField ( $ column , $ alias ) ; } else { $ clone -> setSelect ( $ column ) ; } return $ clone ; }
Return a new SQLSelect that calls the given aggregate functions on this data .
4,361
public function firstRow ( ) { $ query = clone $ this ; $ offset = $ this -> limit ? $ this -> limit [ 'start' ] : 0 ; $ query -> setLimit ( 1 , $ offset ) ; return $ query ; }
Returns a query that returns only the first row of this query
4,362
public function lastRow ( ) { $ query = clone $ this ; $ offset = $ this -> limit ? $ this -> limit [ 'start' ] : 0 ; $ index = max ( $ this -> count ( ) + $ offset - 1 , 0 ) ; $ query -> setLimit ( 1 , $ index ) ; return $ query ; }
Returns a query that returns only the last row of this query
4,363
public function groupedDataClasses ( ) { $ allClasses = get_declared_classes ( ) ; $ rootClasses = [ ] ; foreach ( $ allClasses as $ class ) { if ( get_parent_class ( $ class ) == DataObject :: class ) { $ rootClasses [ $ class ] = array ( ) ; } } foreach ( $ allClasses as $ class ) { if ( ! isset ( $ rootClasses [ $ class ] ) && is_subclass_of ( $ class , DataObject :: class ) ) { foreach ( $ rootClasses as $ rootClass => $ dummy ) { if ( is_subclass_of ( $ class , $ rootClass ) ) { $ rootClasses [ $ rootClass ] [ ] = $ class ; break ; } } } } return $ rootClasses ; }
Get the data classes grouped by their root class
4,364
protected function getReturnURL ( ) { $ url = $ this -> request -> getVar ( 'returnURL' ) ; if ( empty ( $ url ) || ! Director :: is_site_url ( $ url ) ) { return null ; } return Director :: absoluteURL ( $ url , true ) ; }
Gets the url to return to after build
4,365
public function buildDefaults ( ) { $ dataClasses = ClassInfo :: subclassesFor ( DataObject :: class ) ; array_shift ( $ dataClasses ) ; if ( ! Director :: is_cli ( ) ) { echo "<ul>" ; } foreach ( $ dataClasses as $ dataClass ) { singleton ( $ dataClass ) -> requireDefaultRecords ( ) ; if ( Director :: is_cli ( ) ) { echo "Defaults loaded for $dataClass\n" ; } else { echo "<li>Defaults loaded for $dataClass</li>\n" ; } } if ( ! Director :: is_cli ( ) ) { echo "</ul>" ; } }
Build the default data calling requireDefaultRecords on all DataObject classes
4,366
public static function lastBuilt ( ) { $ file = TEMP_PATH . DIRECTORY_SEPARATOR . 'database-last-generated-' . str_replace ( array ( '\\' , '/' , ':' ) , '.' , Director :: baseFolder ( ) ) ; if ( file_exists ( $ file ) ) { return filemtime ( $ file ) ; } return null ; }
Returns the timestamp of the time that the database was last built
4,367
protected function getClassNameRemappingFields ( ) { $ dataClasses = ClassInfo :: getValidSubClasses ( DataObject :: class ) ; $ schema = DataObject :: getSchema ( ) ; $ remapping = [ ] ; foreach ( $ dataClasses as $ className ) { $ fieldSpecs = $ schema -> fieldSpecs ( $ className ) ; foreach ( $ fieldSpecs as $ fieldName => $ fieldSpec ) { if ( Injector :: inst ( ) -> create ( $ fieldSpec , 'Dummy' ) instanceof DBClassName ) { $ remapping [ $ className ] [ ] = $ fieldName ; } } } return $ remapping ; }
Find all DBClassName fields on valid subclasses of DataObject that should be remapped . This includes ClassName fields as well as polymorphic class name fields .
4,368
public function cleanup ( ) { $ baseClasses = [ ] ; foreach ( ClassInfo :: subclassesFor ( DataObject :: class ) as $ class ) { if ( get_parent_class ( $ class ) == DataObject :: class ) { $ baseClasses [ ] = $ class ; } } $ schema = DataObject :: getSchema ( ) ; foreach ( $ baseClasses as $ baseClass ) { $ baseTable = $ schema -> baseDataTable ( $ baseClass ) ; $ subclasses = ClassInfo :: subclassesFor ( $ baseClass ) ; unset ( $ subclasses [ 0 ] ) ; foreach ( $ subclasses as $ k => $ subclass ) { if ( ! DataObject :: getSchema ( ) -> classHasTable ( $ subclass ) ) { unset ( $ subclasses [ $ k ] ) ; } } if ( $ subclasses ) { $ records = DB :: query ( "SELECT * FROM \"$baseTable\"" ) ; foreach ( $ subclasses as $ subclass ) { $ subclassTable = $ schema -> tableName ( $ subclass ) ; $ recordExists [ $ subclass ] = DB :: query ( "SELECT \"ID\" FROM \"$subclassTable\"" ) -> keyedColumn ( ) ; } foreach ( $ records as $ record ) { foreach ( $ subclasses as $ subclass ) { $ subclassTable = $ schema -> tableName ( $ subclass ) ; $ id = $ record [ 'ID' ] ; if ( ( $ record [ 'ClassName' ] != $ subclass ) && ( ! is_subclass_of ( $ record [ 'ClassName' ] , $ subclass ) ) && isset ( $ recordExists [ $ subclass ] [ $ id ] ) ) { $ sql = "DELETE FROM \"$subclassTable\" WHERE \"ID\" = ?" ; echo "<li>$sql [{$id}]</li>" ; DB :: prepared_query ( $ sql , [ $ id ] ) ; } } } } } }
Remove invalid records from tables - that is records that don t have corresponding records in their parent class tables .
4,369
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 ) , $ 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 { $ this -> setAttribute ( 'autocomplete' , 'off' ) ; $ emailField -> setAttribute ( 'autocomplete' , 'off' ) ; } if ( Security :: config ( ) -> get ( 'autologin_enabled' ) ) { $ fields -> push ( CheckboxField :: create ( "Remember" , _t ( 'SilverStripe\\Security\\Member.KEEPMESIGNEDIN' , "Keep me signed in" ) ) -> setAttribute ( 'title' , _t ( 'SilverStripe\\Security\\Member.REMEMBERME' , "Remember me next time? (for {count} days on this device)" , [ '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
4,370
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
4,371
public function getName ( ) { if ( $ this -> getEmbed ( ) -> title ) { return $ this -> getEmbed ( ) -> title ; } return preg_replace ( '/\?.*/' , '' , basename ( $ this -> getEmbed ( ) -> getUrl ( ) ) ) ; }
Get human readable name for this resource
4,372
public function getEmbed ( ) { if ( ! $ this -> embed ) { $ this -> embed = Embed :: create ( $ this -> url , $ this -> getOptions ( ) , $ this -> getDispatcher ( ) ) ; } return $ this -> embed ; }
Returns a bootstrapped Embed object
4,373
public function runTask ( $ request ) { $ name = $ request -> param ( 'TaskName' ) ; $ tasks = $ this -> getTasks ( ) ; $ title = function ( $ content ) { printf ( Director :: is_cli ( ) ? "%s\n\n" : '<h1>%s</h1>' , $ content ) ; } ; $ message = function ( $ content ) { printf ( Director :: is_cli ( ) ? "%s\n" : '<p>%s</p>' , $ content ) ; } ; foreach ( $ tasks as $ task ) { if ( $ task [ 'segment' ] == $ name ) { $ inst = Injector :: inst ( ) -> create ( $ task [ 'class' ] ) ; $ title ( sprintf ( 'Running Task %s' , $ inst -> getTitle ( ) ) ) ; if ( ! $ inst -> isEnabled ( ) ) { $ message ( 'The task is disabled' ) ; return ; } $ inst -> run ( $ request ) ; return ; } } $ message ( sprintf ( 'The build task "%s" could not be found' , Convert :: raw2xml ( $ name ) ) ) ; }
Runs a BuildTask
4,374
public function setDataQueryParam ( $ keyOrArray , $ val = null ) { $ clone = clone $ this ; if ( is_array ( $ keyOrArray ) ) { foreach ( $ keyOrArray as $ key => $ value ) { $ clone -> dataQuery -> setQueryParam ( $ key , $ value ) ; } } else { $ clone -> dataQuery -> setQueryParam ( $ keyOrArray , $ val ) ; } return $ clone ; }
Returns a new DataList instance with the specified query parameter assigned
4,375
public function where ( $ filter ) { return $ this -> alterDataQuery ( function ( DataQuery $ query ) use ( $ filter ) { $ query -> where ( $ filter ) ; } ) ; }
Return a new DataList instance with a WHERE clause added to this list s query .
4,376
public function whereAny ( $ filter ) { return $ this -> alterDataQuery ( function ( DataQuery $ query ) use ( $ filter ) { $ query -> whereAny ( $ filter ) ; } ) ; }
Return a new DataList instance with a WHERE clause added to this list s query . All conditions provided in the filter will be joined with an OR
4,377
public function canFilterBy ( $ fieldName ) { $ model = singleton ( $ this -> dataClass ) ; $ relations = explode ( "." , $ fieldName ) ; $ fieldName = array_pop ( $ relations ) ; foreach ( $ relations as $ r ) { $ relationClass = $ model -> getRelationClass ( $ r ) ; if ( ! $ relationClass ) { return false ; } $ model = singleton ( $ relationClass ) ; if ( ! $ model ) { return false ; } } if ( $ model -> hasDatabaseField ( $ fieldName ) ) { return true ; } return false ; }
Returns true if this DataList can be filtered by the given field .
4,378
public function limit ( $ limit , $ offset = 0 ) { return $ this -> alterDataQuery ( function ( DataQuery $ query ) use ( $ limit , $ offset ) { $ query -> limit ( $ limit , $ offset ) ; } ) ; }
Return a new DataList instance with the records returned in this query restricted by a limit clause .
4,379
public function distinct ( $ value ) { return $ this -> alterDataQuery ( function ( DataQuery $ query ) use ( $ value ) { $ query -> distinct ( $ value ) ; } ) ; }
Return a new DataList instance with distinct records or not
4,380
public function sort ( ) { $ count = func_num_args ( ) ; if ( $ count == 0 ) { return $ this ; } if ( $ count > 2 ) { throw new InvalidArgumentException ( 'This method takes zero, one or two arguments' ) ; } if ( $ count == 2 ) { $ col = null ; $ dir = null ; list ( $ col , $ dir ) = func_get_args ( ) ; if ( ! in_array ( strtolower ( $ dir ) , [ 'desc' , 'asc' ] ) ) { user_error ( 'Second argument to sort must be either ASC or DESC' ) ; } $ sort = [ $ col => $ dir ] ; } else { $ sort = func_get_arg ( 0 ) ; } return $ this -> alterDataQuery ( function ( DataQuery $ query , DataList $ list ) use ( $ sort ) { if ( is_string ( $ sort ) && $ sort ) { if ( false !== stripos ( $ sort , ' asc' ) || false !== stripos ( $ sort , ' desc' ) ) { $ query -> sort ( $ sort ) ; } else { $ list -> applyRelation ( $ sort , $ column , true ) ; $ query -> sort ( $ column , 'ASC' ) ; } } elseif ( is_array ( $ sort ) ) { $ query -> sort ( null , null ) ; foreach ( $ sort as $ column => $ direction ) { $ list -> applyRelation ( $ column , $ relationColumn , true ) ; $ query -> sort ( $ relationColumn , $ direction , false ) ; } } } ) ; }
Return a new DataList instance as a copy of this data list with the sort order set .
4,381
public function filter ( ) { $ arguments = func_get_args ( ) ; switch ( sizeof ( $ arguments ) ) { case 1 : $ filters = $ arguments [ 0 ] ; break ; case 2 : $ filters = [ $ arguments [ 0 ] => $ arguments [ 1 ] ] ; break ; default : throw new InvalidArgumentException ( 'Incorrect number of arguments passed to filter()' ) ; } return $ this -> addFilter ( $ filters ) ; }
Return a copy of this list which only includes items with these charactaristics
4,382
public function addFilter ( $ filterArray ) { $ list = $ this ; foreach ( $ filterArray as $ expression => $ value ) { $ filter = $ this -> createSearchFilter ( $ expression , $ value ) ; $ list = $ list -> alterDataQuery ( [ $ filter , 'apply' ] ) ; } return $ list ; }
Return a new instance of the list with an added filter
4,383
public function applyRelation ( $ field , & $ columnName = null , $ linearOnly = false ) { if ( ! $ this -> isValidRelationName ( $ field ) ) { $ columnName = $ field ; return $ this ; } if ( strpos ( $ field , '.' ) === false ) { $ columnName = '"' . $ field . '"' ; return $ this ; } return $ this -> alterDataQuery ( function ( DataQuery $ query ) use ( $ field , & $ columnName , $ linearOnly ) { $ relations = explode ( '.' , $ field ) ; $ fieldName = array_pop ( $ relations ) ; $ relationModelName = $ query -> applyRelation ( $ relations , $ linearOnly ) ; $ relationPrefix = $ query -> applyRelationPrefix ( $ relations ) ; $ columnName = DataObject :: getSchema ( ) -> sqlColumnForField ( $ relationModelName , $ fieldName , $ relationPrefix ) ; } ) ; }
Given a field or relation name apply it safely to this datalist .
4,384
public function exclude ( ) { $ numberFuncArgs = count ( func_get_args ( ) ) ; $ whereArguments = [ ] ; if ( $ numberFuncArgs == 1 && is_array ( func_get_arg ( 0 ) ) ) { $ whereArguments = func_get_arg ( 0 ) ; } elseif ( $ numberFuncArgs == 2 ) { $ whereArguments [ func_get_arg ( 0 ) ] = func_get_arg ( 1 ) ; } else { throw new InvalidArgumentException ( 'Incorrect number of arguments passed to exclude()' ) ; } return $ this -> alterDataQuery ( function ( DataQuery $ query ) use ( $ whereArguments ) { $ subquery = $ query -> disjunctiveGroup ( ) ; foreach ( $ whereArguments as $ field => $ value ) { $ filter = $ this -> createSearchFilter ( $ field , $ value ) ; $ filter -> exclude ( $ subquery ) ; } } ) ; }
Return a copy of this list which does not contain any items that match all params
4,385
public function excludeAny ( ) { $ numberFuncArgs = count ( func_get_args ( ) ) ; $ whereArguments = [ ] ; if ( $ numberFuncArgs == 1 && is_array ( func_get_arg ( 0 ) ) ) { $ whereArguments = func_get_arg ( 0 ) ; } elseif ( $ numberFuncArgs == 2 ) { $ whereArguments [ func_get_arg ( 0 ) ] = func_get_arg ( 1 ) ; } else { throw new InvalidArgumentException ( 'Incorrect number of arguments passed to excludeAny()' ) ; } return $ this -> alterDataQuery ( function ( DataQuery $ dataQuery ) use ( $ whereArguments ) { foreach ( $ whereArguments as $ field => $ value ) { $ filter = $ this -> createSearchFilter ( $ field , $ value ) ; $ filter -> exclude ( $ dataQuery ) ; } return $ dataQuery ; } ) ; }
Return a copy of this list which does not contain any items with any of these params
4,386
public function innerJoin ( $ table , $ onClause , $ alias = null , $ order = 20 , $ parameters = [ ] ) { return $ this -> alterDataQuery ( function ( DataQuery $ query ) use ( $ table , $ onClause , $ alias , $ order , $ parameters ) { $ query -> innerJoin ( $ table , $ onClause , $ alias , $ order , $ parameters ) ; } ) ; }
Return a new DataList instance with an inner join clause added to this list s query .
4,387
public function toArray ( ) { $ query = $ this -> dataQuery -> query ( ) ; $ rows = $ query -> execute ( ) ; $ results = [ ] ; foreach ( $ rows as $ row ) { $ results [ ] = $ this -> createDataObject ( $ row ) ; } return $ results ; }
Return an array of the actual items that this DataList contains at this stage . This is when the query is actually executed .
4,388
public function getGenerator ( ) { $ query = $ this -> dataQuery -> query ( ) -> execute ( ) ; while ( $ row = $ query -> record ( ) ) { yield $ this -> createDataObject ( $ row ) ; } }
Returns a generator for this DataList
4,389
public function createDataObject ( $ row ) { $ class = $ this -> dataClass ; if ( empty ( $ row [ 'ClassName' ] ) ) { $ row [ 'ClassName' ] = $ class ; } if ( empty ( $ row [ 'RecordClassName' ] ) ) { $ row [ 'RecordClassName' ] = $ row [ 'ClassName' ] ; } if ( class_exists ( $ row [ 'RecordClassName' ] ) ) { $ class = $ row [ 'RecordClassName' ] ; } $ item = Injector :: inst ( ) -> create ( $ class , $ row , false , $ this -> getQueryParams ( ) ) ; return $ item ; }
Create a DataObject from the given SQL row
4,390
public function first ( ) { foreach ( $ this -> dataQuery -> firstRow ( ) -> execute ( ) as $ row ) { return $ this -> createDataObject ( $ row ) ; } return null ; }
Returns the first item in this DataList
4,391
public function last ( ) { foreach ( $ this -> dataQuery -> lastRow ( ) -> execute ( ) as $ row ) { return $ this -> createDataObject ( $ row ) ; } return null ; }
Returns the last item in this DataList
4,392
public function setQueriedColumns ( $ queriedColumns ) { return $ this -> alterDataQuery ( function ( DataQuery $ query ) use ( $ queriedColumns ) { $ query -> setQueriedColumns ( $ queriedColumns ) ; } ) ; }
Restrict the columns to fetch into this DataList
4,393
public function setByIDList ( $ idList ) { $ has = [ ] ; foreach ( $ this -> column ( ) as $ id ) { $ has [ $ id ] = true ; } $ itemsToDelete = $ has ; if ( $ idList ) { foreach ( $ idList as $ id ) { unset ( $ itemsToDelete [ $ id ] ) ; if ( $ id && ! isset ( $ has [ $ id ] ) ) { $ this -> add ( $ id ) ; } } } $ this -> removeMany ( array_keys ( $ itemsToDelete ) ) ; }
Sets the ComponentSet to be the given ID list . Records will be added and deleted as appropriate .
4,394
public function newObject ( $ initialFields = null ) { $ class = $ this -> dataClass ; return Injector :: inst ( ) -> create ( $ class , $ initialFields , false ) ; }
Return a new item to add to this DataList .
4,395
protected function configFor ( $ name ) { if ( array_key_exists ( $ name , $ this -> configs ) ) { return $ this -> configs [ $ name ] ; } $ config = Config :: inst ( ) -> get ( Injector :: class , $ name ) ; $ this -> configs [ $ name ] = $ config ; return $ config ; }
Retrieves the config for a named service without performing a hierarchy walk
4,396
public static function fromString ( $ content , $ cacheTemplate = null ) { $ viewer = SSViewer_FromString :: create ( $ content ) ; if ( $ cacheTemplate !== null ) { $ viewer -> setCacheTemplate ( $ cacheTemplate ) ; } return $ viewer ; }
Create a template from a string instead of a . ss file
4,397
public static function add_themes ( $ themes = [ ] ) { $ currentThemes = SSViewer :: get_themes ( ) ; $ finalThemes = array_merge ( $ themes , $ currentThemes ) ; static :: set_themes ( array_values ( array_unique ( $ finalThemes ) ) ) ; }
Add to the list of active themes to apply
4,398
public static function get_themes ( ) { $ default = [ self :: PUBLIC_THEME , self :: DEFAULT_THEME ] ; if ( ! SSViewer :: config ( ) -> uninherited ( 'theme_enabled' ) ) { return $ default ; } $ themes = static :: $ current_themes ; if ( ! isset ( $ themes ) ) { $ themes = SSViewer :: config ( ) -> uninherited ( 'themes' ) ; } if ( $ themes ) { return $ themes ; } if ( $ theme = SSViewer :: config ( ) -> uninherited ( 'theme' ) ) { return [ self :: PUBLIC_THEME , $ theme , self :: DEFAULT_THEME ] ; } return $ default ; }
Get the list of active themes
4,399
public function getParser ( ) { if ( ! $ this -> parser ) { $ this -> setParser ( Injector :: inst ( ) -> get ( 'SilverStripe\\View\\SSTemplateParser' ) ) ; } return $ this -> parser ; }
Returns the parser that is set for template generation