idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
4,600
|
public function parsePreparedParameters ( $ parameters , & $ blobs ) { $ types = '' ; $ values = array ( ) ; $ blobs = array ( ) ; $ parametersCount = count ( $ parameters ) ; for ( $ index = 0 ; $ index < $ parametersCount ; $ index ++ ) { $ value = $ parameters [ $ index ] ; $ phpType = gettype ( $ value ) ; if ( $ phpType === 'array' ) { $ phpType = $ value [ 'type' ] ; $ value = $ value [ 'value' ] ; } switch ( $ phpType ) { case 'boolean' : case 'integer' : $ types .= 'i' ; break ; case 'float' : case 'double' : $ types .= 'd' ; break ; case 'object' : case 'resource' : case 'string' : case 'NULL' : $ types .= 's' ; break ; case 'blob' : $ types .= 'b' ; $ blobs [ ] = array ( 'index' => $ index , 'value' => $ value ) ; $ value = null ; break ; case 'array' : case 'unknown type' : default : user_error ( "Cannot bind parameter \"$value\" as it is an unsupported type ($phpType)" , E_USER_ERROR ) ; break ; } $ values [ ] = $ value ; } return array_merge ( array ( $ types ) , $ values ) ; }
|
Prepares the list of parameters in preparation for passing to mysqli_stmt_bind_param
|
4,601
|
public function bindParameters ( mysqli_stmt $ statement , array $ parameters ) { $ boundNames = [ ] ; $ parametersCount = count ( $ parameters ) ; for ( $ i = 0 ; $ i < $ parametersCount ; $ i ++ ) { $ boundName = "param$i" ; $ $ boundName = $ parameters [ $ i ] ; $ boundNames [ ] = & $ $ boundName ; } $ statement -> bind_param ( ... $ boundNames ) ; }
|
Binds a list of parameters to a statement
|
4,602
|
public function Short ( ) { if ( ! $ this -> value ) { return null ; } $ formatter = $ this -> getFormatter ( IntlDateFormatter :: SHORT ) ; return $ formatter -> format ( $ this -> getTimestamp ( ) ) ; }
|
Returns the date in the localised short format
|
4,603
|
public function Format ( $ format ) { if ( ! $ this -> value ) { return null ; } $ formatter = $ this -> getFormatter ( ) ; $ formatter -> setPattern ( $ format ) ; return $ formatter -> format ( $ this -> getTimestamp ( ) ) ; }
|
Return the time using a particular formatting string .
|
4,604
|
public function FormatFromSettings ( $ member = null ) { if ( ! $ member ) { $ member = Security :: getCurrentUser ( ) ; } if ( ! $ member ) { return $ this -> Nice ( ) ; } $ format = $ member -> getTimeFormat ( ) ; return $ this -> Format ( $ format ) ; }
|
Return a time formatted as per a CMS user s settings .
|
4,605
|
public static function get_conn ( $ name = 'default' ) { if ( isset ( self :: $ connections [ $ name ] ) ) { return self :: $ connections [ $ name ] ; } $ config = static :: getConfig ( $ name ) ; if ( $ config ) { return static :: connect ( $ config , $ name ) ; } return null ; }
|
Get the global database connection .
|
4,606
|
public static function get_schema ( $ name = 'default' ) { $ connection = self :: get_conn ( $ name ) ; if ( $ connection ) { return $ connection -> getSchemaManager ( ) ; } return null ; }
|
Retrieves the schema manager for the current database
|
4,607
|
public static function get_connector ( $ name = 'default' ) { $ connection = self :: get_conn ( $ name ) ; if ( $ connection ) { return $ connection -> getConnector ( ) ; } return null ; }
|
Retrieves the connector object for the current database
|
4,608
|
public static function set_alternative_database_name ( $ name = null ) { if ( ! Config :: inst ( ) -> get ( static :: class , 'alternative_database_enabled' ) ) { return ; } if ( Director :: is_cli ( ) ) { return ; } if ( $ name && ! self :: valid_alternative_database_name ( $ name ) ) { throw new InvalidArgumentException ( sprintf ( 'Invalid alternative database name: "%s"' , $ name ) ) ; } if ( ! Injector :: inst ( ) -> has ( HTTPRequest :: class ) ) { return ; } $ request = Injector :: inst ( ) -> get ( HTTPRequest :: class ) ; if ( $ name ) { $ request -> getSession ( ) -> set ( self :: ALT_DB_KEY , $ name ) ; } else { $ request -> getSession ( ) -> clear ( self :: ALT_DB_KEY ) ; } }
|
Set an alternative database in a browser cookie with the cookie lifetime set to the browser session . This is useful for integration testing on temporary databases .
|
4,609
|
public static function get_alternative_database_name ( ) { if ( ! Config :: inst ( ) -> get ( static :: class , 'alternative_database_enabled' ) ) { return false ; } if ( Director :: is_cli ( ) ) { return false ; } if ( ! Injector :: inst ( ) -> has ( HTTPRequest :: class ) ) { return null ; } $ request = Injector :: inst ( ) -> get ( HTTPRequest :: class ) ; if ( ! $ request -> getSession ( ) -> isStarted ( ) ) { return null ; } $ name = $ request -> getSession ( ) -> get ( self :: ALT_DB_KEY ) ; if ( self :: valid_alternative_database_name ( $ name ) ) { return $ name ; } return false ; }
|
Get the name of the database in use
|
4,610
|
public static function valid_alternative_database_name ( $ name ) { if ( Director :: isLive ( ) || empty ( $ name ) ) { return false ; } $ prefix = Environment :: getEnv ( 'SS_DATABASE_PREFIX' ) ? : 'ss_' ; $ pattern = strtolower ( sprintf ( '/^%stmpdb\d{7}$/' , $ prefix ) ) ; return ( bool ) preg_match ( $ pattern , $ name ) ; }
|
Determines if the name is valid as a security measure against setting arbitrary databases .
|
4,611
|
public static function connect ( $ databaseConfig , $ label = 'default' ) { if ( $ name = self :: get_alternative_database_name ( ) ) { $ databaseConfig [ 'database' ] = $ name ; } if ( ! isset ( $ databaseConfig [ 'type' ] ) || empty ( $ databaseConfig [ 'type' ] ) ) { throw new InvalidArgumentException ( "DB::connect: Not passed a valid database config" ) ; } self :: $ connection_attempted = true ; $ dbClass = $ databaseConfig [ 'type' ] ; $ conn = Injector :: inst ( ) -> create ( $ dbClass ) ; self :: set_conn ( $ conn , $ label ) ; $ conn -> connect ( $ databaseConfig ) ; return $ conn ; }
|
Specify connection to a database
|
4,612
|
public static function create_field ( $ table , $ field , $ spec ) { return self :: get_schema ( ) -> createField ( $ table , $ field , $ spec ) ; }
|
Create a new field on a table .
|
4,613
|
public function column ( $ column = null ) { $ result = array ( ) ; while ( $ record = $ this -> next ( ) ) { if ( $ column ) { $ result [ ] = $ record [ $ column ] ; } else { $ result [ ] = $ record [ key ( $ record ) ] ; } } return $ result ; }
|
Return an array containing all the values from a specific column . If no column is set then the first will be returned
|
4,614
|
public function keyedColumn ( ) { $ column = array ( ) ; foreach ( $ this as $ record ) { $ val = $ record [ key ( $ record ) ] ; $ column [ $ val ] = $ val ; } return $ column ; }
|
Return an array containing all values in the leftmost column where the keys are the same as the values .
|
4,615
|
public function map ( ) { $ column = array ( ) ; foreach ( $ this as $ record ) { $ key = reset ( $ record ) ; $ val = next ( $ record ) ; $ column [ $ key ] = $ val ; } return $ column ; }
|
Return a map from the first column to the second column .
|
4,616
|
public function table ( ) { $ first = true ; $ result = "<table>\n" ; foreach ( $ this as $ record ) { if ( $ first ) { $ result .= "<tr>" ; foreach ( $ record as $ k => $ v ) { $ result .= "<th>" . Convert :: raw2xml ( $ k ) . "</th> " ; } $ result .= "</tr> \n" ; } $ result .= "<tr>" ; foreach ( $ record as $ k => $ v ) { $ result .= "<td>" . Convert :: raw2xml ( $ v ) . "</td> " ; } $ result .= "</tr> \n" ; $ first = false ; } $ result .= "</table>\n" ; if ( $ first ) { return "No records found" ; } return $ result ; }
|
Return an HTML table containing the full result - set
|
4,617
|
public function flushMemberCache ( $ memberIDs = null ) { if ( ! $ this -> cacheService ) { return ; } if ( ! $ memberIDs ) { $ this -> cacheService -> clear ( ) ; } if ( $ memberIDs && is_array ( $ memberIDs ) ) { foreach ( [ self :: VIEW , self :: EDIT , self :: DELETE ] as $ type ) { foreach ( $ memberIDs as $ memberID ) { $ key = $ this -> generateCacheKey ( $ type , $ memberID ) ; $ this -> cacheService -> delete ( $ key ) ; } } } }
|
Clear the cache for this instance only
|
4,618
|
public function prePopulatePermissionCache ( $ permission = 'edit' , $ ids = [ ] ) { switch ( $ permission ) { case self :: EDIT : $ this -> canEditMultiple ( $ ids , Security :: getCurrentUser ( ) , false ) ; break ; case self :: VIEW : $ this -> canViewMultiple ( $ ids , Security :: getCurrentUser ( ) , false ) ; break ; case self :: DELETE : $ this -> canDeleteMultiple ( $ ids , Security :: getCurrentUser ( ) , false ) ; break ; default : throw new InvalidArgumentException ( "Invalid permission type $permission" ) ; } }
|
Force pre - calculation of a list of permissions for optimisation
|
4,619
|
protected function checkDefaultPermissions ( $ type , Member $ member = null ) { $ defaultPermissions = $ this -> getDefaultPermissions ( ) ; if ( ! $ defaultPermissions ) { return false ; } switch ( $ type ) { case self :: VIEW : return $ defaultPermissions -> canView ( $ member ) ; case self :: EDIT : return $ defaultPermissions -> canEdit ( $ member ) ; case self :: DELETE : return $ defaultPermissions -> canDelete ( $ member ) ; default : return false ; } }
|
Determine default permission for a givion check
|
4,620
|
protected function isVersioned ( ) { if ( ! class_exists ( Versioned :: class ) ) { return false ; } $ singleton = DataObject :: singleton ( $ this -> getBaseClass ( ) ) ; return $ singleton -> hasExtension ( Versioned :: class ) && $ singleton -> hasStages ( ) ; }
|
Check if this model has versioning
|
4,621
|
protected function getCachePermissions ( $ cacheKey ) { if ( isset ( $ this -> cachePermissions [ $ cacheKey ] ) ) { return $ this -> cachePermissions [ $ cacheKey ] ; } if ( $ this -> cacheService ) { $ result = $ this -> cacheService -> get ( $ cacheKey ) ; if ( $ result ) { $ this -> cachePermissions [ $ cacheKey ] = $ result ; return $ result ; } } return null ; }
|
Gets the permission from cache
|
4,622
|
public function extractInheritableQueryParameters ( DataQuery $ query ) { $ params = $ query -> getQueryParams ( ) ; foreach ( array_keys ( $ params ) as $ key ) { if ( stripos ( $ key , 'Foreign.' ) === 0 ) { unset ( $ params [ $ key ] ) ; } } $ inst = Injector :: inst ( ) -> create ( $ query -> dataClass ( ) ) ; $ inst -> setSourceQueryParams ( $ params ) ; return $ inst -> getInheritableQueryParams ( ) ; }
|
Calculate the query parameters that should be inherited from the base many_many to the nested has_many list .
|
4,623
|
protected function bind ( ) { $ variables = array ( ) ; while ( $ field = $ this -> metadata -> fetch_field ( ) ) { $ this -> columns [ ] = $ field -> name ; $ this -> types [ $ field -> name ] = $ field -> type ; $ variables [ ] = & $ this -> boundValues [ $ field -> name ] ; } $ this -> bound = true ; $ this -> metadata -> free ( ) ; $ this -> statement -> store_result ( ) ; call_user_func_array ( array ( $ this -> statement , 'bind_result' ) , $ variables ) ; }
|
Binds this statement to the variables
|
4,624
|
protected function addRelation ( $ name ) { if ( strstr ( $ name , '.' ) ) { $ parts = explode ( '.' , $ name ) ; $ this -> name = array_pop ( $ parts ) ; $ this -> relation = $ parts ; } else { $ this -> name = $ name ; } }
|
Called by constructor to convert a string pathname into a well defined relationship sequence .
|
4,625
|
public function setModifiers ( array $ modifiers ) { $ modifiers = array_map ( 'strtolower' , $ modifiers ) ; $ allowed = $ this -> getSupportedModifiers ( ) ; $ unsupported = array_diff ( $ modifiers , $ allowed ) ; if ( $ unsupported ) { throw new InvalidArgumentException ( static :: class . ' does not accept ' . implode ( ', ' , $ unsupported ) . ' as modifiers' ) ; } $ this -> modifiers = $ modifiers ; }
|
Set the current modifiers to apply to the filter
|
4,626
|
public function getDbName ( ) { if ( $ this -> name === "NULL" ) { return $ this -> name ; } if ( ! is_subclass_of ( $ this -> model , DataObject :: class ) ) { throw new InvalidArgumentException ( "Model supplied to " . static :: class . " should be an instance of DataObject." ) ; } $ tablePrefix = DataQuery :: applyRelationPrefix ( $ this -> relation ) ; $ schema = DataObject :: getSchema ( ) ; if ( $ this -> aggregate ) { $ column = $ this -> aggregate [ 'column' ] ; $ function = $ this -> aggregate [ 'function' ] ; $ table = $ column ? $ schema -> tableForField ( $ this -> model , $ column ) : $ schema -> baseDataTable ( $ this -> model ) ; if ( ! $ table ) { throw new InvalidArgumentException ( sprintf ( 'Invalid column %s for aggregate function %s on %s' , $ column , $ function , $ this -> model ) ) ; } return sprintf ( '%s("%s%s".%s)' , $ function , $ tablePrefix , $ table , $ column ? "\"$column\"" : '"ID"' ) ; } $ table = $ schema -> tableForField ( $ this -> model , $ this -> name ) ; if ( $ table ) { return $ schema -> sqlColumnForField ( $ this -> model , $ this -> name , $ tablePrefix ) ; } $ parts = explode ( '.' , $ this -> fullName ) ; return '"' . implode ( '"."' , $ parts ) . '"' ; }
|
Normalizes the field name to table mapping .
|
4,627
|
public function getDbFormattedValue ( ) { if ( $ this -> aggregate ) { return intval ( $ this -> value ) ; } $ dbField = singleton ( $ this -> model ) -> dbObject ( $ this -> name ) ; $ dbField -> setValue ( $ this -> value ) ; return $ dbField -> RAW ( ) ; }
|
Return the value of the field as processed by the DBField class
|
4,628
|
public function applyAggregate ( DataQuery $ query , $ having ) { $ schema = DataObject :: getSchema ( ) ; $ baseTable = $ schema -> baseDataTable ( $ query -> dataClass ( ) ) ; return $ query -> having ( $ having ) -> groupby ( "\"{$baseTable}\".\"ID\"" ) ; }
|
Given an escaped HAVING clause add it along with the appropriate GROUP BY clause
|
4,629
|
public function exclude ( DataQuery $ query ) { if ( ( $ key = array_search ( 'not' , $ this -> modifiers ) ) !== false ) { unset ( $ this -> modifiers [ $ key ] ) ; return $ this -> apply ( $ query ) ; } if ( is_array ( $ this -> value ) ) { return $ this -> excludeMany ( $ query ) ; } else { return $ this -> excludeOne ( $ query ) ; } }
|
Exclude filter criteria from a SQL query .
|
4,630
|
protected function databaseError ( $ msg , $ errorLevel = E_USER_ERROR , $ sql = null , $ parameters = array ( ) ) { if ( empty ( $ errorLevel ) ) { return ; } if ( ! empty ( $ sql ) ) { $ formatter = new SQLFormatter ( ) ; $ formattedSQL = $ formatter -> formatPlain ( $ sql ) ; $ msg = "Couldn't run query:\n\n{$formattedSQL}\n\n{$msg}" ; } if ( $ errorLevel === E_USER_ERROR ) { throw new DatabaseException ( $ msg , 0 , null , $ sql , $ parameters ) ; } else { user_error ( $ msg , $ errorLevel ) ; } }
|
Error handler for database errors . All database errors will call this function to report the error . It isn t a static function ; it will be called on the object itself and as such can be overridden in a subclass . Subclasses should run all errors through this function .
|
4,631
|
public function isQueryDDL ( $ sql ) { $ operations = Config :: inst ( ) -> get ( static :: class , 'ddl_operations' ) ; return $ this -> isQueryType ( $ sql , $ operations ) ; }
|
Determine if this SQL statement is a DDL operation
|
4,632
|
protected function isQueryType ( $ sql , $ type ) { if ( ! preg_match ( '/^(?<operation>\w+)\b/' , $ sql , $ matches ) ) { return false ; } $ operation = $ matches [ 'operation' ] ; if ( is_array ( $ type ) ) { return in_array ( strtolower ( $ operation ) , $ type ) ; } else { return strcasecmp ( $ sql , $ type ) === 0 ; } }
|
Determine if a query is of the given type
|
4,633
|
protected function parameterValues ( $ parameters ) { $ values = array ( ) ; foreach ( $ parameters as $ value ) { $ values [ ] = is_array ( $ value ) ? $ value [ 'value' ] : $ value ; } return $ values ; }
|
Extracts only the parameter values for error reporting
|
4,634
|
protected function getSession ( ) { $ injector = Injector :: inst ( ) ; if ( $ injector -> has ( HTTPRequest :: class ) ) { return $ injector -> get ( HTTPRequest :: class ) -> getSession ( ) ; } elseif ( Controller :: has_curr ( ) ) { return Controller :: curr ( ) -> getRequest ( ) -> getSession ( ) ; } throw new Exception ( 'No HTTPRequest object or controller available yet!' ) ; }
|
Returns the current session instance from the injector
|
4,635
|
protected function getRequestToken ( $ request ) { $ name = $ this -> getName ( ) ; $ header = 'X-' . ucwords ( strtolower ( $ name ) ) ; if ( $ token = $ request -> getHeader ( $ header ) ) { return $ token ; } return $ request -> requestVar ( $ name ) ; }
|
Get security token from request
|
4,636
|
public function setOptions ( array $ options = [ ] ) { parent :: setOptions ( $ options ) ; if ( array_key_exists ( 'nullifyEmpty' , $ options ) ) { $ this -> options [ 'nullifyEmpty' ] = ( bool ) $ options [ 'nullifyEmpty' ] ; } if ( array_key_exists ( 'default' , $ options ) ) { $ this -> setDefaultValue ( $ options [ 'default' ] ) ; } return $ this ; }
|
Update the optional parameters for this field .
|
4,637
|
public function LimitCharactersToClosestWord ( $ limit = 20 , $ add = '...' ) { $ value = $ this -> Plain ( ) ; if ( mb_strlen ( $ value ) <= $ limit ) { return $ value ; } $ value = mb_substr ( $ value , 0 , $ limit ) ; $ value = preg_replace ( '/[^\w_]+$/' , '' , mb_substr ( $ value , 0 , mb_strrpos ( $ value , " " ) ) ) . $ add ; return $ value ; }
|
Limit this field s content by a number of characters and truncate the field to the closest complete word . All HTML tags are stripped from the field .
|
4,638
|
public function LimitWordCount ( $ numWords = 26 , $ add = '...' ) { $ value = $ this -> Plain ( ) ; $ words = explode ( ' ' , $ value ) ; if ( count ( $ words ) <= $ numWords ) { return $ value ; } $ words = array_slice ( $ words , 0 , $ numWords ) ; return implode ( ' ' , $ words ) . $ add ; }
|
Limit this field s content by a number of words .
|
4,639
|
public function locally ( ) { list ( $ this -> item , $ this -> itemIterator , $ this -> itemIteratorTotal , $ this -> popIndex , $ this -> upIndex , $ this -> currentIndex ) = $ this -> itemStack [ $ this -> localIndex ] ; $ this -> localStack [ ] = array_splice ( $ this -> itemStack , $ this -> localIndex + 1 ) ; return $ this ; }
|
Called at the start of every lookup chain by SSTemplateParser to indicate a new lookup from local scope
|
4,640
|
public function resetLocalScope ( ) { $ previousLocalState = $ this -> localStack ? array_pop ( $ this -> localStack ) : null ; array_splice ( $ this -> itemStack , $ this -> localIndex + 1 , count ( $ this -> itemStack ) , $ previousLocalState ) ; list ( $ this -> item , $ this -> itemIterator , $ this -> itemIteratorTotal , $ this -> popIndex , $ this -> upIndex , $ this -> currentIndex ) = end ( $ this -> itemStack ) ; }
|
Reset the local scope - restores saved state to the global item stack . Typically called after a lookup chain has been completed
|
4,641
|
public function self ( ) { $ result = $ this -> itemIterator ? $ this -> itemIterator -> current ( ) : $ this -> item ; $ this -> resetLocalScope ( ) ; return $ result ; }
|
Gets the current object and resets the scope .
|
4,642
|
public function next ( ) { if ( ! $ this -> item ) { return false ; } if ( ! $ this -> itemIterator ) { if ( is_array ( $ this -> item ) ) { $ this -> itemIterator = new ArrayIterator ( $ this -> item ) ; } else { $ this -> itemIterator = $ this -> item -> getIterator ( ) ; } $ this -> itemStack [ $ this -> localIndex ] [ SSViewer_Scope :: ITEM_ITERATOR ] = $ this -> itemIterator ; $ this -> itemIteratorTotal = iterator_count ( $ this -> itemIterator ) ; $ this -> itemStack [ $ this -> localIndex ] [ SSViewer_Scope :: ITEM_ITERATOR_TOTAL ] = $ this -> itemIteratorTotal ; $ this -> itemIterator -> rewind ( ) ; } else { $ this -> itemIterator -> next ( ) ; } $ this -> resetLocalScope ( ) ; if ( ! $ this -> itemIterator -> valid ( ) ) { return false ; } return $ this -> itemIterator -> key ( ) ; }
|
Fast - forwards the current iterator to the next item
|
4,643
|
protected function isDBTemp ( $ name ) { $ prefix = Environment :: getEnv ( 'SS_DATABASE_PREFIX' ) ? : 'ss_' ; $ result = preg_match ( sprintf ( '/^%stmpdb_[0-9]+_[0-9]+$/i' , preg_quote ( $ prefix , '/' ) ) , $ name ) ; return $ result === 1 ; }
|
Check if the given name matches the temp_db pattern
|
4,644
|
public function rollbackTransaction ( ) { $ success = static :: getConn ( ) -> supportsTransactions ( ) && static :: getConn ( ) -> transactionDepth ( ) ; if ( ! $ success ) { return false ; } try { if ( static :: getConn ( ) -> transactionRollback ( ) === false ) { return false ; } return true ; } catch ( DatabaseException $ ex ) { return false ; } }
|
Rollback a transaction ( or trash all data if the DB doesn t support databases
|
4,645
|
public function kill ( ) { if ( ! $ this -> isUsed ( ) ) { return ; } $ this -> rollbackTransaction ( ) ; $ dbConn = $ this -> getConn ( ) ; $ dbName = $ dbConn -> getSelectedDatabase ( ) ; if ( ! $ dbConn -> databaseExists ( $ dbName ) ) { return ; } foreach ( ClassInfo :: subclassesFor ( DataExtension :: class ) as $ class ) { $ toCall = array ( $ class , 'on_db_reset' ) ; if ( is_callable ( $ toCall ) ) { call_user_func ( $ toCall ) ; } } $ dbConn -> dropSelectedDatabase ( ) ; }
|
Destroy the current temp database
|
4,646
|
public function clearAllData ( ) { if ( ! $ this -> isUsed ( ) ) { return ; } $ this -> getConn ( ) -> clearAllData ( ) ; $ classes = array_merge ( ClassInfo :: subclassesFor ( DataExtension :: class ) , ClassInfo :: subclassesFor ( DataObject :: class ) ) ; foreach ( $ classes as $ class ) { $ toCall = array ( $ class , 'on_db_reset' ) ; if ( is_callable ( $ toCall ) ) { call_user_func ( $ toCall ) ; } } }
|
Remove all content from the temporary database .
|
4,647
|
public function build ( ) { $ oldErrorHandler = set_error_handler ( null ) ; $ dbConn = $ this -> getConn ( ) ; $ prefix = Environment :: getEnv ( 'SS_DATABASE_PREFIX' ) ? : 'ss_' ; do { $ dbname = strtolower ( sprintf ( '%stmpdb_%s_%s' , $ prefix , time ( ) , rand ( 1000000 , 9999999 ) ) ) ; } while ( $ dbConn -> databaseExists ( $ dbname ) ) ; $ dbConn -> selectDatabase ( $ dbname , true ) ; $ this -> resetDBSchema ( ) ; set_error_handler ( $ oldErrorHandler ) ; $ teardownOnExit = Config :: inst ( ) -> get ( static :: class , 'teardown_on_exit' ) ; if ( $ teardownOnExit ) { register_shutdown_function ( function ( ) { try { $ this -> kill ( ) ; } catch ( Exception $ ex ) { } } ) ; } return $ dbname ; }
|
Create temp DB without creating extra objects
|
4,648
|
protected function rebuildTables ( $ extraDataObjects = [ ] ) { DataObject :: reset ( ) ; Injector :: inst ( ) -> unregisterObjects ( DataObject :: class ) ; $ dataClasses = ClassInfo :: subclassesFor ( DataObject :: class ) ; array_shift ( $ dataClasses ) ; $ schema = $ this -> getConn ( ) -> getSchemaManager ( ) ; $ schema -> quiet ( ) ; $ schema -> schemaUpdate ( function ( ) use ( $ dataClasses , $ extraDataObjects ) { foreach ( $ dataClasses as $ dataClass ) { if ( class_exists ( $ dataClass ) ) { $ SNG = singleton ( $ dataClass ) ; if ( ! ( $ SNG instanceof TestOnly ) ) { $ SNG -> requireTable ( ) ; } } } if ( $ extraDataObjects ) { foreach ( $ extraDataObjects as $ dataClass ) { $ SNG = singleton ( $ dataClass ) ; if ( singleton ( $ dataClass ) instanceof DataObject ) { $ SNG -> requireTable ( ) ; } } } } ) ; ClassInfo :: reset_db_cache ( ) ; DataObject :: singleton ( ) -> flushCache ( ) ; }
|
Rebuild all database tables
|
4,649
|
public function deleteAll ( ) { $ schema = $ this -> getConn ( ) -> getSchemaManager ( ) ; foreach ( $ schema -> databaseList ( ) as $ dbName ) { if ( $ this -> isDBTemp ( $ dbName ) ) { $ schema -> dropDatabase ( $ dbName ) ; $ schema -> alterationMessage ( "Dropped database \"$dbName\"" , 'deleted' ) ; flush ( ) ; } } }
|
Clear all temp DBs on this connection
|
4,650
|
public function resetDBSchema ( array $ extraDataObjects = [ ] ) { if ( ! $ this -> isUsed ( ) ) { return ; } try { $ this -> rebuildTables ( $ extraDataObjects ) ; } catch ( DatabaseException $ ex ) { $ this -> kill ( ) ; $ this -> build ( ) ; $ this -> rebuildTables ( $ extraDataObjects ) ; } }
|
Reset the testing database s schema .
|
4,651
|
public function setAllowedHosts ( $ allowedHosts ) { if ( is_string ( $ allowedHosts ) ) { $ allowedHosts = preg_split ( '/ *, */' , $ allowedHosts ) ; } $ this -> allowedHosts = $ allowedHosts ; return $ this ; }
|
Sets the list of allowed Host header values Can also specify a comma separated list
|
4,652
|
public static function caller ( ) { $ bt = debug_backtrace ( ) ; $ caller = isset ( $ bt [ 2 ] ) ? $ bt [ 2 ] : array ( ) ; $ caller [ 'line' ] = $ bt [ 1 ] [ 'line' ] ; $ caller [ 'file' ] = $ bt [ 1 ] [ 'file' ] ; if ( ! isset ( $ caller [ 'class' ] ) ) { $ caller [ 'class' ] = '' ; } if ( ! isset ( $ caller [ 'type' ] ) ) { $ caller [ 'type' ] = '' ; } if ( ! isset ( $ caller [ 'function' ] ) ) { $ caller [ 'function' ] = '' ; } return $ caller ; }
|
Returns the caller for a specific method
|
4,653
|
public static function endshow ( $ val , $ showHeader = true , HTTPRequest $ request = null ) { if ( Director :: isLive ( ) ) { return ; } echo static :: create_debug_view ( $ request ) -> debugVariable ( $ val , static :: caller ( ) , $ showHeader ) ; die ( ) ; }
|
Close out the show dumper . Does not work on live mode
|
4,654
|
public static function message ( $ message , $ showHeader = true , HTTPRequest $ request = null ) { if ( Director :: isLive ( ) ) { return ; } echo static :: create_debug_view ( $ request ) -> renderMessage ( $ message , static :: caller ( ) , $ showHeader ) ; }
|
Show a debugging message . Does not work on live mode
|
4,655
|
public static function create_debug_view ( HTTPRequest $ request = null ) { $ service = static :: supportsHTML ( $ request ) ? DebugView :: class : CliDebugView :: class ; return Injector :: inst ( ) -> get ( $ service ) ; }
|
Create an instance of an appropriate DebugView object .
|
4,656
|
protected static function supportsHTML ( HTTPRequest $ request = null ) { if ( Director :: is_cli ( ) ) { return false ; } if ( ! $ request && Injector :: inst ( ) -> has ( HTTPRequest :: class ) ) { $ request = Injector :: inst ( ) -> get ( HTTPRequest :: class ) ; } if ( ! $ request ) { return false ; } $ accepted = $ request -> getAcceptMimetypes ( false ) ; if ( in_array ( 'text/html' , $ accepted ) ) { return true ; } ; if ( in_array ( 'application/json' , $ accepted ) ) { return false ; } if ( in_array ( '*/*' , $ accepted ) ) { return true ; } return false ; }
|
Determine if the given request supports html output
|
4,657
|
public static function require_developer_login ( ) { if ( Director :: isDev ( ) ) { return ; } if ( isset ( $ _SESSION [ 'loggedInAs' ] ) ) { $ memberID = $ _SESSION [ 'loggedInAs' ] ; $ permission = DB :: prepared_query ( ' SELECT "ID" FROM "Permission" INNER JOIN "Group_Members" ON "Permission"."GroupID" = "Group_Members"."GroupID" WHERE "Permission"."Code" = ? AND "Permission"."Type" = ? AND "Group_Members"."MemberID" = ?' , array ( 'ADMIN' , Permission :: GRANT_PERMISSION , $ memberID ) ) -> value ( ) ; if ( $ permission ) { return ; } } $ _SESSION [ 'SilverStripe\\Security\\Security' ] [ 'Message' ] [ 'message' ] = "You need to login with developer access to make use of debugging tools." ; $ _SESSION [ 'SilverStripe\\Security\\Security' ] [ 'Message' ] [ 'type' ] = 'warning' ; $ _SESSION [ 'BackURL' ] = $ _SERVER [ 'REQUEST_URI' ] ; header ( $ _SERVER [ 'SERVER_PROTOCOL' ] . " 302 Found" ) ; header ( "Location: " . Director :: baseURL ( ) . Security :: login_url ( ) ) ; die ( ) ; }
|
Check if the user has permissions to run URL debug tools else redirect them to log in .
|
4,658
|
public function javascript ( $ file , $ options = array ( ) ) { $ file = ModuleResourceLoader :: singleton ( ) -> resolvePath ( $ file ) ; $ type = null ; if ( isset ( $ this -> javascript [ $ file ] [ 'type' ] ) ) { $ type = $ this -> javascript [ $ file ] [ 'type' ] ; } if ( isset ( $ options [ 'type' ] ) ) { $ type = $ options [ 'type' ] ; } $ async = ( isset ( $ options [ 'async' ] ) && isset ( $ options [ 'async' ] ) == true || ( isset ( $ this -> javascript [ $ file ] ) && isset ( $ this -> javascript [ $ file ] [ 'async' ] ) && $ this -> javascript [ $ file ] [ 'async' ] == true ) ) ; $ defer = ( isset ( $ options [ 'defer' ] ) && isset ( $ options [ 'defer' ] ) == true || ( isset ( $ this -> javascript [ $ file ] ) && isset ( $ this -> javascript [ $ file ] [ 'defer' ] ) && $ this -> javascript [ $ file ] [ 'defer' ] == true ) ) ; $ this -> javascript [ $ file ] = array ( 'async' => $ async , 'defer' => $ defer , 'type' => $ type , ) ; if ( isset ( $ options [ 'provides' ] ) ) { $ this -> providedJavascript [ $ file ] = array_values ( $ options [ 'provides' ] ) ; } }
|
Register the given JavaScript file as required .
|
4,659
|
public function customScript ( $ script , $ uniquenessID = null ) { if ( $ uniquenessID ) { $ this -> customScript [ $ uniquenessID ] = $ script ; } else { $ this -> customScript [ ] = $ script ; } }
|
Register the given JavaScript code into the list of requirements
|
4,660
|
public function customCSS ( $ script , $ uniquenessID = null ) { if ( $ uniquenessID ) { $ this -> customCSS [ $ uniquenessID ] = $ script ; } else { $ this -> customCSS [ ] = $ script ; } }
|
Register the given CSS styles into the list of requirements
|
4,661
|
public function css ( $ file , $ media = null ) { $ file = ModuleResourceLoader :: singleton ( ) -> resolvePath ( $ file ) ; $ this -> css [ $ file ] = [ "media" => $ media ] ; }
|
Register the given stylesheet into the list of requirements .
|
4,662
|
public function clear ( $ fileOrID = null ) { $ types = [ 'javascript' , 'css' , 'customScript' , 'customCSS' , 'customHeadTags' , 'combinedFiles' , ] ; foreach ( $ types as $ type ) { if ( $ fileOrID ) { if ( isset ( $ this -> { $ type } [ $ fileOrID ] ) ) { $ this -> disabled [ $ type ] [ $ fileOrID ] = $ this -> { $ type } [ $ fileOrID ] ; unset ( $ this -> { $ type } [ $ fileOrID ] ) ; } } else { $ this -> disabled [ $ type ] = $ this -> { $ type } ; $ this -> { $ type } = [ ] ; } } }
|
Clear either a single or all requirements
|
4,663
|
public function block ( $ fileOrID ) { if ( is_string ( $ fileOrID ) ) { $ fileOrID = ModuleResourceLoader :: singleton ( ) -> resolvePath ( $ fileOrID ) ; } $ this -> blocked [ $ fileOrID ] = $ fileOrID ; }
|
Block inclusion of a specific file
|
4,664
|
public function includeInResponse ( HTTPResponse $ response ) { $ this -> processCombinedFiles ( ) ; $ jsRequirements = array ( ) ; $ cssRequirements = array ( ) ; foreach ( $ this -> getJavascript ( ) as $ file => $ attributes ) { $ path = $ this -> pathForFile ( $ file ) ; if ( $ path ) { $ jsRequirements [ ] = str_replace ( ',' , '%2C' , $ path ) ; } } if ( count ( $ jsRequirements ) ) { $ response -> addHeader ( 'X-Include-JS' , implode ( ',' , $ jsRequirements ) ) ; } foreach ( $ this -> getCSS ( ) as $ file => $ params ) { $ path = $ this -> pathForFile ( $ file ) ; if ( $ path ) { $ path = str_replace ( ',' , '%2C' , $ path ) ; $ cssRequirements [ ] = isset ( $ params [ 'media' ] ) ? "$path:##:$params[media]" : $ path ; } } if ( count ( $ cssRequirements ) ) { $ response -> addHeader ( 'X-Include-CSS' , implode ( ',' , $ cssRequirements ) ) ; } }
|
Attach requirements inclusion to X - Include - JS and X - Include - CSS headers on the given HTTP Response
|
4,665
|
protected function pathForFile ( $ fileOrUrl ) { if ( preg_match ( '{^(//)|(http[s]?:)}' , $ fileOrUrl ) || Director :: is_root_relative_url ( $ fileOrUrl ) ) { return $ fileOrUrl ; } else { return Injector :: inst ( ) -> get ( ResourceURLGenerator :: class ) -> urlForResource ( $ fileOrUrl ) ; } }
|
Finds the path for specified file
|
4,666
|
protected function parseCombinedFile ( $ file ) { if ( is_array ( $ file ) && isset ( $ file [ 'path' ] ) && isset ( $ file [ 'type' ] ) ) { return array ( $ file [ 'path' ] , $ file [ 'type' ] ) ; } if ( is_array ( $ file ) ) { $ path = array_shift ( $ file ) ; if ( $ file ) { $ type = array_shift ( $ file ) ; return array ( $ path , $ type ) ; } $ file = $ path ; } $ type = File :: get_file_extension ( $ file ) ; return array ( $ file , $ type ) ; }
|
Return path and type of given combined file
|
4,667
|
public function processCombinedFiles ( ) { if ( ! $ this -> getCombinedFilesEnabled ( ) ) { return ; } $ providedScripts = $ this -> getProvidedScripts ( ) ; foreach ( $ this -> getAllCombinedFiles ( ) as $ combinedFile => $ combinedItem ) { $ fileList = $ combinedItem [ 'files' ] ; $ type = $ combinedItem [ 'type' ] ; $ options = $ combinedItem [ 'options' ] ; $ combinedURL = null ; if ( ! isset ( $ this -> blocked [ $ combinedFile ] ) ) { $ filteredFileList = array_diff ( $ fileList , $ this -> getBlocked ( ) , $ providedScripts ) ; $ combinedURL = $ this -> getCombinedFileURL ( $ combinedFile , $ filteredFileList , $ type ) ; } $ included = false ; switch ( $ type ) { case 'css' : { $ newCSS = array ( ) ; foreach ( $ this -> getAllCSS ( ) as $ css => $ spec ) { if ( ! in_array ( $ css , $ fileList ) ) { $ newCSS [ $ css ] = $ spec ; } elseif ( ! $ included && $ combinedURL ) { $ newCSS [ $ combinedURL ] = array ( 'media' => ( isset ( $ options [ 'media' ] ) ? $ options [ 'media' ] : null ) ) ; $ included = true ; } } $ this -> css = $ newCSS ; break ; } case 'js' : { $ newJS = array ( ) ; foreach ( $ this -> getAllJavascript ( ) as $ script => $ attributes ) { if ( ! in_array ( $ script , $ fileList ) ) { $ newJS [ $ script ] = $ attributes ; } elseif ( ! $ included && $ combinedURL ) { $ newJS [ $ combinedURL ] = $ options ; $ included = true ; } } $ this -> javascript = $ newJS ; break ; } } } }
|
Do the heavy lifting involved in combining the combined files .
|
4,668
|
protected function hashedCombinedFilename ( $ combinedFile , $ fileList ) { $ name = pathinfo ( $ combinedFile , PATHINFO_FILENAME ) ; $ hash = $ this -> hashOfFiles ( $ fileList ) ; $ extension = File :: get_file_extension ( $ combinedFile ) ; return $ name . '-' . substr ( $ hash , 0 , 7 ) . '.' . $ extension ; }
|
Given a filename and list of files generate a new filename unique to these files
|
4,669
|
public function getCombinedFilesEnabled ( ) { if ( isset ( $ this -> combinedFilesEnabled ) ) { return $ this -> combinedFilesEnabled ; } if ( ! Director :: isDev ( ) ) { return true ; } return Config :: inst ( ) -> get ( __CLASS__ , 'combine_in_dev' ) ; }
|
Check if combined files are enabled
|
4,670
|
protected function hashOfFiles ( $ fileList ) { $ hash = '' ; foreach ( $ fileList as $ file ) { $ absolutePath = Director :: getAbsFile ( $ file ) ; if ( file_exists ( $ absolutePath ) ) { $ hash .= sha1_file ( $ absolutePath ) ; } else { throw new InvalidArgumentException ( "Combined file {$file} does not exist" ) ; } } return sha1 ( $ hash ) ; }
|
For a given filelist determine some discriminating value to determine if any of these files have changed .
|
4,671
|
public function themedCSS ( $ name , $ media = null ) { $ path = ThemeResourceLoader :: inst ( ) -> findThemedCSS ( $ name , SSViewer :: get_themes ( ) ) ; if ( $ path ) { $ this -> css ( $ path , $ media ) ; } else { throw new InvalidArgumentException ( "The css file doesn't exist. Please check if the file $name.css exists in any context or search for " . "themedCSS references calling this file in your templates." ) ; } }
|
Registers the given themeable stylesheet as required .
|
4,672
|
public function themedJavascript ( $ name , $ type = null ) { $ path = ThemeResourceLoader :: inst ( ) -> findThemedJavascript ( $ name , SSViewer :: get_themes ( ) ) ; if ( $ path ) { $ opts = [ ] ; if ( $ type ) { $ opts [ 'type' ] = $ type ; } $ this -> javascript ( $ path , $ opts ) ; } else { throw new InvalidArgumentException ( "The javascript file doesn't exist. Please check if the file $name.js exists in any " . "context or search for themedJavascript references calling this file in your templates." ) ; } }
|
Registers the given themeable javascript as required .
|
4,673
|
public function debug ( ) { Debug :: show ( $ this -> javascript ) ; Debug :: show ( $ this -> css ) ; Debug :: show ( $ this -> customCSS ) ; Debug :: show ( $ this -> customScript ) ; Debug :: show ( $ this -> customHeadTags ) ; Debug :: show ( $ this -> combinedFiles ) ; }
|
Output debugging information .
|
4,674
|
public function getDatabaseConfig ( $ request , $ databaseClasses , $ realPassword = true ) { if ( isset ( $ request [ 'db' ] [ 'type' ] ) ) { $ type = $ request [ 'db' ] [ 'type' ] ; if ( isset ( $ request [ 'db' ] [ $ type ] ) ) { $ config = $ request [ 'db' ] [ $ type ] ; if ( isset ( $ config [ 'password' ] ) && $ config [ 'password' ] === Installer :: PASSWORD_PLACEHOLDER ) { $ config [ 'password' ] = Environment :: getEnv ( 'SS_DATABASE_PASSWORD' ) ? : '' ; } return array_merge ( [ 'type' => $ type ] , $ config ) ; } } return [ 'type' => $ this -> getDatabaseClass ( $ databaseClasses ) , 'server' => Environment :: getEnv ( 'SS_DATABASE_SERVER' ) ? : 'localhost' , 'username' => Environment :: getEnv ( 'SS_DATABASE_USERNAME' ) ? : 'root' , 'password' => $ realPassword ? ( Environment :: getEnv ( 'SS_DATABASE_PASSWORD' ) ? : '' ) : Installer :: PASSWORD_PLACEHOLDER , 'database' => Environment :: getEnv ( 'SS_DATABASE_NAME' ) ? : 'SS_mysite' , 'path' => Environment :: getEnv ( 'SS_DATABASE_PATH' ) ? : Environment :: getEnv ( 'SS_SQLITE_DATABASE_PATH' ) ? : null , 'key' => Environment :: getEnv ( 'SS_DATABASE_KEY' ) ? : Environment :: getEnv ( 'SS_SQLITE_DATABASE_KEY' ) ? : null , ] ; }
|
Get database config from the current environment
|
4,675
|
public function getAdminConfig ( $ request , $ realPassword = true ) { if ( isset ( $ request [ 'admin' ] ) ) { $ config = $ request [ 'admin' ] ; if ( isset ( $ config [ 'password' ] ) && $ config [ 'password' ] === Installer :: PASSWORD_PLACEHOLDER ) { $ config [ 'password' ] = Environment :: getEnv ( 'SS_DEFAULT_ADMIN_PASSWORD' ) ? : '' ; } return $ request [ 'admin' ] ; } return [ 'username' => Environment :: getEnv ( 'SS_DEFAULT_ADMIN_USERNAME' ) ? : 'admin' , 'password' => $ realPassword ? ( Environment :: getEnv ( 'SS_DEFAULT_ADMIN_PASSWORD' ) ? : '' ) : Installer :: PASSWORD_PLACEHOLDER , ] ; }
|
Get admin config from the environment
|
4,676
|
public function alreadyInstalled ( ) { if ( file_exists ( $ this -> getEnvPath ( ) ) ) { return true ; } if ( ! file_exists ( $ this -> getConfigPath ( ) ) ) { return false ; } $ configContents = file_get_contents ( $ this -> getConfigPath ( ) ) ; if ( strstr ( $ configContents , '$databaseConfig' ) ) { return true ; } if ( strstr ( $ configContents , '$database' ) ) { return true ; } return false ; }
|
Check if this site has already been installed
|
4,677
|
protected function getDatabaseClass ( $ databaseClasses ) { $ envDatabase = Environment :: getEnv ( 'SS_DATABASE_CLASS' ) ; if ( $ envDatabase ) { return $ envDatabase ; } foreach ( $ this -> preferredDatabases as $ candidate ) { if ( ! empty ( $ databaseClasses [ $ candidate ] [ 'supported' ] ) ) { return $ candidate ; } } return null ; }
|
Database configs available for configuration
|
4,678
|
public function getFrameworkVersion ( ) { $ composerLockPath = BASE_PATH . '/composer.lock' ; if ( ! file_exists ( $ composerLockPath ) ) { return 'unknown' ; } $ lockData = json_decode ( file_get_contents ( $ composerLockPath ) , true ) ; if ( json_last_error ( ) || empty ( $ lockData [ 'packages' ] ) ) { return 'unknown' ; } foreach ( $ lockData [ 'packages' ] as $ package ) { if ( $ package [ 'name' ] === 'silverstripe/framework' ) { return $ package [ 'version' ] ; } } return 'unknown' ; }
|
Get string representation of the framework version
|
4,679
|
public static function prepare_tokens ( $ keys , HTTPRequest $ request ) { $ target = null ; foreach ( $ keys as $ key ) { $ token = new static ( $ key , $ request ) ; if ( $ token -> reloadRequired ( ) || $ token -> reloadRequiredIfError ( ) ) { $ token -> suppress ( ) ; $ target = $ token ; } } return $ target ; }
|
Given a list of token names suppress all tokens that have not been validated and return the non - validated token with the highest priority
|
4,680
|
protected function genToken ( ) { $ rg = new RandomGenerator ( ) ; $ token = $ rg -> randomToken ( 'md5' ) ; file_put_contents ( $ this -> pathForToken ( $ token ) , $ token ) ; return $ token ; }
|
Generate a new random token and store it
|
4,681
|
public function reloadWithToken ( ) { $ location = $ this -> redirectURL ( ) ; $ locationJS = Convert :: raw2js ( $ location ) ; $ locationATT = Convert :: raw2att ( $ location ) ; $ body = <<<HTML<script>location.href='$locationJS';</script><noscript><meta http-equiv="refresh" content="0; url=$locationATT"></noscript>You are being redirected. If you are not redirected soon, <a href="$locationATT">click here to continue</a>HTML ; $ result = new HTTPResponse ( $ body ) ; $ result -> redirect ( $ location ) ; return $ result ; }
|
Forces a reload of the request with the token included
|
4,682
|
protected function handleAction ( $ request , $ action ) { $ classMessage = Director :: isLive ( ) ? 'on this handler' : 'on class ' . static :: class ; if ( ! $ this -> hasMethod ( $ action ) ) { return new HTTPResponse ( "Action '$action' isn't available $classMessage." , 404 ) ; } $ res = $ this -> extend ( 'beforeCallActionHandler' , $ request , $ action ) ; if ( $ res ) { return reset ( $ res ) ; } $ actionRes = $ this -> $ action ( $ request ) ; $ res = $ this -> extend ( 'afterCallActionHandler' , $ request , $ action , $ actionRes ) ; if ( $ res ) { return reset ( $ res ) ; } return $ actionRes ; }
|
Given a request and an action name call that action name on this RequestHandler
|
4,683
|
public function allowedActions ( $ limitToClass = null ) { if ( $ limitToClass ) { $ actions = Config :: forClass ( $ limitToClass ) -> get ( 'allowed_actions' , true ) ; } else { $ actions = $ this -> config ( ) -> get ( 'allowed_actions' ) ; } if ( is_array ( $ actions ) ) { if ( array_key_exists ( '*' , $ actions ) ) { throw new InvalidArgumentException ( "Invalid allowed_action '*'" ) ; } $ actions = array_change_key_case ( $ actions , CASE_LOWER ) ; foreach ( $ actions as $ key => $ value ) { if ( is_numeric ( $ key ) ) { $ actions [ $ key ] = strtolower ( $ value ) ; } } return $ actions ; } else { return null ; } }
|
Get a array of allowed actions defined on this controller any parent classes or extensions .
|
4,684
|
public function hasAction ( $ action ) { if ( $ action == 'index' ) { return true ; } $ insts = array_merge ( [ $ this ] , ( array ) $ this -> getExtensionInstances ( ) ) ; foreach ( $ insts as $ inst ) { if ( ! method_exists ( $ inst , $ action ) ) { continue ; } $ r = new ReflectionClass ( get_class ( $ inst ) ) ; $ m = $ r -> getMethod ( $ action ) ; if ( ! $ m || ! $ m -> isPublic ( ) ) { return false ; } } $ action = strtolower ( $ action ) ; $ actions = $ this -> allowedActions ( ) ; if ( is_array ( $ actions ) ) { $ isKey = ! is_numeric ( $ action ) && array_key_exists ( $ action , $ actions ) ; $ isValue = in_array ( $ action , $ actions , true ) ; if ( $ isKey || $ isValue ) { return true ; } } $ actionsWithoutExtra = $ this -> config ( ) -> get ( 'allowed_actions' , true ) ; if ( ! is_array ( $ actions ) || ! $ actionsWithoutExtra ) { if ( ! in_array ( strtolower ( $ action ) , [ 'run' , 'doinit' ] ) && method_exists ( $ this , $ action ) ) { return true ; } } return false ; }
|
Checks if this request handler has a specific action even if the current user cannot access it . Includes class ancestry and extensions in the checks .
|
4,685
|
protected function definingClassForAction ( $ actionOrigCasing ) { $ action = strtolower ( $ actionOrigCasing ) ; $ definingClass = null ; $ insts = array_merge ( [ $ this ] , ( array ) $ this -> getExtensionInstances ( ) ) ; foreach ( $ insts as $ inst ) { if ( ! method_exists ( $ inst , $ action ) ) { continue ; } $ r = new ReflectionClass ( get_class ( $ inst ) ) ; $ m = $ r -> getMethod ( $ actionOrigCasing ) ; return $ m -> getDeclaringClass ( ) -> getName ( ) ; } return null ; }
|
Return the class that defines the given action so that we know where to check allowed_actions .
|
4,686
|
public function Link ( $ action = null ) { $ url = $ this -> config ( ) -> get ( 'url_segment' ) ; if ( $ url ) { $ link = Controller :: join_links ( $ url , $ action , '/' ) ; $ this -> extend ( 'updateLink' , $ link , $ action ) ; return $ link ; } trigger_error ( 'Request handler ' . static :: class . ' does not have a url_segment defined. ' . 'Relying on this link may be an application error' , E_USER_WARNING ) ; return null ; }
|
Returns a link to this controller . Overload with your own Link rules if they exist .
|
4,687
|
public function getReturnReferer ( ) { $ referer = $ this -> getReferer ( ) ; if ( $ referer && Director :: is_site_url ( $ referer ) ) { return $ referer ; } return null ; }
|
Returns the referer if it is safely validated as an internal URL and can be redirected to .
|
4,688
|
public static function create ( $ table = null , $ assignment = array ( ) , $ where = array ( ) ) { return Injector :: inst ( ) -> createWithArgs ( __CLASS__ , func_get_args ( ) ) ; }
|
Construct a new SQLUpdate object
|
4,689
|
public function generateContent ( TinyMCEConfig $ config ) { $ tinymceDir = $ config -> getTinyMCEResource ( ) ; $ files = [ ] ; $ language = $ config -> getOption ( 'language' ) ; if ( $ language ) { $ files [ ] = $ this -> resolveRelativeResource ( $ tinymceDir , "langs/{$language}" ) ; } foreach ( $ config -> getPlugins ( ) as $ plugin => $ path ) { if ( $ path ) { if ( is_string ( $ path ) && ! Director :: is_site_url ( $ path ) ) { continue ; } if ( is_string ( $ path ) ) { $ path = Director :: makeRelative ( $ path ) ; } if ( $ this -> resourceExists ( $ path ) ) { $ files [ ] = $ path ; } continue ; } $ files [ ] = $ this -> resolveRelativeResource ( $ tinymceDir , "plugins/{$plugin}/plugin" ) ; if ( $ language ) { $ files [ ] = $ this -> resolveRelativeResource ( $ tinymceDir , "plugins/{$plugin}/langs/{$language}" ) ; } } $ theme = $ config -> getTheme ( ) ; if ( $ theme ) { $ files [ ] = $ this -> resolveRelativeResource ( $ tinymceDir , "themes/{$theme}/theme" ) ; if ( $ language ) { $ files [ ] = $ this -> resolveRelativeResource ( $ tinymceDir , "themes/{$theme}/langs/{$language}" ) ; } } $ files = array_filter ( $ files ) ; $ libResource = $ this -> resolveRelativeResource ( $ tinymceDir , 'tinymce' ) ; $ libContent = $ this -> getFileContents ( $ libResource ) ; $ baseDirJS = Convert :: raw2js ( Director :: absoluteBaseURL ( ) ) ; $ name = Convert :: raw2js ( $ this -> checkName ( $ config ) ) ; $ buffer = [ ] ; $ buffer [ ] = <<<SCRIPT(function() { var baseTag = window.document.getElementsByTagName('base'); var baseURL = baseTag.length ? baseTag[0].baseURI : '$baseDirJS'; var editorIdentifier = '$name';SCRIPT ; $ buffer [ ] = <<<SCRIPT(function() { // Avoid double-registration if (window.tinymce) { return; } var tinyMCEPreInit = { base: baseURL, suffix: '.min', }; $libContent})();SCRIPT ; foreach ( $ files as $ path ) { $ buffer [ ] = $ this -> getFileContents ( $ path ) ; } $ fileURLS = array_map ( function ( $ path ) { if ( $ path instanceof ModuleResource ) { return Director :: makeRelative ( $ path -> getURL ( ) ) ; } return $ path ; } , $ files ) ; $ filesList = Convert :: raw2js ( implode ( ',' , $ fileURLS ) ) ; $ buffer [ ] = "window.tinymce.each('$filesList'.split(',')," . "function(f){tinymce.ScriptLoader.markDone(baseURL+f);});" ; $ buffer [ ] = '})();' ; return implode ( "\n" , $ buffer ) . "\n" ; }
|
Build raw config for tinymce
|
4,690
|
protected function checkName ( TinyMCEConfig $ config ) { $ configs = HTMLEditorConfig :: get_available_configs_map ( ) ; foreach ( $ configs as $ id => $ name ) { if ( HTMLEditorConfig :: get ( $ id ) === $ config ) { return $ id ; } } return 'custom' ; }
|
Check if this config is registered under a given key
|
4,691
|
public function generateFilename ( TinyMCEConfig $ config ) { $ hash = substr ( sha1 ( json_encode ( $ config -> getAttributes ( ) ) ) , 0 , 10 ) ; $ name = $ this -> checkName ( $ config ) ; $ url = str_replace ( [ '{name}' , '{hash}' ] , [ $ name , $ hash ] , $ this -> config ( ) -> get ( 'filename_base' ) ) ; return $ url ; }
|
Get filename to use for this config
|
4,692
|
protected function resolveRelativeResource ( $ base , $ resource ) { foreach ( [ '' , '.min.js' , '.js' ] as $ ext ) { if ( $ base instanceof ModuleResource ) { $ next = $ base -> getRelativeResource ( $ resource . $ ext ) ; } else { $ next = rtrim ( $ base , '/' ) . '/' . $ resource . $ ext ; } if ( $ this -> resourceExists ( $ next ) ) { return $ next ; } } return null ; }
|
Get relative resource for a given base and string
|
4,693
|
protected function resourceExists ( $ resource ) { if ( ! $ resource ) { return false ; } if ( $ resource instanceof ModuleResource ) { return $ resource -> exists ( ) ; } $ base = rtrim ( Director :: baseFolder ( ) , '/' ) ; return file_exists ( $ base . '/' . $ resource ) ; }
|
Check if the given resource exists
|
4,694
|
public function checkDatabase ( $ databaseConfig ) { if ( ! $ this -> requireDatabaseFunctions ( $ databaseConfig , array ( "Database Configuration" , "Database support" , "Database support in PHP" , $ this -> getDatabaseTypeNice ( $ databaseConfig [ 'type' ] ) ) ) ) { return false ; } $ path = empty ( $ databaseConfig [ 'path' ] ) ? null : $ databaseConfig [ 'path' ] ; $ server = empty ( $ databaseConfig [ 'server' ] ) ? null : $ databaseConfig [ 'server' ] ; $ usePath = $ path && empty ( $ server ) ; if ( ! $ this -> requireDatabaseServer ( $ databaseConfig , array ( "Database Configuration" , "Database server" , $ usePath ? "I couldn't write to path '{$path}'" : "I couldn't find a database server on '{$server}'" , $ usePath ? $ path : $ server ) ) ) { return false ; } if ( ! $ this -> requireDatabaseConnection ( $ databaseConfig , array ( "Database Configuration" , "Database access credentials" , "That username/password doesn't work" ) ) ) { return false ; } if ( ! $ this -> requireDatabaseVersion ( $ databaseConfig , array ( "Database Configuration" , "Database server version requirement" , '' , 'Version ' . $ this -> getDatabaseConfigurationHelper ( $ databaseConfig [ 'type' ] ) -> getDatabaseVersion ( $ databaseConfig ) ) ) ) { return false ; } if ( ! $ this -> requireDatabaseOrCreatePermissions ( $ databaseConfig , array ( "Database Configuration" , "Can I access/create the database" , "I can't create new databases and the database '$databaseConfig[database]' doesn't exist" ) ) ) { return false ; } if ( ! $ this -> requireDatabaseAlterPermissions ( $ databaseConfig , array ( "Database Configuration" , "Can I ALTER tables" , "I don't have permission to ALTER tables" ) ) ) { return false ; } return true ; }
|
Check the database configuration . These are done one after another starting with checking the database function exists in PHP and continuing onto more difficult checks like database permissions .
|
4,695
|
protected function getOriginalIni ( $ settingName ) { if ( isset ( $ this -> originalIni [ $ settingName ] ) ) { return $ this -> originalIni [ $ settingName ] ; } return ini_get ( $ settingName ) ; }
|
Get ini setting
|
4,696
|
public function requireNoClasses ( $ classNames , $ testDetails ) { $ this -> testing ( $ testDetails ) ; $ badClasses = array ( ) ; foreach ( $ classNames as $ className ) { if ( class_exists ( $ className ) ) { $ badClasses [ ] = $ className ; } } if ( $ badClasses ) { $ message = $ testDetails [ 2 ] . ". The following classes are at fault: " . implode ( ', ' , $ badClasses ) ; $ this -> error ( $ testDetails , $ message ) ; return false ; } return true ; }
|
Require that the given class doesn t exist
|
4,697
|
public function DayOfMonth ( $ includeOrdinal = false ) { $ number = $ this -> Format ( 'd' ) ; if ( $ includeOrdinal && $ number ) { $ formatter = NumberFormatter :: create ( i18n :: get_locale ( ) , NumberFormatter :: ORDINAL ) ; return $ formatter -> format ( ( int ) $ number ) ; } return $ number ; }
|
Returns the day of the month .
|
4,698
|
public function Long ( ) { if ( ! $ this -> value ) { return null ; } $ formatter = $ this -> getFormatter ( IntlDateFormatter :: LONG ) ; return $ formatter -> format ( $ this -> getTimestamp ( ) ) ; }
|
Returns the date in the localised long format
|
4,699
|
public function Full ( ) { if ( ! $ this -> value ) { return null ; } $ formatter = $ this -> getFormatter ( IntlDateFormatter :: FULL ) ; return $ formatter -> format ( $ this -> getTimestamp ( ) ) ; }
|
Returns the date in the localised full format
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.