idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
10,500
public function import ( $ pointer , $ filename = false , $ fr = false , $ prefix = null ) { $ fh = $ this -> app -> make ( 'helper/validation/file' ) ; $ fi = $ this -> app -> make ( 'helper/file' ) ; $ cf = $ this -> app -> make ( 'helper/concrete/file' ) ; $ filename = ( string ) $ filename ; if ( $ filename === '' ) { $ filename = basename ( $ pointer ) ; } $ sanitizedFilename = $ fi -> sanitize ( $ filename ) ; if ( ! $ fh -> file ( $ pointer ) ) { return self :: E_FILE_INVALID ; } if ( ! $ fh -> extension ( $ filename ) ) { return self :: E_FILE_INVALID_EXTENSION ; } if ( $ fr instanceof FileEntity ) { $ fsl = $ fr -> getFileStorageLocationObject ( ) ; } else { $ fsl = $ this -> app -> make ( StorageLocationFactory :: class ) -> fetchDefault ( ) ; } if ( ! ( $ fsl instanceof StorageLocation ) ) { return self :: E_FILE_INVALID_STORAGE_LOCATION ; } $ filesystem = $ fsl -> getFileSystemObject ( ) ; if ( $ prefix ) { $ prefixIsAutoGenerated = false ; } else { $ prefix = $ this -> generatePrefix ( ) ; $ prefixIsAutoGenerated = true ; } $ src = @ fopen ( $ pointer , 'rb' ) ; if ( $ src === false ) { return self :: E_FILE_INVALID ; } try { $ filesystem -> writeStream ( $ cf -> prefix ( $ prefix , $ sanitizedFilename ) , $ src , [ 'visibility' => AdapterInterface :: VISIBILITY_PUBLIC , 'mimetype' => $ this -> app -> make ( 'helper/mime' ) -> mimeFromExtension ( $ fi -> getExtension ( $ sanitizedFilename ) ) , ] ) ; } catch ( Exception $ e ) { if ( ! $ prefixIsAutoGenerated ) { return self :: E_FILE_UNABLE_TO_STORE_PREFIX_PROVIDED ; } else { return self :: E_FILE_UNABLE_TO_STORE ; } } finally { @ fclose ( $ src ) ; } if ( ! ( $ fr instanceof FileEntity ) ) { $ fv = File :: add ( $ sanitizedFilename , $ prefix , [ 'fvTitle' => $ filename ] , $ fsl , $ fr ) ; } else { $ fv = $ fr -> getVersionToModify ( true ) ; $ fv -> updateFile ( $ sanitizedFilename , $ prefix ) ; } $ fv -> refreshAttributes ( false ) ; foreach ( $ this -> importProcessors as $ processor ) { if ( $ processor -> shouldProcess ( $ fv ) ) { $ processor -> process ( $ fv ) ; } } if ( $ this -> rescanThumbnailsOnImport ) { $ fv -> refreshThumbnails ( true ) ; } $ fv -> releaseImagineImage ( ) ; return $ fv ; }
Imports a local file into the system .
10,501
public function importIncomingFile ( $ filename , $ fr = false ) { $ fh = $ this -> app -> make ( 'helper/validation/file' ) ; if ( ! $ fh -> extension ( $ filename ) ) { return self :: E_FILE_INVALID_EXTENSION ; } $ incoming = $ this -> app -> make ( Incoming :: class ) ; $ incomingStorageLocation = $ incoming -> getIncomingStorageLocation ( ) ; $ incomingFilesystem = $ incomingStorageLocation -> getFileSystemObject ( ) ; $ incomingPath = $ incoming -> getIncomingPath ( ) ; if ( ! $ incomingFilesystem -> has ( $ incomingPath . '/' . $ filename ) ) { return self :: E_FILE_INVALID ; } if ( $ fr instanceof FileEntity ) { $ destinationStorageLocation = $ fr -> getFileStorageLocationObject ( ) ; } else { $ destinationStorageLocation = $ this -> app -> make ( StorageLocationFactory :: class ) -> fetchDefault ( ) ; } $ destinationFilesystem = $ destinationStorageLocation -> getFileSystemObject ( ) ; $ prefix = $ this -> generatePrefix ( ) ; $ fi = $ this -> app -> make ( 'helper/file' ) ; $ sanitizedFilename = $ fi -> sanitize ( $ filename ) ; $ cf = $ this -> app -> make ( 'helper/concrete/file' ) ; $ destinationPath = $ cf -> prefix ( $ prefix , $ sanitizedFilename ) ; try { $ stream = $ incomingFilesystem -> readStream ( $ incomingPath . '/' . $ filename ) ; } catch ( Exception $ x ) { $ stream = false ; } if ( $ stream === false ) { return self :: E_FILE_INVALID ; } try { $ wrote = $ destinationFilesystem -> writeStream ( $ destinationPath , $ stream ) ; } catch ( Exception $ x ) { $ wrote = false ; } @ fclose ( $ stream ) ; if ( $ wrote === false ) { return self :: E_FILE_UNABLE_TO_STORE ; } if ( ! ( $ fr instanceof FileEntity ) ) { $ fv = File :: add ( $ sanitizedFilename , $ prefix , [ 'fvTitle' => $ filename ] , $ destinationStorageLocation , $ fr ) ; $ fv -> refreshAttributes ( $ this -> rescanThumbnailsOnImport ) ; foreach ( $ this -> importProcessors as $ processor ) { if ( $ processor -> shouldProcess ( $ fv ) ) { $ processor -> process ( $ fv ) ; } } } else { $ fv = $ fr -> getVersionToModify ( true ) ; $ fv -> updateFile ( $ sanitizedFilename , $ prefix ) ; $ fv -> refreshAttributes ( $ this -> rescanThumbnailsOnImport ) ; } return $ fv ; }
Import a file in the default file storage location s incoming directory .
10,502
public function importUploadedFile ( UploadedFile $ uploadedFile = null , $ fr = false ) { if ( $ uploadedFile === null ) { $ result = self :: E_PHP_NO_FILE ; } elseif ( ! $ uploadedFile -> isValid ( ) ) { $ result = $ uploadedFile -> getError ( ) ; } else { $ result = $ this -> import ( $ uploadedFile -> getPathname ( ) , $ uploadedFile -> getClientOriginalName ( ) , $ fr ) ; } return $ result ; }
Import a file received via a POST request to the default file storage location .
10,503
protected function getConfiguredFormat ( ) { $ format = $ this -> config -> get ( 'concrete.misc.default_thumbnail_format' ) ; if ( $ format === static :: FORMAT_AUTO || $ this -> bitmapFormat -> isFormatValid ( $ format ) ) { $ result = $ format ; } elseif ( $ format === 'jpg' ) { $ result = BitmapFormat :: FORMAT_JPEG ; } else { $ result = static :: FORMAT_AUTO ; } return $ result ; }
Get the configured format .
10,504
public function define ( $ extension , $ name , $ type , $ customImporter = '' , $ inlineFileViewer = '' , $ editor = '' , $ pkgHandle = '' ) { $ ext = explode ( ',' , $ extension ) ; foreach ( $ ext as $ e ) { $ this -> types [ strtolower ( $ e ) ] = ( new FileType ( ) ) -> setName ( $ name ) -> setExtension ( $ e ) -> setCustomImporter ( $ customImporter ) -> setEditor ( $ editor ) -> setGenericType ( $ type ) -> setView ( $ inlineFileViewer ) -> setPackageHandle ( $ pkgHandle ) ; } }
Register a file type .
10,505
public function defineMultiple ( array $ types ) { foreach ( $ types as $ type_name => $ type_settings ) { array_splice ( $ type_settings , 1 , 0 , $ type_name ) ; call_user_func_array ( [ $ this , 'define' ] , $ type_settings ) ; } }
Register multiple file types .
10,506
public static function getType ( $ ext ) { $ ftl = static :: getInstance ( ) ; if ( strpos ( $ ext , '.' ) !== false ) { $ app = Application :: getFacadeApplication ( ) ; $ h = $ app -> make ( 'helper/file' ) ; $ ext = $ h -> getExtension ( $ ext ) ; } $ ext = strtolower ( $ ext ) ; if ( isset ( $ ftl -> types [ $ ext ] ) ) { return $ ftl -> types [ $ ext ] ; } else { $ ft = new FileType ( ) ; return $ ft ; } }
Can take an extension or a filename Returns any registered information we have for the particular file type based on its registration .
10,507
public function getHelperObjects ( ) { $ helpers = [ ] ; foreach ( $ this -> helpers as $ handle ) { $ h = Core :: make ( 'helper/' . $ handle ) ; $ helpers [ ( str_replace ( '/' , '_' , $ handle ) ) ] = $ h ; } return $ helpers ; }
Get the the helpers that will be be automatically sent to Views as variables . Array keys are the variable names array values are the helper instances .
10,508
private function getStack ( ) { $ processed = [ ] ; foreach ( $ this -> middlewareGenerator ( ) as $ middleware ) { $ processed [ ] = $ middleware ; } $ middleware = array_reverse ( $ processed ) ; $ stack = array_reduce ( $ middleware , $ this -> getZipper ( ) , $ this -> dispatcher ) ; return $ stack ; }
Reduce middleware into a stack of functions that each call the next
10,509
private function getZipper ( ) { $ app = $ this -> app ; return function ( $ last , MiddlewareInterface $ middleware ) use ( $ app ) { return $ app -> make ( DelegateInterface :: class , [ $ middleware , $ last ] ) ; } ; }
Get the function used to zip up the middleware This function runs as part of the array_reduce routine and reduces the list of middlewares into a single delegate
10,510
private function middlewareGenerator ( ) { $ middlewares = $ this -> middleware ; ksort ( $ middlewares ) ; foreach ( $ middlewares as $ priorityGroup ) { foreach ( $ priorityGroup as $ middleware ) { yield $ middleware ; } } }
Get a generator that converts the stored priority array into a sorted flat list
10,511
public function setActiveContext ( $ context ) { $ oldLocale = isset ( $ this -> activeContext ) ? $ this -> contextLocales [ $ this -> activeContext ] : null ; $ this -> activeContext = $ context ; if ( ! isset ( $ this -> contextLocales [ $ context ] ) ) { $ this -> setContextLocale ( $ context , static :: BASE_LOCALE ) ; } $ newLocale = $ this -> contextLocales [ $ context ] ; if ( $ newLocale !== $ oldLocale ) { $ this -> currentLocaleChanged ( $ newLocale ) ; } }
Sets the active translation context .
10,512
public function pushActiveContext ( $ newContext ) { if ( $ this -> activeContext !== null ) { $ this -> activeContextQueue [ ] = $ this -> activeContext ; } $ this -> setActiveContext ( $ newContext ) ; }
Change the active translation context but remember the previous one . Useful when temporarily setting the translation context to something else than the original .
10,513
public function popActiveContext ( ) { if ( ! empty ( $ this -> activeContextQueue ) ) { $ oldContext = array_pop ( $ this -> activeContextQueue ) ; $ this -> setActiveContext ( $ oldContext ) ; } }
Restore the context that was active before calling pushActiveContext .
10,514
public function withContext ( $ context , callable $ callback ) { $ this -> pushActiveContext ( $ context ) ; try { return $ callback ( ) ; } finally { try { $ this -> popActiveContext ( ) ; } catch ( Exception $ x ) { } catch ( Throwable $ x ) { } } }
Execute a function using a specific localization context .
10,515
public function getTranslatorAdapter ( $ context ) { if ( ! isset ( $ this -> contextLocales [ $ context ] ) ) { throw new Exception ( sprintf ( 'Context locale has not been set for context: %s' , $ context ) ) ; } $ locale = $ this -> contextLocales [ $ context ] ; return $ this -> getTranslatorAdapterRepository ( ) -> getTranslatorAdapter ( $ context , $ locale ) ; }
Gets the translator adapter object for the given context from the translator adapter repository .
10,516
public function setContextLocale ( $ context , $ locale ) { if ( isset ( $ this -> contextLocales [ $ context ] ) && $ this -> contextLocales [ $ context ] == $ locale ) { return ; } $ this -> contextLocales [ $ context ] = $ locale ; if ( $ context === $ this -> activeContext ) { $ this -> currentLocaleChanged ( $ locale ) ; } }
Sets the context locale for the given context as the given locale .
10,517
public function getContextLocale ( $ context ) { return isset ( $ this -> contextLocales [ $ context ] ) ? $ this -> contextLocales [ $ context ] : null ; }
Gets the context locale for the given context .
10,518
public function removeLoadedTranslatorAdapters ( ) { foreach ( $ this -> contextLocales as $ context => $ locale ) { $ this -> getTranslatorAdapterRepository ( ) -> removeTranslatorAdaptersWithHandle ( $ context ) ; } }
Removes all the loaded translator adapters from the translator adapter repository .
10,519
public function getActiveTranslateObject ( ) { $ adapter = $ this -> getTranslatorAdapter ( $ this -> getActiveContext ( ) ) ; if ( is_object ( $ adapter ) ) { return $ adapter -> getTranslator ( ) ; } return null ; }
Gets the translator object for the active context .
10,520
public static function getAvailableInterfaceLanguages ( ) { $ languages = [ ] ; $ fh = Core :: make ( 'helper/file' ) ; if ( file_exists ( DIR_LANGUAGES ) ) { $ contents = $ fh -> getDirectoryContents ( DIR_LANGUAGES ) ; foreach ( $ contents as $ con ) { if ( is_dir ( DIR_LANGUAGES . '/' . $ con ) && file_exists ( DIR_LANGUAGES . '/' . $ con . '/LC_MESSAGES/messages.mo' ) ) { $ languages [ ] = $ con ; } } } if ( file_exists ( DIR_LANGUAGES_CORE ) ) { $ contents = $ fh -> getDirectoryContents ( DIR_LANGUAGES_CORE ) ; foreach ( $ contents as $ con ) { if ( is_dir ( DIR_LANGUAGES_CORE . '/' . $ con ) && file_exists ( DIR_LANGUAGES_CORE . '/' . $ con . '/LC_MESSAGES/messages.mo' ) && ( ! in_array ( $ con , $ languages ) ) ) { $ languages [ ] = $ con ; } } } return $ languages ; }
Gets a list of the available site interface languages . Returns an array that where each item is a locale in format xx_XX .
10,521
public static function clearCache ( ) { $ app = Facade :: getFacadeApplication ( ) ; $ app -> make ( 'cache/expensive' ) -> getItem ( 'zend' ) -> clear ( ) ; $ loc = static :: getInstance ( ) ; $ loc -> removeLoadedTranslatorAdapters ( ) ; }
Clear the translations cache .
10,522
protected function currentLocaleChanged ( $ locale ) { PunicData :: setDefaultLocale ( $ locale ) ; $ app = Facade :: getFacadeApplication ( ) ; if ( $ app -> bound ( 'director' ) ) { $ event = new \ Symfony \ Component \ EventDispatcher \ GenericEvent ( ) ; $ event -> setArgument ( 'locale' , $ locale ) ; $ app -> make ( 'director' ) -> dispatch ( 'on_locale_load' , $ event ) ; } }
To be called every time the current locale changes .
10,523
public function createSession ( ) { $ config = $ this -> app [ 'config' ] [ 'concrete.session' ] ; $ storage = $ this -> getSessionStorage ( $ config ) ; $ session = $ this -> app -> build ( SymfonySession :: class , [ $ storage ] ) ; $ session -> setName ( array_get ( $ config , 'name' ) ) ; $ this -> app -> make ( \ Concrete \ Core \ Http \ Request :: class ) -> setSession ( $ session ) ; return $ session ; }
Create a new symfony session object This method MUST NOT start the session .
10,524
protected function getDatabaseHandler ( array $ config ) { return $ this -> app -> make ( PdoSessionHandler :: class , [ $ this -> app -> make ( Connection :: class ) -> getWrappedConnection ( ) , [ 'db_table' => 'Sessions' , 'db_id_col' => 'sessionID' , 'db_data_col' => 'sessionValue' , 'db_time_col' => 'sessionTime' , 'db_lifetime_col' => 'sessionLifeTime' , 'lock_mode' => PdoSessionHandler :: LOCK_ADVISORY , ] , ] ) ; }
Create a new database session handler to handle session .
10,525
protected function getMemcachedHandler ( array $ config ) { $ memcached = $ this -> app -> make ( Memcached :: class , [ 'CCM_SESSION' , null , ] ) ; $ servers = array_get ( $ config , 'servers' , [ ] ) ; foreach ( $ this -> newMemcachedServers ( $ memcached , $ servers ) as $ server ) { $ memcached -> addServer ( array_get ( $ server , 'host' ) , array_get ( $ server , 'port' ) , array_get ( $ server , 'weight' ) ) ; } return $ this -> app -> make ( MemcachedSessionHandler :: class , [ $ memcached , [ 'prefix' => array_get ( $ config , 'name' ) ? : 'CCM_SESSION' ] , ] ) ; }
Return a built Memcached session handler .
10,526
private function getSessionStorage ( array $ config ) { $ app = $ this -> app ; if ( $ app -> isRunThroughCommandLineInterface ( ) ) { return $ app -> make ( MockArraySessionStorage :: class ) ; } $ handler = $ this -> getSessionHandler ( $ config ) ; $ storage = $ app -> make ( NativeSessionStorage :: class , [ [ ] , $ handler ] ) ; $ options = array_get ( $ config , 'cookie' , [ ] ) ; $ options [ 'gc_maxlifetime' ] = array_get ( $ config , 'max_lifetime' ) ; if ( array_get ( $ options , 'cookie_path' , false ) === false ) { $ options [ 'cookie_path' ] = $ app [ 'app_relative_path' ] . '/' ; } $ storage -> setOptions ( $ options ) ; return $ app -> make ( Storage \ LoggedStorage :: class , [ $ storage ] ) ; }
Get a session storage object based on configuration .
10,527
private function getSessionHandler ( array $ config ) { $ handler = array_get ( $ config , 'handler' , 'default' ) ; $ method = Str :: camel ( "get_{$handler}_handler" ) ; if ( method_exists ( $ this , $ method ) ) { return $ this -> { $ method } ( $ config ) ; } return $ this -> getSessionHandler ( [ 'handler' => 'default' ] + $ config ) ; }
Get a new session handler .
10,528
private function newMemcachedServers ( Memcached $ memcached , array $ servers ) { $ serverIndex = [ ] ; $ existingServers = $ memcached -> getServerList ( ) ; foreach ( $ existingServers as $ server ) { $ serverIndex [ $ server [ 'host' ] . ':' . $ server [ 'port' ] ] = true ; } foreach ( $ servers as $ configServer ) { $ server = [ 'host' => array_get ( $ configServer , 'host' , '' ) , 'port' => array_get ( $ configServer , 'port' , 11211 ) , 'weight' => array_get ( $ configServer , 'weight' , 0 ) , ] ; if ( ! isset ( $ serverIndex [ $ server [ 'host' ] . ':' . $ server [ 'port' ] ] ) ) { yield $ server ; } } }
Generator for only returning hosts that aren t already added to the memcache instance .
10,529
protected function getRedisHandler ( array $ config ) { $ options = array_get ( $ config , 'redis' , [ ] ) ; $ servers = array_get ( $ options , 'servers' , [ ] ) ; if ( empty ( $ servers ) ) { $ servers = array_get ( $ config , 'servers' , [ ] ) ; } $ redis = $ this -> getRedisInstance ( $ servers ) ; if ( ! empty ( $ options [ 'database' ] ) ) { $ redis -> select ( ( int ) $ options [ 'database' ] ) ; } $ prefix = array_get ( $ options , 'prefix' , 'CCM_SESSION' ) ; return $ this -> app -> make ( RedisSessionHandler :: class , [ $ redis , [ 'prefix' => array_get ( $ config , 'name' ) ? : $ prefix ] ] ) ; }
Return a built Redis session handler .
10,530
private function getRedisInstance ( array $ servers ) { if ( count ( $ servers ) == 1 ) { $ server = $ servers [ 0 ] ; $ redis = $ this -> app -> make ( Redis :: class ) ; if ( isset ( $ server [ 'socket' ] ) && $ server [ 'socket' ] ) { $ redis -> connect ( $ server [ 'socket' ] ) ; } else { $ host = array_get ( $ server , 'host' , '' ) ; $ port = array_get ( $ server , 'port' , 6379 ) ; $ ttl = array_get ( $ server , 'ttl' , 0.5 ) ; $ host = ! empty ( $ host ) ? $ host : array_get ( $ server , 'server' , '127.0.0.1' ) ; $ redis -> connect ( $ host , $ port , $ ttl ) ; } if ( isset ( $ server [ 'password' ] ) ) { $ redis -> auth ( $ server [ 'password' ] ) ; } } else { $ serverArray = [ ] ; $ ttl = 0.5 ; foreach ( $ this -> getRedisServers ( $ servers ) as $ server ) { $ serverString = $ server [ 'server' ] ; if ( isset ( $ server [ 'port' ] ) ) { $ serverString .= ':' . $ server [ 'port' ] ; } if ( ! isset ( $ server [ 'ttl' ] ) ) { $ ttl = $ server [ 'ttl' ] ; } $ serverArray [ ] = $ serverString ; } $ redis = $ this -> app -> make ( RedisArray :: class , [ $ serverArray , [ 'connect_timeout' => $ ttl ] ] ) ; } return $ redis ; }
Decides whether to return a Redis Instance or RedisArray Instance depending on the number of servers passed to it .
10,531
private function getRedisServers ( array $ servers ) { if ( ! empty ( $ servers ) ) { foreach ( $ servers as $ server ) { if ( isset ( $ server [ 'socket' ] ) ) { $ server = [ 'server' => array_get ( $ server , 'socket' , '' ) , 'ttl' => array_get ( $ server , 'ttl' , null ) , ] ; } else { $ host = array_get ( $ server , 'host' , '' ) ; $ host = ! empty ( $ host ) ? : array_get ( $ server , 'server' , '127.0.0.1' ) ; $ server = [ 'server' => $ host , 'port' => array_get ( $ server , 'port' , 11211 ) , 'ttl' => array_get ( $ server , 'ttl' , null ) , ] ; } yield $ server ; } } else { yield [ 'server' => '127.0.0.1' , 'port' => '6379' , 'ttl' => 0.5 ] ; } }
Generator for Redis Array .
10,532
public function serializeUploadFileExtensions ( $ types ) { $ serialized = '' ; $ types = preg_replace ( '{[^a-z0-9]}i' , '' , $ types ) ; foreach ( $ types as $ type ) { $ serialized .= '*.' . $ type . ';' ; } $ serialized = substr ( $ serialized , 0 , strlen ( $ serialized ) - 1 ) ; return $ serialized ; }
Serializes an array of strings into format suitable for multi - uploader .
10,533
public function unSerializeUploadFileExtensions ( $ types ) { $ types = preg_split ( '{;}' , $ types , null , PREG_SPLIT_NO_EMPTY ) ; $ types = preg_replace ( '{[^a-z0-9]}i' , '' , $ types ) ; return $ types ; }
Unserializes an array of strings from format suitable for multi - uploader .
10,534
public function getErrorMessage ( ) { $ app = Application :: getFacadeApplication ( ) ; $ request = $ app -> make ( Request :: class ) ; $ ajax = $ app -> make ( Ajax :: class ) ; if ( $ ajax -> isAjaxRequest ( $ request ) ) { return t ( "Invalid token. Please reload the page and retry." ) ; } else { return t ( "Invalid form token. Please reload this form and submit again." ) ; } }
Get the error message to be shown to the users when a token is not valid .
10,535
public function output ( $ action = '' , $ return = false ) { $ hash = $ this -> generate ( $ action ) ; $ token = '<input type="hidden" name="' . static :: DEFAULT_TOKEN_NAME . '" value="' . $ hash . '" />' ; if ( ! $ return ) { echo $ token ; } else { return $ token ; } }
Create the HTML code of a token .
10,536
public function validate ( $ action = '' , $ token = null ) { $ app = Application :: getFacadeApplication ( ) ; if ( $ token == null ) { $ request = $ app -> make ( Request :: class ) ; $ token = $ request -> request -> get ( static :: DEFAULT_TOKEN_NAME ) ; if ( $ token === null ) { $ token = $ request -> query -> get ( static :: DEFAULT_TOKEN_NAME ) ; } } if ( is_string ( $ token ) ) { $ parts = explode ( ':' , $ token ) ; if ( $ parts [ 0 ] && isset ( $ parts [ 1 ] ) ) { $ time = $ parts [ 0 ] ; $ hash = $ parts [ 1 ] ; $ compHash = $ this -> generate ( $ action , $ time ) ; $ now = time ( ) ; if ( substr ( $ compHash , strpos ( $ compHash , ':' ) + 1 ) == $ hash ) { $ diff = $ now - $ time ; return $ diff <= static :: VALID_HASH_TIME_THRESHOLD ; } else { $ logger = $ app -> make ( 'log/factory' ) -> createLogger ( Channels :: CHANNEL_SECURITY ) ; $ u = new User ( ) ; $ logger -> debug ( t ( 'Validation token did not match' ) , [ 'uID' => $ u -> getUserID ( ) , 'action' => $ action , 'time' => $ time , ] ) ; } } } return false ; }
Validate a token against a given action .
10,537
private function parseDouble ( $ data ) { if ( ! isset ( $ data [ 7 ] ) ) { throw new UnexpectedValueException ( ) ; } $ unpacked = unpack ( 'E' , $ data ) ; return array_shift ( $ unpacked ) ; }
IEEE 754 .
10,538
public function canRead ( ) { $ c = Page :: getByPath ( '/dashboard' , 'ACTIVE' ) ; if ( $ c && ! $ c -> isError ( ) ) { $ cp = new Permissions ( $ c ) ; return $ cp -> canViewPage ( ) ; } }
Checks to see if a user has access to the C5 dashboard .
10,539
public function getSiteCanonicalUrl ( ) { $ site = $ this -> getPageListGenerator ( ) -> getSite ( ) ; if ( $ site === null ) { $ result = '' ; } else { $ result = ( string ) $ site -> getConfigRepository ( ) -> get ( 'seo.canonical_url' ) ; } return $ result ; }
Get the currently configured canonical URL of the site .
10,540
protected function withCustomCanonicalUrl ( callable $ run ) { $ customCanonicalUrl = $ this -> getCustomSiteCanonicalUrl ( ) ; if ( $ customCanonicalUrl !== '' ) { $ siteConfig = $ this -> getPageListGenerator ( ) -> getSite ( ) -> getConfigRepository ( ) ; $ originalSiteCanonicalUrl = $ siteConfig -> get ( 'seo.canonical_url' ) ; $ siteConfig -> set ( 'seo.canonical_url' , $ customCanonicalUrl ) ; } try { return $ run ( ) ; } finally { if ( $ customCanonicalUrl !== '' ) { $ siteConfig -> set ( 'seo.canonical_url' , $ originalSiteCanonicalUrl ) ; } } }
Don t use with generators!
10,541
public function file ( $ inputID , $ inputName , $ chooseText , $ preselectedFile = null , $ args = [ ] ) { $ app = Application :: getFacadeApplication ( ) ; $ view = View :: getInstance ( ) ; $ request = $ app -> make ( Request :: class ) ; $ vh = $ app -> make ( 'helper/validation/numbers' ) ; $ view -> requireAsset ( 'core/file-manager' ) ; $ fileSelectorArguments = [ 'inputName' => ( string ) $ inputName , 'fID' => null , 'filters' => [ ] , ] ; if ( $ vh -> integer ( $ request -> request -> get ( $ inputName ) ) ) { $ file = $ app -> make ( EntityManagerInterface :: class ) -> find ( FileEntity :: class , $ request -> request -> get ( $ inputName ) ) ; if ( $ file !== null ) { $ fileSelectorArguments [ 'fID' ] = $ file -> getFileID ( ) ; } } elseif ( $ vh -> integer ( $ preselectedFile ) ) { $ fileSelectorArguments [ 'fID' ] = ( int ) $ preselectedFile ; } elseif ( is_object ( $ preselectedFile ) ) { $ fileSelectorArguments [ 'fID' ] = ( int ) $ preselectedFile -> getFileID ( ) ; } if ( $ fileSelectorArguments [ 'fID' ] === null && ( string ) $ chooseText !== '' ) { $ fileSelectorArguments [ 'chooseText' ] = ( string ) $ chooseText ; } if ( isset ( $ args [ 'filters' ] ) && is_array ( $ args [ 'filters' ] ) ) { $ fileSelectorArguments [ 'filters' ] = $ args [ 'filters' ] ; } $ fileSelectorArgumentsJson = json_encode ( $ fileSelectorArguments ) ; $ html = <<<EOL<div class="ccm-file-selector" data-file-selector="{$inputID}"></div><script type="text/javascript">$(function() { $('[data-file-selector="{$inputID}"]').concreteFileSelector({$fileSelectorArgumentsJson});});</script>EOL ; return $ html ; }
Sets up a form field to let users pick a file .
10,542
public function image ( $ inputID , $ inputName , $ chooseText , $ preselectedFile = null , $ args = [ ] ) { return $ this -> fileOfType ( FileType :: T_IMAGE , $ inputID , $ inputName , $ chooseText , $ preselectedFile , $ args ) ; }
Sets up a form field to let users pick an image file .
10,543
public function video ( $ inputID , $ inputName , $ chooseText , $ preselectedFile = null , $ args = [ ] ) { return $ this -> fileOfType ( FileType :: T_VIDEO , $ inputID , $ inputName , $ chooseText , $ preselectedFile , $ args ) ; }
Sets up a form field to let users pick a video file .
10,544
public function text ( $ inputID , $ inputName , $ chooseText , $ preselectedFile = null , $ args = [ ] ) { return $ this -> fileOfType ( FileType :: T_TEXT , $ inputID , $ inputName , $ chooseText , $ preselectedFile , $ args ) ; }
Sets up a form field to let users pick a text file .
10,545
public function audio ( $ inputID , $ inputName , $ chooseText , $ preselectedFile = null , $ args = [ ] ) { return $ this -> fileOfType ( FileType :: T_AUDIO , $ inputID , $ inputName , $ chooseText , $ preselectedFile , $ args ) ; }
Sets up a form field to let users pick an audio file .
10,546
public function doc ( $ inputID , $ inputName , $ chooseText , $ preselectedFile = null , $ args = [ ] ) { return $ this -> fileOfType ( FileType :: T_DOCUMENT , $ inputID , $ inputName , $ chooseText , $ preselectedFile , $ args ) ; }
Sets up a form field to let users pick a document file .
10,547
public function app ( $ inputID , $ inputName , $ chooseText , $ preselectedFile = null , $ args = [ ] ) { return $ this -> fileOfType ( FileType :: T_APPLICATION , $ inputID , $ inputName , $ chooseText , $ preselectedFile , $ args ) ; }
Sets up a form field to let users pick a application file .
10,548
private function fileOfType ( $ type , $ inputID , $ inputName , $ chooseText , $ preselectedFile = null , $ args = [ ] ) { if ( ! is_array ( $ args ) ) { $ args = [ ] ; } if ( ! isset ( $ args [ 'filters' ] ) || ! is_array ( $ args [ 'filters' ] ) ) { $ args [ 'filters' ] = [ ] ; } $ args [ 'filters' ] = array_merge ( [ [ 'field' => 'type' , 'type' => ( int ) $ type , ] , ] , $ args [ 'filters' ] ) ; return $ this -> file ( $ inputID , $ inputName , $ chooseText , $ preselectedFile , $ args ) ; }
Sets up a form field to let users pick a file of a specific type .
10,549
public function getNodeByDisplayPath ( $ path ) { $ root = $ this -> getRootTreeNodeObject ( ) ; if ( $ path == '/' || ! $ path ) { return $ root ; } $ computedPath = '' ; $ tree = $ this ; $ walk = function ( $ node , $ computedPath ) use ( & $ walk , & $ tree , & $ path ) { $ node -> populateDirectChildrenOnly ( ) ; if ( $ node -> getTreeNodeID ( ) != $ tree -> getRootTreeNodeID ( ) ) { $ name = $ node -> getTreeNodeName ( ) ; $ computedPath .= '/' . $ name ; } if ( strcasecmp ( $ computedPath , $ path ) == 0 ) { return $ node ; } else { $ children = $ node -> getChildNodes ( ) ; foreach ( $ children as $ child ) { $ node = $ walk ( $ child , $ computedPath ) ; if ( $ node !== null ) { return $ node ; } } } return ; } ; $ node = $ walk ( $ root , $ computedPath ) ; return $ node ; }
Iterates through the segments in the path to return the node at the proper display . Mostly used for export and import .
10,550
public static function exportTranslations ( ) { $ translations = new Translations ( ) ; $ loc = Localization :: getInstance ( ) ; $ loc -> pushActiveContext ( Localization :: CONTEXT_SYSTEM ) ; try { $ app = Application :: getFacadeApplication ( ) ; $ db = $ app -> make ( 'database' ) -> connection ( ) ; $ r = $ db -> executeQuery ( 'select treeID from Trees order by treeID asc' ) ; while ( $ row = $ r -> fetch ( ) ) { try { $ tree = static :: getByID ( $ row [ 'treeID' ] ) ; } catch ( Exception $ x ) { $ tree = null ; } if ( isset ( $ tree ) ) { $ treeName = $ tree -> getTreeName ( ) ; if ( is_string ( $ treeName ) && ( $ treeName !== '' ) ) { $ translations -> insert ( 'TreeName' , $ treeName ) ; } $ rootNode = $ tree -> getRootTreeNodeObject ( ) ; if ( isset ( $ rootNode ) ) { $ rootNode -> exportTranslations ( $ translations ) ; } } } } catch ( Exception $ x ) { $ loc -> popActiveContext ( ) ; throw $ x ; } $ loc -> popActiveContext ( ) ; return $ translations ; }
Export all the translations associates to every trees .
10,551
public function getDirectoryContents ( $ dir , $ ignoreFiles = [ ] , $ recursive = false ) { $ aDir = [ ] ; if ( is_dir ( $ dir ) ) { $ handle = opendir ( $ dir ) ; while ( ( $ file = readdir ( $ handle ) ) !== false ) { if ( substr ( $ file , 0 , 1 ) != '.' && ( ! in_array ( $ file , $ ignoreFiles ) ) ) { if ( is_dir ( $ dir . '/' . $ file ) ) { if ( $ recursive ) { $ aDir = array_merge ( $ aDir , $ this -> getDirectoryContents ( $ dir . '/' . $ file , $ ignoreFiles , $ recursive ) ) ; $ file = $ dir . '/' . $ file ; } $ aDir [ ] = preg_replace ( "/\/\//si" , '/' , $ file ) ; } else { if ( $ recursive ) { $ file = $ dir . '/' . $ file ; } $ aDir [ ] = preg_replace ( "/\/\//si" , '/' , $ file ) ; } } } closedir ( $ handle ) ; } return $ aDir ; }
Returns the contents of a directory .
10,552
public function unfilename ( $ filename ) { $ parts = $ this -> splitFilename ( $ filename ) ; $ txt = Core :: make ( 'helper/text' ) ; return $ txt -> unhandle ( $ parts [ 0 ] . $ parts [ 1 ] ) ; }
Removes the extension of a filename uncamelcases it .
10,553
public function copyAll ( $ source , $ target , $ mode = null ) { if ( is_dir ( $ source ) ) { if ( $ mode == null ) { @ mkdir ( $ target , Config :: get ( 'concrete.filesystem.permissions.directory' ) ) ; @ chmod ( $ target , Config :: get ( 'concrete.filesystem.permissions.directory' ) ) ; } else { @ mkdir ( $ target , $ mode ) ; @ chmod ( $ target , $ mode ) ; } $ d = dir ( $ source ) ; while ( false !== ( $ entry = $ d -> read ( ) ) ) { if ( substr ( $ entry , 0 , 1 ) === '.' ) { continue ; } $ Entry = $ source . '/' . $ entry ; if ( is_dir ( $ Entry ) ) { $ this -> copyAll ( $ Entry , $ target . '/' . $ entry , $ mode ) ; continue ; } copy ( $ Entry , $ target . '/' . $ entry ) ; if ( $ mode == null ) { @ chmod ( $ target . '/' . $ entry , $ this -> getCreateFilePermissions ( $ target ) -> file ) ; } else { @ chmod ( $ target . '/' . $ entry , $ mode ) ; } } $ d -> close ( ) ; } else { if ( $ mode == null ) { $ mode = $ this -> getCreateFilePermissions ( dirname ( $ target ) ) -> file ; } copy ( $ source , $ target ) ; chmod ( $ target , $ mode ) ; } }
Recursively copies all items in the source directory or file to the target directory .
10,554
public function removeAll ( $ source , $ inc = false ) { if ( ! is_dir ( $ source ) ) { return false ; } $ iterator = new \ RecursiveIteratorIterator ( new \ RecursiveDirectoryIterator ( $ source , \ FilesystemIterator :: SKIP_DOTS ) , \ RecursiveIteratorIterator :: CHILD_FIRST ) ; foreach ( $ iterator as $ path ) { if ( $ path -> isDir ( ) ) { if ( ! @ rmdir ( $ path -> __toString ( ) ) ) { return false ; } } else { if ( ! @ unlink ( $ path -> __toString ( ) ) ) { return false ; } } } if ( $ inc ) { if ( ! @ rmdir ( $ source ) ) { return false ; } } return true ; }
Removes all files from within a specified directory .
10,555
public function forceDownload ( $ file ) { session_write_close ( ) ; ob_clean ( ) ; header ( 'Content-type: application/octet-stream' ) ; $ filename = basename ( $ file ) ; header ( "Content-Disposition: attachment; filename=\"$filename\"" ) ; header ( 'Content-Length: ' . filesize ( $ file ) ) ; header ( "Pragma: public" ) ; header ( "Expires: 0" ) ; header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" ) ; header ( "Cache-Control: private" , false ) ; header ( "Content-Transfer-Encoding: binary" ) ; header ( "Content-Encoding: plainbinary" ) ; $ buffer = '' ; $ chunk = 1024 * 1024 ; $ handle = fopen ( $ file , 'rb' ) ; if ( $ handle === false ) { return false ; } while ( ! feof ( $ handle ) ) { $ buffer = fread ( $ handle , $ chunk ) ; echo $ buffer ; } fclose ( $ handle ) ; exit ; }
Takes a path to a file and sends it to the browser streaming it and closing the HTTP connection afterwards . Basically a force download method .
10,556
public function getTemporaryDirectory ( ) { $ temp = Config :: get ( 'concrete.filesystem.temp_directory' ) ; if ( $ temp && @ is_dir ( $ temp ) ) { return $ temp ; } if ( ! is_dir ( DIR_FILES_UPLOADED_STANDARD . '/tmp' ) ) { @ mkdir ( DIR_FILES_UPLOADED_STANDARD . '/tmp' , Config :: get ( 'concrete.filesystem.permissions.directory' ) ) ; @ chmod ( DIR_FILES_UPLOADED_STANDARD . '/tmp' , Config :: get ( 'concrete.filesystem.permissions.directory' ) ) ; @ touch ( DIR_FILES_UPLOADED_STANDARD . '/tmp/index.html' ) ; } if ( is_dir ( DIR_FILES_UPLOADED_STANDARD . '/tmp' ) && is_writable ( DIR_FILES_UPLOADED_STANDARD . '/tmp' ) ) { return DIR_FILES_UPLOADED_STANDARD . '/tmp' ; } if ( $ temp = getenv ( 'TMP' ) ) { return str_replace ( DIRECTORY_SEPARATOR , '/' , $ temp ) ; } if ( $ temp = getenv ( 'TEMP' ) ) { return str_replace ( DIRECTORY_SEPARATOR , '/' , $ temp ) ; } if ( $ temp = getenv ( 'TMPDIR' ) ) { return str_replace ( DIRECTORY_SEPARATOR , '/' , $ temp ) ; } $ temp = @ tempnam ( __FILE__ , '' ) ; if ( file_exists ( $ temp ) ) { unlink ( $ temp ) ; return str_replace ( DIRECTORY_SEPARATOR , '/' , dirname ( $ temp ) ) ; } }
Returns the full path to the temporary directory .
10,557
public function sanitize ( $ file ) { $ asciiName = Core :: make ( 'helper/text' ) -> asciify ( $ file ) ; $ asciiName = trim ( preg_replace ( [ "/[\\s]/" , "/[^0-9A-Z_a-z-.]/" ] , [ "_" , "" ] , $ asciiName ) ) ; $ asciiName = trim ( $ asciiName , '_' ) ; if ( ! strlen ( str_replace ( '.' , '' , $ asciiName ) ) ) { $ asciiName = md5 ( $ file ) ; } elseif ( preg_match ( '/^\.\w+$/' , $ asciiName ) ) { $ asciiName = md5 ( $ file ) . $ asciiName ; } return $ asciiName ; }
Cleans up a filename and returns the cleaned up version .
10,558
public function replaceExtension ( $ filename , $ extension ) { $ parts = $ this -> splitFilename ( $ filename ) ; $ newFilename = $ parts [ 0 ] . $ parts [ 1 ] ; if ( is_string ( $ extension ) && ( $ extension !== '' ) ) { $ newFilename .= '.' . $ extension ; } return $ newFilename ; }
Takes a path and replaces the files extension in that path with the specified extension .
10,559
public function isSamePath ( $ path1 , $ path2 ) { $ path1 = str_replace ( DIRECTORY_SEPARATOR , '/' , $ path1 ) ; $ path2 = str_replace ( DIRECTORY_SEPARATOR , '/' , $ path2 ) ; $ checkFile = strtoupper ( __FILE__ ) ; if ( $ checkFile === __FILE__ ) { $ checkFile = strtolower ( __FILE__ ) ; } if ( @ is_file ( $ checkFile ) ) { $ same = ( strcasecmp ( $ path1 , $ path2 ) === 0 ) ? true : false ; } else { $ same = ( $ path1 === $ path2 ) ? true : false ; } return $ same ; }
Checks if two path are the same considering directory separator and OS case sensitivity .
10,560
public function makeExecutable ( $ file , $ who = 'all' ) { if ( ! is_file ( $ file ) ) { throw new Exception ( t ( 'File %s could not be found.' , $ file ) ) ; } $ perms = @ fileperms ( $ file ) ; if ( $ perms === false ) { throw new Exception ( t ( 'Unable to retrieve the permissions of the file %s' , $ file ) ) ; } $ currentMode = $ perms & 0777 ; switch ( $ who ) { case 'user' : $ newMode = $ currentMode | ( 1 << 0 ) ; break ; case 'group' : $ newMode = $ currentMode | ( 1 << 3 ) ; break ; case 'all' : $ newMode = $ currentMode | ( 1 << 6 ) ; break ; default : throw new Exception ( t ( 'Bad parameter: %s' , '$who' ) ) ; } if ( $ currentMode !== $ newMode ) { if ( @ chmod ( $ file , $ newMode ) === false ) { throw new Exception ( t ( 'Unable to set the permissions of the file %s' , $ file ) ) ; } } }
Try to set the executable bit of a file .
10,561
protected function saveFromRequest ( Key $ key , Request $ request ) { $ key -> setAttributeKeyDisplayedOnProfile ( ( string ) $ request -> request -> get ( 'uakProfileDisplay' ) == 1 ) ; $ key -> setAttributeKeyEditableOnProfile ( ( string ) $ request -> request -> get ( 'uakProfileEdit' ) == 1 ) ; $ key -> setAttributeKeyRequiredOnProfile ( ( string ) $ request -> request -> get ( 'uakProfileEditRequired' ) == 1 ) ; $ key -> setAttributeKeyEditableOnRegister ( ( string ) $ request -> request -> get ( 'uakRegisterEdit' ) == 1 ) ; $ key -> setAttributeKeyRequiredOnRegister ( ( string ) $ request -> request -> get ( 'uakRegisterEditRequired' ) == 1 ) ; $ key -> setAttributeKeyDisplayedOnMemberList ( ( string ) $ request -> request -> get ( 'uakMemberListDisplay' ) == 1 ) ; $ this -> entityManager -> flush ( ) ; return $ key ; }
Update the user attribute key with the data received from POST .
10,562
public function get ( $ name , array $ additionalConfig = [ ] ) { $ adapter = new DatabaseQueueAdapter ( [ 'connection' => $ this -> connection , ] ) ; $ config = array_merge ( [ 'name' => $ name , ] , $ additionalConfig ) ; return new ZendQueue ( $ adapter , $ config ) ; }
Get a queue by name .
10,563
private function getWriter ( ) { return $ this -> app -> make ( PageActivityExporter :: class , [ 'writer' => $ this -> app -> make ( WriterFactory :: class ) -> createFromPath ( 'php://output' , 'w' ) , ] ) ; }
Get the writer that will create the CSV .
10,564
private function getVersionList ( ) { $ dt = $ this -> app -> make ( 'helper/form/date_time' ) ; $ startDate = $ dt -> translate ( 'startDate' , null , true ) ; $ endDate = $ dt -> translate ( 'endDate' , null , true ) ; $ versionList = new GlobalVersionList ( ) ; $ versionList -> sortByDateApprovedDesc ( ) ; if ( $ startDate !== null ) { $ versionList -> filterByApprovedAfter ( $ startDate ) ; } if ( $ endDate !== null ) { $ versionList -> filterByApprovedBefore ( $ endDate ) ; } return $ versionList ; }
Get the item list object .
10,565
public function isActive ( & $ c ) { if ( $ c ) { $ cID = ( $ c -> getCollectionPointerID ( ) > 0 ) ? $ c -> getCollectionPointerOriginalID ( ) : $ c -> getCollectionID ( ) ; return $ cID == $ this -> cID ; } }
Determines whether this nav item is the current page the user is on .
10,566
public function getTarget ( ) { if ( $ this -> cPointerExternalLink != '' ) { if ( $ this -> cPointerExternalLinkNewWindow ) { return '_blank' ; } } $ _c = $ this -> getCollectionObject ( ) ; if ( is_object ( $ _c ) ) { return $ _c -> getAttribute ( 'nav_target' ) ; } return '' ; }
Returns a target for the nav item .
10,567
public function getURL ( ) { if ( $ this -> cPointerExternalLink != '' ) { $ link = $ this -> cPointerExternalLink ; } elseif ( $ this -> cPath ) { $ link = $ this -> cPath ; } elseif ( $ this -> cID == Page :: getHomePageID ( ) ) { $ link = DIR_REL . '/' ; } else { $ link = DIR_REL . '/' . DISPATCHER_FILENAME . '?cID=' . $ this -> cID ; } return $ link ; }
Gets a URL that will take the user to this particular page . Checks against concrete . seo . url_rewriting the page s path etc ..
10,568
public function getPath ( Version $ file_version , ThumbnailVersion $ thumbnail ) { $ file = $ file_version -> getFile ( ) ; $ format = $ this -> formatService -> getFormatForFile ( $ file_version ) ; $ file_id = $ file -> getFileID ( ) ; $ storage_location = $ file -> getFileStorageLocationObject ( ) ; $ configuration = $ storage_location -> getConfigurationObject ( ) ; $ version_id = $ file_version -> getFileVersionID ( ) ; $ storage_location_id = $ storage_location -> getID ( ) ; $ thumbnail_handle = $ thumbnail -> getHandle ( ) ; $ defer = $ configuration instanceof DeferredConfigurationInterface ; $ path = $ this -> getStoredThumbnailPath ( $ file_id , $ version_id , $ storage_location_id , $ thumbnail_handle , $ format ) ; if ( ! $ path ) { $ path = $ this -> determineThumbnailPath ( $ file_version , $ thumbnail , $ storage_location , $ configuration , $ format ) ; if ( $ path ) { $ this -> storeThumbnailPath ( $ path , $ file_id , $ version_id , $ storage_location_id , $ thumbnail_handle , $ format , ! $ defer ) ; } } $ realPath = $ this -> getBuiltThumbnailPath ( $ path , $ file_version , $ thumbnail , $ storage_location , $ configuration , $ format ) ; if ( $ path == $ realPath && $ defer ) { try { $ realPath = $ this -> getPathFromConfiguration ( $ realPath , $ configuration ) ; } catch ( \ InvalidArgumentException $ e ) { } } return $ realPath ; }
Get the path for a file version
10,569
protected function getStoredThumbnailPath ( $ file_id , $ version_id , $ storage_location_id , $ thumbnail_handle , $ format ) { $ builder = $ this -> connection -> createQueryBuilder ( ) ; $ query = $ builder -> select ( 'path' ) -> from ( 'FileImageThumbnailPaths' , 'p' ) -> where ( 'p.fileID = :file' ) -> andWhere ( 'p.fileVersionID = :version' ) -> andWhere ( 'p.storageLocationID = :storage' ) -> andWhere ( 'p.thumbnailTypeHandle = :thumbnail' ) -> andWhere ( 'p.thumbnailFormat = :format' ) -> setParameters ( array ( 'file' => $ file_id , 'version' => $ version_id , 'storage' => $ storage_location_id , 'thumbnail' => $ thumbnail_handle , 'format' => $ format , ) ) -> execute ( ) ; if ( $ query -> rowCount ( ) ) { return $ query -> fetchColumn ( ) ; } return null ; }
Get the stored path for a file .
10,570
protected function storeThumbnailPath ( $ path , $ file_id , $ version_id , $ storage_location_id , $ thumbnail_handle , $ format , $ isBuilt = true ) { try { $ this -> connection -> insert ( 'FileImageThumbnailPaths' , array ( 'path' => $ path , 'fileID' => $ file_id , 'fileVersionID' => $ version_id , 'storageLocationID' => $ storage_location_id , 'thumbnailTypeHandle' => $ thumbnail_handle , 'thumbnailFormat' => $ format , 'isBuilt' => $ isBuilt ? 1 : 0 ) ) ; } catch ( InvalidFieldNameException $ e ) { } catch ( UniqueConstraintViolationException $ e ) { } }
Store a path against a storage location for a file version and a thumbnail handle and format
10,571
protected function determineThumbnailPath ( Version $ file_version , ThumbnailVersion $ thumbnail , StorageLocation $ storage , ConfigurationInterface $ configuration , $ format ) { if ( $ thumbnail -> shouldExistFor ( $ file_version -> getAttribute ( 'width' ) , $ file_version -> getAttribute ( 'height' ) , $ file_version -> getFile ( ) ) ) { $ path = $ thumbnail -> getFilePath ( $ file_version , $ format ) ; if ( $ configuration instanceof DeferredConfigurationInterface ) { return $ path ; } return $ configuration -> getRelativePathToFile ( $ path ) ; } }
Determine the path for a file version thumbnail based on the storage location
10,572
protected function getBuiltThumbnailPath ( $ path , Version $ file_version , ThumbnailVersion $ thumbnail , StorageLocation $ storage , ConfigurationInterface $ configuration , $ format ) { return $ path ; }
An access point for overriding how paths are built
10,573
protected function getPathFromConfiguration ( $ path , ConfigurationInterface $ configuration ) { if ( $ configuration -> hasRelativePath ( ) ) { return $ configuration -> getRelativePathToFile ( $ path ) ; } if ( $ configuration -> hasPublicURL ( ) ) { return $ configuration -> getPublicURLToFile ( $ path ) ; } throw new \ InvalidArgumentException ( 'Thumbnail configuration doesn\'t support Paths or URLs' ) ; }
Get the path from a configuration object
10,574
public function canPublishPageTypeBeneathPage ( \ Concrete \ Core \ Page \ Page $ page ) { $ target = $ this -> getPageTypePublishTargetObject ( ) ; if ( is_object ( $ target ) ) { return $ target -> canPublishPageTypeBeneathTarget ( $ this , $ page ) ; } }
Returns true if pages of the current type are allowed beneath the passed parent page .
10,575
public static function deleteByName ( $ arHandle ) { $ db = Loader :: db ( ) ; $ db -> Execute ( 'select cID from Areas where arHandle = ? and arIsGlobal = 1' , [ $ arHandle ] ) ; $ db -> Execute ( 'delete from Areas where arHandle = ? and arIsGlobal = 1' , [ $ arHandle ] ) ; }
Note that this function does not delete the global area s stack . You probably want to call the delete method of the Stack model instead .
10,576
public static function deleteEmptyAreas ( ) { $ app = Application :: getFacadeApplication ( ) ; $ siteService = $ app -> make ( SiteService :: class ) ; $ multilingualSectionIDs = [ ] ; $ sites = $ siteService -> getList ( ) ; foreach ( $ sites as $ site ) { $ multilingualSectionIDs = array_merge ( MultilingualSection :: getIDList ( $ site ) ) ; } $ multilingualSections = [ ] ; foreach ( array_unique ( $ multilingualSectionIDs ) as $ multilingualSectionID ) { $ multilingualSections [ ] = MultilingualSection :: getByID ( $ multilingualSectionID ) ; } $ stackList = new StackList ( ) ; $ stackList -> filterByGlobalAreas ( ) ; $ globalAreaStacks = $ stackList -> getResults ( ) ; foreach ( $ globalAreaStacks as $ stack ) { $ stackAlternatives = [ ] ; if ( $ stack -> isNeutralStack ( ) ) { $ stackAlternatives [ ] = $ stack ; } else { $ stackAlternatives [ ] = $ stack -> getNeutralStack ( ) ; } foreach ( $ multilingualSections as $ multilingualSection ) { $ stackAlternative = $ stackAlternatives [ 0 ] -> getLocalizedStack ( $ multilingualSection ) ; if ( $ stackAlternative !== null ) { $ stackAlternatives [ ] = $ stackAlternative ; } } $ hasBlocks = false ; foreach ( $ stackAlternatives as $ stackAlternative ) { $ versionList = new VersionList ( $ stackAlternative ) ; $ versions = $ versionList -> get ( ) ; foreach ( $ versions as $ version ) { $ pageVersion = Page :: getByID ( $ version -> getCollectionID ( ) , $ version -> getVersionID ( ) ) ; $ totalBlocks = count ( $ pageVersion -> getBlockIDs ( ) ) ; if ( $ totalBlocks > 0 ) { $ hasBlocks = true ; break 2 ; } } } if ( ! $ hasBlocks ) { $ stackAlternatives [ 0 ] -> delete ( ) ; } } }
Searches for global areas without any blocks in it and deletes them . This will have a positive impact on the performance as every global area is rendered for every page .
10,577
protected function detectConsoleEnvironment ( $ environments , array $ args ) { if ( ! is_null ( $ value = $ this -> getEnvironmentArgument ( $ args ) ) ) { return head ( array_slice ( explode ( '=' , $ value ) , 1 ) ) ; } }
Set the application environment from command - line arguments .
10,578
public function filterByStorageLocation ( $ storageLocation ) { if ( $ storageLocation instanceof \ Concrete \ Core \ Entity \ File \ StorageLocation \ StorageLocation ) { $ this -> filterByStorageLocationID ( $ storageLocation -> getID ( ) ) ; } elseif ( ! is_object ( $ storageLocation ) ) { $ this -> filterByStorageLocationID ( $ storageLocation ) ; } else { throw new Exception ( t ( 'Invalid file storage location.' ) ) ; } }
Filter the files by their storage location using a storage location object .
10,579
public function filterByStorageLocationID ( $ fslID ) { $ fslID = ( int ) $ fslID ; $ this -> query -> andWhere ( 'f.fslID = :fslID' ) ; $ this -> query -> setParameter ( 'fslID' , $ fslID ) ; }
Filter the files by their storage location using a storage location id .
10,580
public function filterByTags ( $ tags ) { $ this -> query -> andWhere ( $ this -> query -> expr ( ) -> andX ( $ this -> query -> expr ( ) -> like ( 'fv.fvTags' , ':tags' ) ) ) ; $ this -> query -> setParameter ( 'tags' , '%' . $ tags . '%' ) ; }
Filters by tags only .
10,581
public function getPreconditions ( $ includeWebPreconditions = true ) { $ result = [ ] ; foreach ( $ this -> getAllPreconditions ( ) as $ instance ) { if ( ! $ instance instanceof OptionsPreconditionInterface ) { if ( $ includeWebPreconditions || ! $ instance instanceof WebPreconditionInterface ) { $ result [ ] = $ instance ; } } } return $ result ; }
Get the pre - configuration preconditions .
10,582
public function getOptionsPreconditions ( ) { $ result = [ ] ; foreach ( $ this -> getAllPreconditions ( ) as $ instance ) { if ( $ instance instanceof OptionsPreconditionInterface ) { $ result [ ] = $ instance ; } } return $ result ; }
Get the post - configuration preconditions .
10,583
public function getPreconditionByHandle ( $ handle ) { $ list = $ this -> config -> get ( 'install.preconditions' ) ; if ( ! isset ( $ list [ $ handle ] ) ) { throw new Exception ( sprintf ( 'Unable to find an install precondition with handle %s' , $ handle ) ) ; } if ( ! $ list [ $ handle ] ) { throw new Exception ( sprintf ( 'The precondition with handle %s is disabled' , $ handle ) ) ; } $ className = $ list [ $ handle ] ; $ instance = $ this -> getPreconditionByClassName ( $ className ) ; return $ instance ; }
Get a precondition given its handle .
10,584
public function getPreconditionByClassName ( $ className ) { if ( ! class_exists ( $ className , true ) ) { throw new Exception ( sprintf ( 'The precondition class %s does not exist' , $ className ) ) ; } $ result = $ this -> app -> make ( $ className ) ; if ( ! $ result instanceof PreconditionInterface ) { throw new Exception ( sprintf ( 'The class %1$s should implement the interface %2$s' , $ className , PreconditionInterface :: class ) ) ; } return $ result ; }
Get a precondition given its fully - qualified class name .
10,585
private function getAllPreconditions ( ) { $ result = [ ] ; $ list = $ this -> config -> get ( 'install.preconditions' ) ; foreach ( $ list as $ className ) { if ( $ className ) { $ result [ ] = $ this -> getPreconditionByClassName ( $ className ) ; } } return $ result ; }
Get all the defined preconditions of any kind .
10,586
public function getThemeViewTemplate ( ) { if ( isset ( $ this -> view ) ) { $ templateFromView = $ this -> view -> getViewTemplateFile ( ) ; } if ( isset ( $ this -> themeViewTemplate ) && $ templateFromView == FILENAME_THEMES_VIEW ) { return $ this -> themeViewTemplate ; } if ( ! isset ( $ templateFromView ) ) { $ templateFromView = FILENAME_THEMES_VIEW ; } return $ templateFromView ; }
Returns the wrapper file that holds the content of the view . Usually view . php
10,587
public function getServerTimeZone ( $ fallbackToDefault ) { $ timeZoneId = $ this -> getServerTimeZoneId ( ) ; if ( $ timeZoneId === '' ) { if ( ! $ fallbackToDefault ) { throw new UserMessageException ( t ( 'The server time zone has not been defined.' ) ) ; } $ timeZoneId = @ date_default_timezone_get ( ) ? : 'UTC' ; } try { $ result = new DateTimeZone ( $ timeZoneId ) ; } catch ( Exception $ x ) { $ result = null ; } if ( $ result === null ) { throw new UserMessageException ( t ( 'Invalid server time zone: %s' , $ timeZoneId ) ) ; } return $ result ; }
Get the server time zone instance .
10,588
public function load ( ) { if ( ! $ this -> filesystem -> isFile ( DIR_CONFIG_SITE . '/site_install.php' ) ) { throw new UserMessageException ( t ( 'File %s could not be found.' , DIRNAME_APPLICATION . '/' . DIRNAME_CONFIG . '/site_install.php' ) ) ; } if ( ! $ this -> filesystem -> isFile ( DIR_CONFIG_SITE . '/site_install_user.php' ) ) { throw new UserMessageException ( t ( 'File %s could not be found.' , DIRNAME_APPLICATION . '/' . DIRNAME_CONFIG . '/site_install_user.php' ) ) ; } $ siteInstall = $ this -> filesystem -> getRequire ( DIR_CONFIG_SITE . '/site_install.php' ) ; if ( ! is_array ( $ siteInstall ) ) { throw new UserMessageException ( t ( 'The file %s contains invalid data.' , DIRNAME_APPLICATION . '/' . DIRNAME_CONFIG . '/site_install.php' ) ) ; } $ siteInstallUser = @ $ this -> filesystem -> getRequire ( DIR_CONFIG_SITE . '/site_install_user.php' ) ; if ( is_array ( $ siteInstallUser ) ) { $ siteInstallUser += [ 'startingPointHandle' => '' , 'uiLocaleId' => '' , 'serverTimeZone' => '' , ] ; } else { if ( ! ( defined ( 'INSTALL_USER_EMAIL' ) && defined ( 'INSTALL_USER_PASSWORD_HASH' ) && defined ( 'SITE' ) && defined ( 'SITE_INSTALL_LOCALE' ) ) ) { throw new UserMessageException ( t ( 'The file %s contains invalid data.' , DIRNAME_APPLICATION . '/' . DIRNAME_CONFIG . '/site_install_user.php' ) ) ; } $ siteInstallUser = [ 'userEmail' => INSTALL_USER_EMAIL , 'userPasswordHash' => INSTALL_USER_PASSWORD_HASH , 'startingPointHandle' => defined ( 'INSTALL_STARTING_POINT' ) ? INSTALL_STARTING_POINT : '' , 'siteName' => SITE , 'siteLocaleId' => SITE_INSTALL_LOCALE , 'uiLocaleId' => defined ( 'APP_INSTALL_LANGUAGE' ) ? APP_INSTALL_LANGUAGE : '' , 'serverTimeZone' => defined ( 'INSTALL_TIMEZONE' ) ? INSTALL_TIMEZONE : '' , ] ; } $ this -> setPrivacyPolicyAccepted ( $ siteInstallUser [ 'privacyPolicy' ] ) -> setConfiguration ( $ siteInstall ) -> setUserEmail ( $ siteInstallUser [ 'userEmail' ] ) -> setUserPasswordHash ( $ siteInstallUser [ 'userPasswordHash' ] ) -> setStartingPointHandle ( $ siteInstallUser [ 'startingPointHandle' ] ) -> setSiteName ( $ siteInstallUser [ 'siteName' ] ) -> setSiteLocaleId ( $ siteInstallUser [ 'siteLocaleId' ] ) -> setUiLocaleId ( $ siteInstallUser [ 'uiLocaleId' ] ) -> setServerTimeZoneId ( $ siteInstallUser [ 'serverTimeZone' ] ) ; }
Load the configuration options from file .
10,589
public function save ( ) { $ render = new Renderer ( $ this -> configuration ) ; $ siteInstall = $ render -> render ( ) ; $ render = new Renderer ( [ 'userEmail' => $ this -> getUserEmail ( ) , 'userPasswordHash' => $ this -> getUserPasswordHash ( ) , 'startingPointHandle' => $ this -> getStartingPointHandle ( ) , 'siteName' => $ this -> getSiteName ( ) , 'siteLocaleId' => $ this -> getSiteLocaleId ( ) , 'uiLocaleId' => $ this -> getUiLocaleId ( ) , 'serverTimeZone' => $ this -> getServerTimeZoneId ( ) , 'privacyPolicy' => $ this -> isPrivacyPolicyAccepted ( ) ] ) ; $ siteInstallUser = $ render -> render ( ) ; if ( @ $ this -> filesystem -> put ( DIR_CONFIG_SITE . '/site_install.php' , $ siteInstall ) === false ) { throw new UserMessageException ( t ( 'Failed to write to file %s' , DIRNAME_APPLICATION . '/' . DIRNAME_CONFIG . '/site_install.php' ) ) ; } OpCache :: clear ( DIR_CONFIG_SITE . '/site_install_user.php' ) ; if ( @ $ this -> filesystem -> put ( DIR_CONFIG_SITE . '/site_install_user.php' , $ siteInstallUser ) === false ) { throw new UserMessageException ( t ( 'Failed to write to file %s' , DIRNAME_APPLICATION . '/' . DIRNAME_CONFIG . '/site_install_user.php' ) ) ; } OpCache :: clear ( DIR_CONFIG_SITE . '/site_install_user.php' ) ; }
Save the configuration options to file .
10,590
public function setCustomPageTheme ( PageTheme $ pt ) { $ this -> themeObject = $ pt ; $ this -> themePkgHandle = $ pt -> getPackageHandle ( ) ; }
Called from previewing functions this lets us override the page s theme with one of our own choosing .
10,591
public function add_attribute ( ) { $ allowed = $ this -> assignment -> getAttributesAllowedArray ( ) ; $ ak = CollectionAttributeKey :: getByID ( $ _REQUEST [ 'akID' ] ) ; if ( is_object ( $ ak ) && in_array ( $ ak -> getAttributeKeyID ( ) , $ allowed ) ) { $ obj = $ this -> getAttributeJSONRepresentation ( $ ak , 'add' ) ; $ obj -> pending = true ; $ obj -> assets = array ( ) ; $ ag = ResponseAssetGroup :: get ( ) ; foreach ( $ ag -> getAssetsToOutput ( ) as $ position => $ assets ) { foreach ( $ assets as $ asset ) { if ( is_object ( $ asset ) ) { $ obj -> assets [ $ asset -> getAssetType ( ) ] [ ] = $ asset -> getAssetURL ( ) ; } } } Loader :: helper ( 'ajax' ) -> sendResult ( $ obj ) ; } }
Retrieve attribute HTML to inject into the other view .
10,592
public function insertEntryList ( EntryList $ list ) { $ list = clone $ list ; $ this -> writer -> insertAll ( $ this -> projectList ( $ list ) ) ; }
Insert all data from the passed EntryList
10,593
private function projectList ( EntryList $ list ) { $ headers = array_keys ( iterator_to_array ( $ this -> getHeaders ( $ list -> getEntity ( ) ) ) ) ; $ statement = $ list -> deliverQueryObject ( ) -> execute ( ) ; foreach ( $ statement as $ result ) { if ( $ entry = $ list -> getResult ( $ result ) ) { yield $ this -> orderedEntry ( iterator_to_array ( $ this -> projectEntry ( $ entry ) ) , $ headers ) ; } } }
A generator that takes an EntryList and converts it to CSV rows
10,594
private function projectEntry ( Entry $ entry ) { $ date = $ entry -> getDateCreated ( ) ; if ( $ date ) { yield 'ccm_date_created' => $ this -> dateFormatter -> formatCustom ( \ DateTime :: ATOM , $ date ) ; } else { yield 'ccm_date_created' => null ; } $ attributes = $ entry -> getAttributes ( ) ; foreach ( $ attributes as $ attribute ) { yield $ attribute -> getAttributeKey ( ) -> getAttributeKeyHandle ( ) => $ attribute -> getPlainTextValue ( ) ; } }
Turn an Entry into an array
10,595
public function getAvailablePackages ( $ onlyNotInstalled = true ) { $ dh = $ this -> application -> make ( 'helper/file' ) ; $ packages = $ dh -> getDirectoryContents ( DIR_PACKAGES ) ; if ( $ onlyNotInstalled ) { $ handles = $ this -> getInstalledHandles ( ) ; $ packages = array_diff ( $ packages , $ handles ) ; } if ( count ( $ packages ) > 0 ) { $ packagesTemp = [ ] ; foreach ( $ packages as $ p ) { if ( file_exists ( DIR_PACKAGES . '/' . $ p . '/' . FILENAME_CONTROLLER ) ) { $ pkg = $ this -> getClass ( $ p ) ; if ( ! empty ( $ pkg ) ) { $ packagesTemp [ ] = $ pkg ; } } } $ packages = $ packagesTemp ; } return $ packages ; }
Get the package controllers of the available packages .
10,596
public function getLocalUpgradeablePackages ( ) { $ packages = $ this -> getAvailablePackages ( false ) ; $ upgradeables = [ ] ; foreach ( $ packages as $ p ) { $ entity = $ this -> getByHandle ( $ p -> getPackageHandle ( ) ) ; if ( $ entity ) { if ( version_compare ( $ p -> getPackageVersion ( ) , $ entity -> getPackageVersion ( ) , '>' ) ) { $ p -> pkgCurrentVersion = $ entity -> getPackageVersion ( ) ; $ upgradeables [ ] = $ p ; } } } return $ upgradeables ; }
Get the controllers of packages that have newer versions in the local packages directory than those which are in the Packages table . This means they re ready to be upgraded .
10,597
public function getInstalledHandles ( ) { $ query = 'select p.pkgHandle from \\Concrete\\Core\\Entity\\Package p' ; $ r = $ this -> entityManager -> createQuery ( $ query ) ; $ result = $ r -> getArrayResult ( ) ; $ handles = [ ] ; foreach ( $ result as $ r ) { $ handles [ ] = $ r [ 'pkgHandle' ] ; } return $ handles ; }
Get the handles of all the installed packages .
10,598
public function getRemotelyUpgradeablePackages ( ) { $ packages = $ this -> getInstalledList ( ) ; $ upgradeables = [ ] ; foreach ( $ packages as $ p ) { if ( version_compare ( $ p -> getPackageVersion ( ) , $ p -> getPackageVersionUpdateAvailable ( ) , '<' ) ) { $ upgradeables [ ] = $ p ; } } return $ upgradeables ; }
Get the controllers of the packages that have an upgraded version available in the marketplace .
10,599
public function bootPackageEntityManager ( Package $ p , $ clearCache = false ) { $ configUpdater = new EntityManagerConfigUpdater ( $ this -> entityManager ) ; $ providerFactory = new PackageProviderFactory ( $ this -> application , $ p ) ; $ provider = $ providerFactory -> getEntityManagerProvider ( ) ; $ configUpdater -> addProvider ( $ provider ) ; if ( $ clearCache ) { $ cache = $ this -> entityManager -> getConfiguration ( ) -> getMetadataCacheImpl ( ) ; if ( $ cache ) { $ cache -> flushAll ( ) ; } } }
Initialize the entity manager for a package .