idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
4,400
|
public static function flush_template_cache ( $ force = false ) { if ( ! self :: $ template_cache_flushed || $ force ) { $ dir = dir ( TEMP_PATH ) ; while ( false !== ( $ file = $ dir -> read ( ) ) ) { if ( strstr ( $ file , '.cache' ) ) { unlink ( TEMP_PATH . DIRECTORY_SEPARATOR . $ file ) ; } } self :: $ template_cache_flushed = true ; } }
|
Clears all parsed template files in the cache folder .
|
4,401
|
public static function flush_cacheblock_cache ( $ force = false ) { if ( ! self :: $ cacheblock_cache_flushed || $ force ) { $ cache = Injector :: inst ( ) -> get ( CacheInterface :: class . '.cacheblock' ) ; $ cache -> clear ( ) ; self :: $ cacheblock_cache_flushed = true ; } }
|
Clears all partial cache blocks .
|
4,402
|
protected function includeGeneratedTemplate ( $ cacheFile , $ item , $ overlay , $ underlay , $ inheritedScope = null ) { if ( isset ( $ _GET [ 'showtemplate' ] ) && $ _GET [ 'showtemplate' ] && Permission :: check ( 'ADMIN' ) ) { $ lines = file ( $ cacheFile ) ; echo "<h2>Template: $cacheFile</h2>" ; echo "<pre>" ; foreach ( $ lines as $ num => $ line ) { echo str_pad ( $ num + 1 , 5 ) . htmlentities ( $ line , ENT_COMPAT , 'UTF-8' ) ; } echo "</pre>" ; } $ cache = $ this -> getPartialCacheStore ( ) ; $ scope = new SSViewer_DataPresenter ( $ item , $ overlay , $ underlay , $ inheritedScope ) ; $ val = '' ; [ $ cache , $ scope , $ val ] ; include ( $ cacheFile ) ; return $ val ; }
|
An internal utility function to set up variables in preparation for including a compiled template then do the include
|
4,403
|
protected function getSubtemplateFor ( $ subtemplate ) { if ( isset ( $ this -> subTemplates [ $ subtemplate ] ) ) { return $ this -> subTemplates [ $ subtemplate ] ; } if ( isset ( $ this -> templates [ 'type' ] ) ) { return null ; } $ templates = array_filter ( ( array ) $ this -> templates , function ( $ template ) { return ! isset ( $ template [ 'type' ] ) ; } ) ; if ( empty ( $ templates ) ) { return null ; } $ templates [ 'type' ] = $ subtemplate ; return $ templates ; }
|
Get the appropriate template to use for the named sub - template or null if none are appropriate
|
4,404
|
public static function execute_string ( $ content , $ data , $ arguments = null , $ globalRequirements = false ) { $ v = SSViewer :: fromString ( $ content ) ; if ( $ globalRequirements ) { $ v -> includeRequirements ( false ) ; } else { $ origBackend = Requirements :: backend ( ) ; Requirements :: set_backend ( Requirements_Backend :: create ( ) ) ; } try { return $ v -> process ( $ data , $ arguments ) ; } finally { if ( ! $ globalRequirements ) { Requirements :: set_backend ( $ origBackend ) ; } } }
|
Execute the evaluated string passing it the given data . Used by partial caching to evaluate custom cache keys expressed using template expressions
|
4,405
|
public function parseTemplateContent ( $ content , $ template = "" ) { return $ this -> getParser ( ) -> compileString ( $ content , $ template , Director :: isDev ( ) && SSViewer :: config ( ) -> uninherited ( 'source_file_comments' ) ) ; }
|
Parse given template contents
|
4,406
|
public function createObject ( $ name , $ identifier , $ data = null ) { if ( ! isset ( $ this -> blueprints [ $ name ] ) ) { $ this -> blueprints [ $ name ] = new FixtureBlueprint ( $ name ) ; } $ blueprint = $ this -> blueprints [ $ name ] ; $ obj = $ blueprint -> createObject ( $ identifier , $ data , $ this -> fixtures ) ; $ class = $ blueprint -> getClass ( ) ; if ( ! isset ( $ this -> fixtures [ $ class ] ) ) { $ this -> fixtures [ $ class ] = array ( ) ; } $ this -> fixtures [ $ class ] [ $ identifier ] = $ obj -> ID ; return $ obj ; }
|
Writes the fixture into the database using DataObjects
|
4,407
|
public function createRaw ( $ table , $ identifier , $ data ) { $ fields = array ( ) ; foreach ( $ data as $ fieldName => $ fieldVal ) { $ fields [ "\"{$fieldName}\"" ] = $ this -> parseValue ( $ fieldVal ) ; } $ insert = new SQLInsert ( "\"{$table}\"" , $ fields ) ; $ insert -> execute ( ) ; $ id = DB :: get_generated_id ( $ table ) ; $ this -> fixtures [ $ table ] [ $ identifier ] = $ id ; return $ id ; }
|
Writes the fixture into the database directly using a database manipulation . Does not use blueprints . Only supports tables with a primary key .
|
4,408
|
public function getId ( $ class , $ identifier ) { if ( isset ( $ this -> fixtures [ $ class ] [ $ identifier ] ) ) { return $ this -> fixtures [ $ class ] [ $ identifier ] ; } else { return false ; } }
|
Get the ID of an object from the fixture .
|
4,409
|
public function get ( $ class , $ identifier ) { $ id = $ this -> getId ( $ class , $ identifier ) ; if ( ! $ id ) { return null ; } if ( ! class_exists ( $ class ) ) { $ tableNames = DataObject :: getSchema ( ) -> getTableNames ( ) ; $ potential = array_search ( $ class , $ tableNames ) ; if ( ! $ potential ) { throw new \ LogicException ( "'$class' is neither a class nor a table name" ) ; } $ class = $ potential ; } return DataObject :: get_by_id ( $ class , $ id ) ; }
|
Get an object from the fixture .
|
4,410
|
public static function getTempFolder ( $ base ) { $ parent = static :: getTempParentFolder ( $ base ) ; $ subfolder = Path :: join ( $ parent , static :: getTempFolderUsername ( ) ) ; if ( ! @ file_exists ( $ subfolder ) ) { mkdir ( $ subfolder ) ; } return $ subfolder ; }
|
Returns the temporary folder path that silverstripe should use for its cache files .
|
4,411
|
public static function getTempFolderUsername ( ) { $ user = Environment :: getEnv ( 'APACHE_RUN_USER' ) ; if ( ! $ user ) { $ user = Environment :: getEnv ( 'USER' ) ; } if ( ! $ user ) { $ user = Environment :: getEnv ( 'USERNAME' ) ; } if ( ! $ user && function_exists ( 'posix_getpwuid' ) && function_exists ( 'posix_getuid' ) ) { $ userDetails = posix_getpwuid ( posix_getuid ( ) ) ; $ user = $ userDetails [ 'name' ] ; } if ( ! $ user ) { $ user = 'unknown' ; } $ user = preg_replace ( '/[^A-Za-z0-9_\-]/' , '' , $ user ) ; return $ user ; }
|
Returns as best a representation of the current username as we can glean .
|
4,412
|
protected static function getTempParentFolder ( $ base ) { $ localPath = Path :: join ( $ base , 'silverstripe-cache' ) ; if ( @ file_exists ( $ localPath ) ) { if ( ( fileperms ( $ localPath ) & 0777 ) != 0777 ) { @ chmod ( $ localPath , 0777 ) ; } return $ localPath ; } $ tempPath = Path :: join ( sys_get_temp_dir ( ) , 'silverstripe-cache-php' . preg_replace ( '/[^\w\-\.+]+/' , '-' , PHP_VERSION ) . str_replace ( array ( ' ' , '/' , ':' , '\\' ) , '-' , $ base ) ) ; if ( ! @ file_exists ( $ tempPath ) ) { $ oldUMask = umask ( 0 ) ; @ mkdir ( $ tempPath , 0777 ) ; umask ( $ oldUMask ) ; } else { if ( ( fileperms ( $ tempPath ) & 0777 ) != 0777 ) { @ chmod ( $ tempPath , 0777 ) ; } } $ worked = @ file_exists ( $ tempPath ) && @ is_writable ( $ tempPath ) ; if ( ! $ worked ) { $ tempPath = $ localPath ; if ( ! @ file_exists ( $ tempPath ) ) { $ oldUMask = umask ( 0 ) ; @ mkdir ( $ tempPath , 0777 ) ; umask ( $ oldUMask ) ; } $ worked = @ file_exists ( $ tempPath ) && @ is_writable ( $ tempPath ) ; } if ( ! $ worked ) { throw new Exception ( 'Permission problem gaining access to a temp folder. ' . 'Please create a folder named silverstripe-cache in the base folder ' . 'of the installation and ensure it has the correct permissions' ) ; } return $ tempPath ; }
|
Return the parent folder of the temp folder . The temp folder will be a subfolder of this named by username . This structure prevents permission problems .
|
4,413
|
public function getSortedModules ( ) { $ i18nOrder = Sources :: config ( ) -> uninherited ( 'module_priority' ) ; $ sortedModules = [ ] ; if ( $ i18nOrder ) { Deprecation :: notice ( '5.0' , sprintf ( '%s.module_priority is deprecated. Use %s.module_priority instead.' , __CLASS__ , ModuleManifest :: class ) ) ; } foreach ( ModuleLoader :: inst ( ) -> getManifest ( ) -> getModules ( ) as $ module ) { $ sortedModules [ $ module -> getName ( ) ] = $ module -> getPath ( ) ; } ; return $ sortedModules ; }
|
Get sorted modules
|
4,414
|
protected function getLangFiles ( ) { if ( static :: $ cache_lang_files ) { return static :: $ cache_lang_files ; } $ locales = [ ] ; foreach ( $ this -> getLangDirs ( ) as $ langPath ) { $ langFiles = scandir ( $ langPath ) ; foreach ( $ langFiles as $ langFile ) { $ locale = pathinfo ( $ langFile , PATHINFO_FILENAME ) ; $ ext = pathinfo ( $ langFile , PATHINFO_EXTENSION ) ; if ( $ locale && $ ext === 'yml' ) { $ locales [ $ locale ] = $ locale ; } } } ksort ( $ locales ) ; static :: $ cache_lang_files = $ locales ; return $ locales ; }
|
Search directories for list of distinct locale filenames
|
4,415
|
public function getManifest ( ) { if ( $ this !== self :: $ instance ) { throw new BadMethodCallException ( "Non-current injector manifest cannot be accessed. Please call ->activate() first" ) ; } if ( empty ( $ this -> manifests ) ) { throw new BadMethodCallException ( "No injector manifests available" ) ; } return $ this -> manifests [ count ( $ this -> manifests ) - 1 ] ; }
|
Returns the currently active class manifest instance that is used for loading classes .
|
4,416
|
public function performReadonlyTransformation ( ) { $ field = new CheckboxField_Readonly ( $ this -> name , $ this -> title , $ this -> value ) ; $ field -> setForm ( $ this -> form ) ; return $ field ; }
|
Returns a readonly version of this field
|
4,417
|
protected function getFieldOption ( $ valueOrGroup , $ titleOrOptions ) { if ( ! is_array ( $ titleOrOptions ) ) { return parent :: getFieldOption ( $ valueOrGroup , $ titleOrOptions ) ; } $ options = new ArrayList ( ) ; foreach ( $ titleOrOptions as $ childValue => $ childTitle ) { $ options -> push ( $ this -> getFieldOption ( $ childValue , $ childTitle ) ) ; } return new ArrayData ( array ( 'Title' => $ valueOrGroup , 'Options' => $ options ) ) ; }
|
Build a potentially nested fieldgroup
|
4,418
|
public function loadFile ( $ path , $ overload = false ) { if ( ! file_exists ( $ path ) || ! is_readable ( $ path ) ) { return null ; } $ result = [ ] ; $ variables = Parser :: parse ( file_get_contents ( $ path ) ) ; foreach ( $ variables as $ name => $ value ) { if ( ! $ overload ) { $ existing = Environment :: getEnv ( $ name ) ; if ( $ existing !== false ) { $ result [ $ name ] = $ existing ; continue ; } } Environment :: setEnv ( $ name , $ value ) ; $ result [ $ name ] = $ value ; } return $ result ; }
|
Load environment variables from . env file
|
4,419
|
public function handleAction ( GridField $ gridField , $ actionName , $ arguments , $ data ) { if ( ! $ this -> checkDataType ( $ gridField -> getList ( ) ) ) { return ; } $ state = $ gridField -> State -> GridFieldFilterHeader ; $ state -> Columns = null ; if ( $ actionName === 'filter' ) { if ( isset ( $ data [ 'filter' ] [ $ gridField -> getName ( ) ] ) ) { foreach ( $ data [ 'filter' ] [ $ gridField -> getName ( ) ] as $ key => $ filter ) { $ state -> Columns -> $ key = $ filter ; } } } }
|
If the GridField has a filterable datalist return an array of actions
|
4,420
|
public function getSearchFieldSchema ( GridField $ gridField ) { $ schemaUrl = Controller :: join_links ( $ gridField -> Link ( ) , 'schema/SearchForm' ) ; $ context = $ this -> getSearchContext ( $ gridField ) ; $ params = $ gridField -> getRequest ( ) -> postVar ( 'filter' ) ? : [ ] ; if ( array_key_exists ( $ gridField -> getName ( ) , $ params ) ) { $ params = $ params [ $ gridField -> getName ( ) ] ; } if ( $ context -> getSearchParams ( ) ) { $ params = array_merge ( $ context -> getSearchParams ( ) , $ params ) ; } $ context -> setSearchParams ( $ params ) ; $ searchField = $ context -> getSearchFields ( ) -> first ( ) ; $ searchField = $ searchField && property_exists ( $ searchField , 'name' ) ? $ searchField -> name : null ; $ name = $ gridField -> Title ? : singleton ( $ gridField -> getModelClass ( ) ) -> i18n_plural_name ( ) ; $ filters = $ context -> getSearchParams ( ) ; if ( ! $ this -> useLegacyFilterHeader && ! empty ( $ filters ) ) { $ filters = array_combine ( array_map ( function ( $ key ) { return 'Search__' . $ key ; } , array_keys ( $ filters ) ) , $ filters ) ; } $ searchAction = GridField_FormAction :: create ( $ gridField , 'filter' , false , 'filter' , null ) ; $ clearAction = GridField_FormAction :: create ( $ gridField , 'reset' , false , 'reset' , null ) ; $ schema = [ 'formSchemaUrl' => $ schemaUrl , 'name' => $ searchField , 'placeholder' => _t ( __CLASS__ . '.Search' , 'Search "{name}"' , [ 'name' => $ name ] ) , 'filters' => $ filters ? : new \ stdClass , 'gridfield' => $ gridField -> getName ( ) , 'searchAction' => $ searchAction -> getAttribute ( 'name' ) , 'searchActionState' => $ searchAction -> getAttribute ( 'data-action-state' ) , 'clearAction' => $ clearAction -> getAttribute ( 'name' ) , 'clearActionState' => $ clearAction -> getAttribute ( 'data-action-state' ) , ] ; return json_encode ( $ schema ) ; }
|
Returns the search field schema for the component
|
4,421
|
public function getSearchForm ( GridField $ gridField ) { $ searchContext = $ this -> getSearchContext ( $ gridField ) ; $ searchFields = $ searchContext -> getSearchFields ( ) ; if ( $ searchFields -> count ( ) === 0 ) { return null ; } if ( $ this -> searchForm ) { return $ this -> searchForm ; } foreach ( $ searchFields as $ field ) { $ field -> setName ( 'Search__' . $ field -> getName ( ) ) ; } $ columns = $ gridField -> getColumns ( ) ; foreach ( $ columns as $ columnField ) { $ metadata = $ gridField -> getColumnMetadata ( $ columnField ) ; $ name = explode ( '.' , $ columnField ) ; $ title = $ metadata [ 'title' ] ; $ field = $ searchFields -> fieldByName ( $ name [ 0 ] ) ; if ( $ field ) { $ field -> setTitle ( $ title ) ; } } foreach ( $ searchFields -> getIterator ( ) as $ field ) { $ field -> addExtraClass ( 'stacked' ) ; } $ name = $ gridField -> Title ? : singleton ( $ gridField -> getModelClass ( ) ) -> i18n_plural_name ( ) ; $ this -> searchForm = $ form = new Form ( $ gridField , $ name . "SearchForm" , $ searchFields , new FieldList ( ) ) ; $ form -> setFormMethod ( 'get' ) ; $ form -> setFormAction ( $ gridField -> Link ( ) ) ; $ form -> addExtraClass ( 'cms-search-form form--no-dividers' ) ; $ form -> disableSecurityToken ( ) ; $ form -> loadDataFrom ( $ searchContext -> getSearchParams ( ) ) ; if ( $ this -> updateSearchFormCallback ) { call_user_func ( $ this -> updateSearchFormCallback , $ form ) ; } return $ this -> searchForm ; }
|
Returns the search form for the component
|
4,422
|
public function getSearchFormSchema ( GridField $ gridField ) { $ form = $ this -> getSearchForm ( $ gridField ) ; if ( ! $ form ) { return new HTTPResponse ( _t ( __CLASS__ . '.SearchFormFaliure' , 'No search form could be generated' ) , 400 ) ; } $ parts = $ gridField -> getRequest ( ) -> getHeader ( LeftAndMain :: SCHEMA_HEADER ) ; $ schemaID = $ gridField -> getRequest ( ) -> getURL ( ) ; $ data = FormSchema :: singleton ( ) -> getMultipartSchema ( $ parts , $ schemaID , $ form ) ; $ response = new HTTPResponse ( json_encode ( $ data ) ) ; $ response -> addHeader ( 'Content-Type' , 'application/json' ) ; return $ response ; }
|
Returns the search form schema for the component
|
4,423
|
public function getHTMLFragments ( $ gridField ) { $ forTemplate = new ArrayData ( [ ] ) ; if ( ! $ this -> canFilterAnyColumns ( $ gridField ) ) { return null ; } if ( $ this -> useLegacyFilterHeader ) { $ fieldsList = $ this -> getLegacyFilterHeader ( $ gridField ) ; $ forTemplate -> Fields = $ fieldsList ; $ filterTemplates = SSViewer :: get_templates_by_class ( $ this , '_Row' , __CLASS__ ) ; return [ 'header' => $ forTemplate -> renderWith ( $ filterTemplates ) ] ; } else { $ fieldSchema = $ this -> getSearchFieldSchema ( $ gridField ) ; $ forTemplate -> SearchFieldSchema = $ fieldSchema ; $ searchTemplates = SSViewer :: get_templates_by_class ( $ this , '_Search' , __CLASS__ ) ; return [ 'before' => $ forTemplate -> renderWith ( $ searchTemplates ) , 'buttons-before-right' => sprintf ( '<button type="button" name="showFilter" aria-label="%s" title="%s"' . ' class="btn btn-secondary font-icon-search btn--no-text btn--icon-large grid-field__filter-open"></button>' , _t ( 'SilverStripe\\Forms\\GridField\\GridField.OpenFilter' , "Open search and filter" ) , _t ( 'SilverStripe\\Forms\\GridField\\GridField.OpenFilter' , "Open search and filter" ) ) ] ; } }
|
Either returns the legacy filter header or the search button and field
|
4,424
|
public function finalize ( ) { $ lines = array ( ) ; foreach ( $ this -> edits as $ edit ) { if ( $ edit -> final ) array_splice ( $ lines , sizeof ( $ lines ) , 0 , $ edit -> final ) ; } return $ lines ; }
|
Get the final set of lines .
|
4,425
|
public static function register ( $ config ) { $ missing = array_diff ( [ 'title' , 'class' , 'helperClass' , 'supported' ] , array_keys ( $ config ) ) ; if ( $ missing ) { throw new InvalidArgumentException ( "Missing database helper config keys: '" . implode ( "', '" , $ missing ) . "'" ) ; } if ( empty ( $ config [ 'missingModuleText' ] ) ) { if ( empty ( $ config [ 'module' ] ) ) { $ moduleText = 'Module for database connector ' . $ config [ 'title' ] . 'is missing.' ; } else { $ moduleText = "The SilverStripe module '" . $ config [ 'module' ] . "' is missing." ; } $ config [ 'missingModuleText' ] = $ moduleText . ' Please install it via composer or from http://addons.silverstripe.org/.' ; } if ( empty ( $ config [ 'missingExtensionText' ] ) ) { $ config [ 'missingExtensionText' ] = 'The PHP extension is missing, please enable or install it.' ; } if ( ! isset ( $ config [ 'fields' ] ) ) { $ config [ 'fields' ] = self :: $ default_fields ; } self :: $ adapters [ $ config [ 'class' ] ] = $ config ; }
|
Add new adapter to the registry
|
4,426
|
public static function getDatabaseConfigurationHelper ( $ databaseClass ) { $ adapters = static :: get_adapters ( ) ; if ( empty ( $ adapters [ $ databaseClass ] ) || empty ( $ adapters [ $ databaseClass ] [ 'helperClass' ] ) ) { return null ; } if ( isset ( $ adapters [ $ databaseClass ] [ 'helperPath' ] ) ) { include_once $ adapters [ $ databaseClass ] [ 'helperPath' ] ; } $ class = $ adapters [ $ databaseClass ] [ 'helperClass' ] ; return ( class_exists ( $ class ) ) ? new $ class ( ) : null ; }
|
Build configuration helper for a given class
|
4,427
|
protected function getExtraConfig ( $ class , $ classConfig , $ excludeMiddleware ) { $ extensionSourceConfig = Config :: inst ( ) -> get ( $ class , null , Config :: UNINHERITED | $ excludeMiddleware | $ this -> disableFlag ) ; if ( empty ( $ extensionSourceConfig [ 'extensions' ] ) ) { return ; } $ extensions = $ extensionSourceConfig [ 'extensions' ] ; foreach ( $ extensions as $ extension ) { list ( $ extensionClass , $ extensionArgs ) = ClassInfo :: parse_class_spec ( $ extension ) ; $ extensionClass = strtok ( $ extensionClass , '.' ) ; if ( ! class_exists ( $ extensionClass ) ) { throw new InvalidArgumentException ( "$class references nonexistent $extensionClass in 'extensions'" ) ; } call_user_func ( array ( $ extensionClass , 'add_to_class' ) , $ class , $ extensionClass , $ extensionArgs ) ; foreach ( ClassInfo :: ancestry ( $ extensionClass ) as $ extensionClassParent ) { switch ( $ extensionClassParent ) { case Extension :: class : case DataExtension :: class : continue 2 ; default : } $ extensionConfig = Config :: inst ( ) -> get ( $ extensionClassParent , null , Config :: EXCLUDE_EXTRA_SOURCES | Config :: UNINHERITED ) ; if ( $ extensionConfig ) { yield $ extensionConfig ; } if ( ClassInfo :: has_method_from ( $ extensionClassParent , 'get_extra_config' , $ extensionClassParent ) ) { $ extensionConfig = call_user_func ( [ $ extensionClassParent , 'get_extra_config' ] , $ class , $ extensionClass , $ extensionArgs ) ; if ( $ extensionConfig ) { yield $ extensionConfig ; } } } } }
|
Applied config to a class from its extensions
|
4,428
|
public function handleRequestWithTokenChain ( HTTPRequest $ request , ConfirmationTokenChain $ confirmationTokenChain , Kernel $ kernel ) { Injector :: inst ( ) -> registerService ( $ request , HTTPRequest :: class ) ; $ reload = function ( HTTPRequest $ request ) use ( $ confirmationTokenChain , $ kernel ) { if ( $ kernel -> getEnvironment ( ) === Kernel :: DEV || ! Security :: database_is_ready ( ) || Permission :: check ( 'ADMIN' ) ) { return $ confirmationTokenChain -> reloadWithTokens ( ) ; } return null ; } ; try { return $ this -> callMiddleware ( $ request , $ reload ) ; } finally { Injector :: inst ( ) -> unregisterNamedObject ( HTTPRequest :: class ) ; } }
|
Redirect with token if allowed or null if not allowed
|
4,429
|
public function logout ( ) { $ member = Security :: getCurrentUser ( ) ; if ( $ member && ! SecurityToken :: inst ( ) -> checkRequest ( $ this -> getRequest ( ) ) ) { Security :: singleton ( ) -> setSessionMessage ( _t ( 'SilverStripe\\Security\\Security.CONFIRMLOGOUT' , "Please click the button below to confirm that you wish to log out." ) , ValidationResult :: TYPE_WARNING ) ; return [ 'Form' => $ this -> logoutForm ( ) ] ; } return $ this -> doLogOut ( $ member ) ; }
|
Log out form handler method
|
4,430
|
public function collateFamilyIDs ( ) { if ( ! $ this -> exists ( ) ) { throw new \ InvalidArgumentException ( "Cannot call collateFamilyIDs on unsaved Group." ) ; } $ familyIDs = array ( ) ; $ chunkToAdd = array ( $ this -> ID ) ; while ( $ chunkToAdd ) { $ familyIDs = array_merge ( $ familyIDs , $ chunkToAdd ) ; $ chunkToAdd = Group :: get ( ) -> filter ( "ParentID" , $ chunkToAdd ) -> column ( 'ID' ) ; } return $ familyIDs ; }
|
Return a set of this record s family of IDs - the IDs of this record and all its descendants .
|
4,431
|
public function collateAncestorIDs ( ) { $ parent = $ this ; $ items = [ ] ; while ( $ parent instanceof Group ) { $ items [ ] = $ parent -> ID ; $ parent = $ parent -> getParent ( ) ; } return $ items ; }
|
Returns an array of the IDs of this group and all its parents
|
4,432
|
public function inGroups ( $ groups , $ requireAll = false ) { $ ancestorIDs = $ this -> collateAncestorIDs ( ) ; $ candidateIDs = [ ] ; foreach ( $ groups as $ group ) { $ groupID = $ this -> identifierToGroupID ( $ group ) ; if ( $ groupID ) { $ candidateIDs [ ] = $ groupID ; } elseif ( $ requireAll ) { return false ; } } if ( empty ( $ candidateIDs ) ) { return false ; } $ matches = array_intersect ( $ candidateIDs , $ ancestorIDs ) ; if ( $ requireAll ) { return count ( $ candidateIDs ) === count ( $ matches ) ; } return ! empty ( $ matches ) ; }
|
Check if the group is a child of the given groups or any parent groups
|
4,433
|
protected function identifierToGroupID ( $ groupID ) { if ( is_numeric ( $ groupID ) && Group :: get ( ) -> byID ( $ groupID ) ) { return $ groupID ; } elseif ( is_string ( $ groupID ) && $ groupByCode = Group :: get ( ) -> filter ( [ 'Code' => $ groupID ] ) -> first ( ) ) { return $ groupByCode -> ID ; } elseif ( $ groupID instanceof Group && $ groupID -> exists ( ) ) { return $ groupID -> ID ; } return null ; }
|
Turn a string|int|Group into a GroupID
|
4,434
|
public function stageChildren ( ) { return Group :: get ( ) -> filter ( "ParentID" , $ this -> ID ) -> exclude ( "ID" , $ this -> ID ) -> sort ( '"Sort"' ) ; }
|
Override this so groups are ordered in the CMS
|
4,435
|
public function canEdit ( $ member = null ) { if ( ! $ member ) { $ member = Security :: getCurrentUser ( ) ; } $ results = $ this -> extend ( 'canEdit' , $ member ) ; if ( $ results && is_array ( $ results ) ) { if ( ! min ( $ results ) ) { return false ; } } if ( ( bool ) Permission :: checkMember ( $ member , "ADMIN" ) || ( Permission :: checkMember ( $ member , "CMS_ACCESS_SecurityAdmin" ) && ! Permission :: get ( ) -> filter ( array ( 'GroupID' => $ this -> ID , 'Code' => 'ADMIN' ) ) -> exists ( ) ) ) { return true ; } return false ; }
|
Checks for permission - code CMS_ACCESS_SecurityAdmin . If the group has ADMIN permissions it requires the user to have ADMIN permissions as well .
|
4,436
|
public function canView ( $ member = null ) { if ( ! $ member ) { $ member = Security :: getCurrentUser ( ) ; } $ results = $ this -> extend ( 'canView' , $ member ) ; if ( $ results && is_array ( $ results ) ) { if ( ! min ( $ results ) ) { return false ; } } if ( Permission :: checkMember ( $ member , "CMS_ACCESS_SecurityAdmin" ) ) { return true ; } return false ; }
|
Checks for permission - code CMS_ACCESS_SecurityAdmin .
|
4,437
|
public function AllChildrenIncludingDeleted ( ) { $ children = parent :: AllChildrenIncludingDeleted ( ) ; $ filteredChildren = new ArrayList ( ) ; if ( $ children ) { foreach ( $ children as $ child ) { if ( $ child -> canView ( ) ) { $ filteredChildren -> push ( $ child ) ; } } } return $ filteredChildren ; }
|
Returns all of the children for the CMS Tree . Filters to only those groups that the current user can edit
|
4,438
|
public function mapColumns ( $ columnMap ) { if ( $ columnMap ) { $ lowerColumnMap = array ( ) ; foreach ( $ columnMap as $ k => $ v ) { $ lowerColumnMap [ strtolower ( $ k ) ] = $ v ; } $ this -> columnMap = array_merge ( $ this -> columnMap , $ lowerColumnMap ) ; } }
|
Re - map columns in the CSV file .
|
4,439
|
protected function openFile ( ) { ini_set ( 'auto_detect_line_endings' , 1 ) ; $ this -> fileHandle = fopen ( $ this -> filename , 'r' ) ; if ( $ this -> providedHeaderRow ) { $ this -> headerRow = $ this -> remapHeader ( $ this -> providedHeaderRow ) ; } }
|
Open the CSV file for reading .
|
4,440
|
protected function closeFile ( ) { if ( $ this -> fileHandle ) { fclose ( $ this -> fileHandle ) ; } $ this -> fileHandle = null ; $ this -> rowNum = 0 ; $ this -> currentRow = null ; $ this -> headerRow = null ; }
|
Close the CSV file and re - set all of the internal variables .
|
4,441
|
protected function fetchCSVHeader ( ) { $ srcRow = fgetcsv ( $ this -> fileHandle , 0 , $ this -> delimiter , $ this -> enclosure ) ; $ this -> headerRow = $ this -> remapHeader ( $ srcRow ) ; }
|
Get a header row from the CSV file .
|
4,442
|
public function getCacheKey ( $ includeTests = false ) { return sha1 ( sprintf ( "manifest-%s-%s-%u" , $ this -> base , $ this -> project , $ includeTests ) ) ; }
|
Generate a unique cache key to avoid manifest cache collisions . We compartmentalise based on the base path the given project and whether or not we intend to include tests .
|
4,443
|
public function handleDirectory ( $ basename , $ pathname , $ depth ) { if ( $ basename !== self :: TEMPLATES_DIR ) { return ; } $ dir = trim ( substr ( dirname ( $ pathname ) , strlen ( $ this -> base ) ) , '/\\' ) ; $ this -> themes [ ] = "/" . $ dir ; }
|
Add a directory to the manifest
|
4,444
|
public function getSet ( $ set ) { if ( isset ( $ this -> sets [ $ set ] ) ) { return $ this -> sets [ $ set ] ; } return null ; }
|
Get a named theme set
|
4,445
|
public function getPath ( $ identifier ) { $ slashPos = strpos ( $ identifier , '/' ) ; $ parts = explode ( ':' , $ identifier , 2 ) ; if ( $ slashPos === 0 ) { if ( count ( $ parts ) > 1 ) { throw new InvalidArgumentException ( "Invalid theme identifier {$identifier}" ) ; } return Path :: normalise ( $ identifier , true ) ; } if ( $ slashPos === false && count ( $ parts ) === 1 ) { return Path :: join ( THEMES_DIR , $ identifier ) ; } $ moduleName = $ parts [ 0 ] ; $ module = ModuleLoader :: inst ( ) -> getManifest ( ) -> getModule ( $ moduleName ) ; if ( $ module ) { $ modulePath = $ module -> getRelativePath ( ) ; } else { if ( strstr ( '/' , $ moduleName ) ) { list ( , $ modulePath ) = explode ( '/' , $ parts [ 0 ] , 2 ) ; } else { $ modulePath = $ moduleName ; } trigger_error ( "No module named {$moduleName} found. Assuming path {$modulePath}" , E_USER_WARNING ) ; } $ theme = count ( $ parts ) > 1 ? $ parts [ 1 ] : '' ; if ( empty ( $ theme ) ) { $ subpath = '' ; } elseif ( strpos ( $ theme , '/' ) === 0 ) { $ subpath = rtrim ( $ theme , '/' ) ; } else { $ subpath = '/themes/' . $ theme ; } return Path :: normalise ( $ modulePath . $ subpath , true ) ; }
|
Given a theme identifier determine the path from the root directory
|
4,446
|
public function findTemplate ( $ template , $ themes = null ) { if ( $ themes === null ) { $ themes = SSViewer :: get_themes ( ) ; } $ cacheKey = md5 ( json_encode ( $ template ) . json_encode ( $ themes ) ) ; if ( $ this -> getCache ( ) -> has ( $ cacheKey ) ) { return $ this -> getCache ( ) -> get ( $ cacheKey ) ; } $ type = '' ; if ( is_array ( $ template ) ) { if ( array_key_exists ( 'type' , $ template ) ) { $ type = $ template [ 'type' ] ; unset ( $ template [ 'type' ] ) ; } $ templateList = array_key_exists ( 'templates' , $ template ) ? $ template [ 'templates' ] : $ template ; } else { $ templateList = array ( $ template ) ; } foreach ( $ templateList as $ i => $ template ) { if ( is_array ( $ template ) ) { $ path = $ this -> findTemplate ( $ template , $ themes ) ; if ( $ path ) { $ this -> getCache ( ) -> set ( $ cacheKey , $ path ) ; return $ path ; } continue ; } if ( substr ( $ template , - 3 ) == '.ss' && file_exists ( $ template ) ) { $ this -> getCache ( ) -> set ( $ cacheKey , $ template ) ; return $ template ; } $ template = str_replace ( '\\' , '/' , $ template ) ; $ parts = explode ( '/' , $ template ) ; $ tail = array_pop ( $ parts ) ; $ head = implode ( '/' , $ parts ) ; $ themePaths = $ this -> getThemePaths ( $ themes ) ; foreach ( $ themePaths as $ themePath ) { $ pathParts = [ $ this -> base , $ themePath , 'templates' , $ head , $ type , $ tail ] ; $ path = Path :: join ( $ pathParts ) . '.ss' ; if ( file_exists ( $ path ) ) { $ this -> getCache ( ) -> set ( $ cacheKey , $ path ) ; return $ path ; } } } $ this -> getCache ( ) -> set ( $ cacheKey , null ) ; return null ; }
|
Attempts to find possible candidate templates from a set of template names from modules current theme directory and finally the application folder .
|
4,447
|
public function findThemedJavascript ( $ name , $ themes = null ) { if ( $ themes === null ) { $ themes = SSViewer :: get_themes ( ) ; } if ( substr ( $ name , - 3 ) !== '.js' ) { $ name .= '.js' ; } $ filename = $ this -> findThemedResource ( "javascript/$name" , $ themes ) ; if ( $ filename === null ) { $ filename = $ this -> findThemedResource ( $ name , $ themes ) ; } return $ filename ; }
|
Resolve themed javascript path
|
4,448
|
public function findThemedResource ( $ resource , $ themes = null ) { if ( $ themes === null ) { $ themes = SSViewer :: get_themes ( ) ; } $ paths = $ this -> getThemePaths ( $ themes ) ; foreach ( $ paths as $ themePath ) { $ relativePath = Path :: join ( $ themePath , $ resource ) ; $ absolutePath = Path :: join ( $ this -> base , $ relativePath ) ; if ( file_exists ( $ absolutePath ) ) { return $ relativePath ; } } return null ; }
|
Resolve a themed resource
|
4,449
|
public function getThemePaths ( $ themes = null ) { if ( $ themes === null ) { $ themes = SSViewer :: get_themes ( ) ; } $ paths = [ ] ; foreach ( $ themes as $ themename ) { $ set = $ this -> getSet ( $ themename ) ; $ subthemes = $ set ? $ set -> getThemes ( ) : [ $ themename ] ; foreach ( $ subthemes as $ theme ) { $ paths [ ] = $ this -> getPath ( $ theme ) ; } } return $ paths ; }
|
Resolve all themes to the list of root folders relative to site root
|
4,450
|
public function setUrl ( $ url ) { $ this -> url = $ url ; if ( Director :: is_relative_url ( $ url ) || preg_match ( '/^\//' , $ url ) ) { $ this -> url = preg_replace ( array ( '/\/+/' , '/^\//' , '/\/$/' ) , array ( '/' , '' , '' ) , $ this -> url ) ; } if ( preg_match ( '/^(.*)\.([A-Za-z][A-Za-z0-9]*)$/' , $ this -> url , $ matches ) ) { $ this -> url = $ matches [ 1 ] ; $ this -> extension = $ matches [ 2 ] ; } if ( $ this -> url ) { $ this -> dirParts = preg_split ( '|/+|' , $ this -> url ) ; } else { $ this -> dirParts = array ( ) ; } return $ this ; }
|
Allow the setting of a URL
|
4,451
|
public function addHeader ( $ header , $ value ) { $ header = strtolower ( $ header ) ; $ this -> headers [ $ header ] = $ value ; return $ this ; }
|
Add a HTTP header to the response replacing any header of the same name .
|
4,452
|
public function getURL ( $ includeGetVars = false ) { $ url = ( $ this -> getExtension ( ) ) ? $ this -> url . '.' . $ this -> getExtension ( ) : $ this -> url ; if ( $ includeGetVars ) { $ vars = $ this -> getVars ( ) ; if ( count ( $ vars ) ) { $ url .= '?' . http_build_query ( $ vars ) ; } } elseif ( strpos ( $ url , "?" ) !== false ) { $ url = substr ( $ url , 0 , strpos ( $ url , "?" ) ) ; } return $ url ; }
|
Returns the URL used to generate the page
|
4,453
|
public function shiftAllParams ( ) { $ keys = array_keys ( $ this -> allParams ) ; $ values = array_values ( $ this -> allParams ) ; $ value = array_shift ( $ values ) ; if ( array_key_exists ( $ this -> unshiftedButParsedParts , $ this -> dirParts ) ) { $ values [ ] = $ this -> dirParts [ $ this -> unshiftedButParsedParts ] ; } foreach ( $ keys as $ position => $ key ) { $ this -> allParams [ $ key ] = isset ( $ values [ $ position ] ) ? $ values [ $ position ] : null ; } return $ value ; }
|
Shift all the parameter values down a key space and return the shifted value .
|
4,454
|
public function isEmptyPattern ( $ pattern ) { if ( preg_match ( '/^([A-Za-z]+) +(.*)$/' , $ pattern , $ matches ) ) { $ pattern = $ matches [ 2 ] ; } if ( trim ( $ pattern ) == "" ) { return true ; } return false ; }
|
Returns true if this is a URL that will match without shifting off any of the URL . This is used by the request handler to prevent infinite parsing loops .
|
4,455
|
public function shift ( $ count = 1 ) { $ return = array ( ) ; if ( $ count == 1 ) { return array_shift ( $ this -> dirParts ) ; } for ( $ i = 0 ; $ i < $ count ; $ i ++ ) { $ value = array_shift ( $ this -> dirParts ) ; if ( $ value === null ) { break ; } $ return [ ] = $ value ; } return $ return ; }
|
Shift one or more parts off the beginning of the URL . If you specify shifting more than 1 item off then the items will be returned as an array
|
4,456
|
public function setIP ( $ ip ) { if ( ! filter_var ( $ ip , FILTER_VALIDATE_IP ) ) { throw new InvalidArgumentException ( "Invalid ip $ip" ) ; } $ this -> ip = $ ip ; return $ this ; }
|
Sets the client IP address which originated this request . Use setIPFromHeaderValue if assigning from header value .
|
4,457
|
public function getAcceptMimetypes ( $ includeQuality = false ) { $ mimetypes = array ( ) ; $ mimetypesWithQuality = preg_split ( '#\s*,\s*#' , $ this -> getHeader ( 'accept' ) ) ; foreach ( $ mimetypesWithQuality as $ mimetypeWithQuality ) { $ mimetypes [ ] = ( $ includeQuality ) ? $ mimetypeWithQuality : preg_replace ( '/;.*/' , '' , $ mimetypeWithQuality ) ; } return $ mimetypes ; }
|
Returns all mimetypes from the HTTP Accept header as an array .
|
4,458
|
public static function detect_method ( $ origMethod , $ postVars ) { if ( isset ( $ postVars [ '_method' ] ) ) { if ( ! in_array ( strtoupper ( $ postVars [ '_method' ] ) , array ( 'GET' , 'POST' , 'PUT' , 'DELETE' , 'HEAD' ) ) ) { user_error ( 'HTTPRequest::detect_method(): Invalid "_method" parameter' , E_USER_ERROR ) ; } return strtoupper ( $ postVars [ '_method' ] ) ; } else { return $ origMethod ; } }
|
Gets the real HTTP method for a request .
|
4,459
|
public static function create_field ( $ spec , $ value , $ name = null , ... $ args ) { if ( $ args && strpos ( $ spec , '(' ) !== false ) { trigger_error ( 'Additional args provided in both $spec and $args' , E_USER_WARNING ) ; } array_unshift ( $ args , $ name ) ; $ dbField = Injector :: inst ( ) -> createWithArgs ( $ spec , $ args ) ; $ dbField -> setValue ( $ value , null , false ) ; return $ dbField ; }
|
Create a DBField object that s not bound to any particular field .
|
4,460
|
public function setName ( $ name ) { if ( $ this -> name && $ this -> name !== $ name ) { user_error ( "DBField::setName() shouldn't be called once a DBField already has a name." . "It's partially immutable - it shouldn't be altered after it's given a value." , E_USER_WARNING ) ; } $ this -> name = $ name ; return $ this ; }
|
Set the name of this field .
|
4,461
|
public function prepValueForDB ( $ value ) { if ( $ value === null || $ value === "" || $ value === false || ( $ this -> scalarValueOnly ( ) && ! is_scalar ( $ value ) ) ) { return null ; } else { return $ value ; } }
|
Return the transformed value ready to be sent to the database . This value will be escaped automatically by the prepared query processor so it should not be escaped or quoted at all .
|
4,462
|
public function saveInto ( $ dataObject ) { $ fieldName = $ this -> name ; if ( empty ( $ fieldName ) ) { throw new \ BadMethodCallException ( "DBField::saveInto() Called on a nameless '" . static :: class . "' object" ) ; } $ dataObject -> $ fieldName = $ this -> value ; }
|
Saves this field to the given data object .
|
4,463
|
public function scaffoldFormField ( $ title = null , $ params = null ) { return TextField :: create ( $ this -> name , $ title ) ; }
|
Returns a FormField instance used as a default for form scaffolding .
|
4,464
|
function compile ( $ indent ) { $ function_name = $ this -> function_name ( $ this -> name ) ; $ typestack = array ( ) ; $ class = $ this ; do { $ typestack [ ] = $ this -> function_name ( $ class -> name ) ; } while ( $ class = $ class -> extends ) ; $ typestack = "array('" . implode ( "','" , $ typestack ) . "')" ; if ( empty ( $ this -> arguments ) ) { $ arguments = 'null' ; } else { $ arguments = "array(" ; foreach ( $ this -> arguments as $ k => $ v ) { $ arguments .= "'$k' => '$v'" ; } $ arguments .= ")" ; } $ match = PHPBuilder :: build ( ) ; $ match -> l ( "protected \$match_{$function_name}_typestack = $typestack;" ) ; $ match -> b ( "function match_{$function_name} (\$stack = array())" , '$matchrule = "' . $ function_name . '"; $result = $this->construct($matchrule, $matchrule, ' . $ arguments . ');' , $ this -> parsed -> compile ( ) -> replace ( array ( 'MATCH' => 'return $this->finalise($result);' , 'FAIL' => 'return FALSE;' ) ) ) ; $ functions = array ( ) ; foreach ( $ this -> functions as $ name => $ function ) { $ function_name = $ this -> function_name ( preg_match ( '/^_/' , $ name ) ? $ this -> name . $ name : $ this -> name . '_' . $ name ) ; $ functions [ ] = implode ( PHP_EOL , array ( 'function ' . $ function_name . ' ' . $ function ) ) ; } return $ match -> render ( NULL , $ indent ) . PHP_EOL . PHP_EOL . implode ( PHP_EOL , $ functions ) ; }
|
Generate the PHP code for a function to match against a string for this rule
|
4,465
|
public function addDelete ( $ tables ) { if ( is_array ( $ tables ) ) { $ this -> delete = array_merge ( $ this -> delete , $ tables ) ; } elseif ( ! empty ( $ tables ) ) { $ this -> delete [ str_replace ( array ( '"' , '`' ) , '' , $ tables ) ] = $ tables ; } return $ this ; }
|
Sets the list of tables to limit the delete to if multiple tables are specified in the condition clause
|
4,466
|
protected function load ( $ locale ) { if ( isset ( $ this -> loadedLocales [ $ locale ] ) ) { return ; } $ this -> getTranslator ( ) -> addResource ( 'ss' , $ this -> getSourceDirs ( ) , $ locale ) ; $ lang = i18n :: getData ( ) -> langFromLocale ( $ locale ) ; if ( $ lang !== $ locale ) { $ this -> getTranslator ( ) -> addResource ( 'ss' , $ this -> getSourceDirs ( ) , $ lang ) ; } $ this -> loadedLocales [ $ locale ] = true ; }
|
Load resources for the given locale
|
4,467
|
protected function templateInjection ( $ injection ) { $ injection = $ injection ? : [ ] ; $ arguments = array_combine ( array_map ( function ( $ val ) { return '{' . $ val . '}' ; } , array_keys ( $ injection ) ) , $ injection ) ; return $ arguments ; }
|
Generate template safe injection parameters
|
4,468
|
public function schemaUpdate ( $ callback ) { $ this -> schemaIsUpdating = true ; $ this -> tableList = array ( ) ; $ tables = $ this -> tableList ( ) ; foreach ( $ tables as $ table ) { $ this -> tableList [ strtolower ( $ table ) ] = $ table ; } $ this -> schemaUpdateTransaction = array ( ) ; $ error = null ; try { $ callback ( ) ; if ( ! $ this -> isSchemaUpdating ( ) ) { return ; } foreach ( $ this -> schemaUpdateTransaction as $ tableName => $ changes ) { $ advancedOptions = isset ( $ changes [ 'advancedOptions' ] ) ? $ changes [ 'advancedOptions' ] : null ; switch ( $ changes [ 'command' ] ) { case 'create' : $ this -> createTable ( $ tableName , $ changes [ 'newFields' ] , $ changes [ 'newIndexes' ] , $ changes [ 'options' ] , $ advancedOptions ) ; break ; case 'alter' : $ this -> alterTable ( $ tableName , $ changes [ 'newFields' ] , $ changes [ 'newIndexes' ] , $ changes [ 'alteredFields' ] , $ changes [ 'alteredIndexes' ] , $ changes [ 'alteredOptions' ] , $ advancedOptions ) ; break ; } } } finally { $ this -> schemaUpdateTransaction = null ; $ this -> schemaIsUpdating = false ; } }
|
Initiates a schema update within a single callback
|
4,469
|
public function transCreateTable ( $ table , $ options = null , $ advanced_options = null ) { $ this -> schemaUpdateTransaction [ $ table ] = array ( 'command' => 'create' , 'newFields' => array ( ) , 'newIndexes' => array ( ) , 'options' => $ options , 'advancedOptions' => $ advanced_options ) ; }
|
Instruct the schema manager to record a table creation to later execute
|
4,470
|
public function transAlterTable ( $ table , $ options , $ advanced_options ) { $ this -> transInitTable ( $ table ) ; $ this -> schemaUpdateTransaction [ $ table ] [ 'alteredOptions' ] = $ options ; $ this -> schemaUpdateTransaction [ $ table ] [ 'advancedOptions' ] = $ advanced_options ; }
|
Instruct the schema manager to record a table alteration to later execute
|
4,471
|
public function transCreateField ( $ table , $ field , $ schema ) { $ this -> transInitTable ( $ table ) ; $ this -> schemaUpdateTransaction [ $ table ] [ 'newFields' ] [ $ field ] = $ schema ; }
|
Instruct the schema manager to record a field to be later created
|
4,472
|
public function transCreateIndex ( $ table , $ index , $ schema ) { $ this -> transInitTable ( $ table ) ; $ this -> schemaUpdateTransaction [ $ table ] [ 'newIndexes' ] [ $ index ] = $ schema ; }
|
Instruct the schema manager to record an index to be later created
|
4,473
|
public function transAlterField ( $ table , $ field , $ schema ) { $ this -> transInitTable ( $ table ) ; $ this -> schemaUpdateTransaction [ $ table ] [ 'alteredFields' ] [ $ field ] = $ schema ; }
|
Instruct the schema manager to record a field to be later updated
|
4,474
|
public function transAlterIndex ( $ table , $ index , $ schema ) { $ this -> transInitTable ( $ table ) ; $ this -> schemaUpdateTransaction [ $ table ] [ 'alteredIndexes' ] [ $ index ] = $ schema ; }
|
Instruct the schema manager to record an index to be later updated
|
4,475
|
protected function determineIndexType ( $ spec ) { if ( is_array ( $ spec ) && isset ( $ spec [ 'type' ] ) ) { return $ spec [ 'type' ] ; } elseif ( ! is_array ( $ spec ) && preg_match ( '/(?<type>\w+)\s*\(/' , $ spec , $ matchType ) ) { return strtolower ( $ matchType [ 'type' ] ) ; } else { return 'index' ; } }
|
Given an index spec determines the index type
|
4,476
|
public function hasField ( $ tableName , $ fieldName ) { if ( ! $ this -> hasTable ( $ tableName ) ) { return false ; } $ fields = $ this -> fieldList ( $ tableName ) ; return array_key_exists ( $ fieldName , $ fields ) ; }
|
Return true if the table exists and already has a the field specified
|
4,477
|
public function alterationMessage ( $ message , $ type = "" ) { if ( ! $ this -> supressOutput ) { if ( Director :: is_cli ( ) ) { switch ( $ type ) { case "created" : case "changed" : case "repaired" : $ sign = "+" ; break ; case "obsolete" : case "deleted" : $ sign = '-' ; break ; case "notice" : $ sign = '*' ; break ; case "error" : $ sign = "!" ; break ; default : $ sign = " " ; } $ message = strip_tags ( $ message ) ; echo " $sign $message\n" ; } else { switch ( $ type ) { case "created" : $ class = "success" ; break ; case "obsolete" : $ class = "error" ; break ; case "notice" : $ class = "warning" ; break ; case "error" : $ class = "error" ; break ; case "deleted" : $ class = "error" ; break ; case "changed" : $ class = "info" ; break ; case "repaired" : $ class = "info" ; break ; default : $ class = "" ; } echo "<li class=\"$class\">$message</li>" ; } } }
|
Show a message about database alteration
|
4,478
|
public function fixTableCase ( $ tableName ) { $ tables = $ this -> tableList ( ) ; if ( ! array_key_exists ( strtolower ( $ tableName ) , $ tables ) ) { return ; } $ currentName = $ tables [ strtolower ( $ tableName ) ] ; if ( $ currentName === $ tableName ) { return ; } $ this -> alterationMessage ( "Table $tableName: renamed from $currentName" , "repaired" ) ; $ tempTable = "__TEMP__{$tableName}" ; $ this -> renameTable ( $ currentName , $ tempTable ) ; $ this -> renameTable ( $ tempTable , $ tableName ) ; }
|
Ensure the given table has the correct case
|
4,479
|
protected function getIsMerge ( $ request ) { $ merge = $ request -> getVar ( 'merge' ) ; if ( ! isset ( $ merge ) ) { return true ; } return ! in_array ( $ merge , array ( '0' , 'false' ) ) ; }
|
Check if we should merge
|
4,480
|
protected function linkJoinTable ( ) { $ dataClassIDColumn = DataObject :: getSchema ( ) -> sqlColumnForField ( $ this -> dataClass ( ) , 'ID' ) ; $ this -> dataQuery -> innerJoin ( $ this -> joinTable , "\"{$this->joinTable}\".\"{$this->localKey}\" = {$dataClassIDColumn}" ) ; if ( $ this -> extraFields ) { $ this -> appendExtraFieldsToQuery ( ) ; } }
|
Setup the join between this dataobject and the necessary mapping table
|
4,481
|
public function createDataObject ( $ row ) { $ add = [ ] ; if ( $ this -> _compositeExtraFields ) { foreach ( $ this -> _compositeExtraFields as $ fieldName => $ composed ) { $ value = [ ] ; foreach ( $ composed as $ subField ) { if ( isset ( $ row [ $ fieldName . $ subField ] ) ) { $ value [ $ subField ] = $ row [ $ fieldName . $ subField ] ; unset ( $ row [ $ fieldName . $ subField ] ) ; } } $ obj = Injector :: inst ( ) -> create ( $ this -> extraFields [ $ fieldName ] , $ fieldName ) ; $ obj -> setValue ( $ value , null , false ) ; $ add [ $ fieldName ] = $ obj ; } } $ dataObject = parent :: createDataObject ( $ row ) ; foreach ( $ add as $ fieldName => $ obj ) { $ dataObject -> $ fieldName = $ obj ; } return $ dataObject ; }
|
Create a DataObject from the given SQL row .
|
4,482
|
protected function foreignIDFilter ( $ id = null ) { if ( $ id === null ) { $ id = $ this -> getForeignID ( ) ; } $ key = "\"{$this->joinTable}\".\"{$this->foreignKey}\"" ; if ( is_array ( $ id ) ) { return [ "$key IN (" . DB :: placeholders ( $ id ) . ")" => $ id ] ; } if ( $ id !== null ) { return [ $ key => $ id ] ; } return null ; }
|
Return a filter expression for when getting the contents of the relationship for some foreign ID
|
4,483
|
public function getExtraData ( $ componentName , $ itemID ) { $ result = [ ] ; if ( empty ( $ this -> extraFields ) || empty ( $ itemID ) ) { return $ result ; } if ( ! is_numeric ( $ itemID ) ) { throw new InvalidArgumentException ( 'ManyManyList::getExtraData() passed a non-numeric child ID' ) ; } $ cleanExtraFields = [ ] ; foreach ( $ this -> extraFields as $ fieldName => $ dbFieldSpec ) { $ cleanExtraFields [ ] = "\"{$fieldName}\"" ; } $ query = SQLSelect :: create ( $ cleanExtraFields , "\"{$this->joinTable}\"" ) ; $ filter = $ this -> foreignIDWriteFilter ( $ this -> getForeignID ( ) ) ; if ( $ filter ) { $ query -> setWhere ( $ filter ) ; } else { throw new BadMethodCallException ( "Can't call ManyManyList::getExtraData() until a foreign ID is set" ) ; } $ query -> addWhere ( [ "\"{$this->joinTable}\".\"{$this->localKey}\"" => $ itemID ] ) ; $ queryResult = $ query -> execute ( ) -> current ( ) ; if ( $ queryResult ) { foreach ( $ queryResult as $ fieldName => $ value ) { $ result [ $ fieldName ] = $ value ; } } return $ result ; }
|
Find the extra field data for a single row of the relationship join table given the known child ID .
|
4,484
|
public function AllChildrenIncludingDeleted ( ) { $ owner = $ this -> owner ; $ stageChildren = $ owner -> stageChildren ( true ) ; if ( $ owner -> hasExtension ( Versioned :: class ) && $ owner -> hasStages ( ) ) { $ liveChildren = $ owner -> liveChildren ( true , true ) ; if ( $ liveChildren ) { $ merged = new ArrayList ( ) ; $ merged -> merge ( $ stageChildren ) ; $ merged -> merge ( $ liveChildren ) ; $ stageChildren = $ merged ; } } $ owner -> extend ( "augmentAllChildrenIncludingDeleted" , $ stageChildren ) ; return $ stageChildren ; }
|
Return all children including those that have been deleted but are still in live . - Deleted children will be marked as DeletedFromStage - Added children will be marked as AddedToStage - Modified children will be marked as ModifiedOnStage - Everything else has SameOnStage set as an indicator that this information has been looked up .
|
4,485
|
public function AllHistoricalChildren ( ) { $ owner = $ this -> owner ; if ( ! $ owner -> hasExtension ( Versioned :: class ) || ! $ owner -> hasStages ( ) ) { throw new Exception ( 'Hierarchy->AllHistoricalChildren() only works with Versioned extension applied with staging' ) ; } $ baseTable = $ owner -> baseTable ( ) ; $ parentIDColumn = $ owner -> getSchema ( ) -> sqlColumnForField ( $ owner , 'ParentID' ) ; return Versioned :: get_including_deleted ( $ owner -> baseClass ( ) , [ $ parentIDColumn => $ owner -> ID ] , "\"{$baseTable}\".\"ID\" ASC" ) ; }
|
Return all the children that this page had including pages that were deleted from both stage & live .
|
4,486
|
public function showingCMSTree ( ) { if ( ! Controller :: has_curr ( ) || ! class_exists ( LeftAndMain :: class ) ) { return false ; } $ controller = Controller :: curr ( ) ; return $ controller instanceof LeftAndMain && in_array ( $ controller -> getAction ( ) , array ( "treeview" , "listview" , "getsubtree" ) ) ; }
|
Checks if we re on a controller where we should filter . ie . Are we loading the SiteTree?
|
4,487
|
public function stageChildren ( $ showAll = false , $ skipParentIDFilter = false ) { $ hideFromHierarchy = $ this -> owner -> config ( ) -> hide_from_hierarchy ; $ hideFromCMSTree = $ this -> owner -> config ( ) -> hide_from_cms_tree ; $ baseClass = $ this -> owner -> baseClass ( ) ; $ baseTable = $ this -> owner -> baseTable ( ) ; $ staged = DataObject :: get ( $ baseClass ) -> where ( sprintf ( '%s.%s <> %s.%s' , Convert :: symbol2sql ( $ baseTable ) , Convert :: symbol2sql ( "ParentID" ) , Convert :: symbol2sql ( $ baseTable ) , Convert :: symbol2sql ( "ID" ) ) ) ; if ( ! $ skipParentIDFilter ) { $ staged = $ staged -> filter ( 'ParentID' , ( int ) $ this -> owner -> ID ) ; } if ( $ hideFromHierarchy ) { $ staged = $ staged -> exclude ( 'ClassName' , $ hideFromHierarchy ) ; } if ( $ hideFromCMSTree && $ this -> showingCMSTree ( ) ) { $ staged = $ staged -> exclude ( 'ClassName' , $ hideFromCMSTree ) ; } if ( ! $ showAll && DataObject :: getSchema ( ) -> fieldSpec ( $ this -> owner , 'ShowInMenus' ) ) { $ staged = $ staged -> filter ( 'ShowInMenus' , 1 ) ; } $ this -> owner -> extend ( "augmentStageChildren" , $ staged , $ showAll ) ; return $ staged ; }
|
Return children in the stage site .
|
4,488
|
public function liveChildren ( $ showAll = false , $ onlyDeletedFromStage = false ) { $ owner = $ this -> owner ; if ( ! $ owner -> hasExtension ( Versioned :: class ) || ! $ owner -> hasStages ( ) ) { throw new Exception ( 'Hierarchy->liveChildren() only works with Versioned extension applied with staging' ) ; } $ hideFromHierarchy = $ owner -> config ( ) -> hide_from_hierarchy ; $ hideFromCMSTree = $ owner -> config ( ) -> hide_from_cms_tree ; $ children = DataObject :: get ( $ owner -> baseClass ( ) ) -> filter ( 'ParentID' , ( int ) $ owner -> ID ) -> exclude ( 'ID' , ( int ) $ owner -> ID ) -> setDataQueryParam ( array ( 'Versioned.mode' => $ onlyDeletedFromStage ? 'stage_unique' : 'stage' , 'Versioned.stage' => 'Live' ) ) ; if ( $ hideFromHierarchy ) { $ children = $ children -> exclude ( 'ClassName' , $ hideFromHierarchy ) ; } if ( $ hideFromCMSTree && $ this -> showingCMSTree ( ) ) { $ children = $ children -> exclude ( 'ClassName' , $ hideFromCMSTree ) ; } if ( ! $ showAll && DataObject :: getSchema ( ) -> fieldSpec ( $ owner , 'ShowInMenus' ) ) { $ children = $ children -> filter ( 'ShowInMenus' , 1 ) ; } return $ children ; }
|
Return children in the live site if it exists .
|
4,489
|
public function getParent ( $ filter = null ) { $ parentID = $ this -> owner -> ParentID ; if ( empty ( $ parentID ) ) { return null ; } $ baseClass = $ this -> owner -> baseClass ( ) ; $ idSQL = $ this -> owner -> getSchema ( ) -> sqlColumnForField ( $ baseClass , 'ID' ) ; return DataObject :: get_one ( $ baseClass , [ [ $ idSQL => $ parentID ] , $ filter ] ) ; }
|
Get this object s parent optionally filtered by an SQL clause . If the clause doesn t match the parent nothing is returned .
|
4,490
|
public function getAncestors ( $ includeSelf = false ) { $ ancestors = new ArrayList ( ) ; $ object = $ this -> owner ; if ( $ includeSelf ) { $ ancestors -> push ( $ object ) ; } while ( $ object = $ object -> getParent ( ) ) { $ ancestors -> push ( $ object ) ; } return $ ancestors ; }
|
Return all the parents of this class in a set ordered from the closest to furtherest parent .
|
4,491
|
protected function writeConfigEnv ( $ config ) { if ( ! $ config [ 'usingEnv' ] ) { return ; } $ path = $ this -> getBaseDir ( ) . '.env' ; $ vars = [ ] ; $ env = new EnvironmentLoader ( ) ; if ( file_exists ( $ path ) ) { $ vars = $ env -> loadFile ( $ path ) ? : [ ] ; } if ( ! isset ( $ vars [ 'SS_BASE_URL' ] ) && isset ( $ _SERVER [ 'HTTP_HOST' ] ) ) { $ vars [ 'SS_BASE_URL' ] = 'http://' . $ _SERVER [ 'HTTP_HOST' ] . BASE_URL ; } if ( empty ( $ config [ 'db' ] [ 'database' ] ) ) { $ vars [ 'SS_DATABASE_CHOOSE_NAME' ] = true ; } else { $ vars [ 'SS_DATABASE_NAME' ] = $ config [ 'db' ] [ 'database' ] ; } $ vars [ 'SS_DATABASE_CLASS' ] = $ config [ 'db' ] [ 'type' ] ; if ( isset ( $ config [ 'db' ] [ 'server' ] ) ) { $ vars [ 'SS_DATABASE_SERVER' ] = $ config [ 'db' ] [ 'server' ] ; } if ( isset ( $ config [ 'db' ] [ 'username' ] ) ) { $ vars [ 'SS_DATABASE_USERNAME' ] = $ config [ 'db' ] [ 'username' ] ; } if ( isset ( $ config [ 'db' ] [ 'password' ] ) ) { $ vars [ 'SS_DATABASE_PASSWORD' ] = $ config [ 'db' ] [ 'password' ] ; } if ( isset ( $ config [ 'db' ] [ 'path' ] ) ) { $ vars [ 'SS_DATABASE_PATH' ] = $ config [ 'db' ] [ 'path' ] ; $ vars [ 'SS_SQLITE_DATABASE_PATH' ] = $ config [ 'db' ] [ 'path' ] ; } if ( isset ( $ config [ 'db' ] [ 'key' ] ) ) { $ vars [ 'SS_DATABASE_KEY' ] = $ config [ 'db' ] [ 'key' ] ; $ vars [ 'SS_SQLITE_DATABASE_KEY' ] = $ config [ 'db' ] [ 'key' ] ; } $ lines = [ '# Generated by SilverStripe Installer' ] ; ksort ( $ vars ) ; foreach ( $ vars as $ key => $ value ) { $ lines [ ] = $ key . '="' . addcslashes ( $ value , '"' ) . '"' ; } $ this -> writeToFile ( '.env' , implode ( "\n" , $ lines ) ) ; $ env -> loadFile ( $ path ) ; }
|
Write all . env files
|
4,492
|
public function writeToFile ( $ filename , $ content , $ absolute = false ) { list ( $ absolutePath , $ relativePath ) = $ absolute ? [ $ filename , substr ( $ filename , strlen ( $ this -> getBaseDir ( ) ) ) ] : [ $ this -> getBaseDir ( ) . $ filename , $ filename ] ; $ this -> statusMessage ( "Setting up $relativePath" ) ; if ( ( @ $ fh = fopen ( $ absolutePath , 'wb' ) ) && fwrite ( $ fh , $ content ) && fclose ( $ fh ) ) { @ chmod ( $ absolutePath , 0775 ) ; return true ; } $ this -> error ( "Couldn't write to file $relativePath" ) ; return false ; }
|
Write file to given location
|
4,493
|
public function createHtaccess ( ) { $ start = "### SILVERSTRIPE START ###\n" ; $ end = "\n### SILVERSTRIPE END ###" ; $ base = dirname ( $ _SERVER [ 'SCRIPT_NAME' ] ) ; $ base = Convert :: slashes ( $ base , '/' ) ; if ( $ base != '.' ) { $ baseClause = "RewriteBase '$base'\n" ; } else { $ baseClause = "" ; } if ( strpos ( strtolower ( php_sapi_name ( ) ) , "cgi" ) !== false ) { $ cgiClause = "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n" ; } else { $ cgiClause = "" ; } $ rewrite = <<<TEXT# Deny access to templates (but allow from localhost)<Files *.ss> Order deny,allow Deny from all Allow from 127.0.0.1</Files># Deny access to IIS configuration<Files web.config> Order deny,allow Deny from all</Files># Deny access to YAML configuration files which might include sensitive information<Files ~ "\.ya?ml$"> Order allow,deny Deny from all</Files># Route errors to static pages automatically generated by SilverStripeErrorDocument 404 /assets/error-404.htmlErrorDocument 500 /assets/error-500.html<IfModule mod_rewrite.c> # Turn off index.php handling requests to the homepage fixes issue in apache >=2.4 <IfModule mod_dir.c> DirectoryIndex disabled DirectorySlash On </IfModule> SetEnv HTTP_MOD_REWRITE On RewriteEngine On $baseClause $cgiClause # Deny access to potentially sensitive files and folders RewriteRule ^vendor(/|$) - [F,L,NC] RewriteRule ^\.env - [F,L,NC] RewriteRule silverstripe-cache(/|$) - [F,L,NC] RewriteRule composer\.(json|lock) - [F,L,NC] RewriteRule (error|silverstripe|debug)\.log - [F,L,NC] # Process through SilverStripe if no file with the requested name exists. # Pass through the original path as a query parameter, and retain the existing parameters. # Try finding framework in the vendor folder first RewriteCond %{REQUEST_URI} ^(.*)$ RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* index.php</IfModule>TEXT ; $ htaccessPath = $ this -> getPublicDir ( ) . '.htaccess' ; if ( file_exists ( $ htaccessPath ) ) { $ htaccess = file_get_contents ( $ htaccessPath ) ; if ( strpos ( $ htaccess , '### SILVERSTRIPE START ###' ) === false && strpos ( $ htaccess , '### SILVERSTRIPE END ###' ) === false ) { $ htaccess .= "\n### SILVERSTRIPE START ###\n### SILVERSTRIPE END ###\n" ; } if ( strpos ( $ htaccess , '### SILVERSTRIPE START ###' ) !== false && strpos ( $ htaccess , '### SILVERSTRIPE END ###' ) !== false ) { $ start = substr ( $ htaccess , 0 , strpos ( $ htaccess , '### SILVERSTRIPE START ###' ) ) . "### SILVERSTRIPE START ###\n" ; $ end = "\n" . substr ( $ htaccess , strpos ( $ htaccess , '### SILVERSTRIPE END ###' ) ) ; } } $ this -> writeToFile ( $ htaccessPath , $ start . $ rewrite . $ end , true ) ; }
|
Ensure root . htaccess is setup
|
4,494
|
public function createWebConfig ( ) { $ content = <<<TEXT<?xml version="1.0" encoding="utf-8"?><configuration> <system.webServer> <security> <requestFiltering> <hiddenSegments applyToWebDAV="false"> <add segment="silverstripe-cache" /> <add segment="composer.json" /> <add segment="composer.lock" /> </hiddenSegments> <fileExtensions allowUnlisted="true" > <add fileExtension=".ss" allowed="false"/> <add fileExtension=".yml" allowed="false"/> </fileExtensions> </requestFiltering> </security> <rewrite> <rules> <rule name="SilverStripe Clean URLs" stopProcessing="true"> <match url="^(.*)$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> </conditions> <action type="Rewrite" url="index.php" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer></configuration>TEXT ; $ path = $ this -> getPublicDir ( ) . 'web.config' ; $ this -> writeToFile ( $ path , $ content , true ) ; }
|
Writes basic configuration to the web . config for IIS so that rewriting capability can be use .
|
4,495
|
public static function ModulePath ( $ name ) { $ legacyMapping = [ 'framework' => 'silverstripe/framework' , 'frameworkadmin' => 'silverstripe/admin' , ] ; if ( isset ( $ legacyMapping [ $ name ] ) ) { $ name = $ legacyMapping [ $ name ] ; } return ModuleLoader :: getModule ( $ name ) -> getRelativePath ( ) ; }
|
Given some pre - defined modules return the filesystem path of the module .
|
4,496
|
public function FirstLast ( ) { if ( $ this -> First ( ) && $ this -> Last ( ) ) { return 'first last' ; } if ( $ this -> First ( ) ) { return 'first' ; } if ( $ this -> Last ( ) ) { return 'last' ; } return null ; }
|
Returns first or last if this is the first or last object in the set .
|
4,497
|
public function getShortName ( ) { if ( $ this -> path === $ this -> basePath && $ this -> composerData ) { if ( isset ( $ this -> composerData [ 'extra' ] [ 'installer-name' ] ) ) { return $ this -> composerData [ 'extra' ] [ 'installer-name' ] ; } $ composerName = $ this -> getComposerName ( ) ; if ( $ composerName ) { list ( , $ name ) = explode ( '/' , $ composerName ) ; return $ name ; } } return basename ( $ this -> path ) ; }
|
Gets short name of this module . This is the base directory this module is installed in .
|
4,498
|
public function getResource ( $ path ) { $ path = Path :: normalise ( $ path , true ) ; if ( empty ( $ path ) ) { throw new InvalidArgumentException ( '$path is required' ) ; } if ( isset ( $ this -> resources [ $ path ] ) ) { return $ this -> resources [ $ path ] ; } return $ this -> resources [ $ path ] = new ModuleResource ( $ this , $ path ) ; }
|
Get resource for this module
|
4,499
|
public function setSchemaManager ( DBSchemaManager $ schemaManager ) { $ this -> schemaManager = $ schemaManager ; if ( $ this -> schemaManager ) { $ this -> schemaManager -> setDatabase ( $ this ) ; } }
|
Injector injection point for schema manager
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.