idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
23,700
private function createDeleteForm ( Localidad $ localidad ) { return $ this -> createFormBuilder ( ) -> setAction ( $ this -> generateUrl ( 'localidad_delete' , array ( 'id' => $ localidad -> getId ( ) ) ) ) -> setMethod ( 'DELETE' ) -> getForm ( ) ; }
Creates a form to delete a Localidad entity .
23,701
public function setVars ( $ vars ) { if ( is_array ( $ vars ) && count ( $ vars ) ) { foreach ( $ vars as $ key => $ value ) { $ this -> setVar ( $ key , $ value ) ; } } return $ this ; }
Sets a variable for the view
23,702
public function getVar ( $ key ) { return ( array_key_exists ( $ key , $ this -> vars ) ) ? $ this -> vars [ $ key ] : null ; }
Retrieves a stored variable
23,703
public function get ( $ key ) { return array_key_exists ( $ key , $ this -> vars ) ? $ this -> vars [ $ key ] : null ; }
Retrieve a view variable
23,704
public function output ( ) { if ( $ this -> hasFile ( ) ) { extract ( $ this -> getVars ( ) ) ; ob_start ( ) ; include ( $ this -> getPath ( ) . '/' . $ this -> getFile ( true ) ) ; $ html = ob_get_contents ( ) ; ob_end_clean ( ) ; return $ html ; } else { die ( 'Fatal Error: ' . $ this -> getPath ( ) . '/' . $ this -> getFile ( true ) . ' does not exist.' ) ; } }
Retrieve s the view output
23,705
public function translate ( $ string , $ namespace , $ arguments = array ( ) ) { if ( ! isset ( $ this -> translatedStrings [ $ namespace ] ) || ! is_array ( $ this -> translatedStrings [ $ namespace ] ) ) { $ this -> loadLanguageFileForNamespace ( $ namespace ) ; } if ( ! isset ( $ this -> translatedStrings [ $ namespace ] [ $ string ] ) || $ this -> translatedStrings [ $ namespace ] [ $ string ] == '' ) { return $ this -> replacePlaceholders ( $ string , $ arguments ) ; } return $ this -> replacePlaceholders ( $ this -> translatedStrings [ $ namespace ] [ $ string ] , $ arguments ) ; }
Returns the translated version of the given string . If no translation is available the function will return the given string back .
23,706
protected function replacePlaceholders ( $ string , $ arguments ) { if ( count ( $ arguments ) == 0 ) { return $ string ; } foreach ( $ arguments as $ key => $ value ) { $ string = str_replace ( '%' . $ key . '%' , $ value , $ string ) ; } return $ string ; }
Replaces the placeholders in the string with the correct values
23,707
protected function loadLanguageFileForNamespace ( $ namespace ) { $ loadedLocale = $ this -> request -> getLocale ( ) ; $ content = $ this -> languageFileManager -> loadTranslationFileContent ( $ namespace , $ loadedLocale ) ; if ( $ content === false ) { return false ; } $ lines = explode ( PHP_EOL , $ content ) ; foreach ( $ lines as $ line ) { $ delimiter = strpos ( $ line , ' = ' ) ; if ( $ delimiter === false ) { continue ; } $ pattern = substr ( $ line , 0 , $ delimiter ) ; $ replacement = substr ( $ line , $ delimiter + 3 ) ; if ( ! isset ( $ this -> translatedStrings [ $ namespace ] ) || ! is_array ( $ this -> translatedStrings [ $ namespace ] ) ) { $ this -> translatedStrings [ $ namespace ] = array ( ) ; } $ this -> translatedStrings [ $ namespace ] [ $ pattern ] = $ replacement ; } }
Searches all language files which should be loaded for the requested locale .
23,708
public static function explode ( $ delimiter , $ string , $ limit = null ) { $ array = explode ( $ delimiter , $ string ) ; if ( ! is_null ( $ limit ) ) { $ array = explode ( $ delimiter , $ string , $ limit ) ; } return new static ( $ array ) ; }
Explode a string and return a collection .
23,709
public static function parseMixed ( $ items , $ delimiter = ',' ) { if ( is_string ( $ items ) ) { if ( is_string ( $ delimiter ) ) { $ delimiters = str_split ( $ delimiter ) ; } $ delimiters [ ] = $ delimiter ; $ separator = '|' ; $ items = str_replace ( $ delimiters , $ separator , $ items ) ; $ items = explode ( $ separator , trim ( $ items , $ separator ) ) ; } if ( ! is_array ( $ items ) ) { $ items = [ $ items ] ; } $ items = array_filter ( $ items , function ( $ input ) { $ isBlankString = is_string ( $ input ) && trim ( $ input ) == '' ; $ isNullString = is_null ( $ input ) ; return $ isNullString || $ isBlankString ? false : true ; } ) ; return new static ( $ items ) ; }
Creates a new Collection from a mixed variable . Strings are assumed to be delimiter separated and are converted to arrays .
23,710
public function addEnvironmentReader ( array $ arguments = [ ] ) { $ this -> addDefinition ( 'Environment' , 'Reader' , EnvironmentExtensionReader :: class , EnvironmentExtension :: READER_TAG , array_merge ( [ $ this -> namespace , $ this -> path ] , $ arguments ) ) ; }
Implement extension s own environment reader .
23,711
public function load ( ) { foreach ( $ this -> definitions as $ tag => $ definition ) { $ this -> extendContainer ( $ tag , $ definition ) ; } }
Extend DI container by dependencies .
23,712
private function addDefinition ( $ subNamespace , $ objectType , $ interface , $ tag , array $ arguments = [ ] ) { $ class = sprintf ( $ this -> classPath , $ subNamespace ) . $ subNamespace . $ objectType ; if ( ! class_exists ( $ class ) ) { throw new \ RuntimeException ( sprintf ( 'Class "%s" does not exists!' , $ class ) ) ; } if ( ! in_array ( $ interface , class_implements ( $ class ) ) ) { throw new \ RuntimeException ( sprintf ( 'Class "%s" must implement the "%s" interface!' , $ class , $ interface ) ) ; } $ this -> definitions [ $ tag ] = new Definition ( $ class , $ arguments ) ; }
Add dependency definition for DI container .
23,713
private function extendContainer ( $ tag , Definition $ definition , $ identifier = '' ) { if ( '' !== $ identifier ) { $ identifier .= '.' ; } $ this -> container -> setDefinition ( "$this->configKey.$identifier$tag" , $ definition ) -> addTag ( $ tag ) ; }
Add dependency to DI container .
23,714
public function unserialize ( $ data ) { list ( $ this -> _server , $ this -> _username , $ this -> _password , $ this -> _database , $ this -> _port , ) = unserialize ( $ data ) ; $ this -> _connect ( ) ; }
Function unserialize .
23,715
public function query ( $ query , $ return_set = false , $ buffered = true ) { $ this -> _result = null ; $ query = trim ( $ query ) ; $ this -> _result = @ pg_query ( $ this -> _connection , $ query ) ; if ( ! $ this -> _result ) { $ error_message = @ \ pg_last_error ( $ this -> _connection ) ; throw new ConnectionException ( 'An error occurred while attempting to query the PostGres server: ' . $ error_message ) ; } else { $ num_rows = @ \ pg_num_rows ( $ this -> _result ) ; $ matches = [ ] ; $ match_count = preg_match ( '/^([\w]+)(?:[\W]+|$)/i' , $ query , $ matches ) ; assert ( '$match_count === 1' ) ; $ query_type = strtoupper ( $ matches [ 1 ] ) ; switch ( $ query_type ) { case 'SELECT' : case 'SHOW' : case 'EXPLAIN' : case 'DESCRIBE' : if ( $ return_set && $ num_rows >= 1 ) { return new PostGresResultSet ( $ this -> _result , $ buffered ) ; } elseif ( $ num_rows == 1 ) { return new PostGresResultRow ( $ this -> _result ) ; } elseif ( $ num_rows > 1 ) { return new PostGresResultSet ( $ this -> _result , $ buffered ) ; } else { return false ; } break ; case 'DELETE' : case 'INSERT' : case 'REPLACE' : case 'UPDATE' : return $ this -> getAffectedRows ( ) ; break ; case 'START' : case 'COMMIT' : case 'ROLLBACK' : case 'SET' : return true ; break ; default : return false ; } } }
Send a query to the PostGres server .
23,716
public function renderMetaContent ( $ name , $ content = '' ) { $ view = $ this -> getView ( ) ; $ middle = $ this -> getMiddleLayoutModel ( ) ; $ paragraph = $ middle -> getParagraphModel ( ) ; $ renderList = $ paragraph -> findRenderList ( $ name ) ; if ( empty ( $ renderList ) ) { return $ content ; } $ meta = reset ( $ renderList ) [ 1 ] ; if ( empty ( $ meta ) ) { return $ content ; } $ appService = $ view -> plugin ( 'appService' ) ; $ serviceManager = $ appService ( ) ; $ allowOverride = $ serviceManager -> getAllowOverride ( ) ; if ( ! $ allowOverride ) { $ serviceManager -> setAllowOverride ( true ) ; } $ serviceManager -> setService ( 'RenderedContent' , $ meta ) ; if ( ! $ allowOverride ) { $ serviceManager -> setAllowOverride ( false ) ; } if ( $ meta instanceof LayoutAwareInterface ) { $ view -> plugin ( 'layout' ) -> setMiddleLayout ( $ middle -> findMiddleParagraphLayoutById ( $ meta -> getLayoutId ( ) ) ) ; } return $ view -> render ( 'grid/paragraph/render/paragraph' , array ( 'paragraphRenderList' => $ renderList , 'content' => $ content , ) ) ; }
Set meta - content
23,717
public static function reconstitute ( iterable $ eventRecords ) { $ reflection = new ReflectionClass ( static :: class ) ; $ aggregate = $ reflection -> newInstanceWithoutConstructor ( ) ; $ lastSequence = null ; foreach ( $ eventRecords as $ eventRecord ) { $ lastSequence = $ eventRecord -> sequenceNumber ( ) ; $ event = $ eventRecord -> eventMessage ( ) -> payload ( ) ; $ aggregate -> handleRecursively ( $ event ) ; } $ aggregate -> initializeCommittedVersion ( $ lastSequence ) ; return $ aggregate ; }
Creates instance from an event stream history
23,718
public function build ( ) { $ files = $ this -> filesystem -> listFiles ( $ this -> directory ) ; $ this -> cache -> clear ( ) ; foreach ( $ files as $ file ) { if ( $ file [ 'extension' ] == 'yml' || $ file [ 'extension' ] == 'yaml' ) { $ this -> cache -> put ( $ file [ 'filename' ] , $ this -> yaml -> parse ( $ this -> filesystem -> read ( $ file [ 'path' ] ) ) ) ; } } $ this -> cache -> persist ( ) ; $ this -> updateValues ( ) ; }
Parse the config files and save the values in the cache and in memory
23,719
public function prepareExceptionViewModel ( MvcEvent $ e ) { if ( ! ( $ error = $ e -> getError ( ) ) ) { return ; } $ result = $ e -> getResult ( ) ; if ( $ result instanceof Response ) { return ; } if ( $ error != Application :: ERROR_EXCEPTION ) { return ; } if ( ! $ e -> getRequest ( ) instanceof Request ) { return ; } $ accept = $ e -> getRequest ( ) -> getHeaders ( ) -> get ( 'Accept' ) ; if ( ! ( $ accept && $ accept -> match ( 'application/json' ) ) ) { return ; } if ( ! ( $ exception = $ e -> getParam ( 'exception' ) ) ) { return ; } $ modelData = $ this -> serializeException ( $ exception ) ; $ e -> setResult ( new JsonModel ( $ modelData ) ) ; $ e -> setError ( false ) ; $ response = $ e -> getResponse ( ) ; if ( ! $ response ) { $ response = new HttpResponse ( ) ; $ e -> setResponse ( $ response ) ; } if ( isset ( $ modelData [ 'statusCode' ] ) ) { $ response -> setStatusCode ( $ modelData [ 'statusCode' ] ) ; } else { $ response -> setStatusCode ( 500 ) ; } $ response -> getHeaders ( ) -> addHeaders ( [ $ accept , ContentType :: fromString ( 'Content-type: application/api-problem+json' ) ] ) ; }
Create an exception json view model and set the HTTP status code
23,720
public function removeHost ( $ host ) { $ ips = $ this -> getIp ( $ host ) ; unset ( $ this -> hosts [ $ host ] ) ; foreach ( $ ips as $ ip ) { unset ( $ this -> ips [ $ ip ] [ $ host ] ) ; } }
removes an host .
23,721
public function removeIp ( $ ip ) { $ hosts = $ this -> getHosts ( $ ip ) ; unset ( $ this -> ips [ $ ip ] ) ; foreach ( $ hosts as $ host ) { unset ( $ this -> hosts [ $ host ] ) ; } }
removes an ip and all associated hosts
23,722
public function getContent ( ) { $ this -> processFile ( $ this -> getFile ( ) ) ; $ buffer = array ( '#' , '# Generated by SagePHP HostsFile Component' , '# see https://github.com/SagePHP/' , '#' , '' , ) ; foreach ( $ this -> ips as $ ip => $ hosts ) { $ buffer [ ] = sprintf ( "%s\t%s" , $ ip , implode ( $ hosts , ' ' ) ) ; } return implode ( $ buffer , "\n" ) ; }
Returns the formatted filr contend
23,723
final public function install ( ) { $ this -> files = new Filesystem ( ) ; if ( empty ( $ this -> getCommand ( ) ) ) { throw new InstallPackageException ( 'Could not run install sequence. Reason: Missing Console Output reference.' ) ; } $ this -> prepareInstall ( ) ; $ this -> installConfigs ( ) ; $ this -> installFacades ( ) ; $ this -> installScaffolding ( ) ; $ this -> installViews ( ) ; $ this -> installAssets ( ) ; $ this -> installCustom ( ) ; $ this -> installDatabase ( ) ; $ this -> finishInstall ( ) ; }
Install service provider .
23,724
final protected function runDatabaseMigrationsAndSeeders ( ) { if ( ! empty ( $ this -> migrations ) && $ this -> getCommand ( ) -> confirm ( 'Do you wish to migrate your database?' , true ) ) { try { $ this -> getCommand ( ) -> call ( 'migrate' ) ; } catch ( Exception $ e ) { $ this -> getCommand ( ) -> error ( sprintf ( 'Could not migrate your database. Reason: %s' , $ e -> getMessage ( ) ) ) ; } } $ seeders = [ ] ; foreach ( $ this -> seeders as $ seeder ) { if ( is_dir ( base_path ( $ seeder ) ) ) { continue ; } $ seeders [ ] = $ seeder ; } if ( ! empty ( $ seeders ) && $ this -> getCommand ( ) -> confirm ( 'Do you wish to seed your database?' , true ) ) { load_directory ( $ this -> getInstaller ( ) -> getBasePath ( 'database/seeds/' ) ) ; foreach ( $ seeders as $ seeder ) { try { $ seederFilename = substr ( $ seeder , strrpos ( $ seeder , '/' ) + 1 ) ; $ this -> getCommand ( ) -> call ( 'db:seed' , [ '--class' => substr ( $ seederFilename , 0 , strrpos ( $ seederFilename , '.' ) ) , ] ) ; } catch ( Exception $ e ) { $ this -> getCommand ( ) -> error ( sprintf ( 'Could not seed database. Reason: %s' , $ e -> getMessage ( ) ) ) ; } } } }
Run database migrations and seeders .
23,725
final protected function publishFile ( $ from , $ to ) { $ directoryDestination = dirname ( $ to ) ; if ( ! $ this -> files -> isDirectory ( $ directoryDestination ) ) { $ this -> files -> makeDirectory ( $ directoryDestination , 0755 , true ) ; } $ this -> files -> copy ( $ from , $ to ) ; $ this -> getCommand ( ) -> line ( sprintf ( '<info>Copied %s</info> <comment>[%s]</comment> <info>To</info> <comment>[%s]</comment>' , 'File' , str_replace ( base_path ( ) , '' , realpath ( $ from ) ) , str_replace ( base_path ( ) , '' , realpath ( $ to ) ) ) ) ; }
Publish file to application .
23,726
final protected function publishDirectory ( $ from , $ to ) { $ manager = new MountManager ( [ 'from' => new Flysystem ( new LocalAdapter ( $ from ) ) , 'to' => new Flysystem ( new LocalAdapter ( $ to ) ) , ] ) ; foreach ( $ manager -> listContents ( 'from://' , true ) as $ file ) { if ( $ file [ 'type' ] !== 'file' ) { continue ; } $ manager -> put ( sprintf ( 'to://%s' , $ file [ 'path' ] ) , $ manager -> read ( sprintf ( 'from://%s' , $ file [ 'path' ] ) ) ) ; } $ this -> getCommand ( ) -> line ( sprintf ( '<info>Copied %s</info> <comment>[%s]</comment> <info>To</info> <comment>[%s]</comment>' , 'Directory' , str_replace ( base_path ( ) , '' , realpath ( $ from ) ) , str_replace ( base_path ( ) , '' , realpath ( $ to ) ) ) ) ; }
Publish directory to application .
23,727
public function ini ( $ related , $ model , $ local = null , $ remote = null ) { $ this -> setCurrent ( $ model ) ; $ this -> checkModels ( $ related ) ; if ( $ this -> isOneToOne ( $ related , $ model , $ local , $ remote ) ) { return $ this -> prepare ( $ this -> OneToOne ( $ related , $ model , $ local , $ remote ) ) ; } elseif ( $ this -> isOneToMany ( $ related , $ model , $ local , $ remote ) ) { return $ this -> prepare ( $ this -> OneToMany ( $ related , $ model , $ local , $ remote ) ) ; } }
The belongs to relation .
23,728
protected function setCurrent ( $ model ) { $ this -> currentModel = get_class ( $ model ) ; $ this -> currentTable = $ this -> getTable ( $ model ) ; }
set current model name and data table name .
23,729
protected function oneRelationValue ( $ related , $ model , $ column = null ) { $ table = $ this -> checkModelType ( $ model ) ; return $ model -> { ! is_null ( $ column ) ? $ column : $ this -> idKey ( $ table ) } ; }
get the value of column of the relation .
23,730
protected function checkModelType ( $ model ) { if ( is_string ( $ model ) ) { return $ this -> getTable ( $ model ) ; } elseif ( is_object ( $ model ) ) { return $ this -> getTable ( get_class ( $ model ) ) ; } }
get database table .
23,731
protected function getType ( $ model , $ related , $ local , $ remote ) { $ modelObject = new $ model ( ) ; $ remoteObject = new $ related ( ) ; $ tablemodel = $ this -> getTable ( $ modelObject ) ; $ tableremote = $ this -> getTable ( $ remoteObject ) ; if ( is_null ( $ local ) && is_null ( $ remote ) ) { $ model = $ tablemodel . '_id' ; $ remote = $ tableremote . '_id' ; } else { $ model = $ remote ; } if ( in_array ( strtolower ( $ model ) , $ remoteObject -> _columns ) ) { $ this -> relation = OneToOneRelation ; } if ( in_array ( strtolower ( $ remote ) , $ modelObject -> _columns ) ) { $ this -> relation = OneToManyRelation ; } return $ this -> relation ; }
get the type of relation .
23,732
private function getDictionaryOverrides ( array & $ data ) : array { $ overrides = [ ] ; foreach ( [ 'source_language' , 'target_language' ] as $ key ) { if ( array_key_exists ( $ key , $ data ) ) { $ overrides [ $ key ] = $ data [ $ key ] ; unset ( $ data [ $ key ] ) ; } } return $ overrides ; }
Obtain the overrides for a dictionary .
23,733
private function makeDictionary ( Configuration $ configuration , $ dictionary , array $ overrides , string $ path ) : ExtendedDictionaryDefinition { $ name = $ dictionary ; if ( is_array ( $ dictionary ) ) { if ( ! isset ( $ dictionary [ 'name' ] ) ) { throw new \ InvalidArgumentException ( 'Dictionary "' . $ path . '" information is missing key "name".' ) ; } $ name = $ dictionary [ 'name' ] ; $ overrides = array_merge ( $ overrides , $ dictionary ) ; unset ( $ overrides [ 'name' ] ) ; } return new ExtendedDictionaryDefinition ( $ name , $ configuration , $ overrides ) ; }
Make the passed value a valid dictionary .
23,734
static function rmdir ( $ dir , $ deleteRoot = TRUE , $ stopOnError = TRUE , & $ debug = NULL ) { if ( is_dir ( $ dir ) ) { if ( NULL === $ debug ) $ debug = [ ] ; try { foreach ( glob ( $ dir . '/*' ) as $ file ) { if ( is_dir ( $ file ) ) { self :: rmdir ( $ file , TRUE , $ stopOnError , $ debug ) ; } else { $ debug [ ] = printf ( "File: %s" , Debug :: path ( $ file ) ) ; } unlink ( $ file ) ; } if ( $ deleteRoot ) { $ debug [ ] = printf ( "Dir: %s" , Debug :: path ( $ dir ) ) ; rmdir ( $ dir ) ; } return TRUE ; } catch ( Exception $ e ) { if ( $ stopOnError ) { $ debug [ ] = $ e -> getMessage ( ) ; return FALSE ; } } } return FALSE ; }
Recursive directory delete
23,735
public function set_error ( $ message , $ halt = false ) { if ( $ message instanceof Exception ) { $ message = $ message -> getMessage ( ) ; } $ this -> _errors [ ] = $ message ; log_message ( 'error' , $ message ) ; if ( $ halt ) { show_error ( $ message ) ; } }
Setup error message
23,736
public function getNext ( ) { reset ( $ this -> groups ) ; while ( $ key = key ( $ this -> groups ) ) { $ nextGroup = next ( $ this -> groups ) ; if ( $ this -> groups [ $ key ] === $ this -> group && $ nextGroup ) { return $ nextGroup ; } } return $ this -> group ; }
Get next group
23,737
public function getPrev ( ) { end ( $ this -> groups ) ; while ( $ key = key ( $ this -> groups ) ) { $ prevGroup = prev ( $ this -> groups ) ; if ( $ this -> groups [ $ key ] === $ this -> group && $ prevGroup ) { return $ prevGroup ; } } return $ this -> group ; }
Get prev group
23,738
public static function init ( ) { if ( class_exists ( 'CTFW_Widget' ) ) { return ; } $ pluginDir = untrailingslashit ( plugin_dir_path ( __FILE__ ) ) ; $ pluginURL = untrailingslashit ( plugin_dir_url ( __FILE__ ) ) ; define ( 'CTFW_WIDGETS_INC_DIR' , $ pluginDir . '/includes' ) ; define ( 'CTFW_WIDGETS_CLASS_DIR' , CTFW_WIDGETS_INC_DIR . '/classes' ) ; define ( 'CTFW_WIDGETS_ADMIN_DIR' , CTFW_WIDGETS_INC_DIR . '/admin' ) ; define ( 'CTFW_WIDGETS_WIDGET_TEMPLATE_DIR' , CTFW_WIDGETS_INC_DIR . '/widget-templates' ) ; define ( 'CTFW_WIDGETS_JS_DIR' , CTFW_WIDGETS_INC_DIR . '/js' ) ; define ( 'CTFW_WIDGETS_CSS_DIR' , CTFW_WIDGETS_INC_DIR . '/css' ) ; define ( 'CTFW_WIDGETS_DIR_URL' , $ pluginURL ) ; define ( 'CTFW_WIDGETS_JS_DIR_URL' , $ pluginURL . '/js' ) ; define ( 'CTFW_WIDGETS_CSS_DIR_URL' , $ pluginURL . '/css' ) ; define ( 'CTFW_WIDGETS_VERSION' , 1.0 ) ; add_action ( 'plugins_loaded' , array ( __CLASS__ , 'setup' ) ) ; }
define plugin directory
23,739
public static function splitSql ( $ sql ) { $ start = 0 ; $ open = false ; $ char = '' ; $ end = strlen ( $ sql ) ; $ queries = [ ] ; for ( $ i = 0 ; $ i < $ end ; $ i ++ ) { $ current = substr ( $ sql , $ i , 1 ) ; if ( $ current == '"' || $ current == '\'' ) { $ n = 2 ; while ( substr ( $ sql , $ i - $ n + 1 , 1 ) == '\\' && $ n < $ i ) { $ n ++ ; } if ( $ n % 2 == 0 ) { if ( $ open ) { if ( $ current == $ char ) { $ open = false ; $ char = '' ; } } else { $ open = true ; $ char = $ current ; } } } if ( ( $ current == ';' && ! $ open ) || $ i == $ end - 1 ) { $ queries [ ] = substr ( $ sql , $ start , ( $ i - $ start + 1 ) ) ; $ start = $ i + 1 ; } } return $ queries ; }
Splits a string of multiple queries into an array of individual queries .
23,740
protected function splitData ( $ data , $ sectionNames ) { $ sections = explode ( $ this -> getDataSeparator ( ) , str_replace ( "\n\r" , "\n" , $ data ) , count ( $ sectionNames ) ) ; try { $ parts = array_combine ( $ sectionNames , $ sections ) ; } catch ( \ Exception $ e ) { throw new EntityParseException ; } return $ parts ; }
Split data by the separator
23,741
public function duplicate ( Model $ Model , $ data , $ config = array ( ) ) { $ config = array_merge ( $ this -> settings [ $ Model -> alias ] , $ config ) ; if ( empty ( $ Model -> id ) && empty ( $ data [ $ Model -> alias ] [ $ Model -> primaryKey ] ) ) { throw new Exception ( __d ( 'common' , "Missing primary key for duplicatable '%s' data" , $ Model -> name ) ) ; } $ id = $ Model -> id ? $ Model -> id : $ data [ $ Model -> alias ] [ $ Model -> primaryKey ] ; $ conditions = array ( $ Model -> primaryKey => $ id ) + ( array ) $ this -> settings [ $ Model -> alias ] [ 'scope' ] ; if ( ! empty ( $ this -> settings [ $ Model -> alias ] [ 'scope' ] ) && ! $ Model -> find ( 'count' , compact ( 'conditions' ) ) ) { return false ; } $ duplicateData = array ( $ config [ 'duplicatedKey' ] => $ id , $ config [ 'duplicatedModel' ] => ( ! empty ( $ Model -> plugin ) ? $ Model -> plugin . '.' : '' ) . $ Model -> name ) ; $ DuplicateModel = ClassRegistry :: init ( $ config [ 'model' ] ) ; $ DuplicateModel -> create ( ) ; $ duplicateRecord = $ DuplicateModel -> find ( 'first' , array ( 'conditions' => $ duplicateData , 'recursive' => - 1 ) ) ; if ( ! empty ( $ duplicateRecord ) ) { $ DuplicateModel -> id = $ duplicateRecord [ $ DuplicateModel -> alias ] [ $ DuplicateModel -> primaryKey ] ; } foreach ( ( array ) $ config [ 'mapFields' ] as $ field => $ path ) { $ value = Hash :: extract ( $ data , $ path ) ; $ duplicateData [ $ field ] = array_pop ( $ value ) ; if ( ! empty ( $ duplicateRecord [ $ DuplicateModel -> alias ] [ $ field ] ) && $ duplicateRecord [ $ DuplicateModel -> alias ] [ $ field ] === $ duplicateData [ $ field ] ) { unset ( $ duplicateData [ $ field ] ) ; } } if ( ( empty ( $ duplicateRecord ) || 1 < count ( $ duplicateData ) ) && ( ! empty ( $ DuplicateModel -> id ) || $ DuplicateModel -> create ( $ duplicateData ) ) && ! $ DuplicateModel -> save ( ) ) { return false ; } return true ; }
Clone model s data .
23,742
public static function instance ( $ name = 'default' ) { if ( \ array_key_exists ( $ name , static :: $ instances ) ) { return static :: $ instances [ $ name ] ; } if ( empty ( static :: $ instances ) ) { \ Config :: load ( 'db' , true ) ; } if ( ! ( $ config = \ Config :: get ( 'db.mongo.' . $ name ) ) ) { throw new \ Mongo_DbException ( 'Invalid instance name given.' ) ; } static :: $ instances [ $ name ] = new static ( $ config ) ; return static :: $ instances [ $ name ] ; }
Acts as a Multiton . Will return the requested instance or will create a new one if it does not exist .
23,743
public function apiAction ( Request $ request ) { if ( $ request -> isXmlHttpRequest ( ) or $ request -> headers -> get ( 'Content-Type' ) == 'application/json' ) { $ pathInfo = $ request -> getPathInfo ( ) ; if ( ! $ this -> getApiRequestAllow ( ) -> isAllow ( $ pathInfo ) ) { throw new NotFoundHttpException ( 'No route allow for " ' . $ request -> getMethod ( ) . ' ' . $ pathInfo . '"' ) ; } $ query_string = null ; if ( $ request -> server -> get ( 'QUERY_STRING' ) ) { $ query_string = '?' . $ request -> server -> get ( 'QUERY_STRING' ) ; } $ url_api = $ pathInfo . $ query_string ; $ array = explode ( "/" , $ url_api ) ; unset ( $ array [ 1 ] ) ; $ text = implode ( "/" , $ array ) ; $ url_api = "/api" . $ text ; $ apiUri = trim ( $ url_api , '/' ) ; try { return $ this -> container -> get ( 'antwebes_chateaclient_bundle.http.api_client' ) -> sendRequest ( 'GET' , $ apiUri ) ; } catch ( ClientErrorResponseException $ e ) { $ headersGuzzle = $ e -> getResponse ( ) -> getHeaders ( ) -> toArray ( ) ; $ headersSymfony = array ( ) ; foreach ( $ headersGuzzle as $ key => $ value ) { if ( $ key != 'Transfer-Encoding' && $ value !== 'chunked' ) { $ headersSymfony [ $ key ] = $ value [ 0 ] ; } } return new Response ( $ e -> getResponse ( ) -> getBody ( true ) , $ e -> getResponse ( ) -> getStatusCode ( ) , $ headersSymfony ) ; } } else { throw new NotFoundHttpException ( ) ; } }
Resolve api calls
23,744
public function Confirm ( $ Action , $ LogIDs = '' ) { $ this -> Permission ( 'Garden.Moderation.Manage' ) ; $ this -> Form -> InputPrefix = '' ; $ this -> Form -> IDPrefix = 'Confirm_' ; if ( trim ( $ LogIDs ) ) $ LogIDArray = explode ( ',' , $ LogIDs ) ; else $ LogIDArray = array ( ) ; $ Logs = $ this -> LogModel -> GetIDs ( $ LogIDArray ) ; $ Users = array ( ) ; foreach ( $ Logs as $ Log ) { $ UserID = $ Log [ 'RecordUserID' ] ; if ( ! $ UserID ) continue ; $ Users [ $ UserID ] = array ( 'UserID' => $ UserID ) ; } Gdn :: UserModel ( ) -> JoinUsers ( $ Users , array ( 'UserID' ) ) ; $ this -> SetData ( 'Users' , $ Users ) ; $ this -> SetData ( 'Action' , $ Action ) ; $ this -> SetData ( 'ActionUrl' , Url ( "/log/$Action?logids=" . urlencode ( $ LogIDs ) ) ) ; $ this -> SetData ( 'ItemCount' , count ( $ LogIDArray ) ) ; $ this -> Render ( ) ; }
Confirmation page .
23,745
public function Count ( $ Operation ) { $ this -> Permission ( 'Garden.Moderation.Manage' ) ; if ( $ Operation == 'edits' ) $ Operation = array ( 'edit' , 'delete' ) ; else $ Operation = explode ( ',' , $ Operation ) ; array_map ( 'ucfirst' , $ Operation ) ; $ Count = $ this -> LogModel -> GetCountWhere ( array ( 'Operation' => $ Operation ) ) ; if ( $ Count > 0 ) echo '<span class="Alert">' , $ Count , '</span>' ; }
Count log items .
23,746
public function Delete ( $ LogIDs ) { $ this -> Permission ( 'Garden.Moderation.Manage' ) ; $ this -> LogModel -> Delete ( $ LogIDs ) ; $ this -> Render ( 'Blank' , 'Utility' ) ; }
Delete logs .
23,747
public function DeleteSpam ( $ LogIDs ) { $ this -> Permission ( 'Garden.Moderation.Manage' ) ; if ( ! $ this -> Request -> IsPostBack ( ) ) throw PermissionException ( 'Javascript' ) ; $ LogIDs = explode ( ',' , $ LogIDs ) ; $ UserIDs = $ this -> Form -> GetFormValue ( 'UserID' , array ( ) ) ; if ( ! is_array ( $ UserIDs ) ) $ UserIDs = array ( ) ; if ( ! empty ( $ UserIDs ) ) { $ OtherLogIDs = $ this -> LogModel -> GetWhere ( array ( 'Operation' => 'Spam' , 'RecordUserID' => $ UserIDs ) ) ; $ OtherLogIDs = ConsolidateArrayValuesByKey ( $ OtherLogIDs , 'LogID' ) ; $ LogIDs = array_merge ( $ LogIDs , $ OtherLogIDs ) ; foreach ( $ UserIDs as $ UserID ) { Gdn :: UserModel ( ) -> Ban ( $ UserID , array ( 'Reason' => 'Spam' , 'DeleteContent' => TRUE , 'Log' => TRUE ) ) ; } } $ this -> LogModel -> Delete ( $ LogIDs ) ; $ this -> Render ( 'Blank' , 'Utility' ) ; }
Delete spam and optionally delete the users .
23,748
public function Initialize ( ) { parent :: Initialize ( ) ; Gdn_Theme :: Section ( 'Dashboard' ) ; $ this -> AddJsFile ( 'log.js' ) ; $ this -> AddJsFile ( 'jquery.expander.js' ) ; $ this -> AddJsFile ( 'jquery-ui.js' ) ; $ this -> Form -> InputPrefix = '' ; }
Always triggered first . Add Javascript files .
23,749
public function Moderation ( $ Page = '' ) { $ this -> Permission ( 'Garden.Moderation.Manage' ) ; $ Where = array ( 'Operation' => array ( 'Moderate' , 'Pending' ) ) ; if ( $ CategoryID = Gdn :: Request ( ) -> GetValue ( 'CategoryID' ) ) { $ this -> SetData ( 'ModerationCategoryID' , $ CategoryID ) ; $ Where [ 'CategoryID' ] = $ CategoryID ; } list ( $ Offset , $ Limit ) = OffsetLimit ( $ Page , 10 ) ; $ this -> SetData ( 'Title' , T ( 'Moderation Queue' ) ) ; $ RecordCount = $ this -> LogModel -> GetCountWhere ( $ Where ) ; $ this -> SetData ( 'RecordCount' , $ RecordCount ) ; if ( $ Offset >= $ RecordCount ) $ Offset = $ RecordCount - $ Limit ; $ Log = $ this -> LogModel -> GetWhere ( $ Where , 'LogID' , 'Desc' , $ Offset , $ Limit ) ; $ this -> SetData ( 'Log' , $ Log ) ; if ( $ this -> DeliveryType ( ) == DELIVERY_TYPE_VIEW ) $ this -> View = 'Table' ; $ this -> AddSideMenu ( 'dashboard/log/moderation' ) ; $ this -> Render ( ) ; }
View moderation logs .
23,750
public function Restore ( $ LogIDs ) { $ this -> Permission ( 'Garden.Moderation.Manage' ) ; $ Logs = $ this -> LogModel -> GetIDs ( $ LogIDs ) ; try { foreach ( $ Logs as $ Log ) { $ this -> LogModel -> Restore ( $ Log ) ; } } catch ( Exception $ Ex ) { $ this -> Form -> AddError ( $ Ex -> getMessage ( ) ) ; } $ this -> LogModel -> Recalculate ( ) ; $ this -> Render ( 'Blank' , 'Utility' ) ; }
Restore logs .
23,751
public function Spam ( $ Page = '' ) { $ this -> Permission ( 'Garden.Moderation.Manage' ) ; list ( $ Offset , $ Limit ) = OffsetLimit ( $ Page , 10 ) ; $ this -> SetData ( 'Title' , T ( 'Spam Queue' ) ) ; $ Where = array ( 'Operation' => array ( 'Spam' ) ) ; $ RecordCount = $ this -> LogModel -> GetCountWhere ( $ Where ) ; $ this -> SetData ( 'RecordCount' , $ RecordCount ) ; if ( $ Offset >= $ RecordCount ) $ Offset = $ RecordCount - $ Limit ; $ Log = $ this -> LogModel -> GetWhere ( $ Where , 'LogID' , 'Desc' , $ Offset , $ Limit ) ; $ this -> SetData ( 'Log' , $ Log ) ; if ( $ this -> DeliveryType ( ) == DELIVERY_TYPE_VIEW ) $ this -> View = 'Table' ; $ this -> AddSideMenu ( 'dashboard/log/spam' ) ; $ this -> Render ( ) ; }
View spam logs .
23,752
public static function make ( $ data , string $ reason , ? \ Throwable $ previous = null ) : self { $ message = self :: buildMessage ( $ data , $ reason ) ; return new static ( $ message , $ previous ) ; }
InvalidItemException named constructor .
23,753
public function getTokenName ( $ type ) { if ( ! isset ( $ this -> tokenNames [ $ type ] ) ) { throw new \ RuntimeException ( "Unknown token $type." ) ; } return $ this -> tokenNames [ $ type ] ; }
Get token name
23,754
public function ajouterParcours ( $ params = array ( ) ) { if ( isset ( $ this -> variablesPost [ 'libelleParcours' ] ) && $ this -> variablesPost [ 'libelleParcours' ] != '' && isset ( $ this -> variablesPost [ 'dateAjoutParcours' ] ) && $ this -> variablesPost [ 'dateAjoutParcours' ] != '' ) { $ d = new dateObject ( ) ; $ parcoursActif = '0' ; if ( isset ( $ this -> variablesPost [ 'isActif' ] ) && $ this -> variablesPost [ 'isActif' ] == '1' ) { $ parcoursActif = '1' ; } $ reqInsert = "INSERT INTO parcoursArt (libelleParcours, isActif, dateAjoutParcours,commentaireParcours, idSource ) VALUES (" ; $ reqInsert .= "\"" . mysql_real_escape_string ( $ this -> variablesPost [ 'libelleParcours' ] ) . "\"," ; $ reqInsert .= "'" . $ parcoursActif . "'," ; $ reqInsert .= "'" . $ d -> toBdd ( $ this -> variablesPost [ 'dateAjoutParcours' ] ) . "'," ; $ reqInsert .= "\"" . mysql_real_escape_string ( $ this -> variablesPost [ 'commentaireParcours' ] ) . "\"," ; $ reqInsert .= "'" . $ this -> variablesPost [ 'idSource' ] . "'" ; $ reqInsert .= ")" ; $ resInsert = $ this -> connexionBdd -> requete ( $ reqInsert ) ; } }
Ajouter un parcours
23,755
public function modifierParcours ( $ params = array ( ) ) { if ( isset ( $ this -> variablesPost [ 'idParcours' ] ) && $ this -> variablesPost [ 'idParcours' ] != '' && $ this -> variablesPost [ 'idParcours' ] != '0' && isset ( $ this -> variablesPost [ 'libelleParcours' ] ) && $ this -> variablesPost [ 'libelleParcours' ] != '' && isset ( $ this -> variablesPost [ 'dateAjoutParcours' ] ) && $ this -> variablesPost [ 'dateAjoutParcours' ] != '' ) { $ d = new dateObject ( ) ; $ parcoursActif = '0' ; if ( isset ( $ this -> variablesPost [ 'isActif' ] ) && $ this -> variablesPost [ 'isActif' ] == '1' ) { $ parcoursActif = '1' ; } $ reqUpdate = "UPDATE parcoursArt set dateAjoutParcours='" . $ d -> toBdd ( $ this -> variablesPost [ 'dateAjoutParcours' ] ) . "',isActif='" . $ parcoursActif . "',libelleParcours=\"" . mysql_real_escape_string ( $ this -> variablesPost [ 'libelleParcours' ] ) . "\",commentaireParcours=\"" . mysql_real_escape_string ( $ this -> variablesPost [ 'commentaireParcours' ] ) . "\",idSource='" . $ this -> variablesPost [ 'idSource' ] . "', trace='" . mysql_escape_string ( $ this -> variablesPost [ 'trace' ] ) . "', levels='" . mysql_escape_string ( $ this -> variablesPost [ 'newLevels' ] ) . "' WHERE idParcours='" . $ this -> variablesPost [ 'idParcours' ] . "'" ; $ resUpdate = $ this -> connexionBdd -> requete ( $ reqUpdate ) ; } }
Modifier un parcours
23,756
static public function toArray ( $ args , $ type_of = null ) { if ( is_array ( $ args ) ) { $ failed = array_filter ( $ args , function ( $ e ) use ( $ type_of ) { return ( ! is_object ( $ e ) || ! $ e instanceof $ type_of ) ; } ) ; if ( 0 < count ( $ failed ) ) { throw new \ DomainException ( sprintf ( 'You must provide only objects of class %s.' , $ type_of ) ) ; } } else { if ( ! is_object ( $ args ) || ! $ args instanceof $ type_of ) { throw new \ DomainException ( sprintf ( 'You must provide only objects of class %s.' , $ type_of ) ) ; } $ args = array ( $ args ) ; } return $ args ; }
Returns an array of objects of the same type
23,757
private function manyNestedInThe ( string $ property ) : MapsProperty { if ( null !== $ this -> container && ! class_exists ( $ this -> container ) ) { throw NoSuchClass :: couldNotLoadCollection ( $ this -> container ) ; } return $ this -> addConstraintTo ( HasManyNested :: inPropertyWithDifferentKey ( $ property , $ this -> keyOr ( $ property ) , $ this -> container ( ) , $ this -> hydrator ( ) ) ) ; }
Maps an eagerly loaded collection from a nested data set .
23,758
private function manyProxiesInThe ( string $ property ) : MapsProperty { if ( null === $ this -> loader ) { throw NoLoaderAvailable :: whilstRequiredFor ( $ this -> class ) ; } return $ this -> addConstraintTo ( HasManyProxies :: inPropertyWithDifferentKey ( $ property , $ this -> keyOr ( $ property ) , $ this -> container ( ) , ProxyFactory :: fromThis ( SimpleHydrator :: forThe ( $ this -> class ) , $ this -> loader , $ this -> updaterFactory ( ) ) ) ) ; }
Maps an extra lazily loaded collection as list of proxies .
23,759
private function oneProxyInThe ( string $ property ) : MapsProperty { if ( null === $ this -> loader ) { throw NoLoaderAvailable :: whilstRequiredFor ( $ this -> class ) ; } if ( null === $ this -> container ) { throw NoContainerAvailable :: whilstRequiredFor ( $ this -> class ) ; } try { return HasOneProxy :: inProperty ( $ property , ProxyFactory :: fromThis ( SimpleHydrator :: forThe ( $ this -> container ) , $ this -> loader , new PropertyUpdaterFactory ) ) ; } catch ( CannotInstantiateThis $ problem ) { throw NoSuchClass :: couldNotLoadCollection ( $ this -> container ) ; } }
Maps a lazily loaded collection as a single proxy .
23,760
public static function rgb ( $ r = 255 , $ g = 255 , $ b = 255 ) { static :: validateComp ( 'R' , $ r , 0 , 255 ) ; static :: validateComp ( 'G' , $ g , 0 , 255 ) ; static :: validateComp ( 'B' , $ b , 0 , 255 ) ; return new static ( $ r , $ g , $ b ) ; }
Creates a new Color instance from RGB components ranging from 0 to 255 .
23,761
public static function hex ( $ hex ) { static :: hex2rgb ( $ hex , $ r , $ g , $ b ) ; return static :: rgb ( $ r , $ g , $ b ) ; }
Creates a new Color instance from an RGB hex color code . Both six digit and 3 digit hex codes are supported .
23,762
public static function rand ( $ h = [ 0 , 360 ] , $ s = [ 0 , 1 ] , $ l = [ 0 , 1 ] ) { static :: validateComp ( 'H low' , $ h [ 0 ] , 0 , 360 ) ; static :: validateComp ( 'S low' , $ s [ 0 ] , 0 , 1 ) ; static :: validateComp ( 'L low' , $ l [ 0 ] , 0 , 1 ) ; static :: validateComp ( 'H high' , $ h [ 1 ] , 0 , 360 ) ; static :: validateComp ( 'S high' , $ s [ 1 ] , 0 , 1 ) ; static :: validateComp ( 'L high' , $ l [ 1 ] , 0 , 1 ) ; $ i = 0 ; while ( true ) { $ color = static :: hsl ( static :: randFloat ( $ h [ 0 ] , $ h [ 1 ] , 1 ) , static :: randFloat ( $ s [ 0 ] , $ s [ 1 ] , 0.001 ) , static :: randFloat ( $ l [ 0 ] , $ l [ 1 ] , 0.001 ) ) ; $ hMatch = $ color -> h >= $ h [ 0 ] && $ color -> h <= $ h [ 1 ] ; $ sMatch = $ color -> s >= $ s [ 0 ] && $ color -> s <= $ s [ 1 ] ; $ lMatch = $ color -> l >= $ l [ 0 ] && $ color -> l <= $ l [ 1 ] ; if ( $ hMatch && $ sMatch && $ lMatch ) { break ; } elseif ( $ i > 50 ) { throw new Exception ( ) ; break ; } else { $ i ++ ; } } return $ color ; }
Generates a random color . Minimum and maximum values are specified for all of the HSL components .
23,763
public static function parse ( $ color ) { $ hsl = '/hsl\(([0-9]{1,3}),\s*([0-9]{1,3})%,\s*([0-9]{1,3})%\)/' ; $ rgb = '/rgb\(([0-9]{1,3}),\s*([0-9]{1,3}),\s*([0-9]{1,3})\)/' ; if ( preg_match ( $ hsl , $ color , $ m ) ) { return static :: hsl ( ( int ) $ m [ 1 ] , ( int ) $ m [ 2 ] / 100 , ( int ) $ m [ 3 ] / 100 ) ; } elseif ( preg_match ( $ rgb , $ color , $ m ) ) { return static :: rgb ( ( int ) $ m [ 1 ] , ( int ) $ m [ 2 ] , ( int ) $ m [ 3 ] ) ; } else { return static :: hex ( $ color ) ; } ; }
Parses an HTML color in either hex hsl or rgb .
23,764
public function dist ( Color $ c ) { return sqrt ( ( $ c -> r - $ this -> r ) ** 2 + ( $ c -> g - $ this -> g ) ** 2 + ( $ c -> b - $ this -> b ) ** 2 ) ; }
Calculates the distance between this color and another .
23,765
private function calcHSL ( ) { self :: rgb2hsl ( $ this -> r , $ this -> g , $ this -> b , $ h , $ s , $ l ) ; return [ $ h , $ s , $ l ] ; }
Calculates this color s HSL components .
23,766
private static function validateComp ( $ component , $ value , $ min , $ max ) { if ( $ value < $ min || $ value > $ max ) { throw new Exception ( "{$component} component {$value} must be {$min}-{$max}" ) ; } }
Validates a color component to see if fits within a range .
23,767
private static function rgb2hsl ( $ r , $ g , $ b , & $ h , & $ s , & $ l ) { $ r /= 255 ; $ g /= 255 ; $ b /= 255 ; $ min = min ( [ $ r , $ g , $ b ] ) ; $ max = max ( [ $ r , $ g , $ b ] ) ; $ l = ( $ min + $ max ) / 2 ; $ l = round ( $ l , 2 ) ; if ( $ min == $ max ) { $ s = 0 ; $ h = 0 ; return ; } if ( $ l < 0.5 ) { $ s = ( $ max - $ min ) / ( $ max + $ min ) ; } else { $ s = ( $ max - $ min ) / ( 2.0 - $ max - $ min ) ; } if ( $ r == $ max ) { $ h = ( $ g - $ b ) / ( $ max - $ min ) ; } elseif ( $ g == $ max ) { $ h = 2.0 + ( $ b - $ r ) / ( $ max - $ min ) ; } else { $ h = 4.0 + ( $ r - $ g ) / ( $ max - $ min ) ; } $ h *= 60 ; $ h = $ h < 0 ? $ h + 360 : $ h ; $ h = ( int ) round ( $ h ) ; $ s = round ( $ s , 2 ) ; }
Converts RGB to HSL .
23,768
private static function hex2rgb ( $ hex , & $ r , & $ g , & $ b ) { $ hex = preg_replace ( '/[^a-fA-F0-9]/' , '' , $ hex ) ; if ( strlen ( $ hex ) == 6 ) { $ r = substr ( $ hex , 0 , 2 ) ; $ g = substr ( $ hex , 2 , 2 ) ; $ b = substr ( $ hex , 4 , 2 ) ; } else { $ r = $ hex [ 0 ] . $ hex [ 0 ] ; $ g = $ hex [ 1 ] . $ hex [ 1 ] ; $ b = $ hex [ 2 ] . $ hex [ 2 ] ; } $ r = hexdec ( $ r ) ; $ g = hexdec ( $ g ) ; $ b = hexdec ( $ b ) ; }
Converts an RGB Hex code to RGB .
23,769
public function getClone ( $ withParameters = true ) { $ clone = new static ( $ this -> sqlAdapter , $ this -> idField , $ this -> class ) ; if ( $ withParameters ) { $ clone -> parameters = $ this -> parameters ; } return $ clone ; }
Get a clone of current request
23,770
protected function get ( $ parameter , $ default = null ) { return isset ( $ this -> parameters [ $ parameter ] ) ? $ this -> parameters [ $ parameter ] : $ default ; }
Get a parameter for this query
23,771
public function getQuery ( ) { $ output = $ this -> get ( 'output' ) ; try { $ this -> set ( 'output' , SQLAdapter :: SQLQUERY ) ; $ result = $ this -> run ( ) ; } catch ( \ Exception $ e ) { } $ this -> set ( 'output' , $ output ) ; if ( isset ( $ e ) ) { throw $ e ; } return $ result ; }
Get the query as string
23,772
protected function formatCacheInfo ( $ MaxAge , $ isPublic ) { if ( is_null ( $ MaxAge ) ) { $ MaxAge = 0 ; } return array ( self :: MAX_AGE => $ MaxAge , self :: IS_PUBLIC => $ isPublic ) ; }
Generate a CacheInfo
23,773
protected function mergeCacheInfo ( array $ cacheInfo1 , array $ cacheInfo2 ) { $ maxAge = $ cacheInfo1 [ self :: MAX_AGE ] ; if ( $ maxAge < 0 || ( ( $ cacheInfo2 [ self :: MAX_AGE ] < $ maxAge ) ) && ( - 1 < $ cacheInfo2 [ self :: MAX_AGE ] ) ) { $ maxAge = $ cacheInfo2 [ self :: MAX_AGE ] ; } $ isPublic = $ cacheInfo1 [ self :: IS_PUBLIC ] && $ cacheInfo2 [ self :: IS_PUBLIC ] ; return $ this -> formatCacheInfo ( $ maxAge , $ isPublic ) ; }
Merge two CacheInfo
23,774
public function offsetGet ( $ field ) { if ( isset ( $ this -> values [ $ field ] ) || $ this -> load ( $ field ) ) { return $ this -> values [ $ field ] ; } return NULL ; }
Retrieves a config value . If there is none it will attempt to run a factory if available .
23,775
protected function load ( $ field ) { if ( $ this -> factoryExists ( $ field ) ) { $ this -> values [ $ field ] = $ this -> runFactory ( $ field ) ; return TRUE ; } return FALSE ; }
Populates a config field with the result of a factory being run if one exists .
23,776
protected function createTable ( SiteCapsuleInterface $ capsule , array $ parameters ) { if ( $ this -> tableExists ( $ capsule ) ) { return ; } $ connection = $ this -> getConnection ( ) ; $ schemaManager = $ connection -> getSchemaManager ( ) ; $ table = $ this -> buildTable ( $ capsule , $ parameters ) ; $ schemaManager -> createTable ( $ table ) ; }
Creates Table needed to persist the wished response
23,777
public function end_lvl ( & $ output , $ depth = 0 , $ args = [ ] ) { $ indent = str_repeat ( ' ' , $ this -> indent + $ depth + 1 ) ; $ output .= sprintf ( '%s</ul>%s' , $ indent , PHP_EOL ) ; }
Ends the list of after the elements are added
23,778
public function end_el ( & $ output , $ item , $ depth = 0 , $ args = [ ] ) { if ( $ depth === 0 && in_array ( 'menu-item-has-children' , $ item -> classes ) ) { $ indent = str_repeat ( ' ' , $ this -> indent + $ depth ) ; $ output .= sprintf ( '%s</li>%s' , $ indent , PHP_EOL ) ; } else { $ output .= sprintf ( '</li>%s' , PHP_EOL ) ; } }
Ends the element output if needed
23,779
public function display_element ( $ element , & $ children_elements , $ max_depth , $ depth , $ args , & $ output ) { if ( ! $ element ) { return ; } $ id_field = $ this -> db_fields [ 'id' ] ; if ( is_object ( $ args [ 0 ] ) ) { $ args [ 0 ] -> has_children = ! empty ( $ children_elements [ $ element -> $ id_field ] ) ; } return parent :: display_element ( $ element , $ children_elements , $ max_depth , $ depth , $ args , $ output ) ; }
Traverse elements to create list from elements
23,780
public function setEncoding ( $ encoding = null ) { if ( $ encoding !== null ) { if ( ! function_exists ( 'mb_strtolower' ) ) { throw new Exception \ ExtensionNotLoadedException ( sprintf ( '%s requires mbstring extension to be loaded' , get_class ( $ this ) ) ) ; } $ encoding = strtolower ( $ encoding ) ; $ mbEncodings = array_map ( 'strtolower' , mb_list_encodings ( ) ) ; if ( ! in_array ( $ encoding , $ mbEncodings ) ) { throw new Exception \ InvalidArgumentException ( sprintf ( "Encoding '%s' is not supported by mbstring extension" , $ encoding ) ) ; } } $ this -> options [ 'encoding' ] = $ encoding ; return $ this ; }
Set the input encoding for the given string
23,781
public function getEncoding ( ) { if ( $ this -> options [ 'encoding' ] === null && function_exists ( 'mb_internal_encoding' ) ) { $ this -> options [ 'encoding' ] = mb_internal_encoding ( ) ; } return $ this -> options [ 'encoding' ] ; }
Returns the set encoding
23,782
public function json ( ) { $ this -> response -> data = json_decode ( $ this -> response -> body ) ; return $ this -> response ; }
Convert to JSON string
23,783
public static function detectBaseURL ( ) { if ( PHP_SAPI == 'cli' ) return 'http://php-cli.invalid/' ; $ protocol = 'http://' ; if ( isset ( $ _SERVER [ 'HTTPS' ] ) && filter_var ( $ _SERVER [ 'HTTPS' ] , FILTER_VALIDATE_BOOLEAN ) ) { $ protocol = 'https://' ; } if ( isset ( $ _SERVER [ 'CONTEXT_PREFIX' ] ) ) { $ path = trim ( $ _SERVER [ 'CONTEXT_PREFIX' ] , '/\\' ) . '/' ; } else { $ path = './' ; } return self :: normaliseURL ( "{$protocol}{$_SERVER['HTTP_HOST']}/{$path}" ) ; }
Detect the base URL for the current request .
23,784
public static function status ( $ status , $ suppress = false ) { $ message = self :: getStatusMessage ( $ status ) ; if ( $ suppress ) { @ header ( "HTTP/1.1 $status $message" ) ; } else { header ( "HTTP/1.1 $status $message" ) ; } return $ message ; }
Set HTTP status - code .
23,785
public static function message ( $ status , $ message ) { $ title = self :: status ( $ status ) ; ?> <html> <head> <title> <?= $ title ; ?> </title> </head> <body> <h1> <?= $ title ; ?> </h1> <p> <?= htmlentities ( $ message , ENT_COMPAT | ENT_HTML401 , 'ISO-8859-1' ) ; ?> . </p> </body> </html> <?php }
Set HTTP status - code and display a message .
23,786
public static function redirect ( $ url , $ status = 307 ) { if ( ! in_array ( $ status , [ 300 , 301 , 302 , 303 , 307 ] ) ) { $ status = 307 ; } $ url = trim ( $ url ) ; if ( strtolower ( substr ( $ url , 0 , 4 ) ) != 'http' ) { $ base_url = self :: detectBaseURL ( ) ; if ( empty ( $ base_url ) ) { self :: message ( 500 , 'Unable to detect base URL' ) ; return ; } $ url = $ base_url . ltrim ( $ url , '/' ) ; } $ url = self :: normaliseURL ( $ url ) ; if ( $ url == '' ) { self :: message ( 500 , 'Invalid URL provided for redirect operation' ) ; return ; } if ( $ status != HTTP :: MULTIPLE_CHOICES ) { self :: status ( $ status ) ; header ( "Location: $url" ) ; } else { self :: status ( HTTP :: MULTIPLE_CHOICES ) ; header ( 'Cache-Control: no-cache, must-revalidate' ) ; header ( 'Expires: Sat, 26 Jul 1997 05:00:00 CEST' ) ; } ?> <html> <head> <title>This Page has Moved</title> </head> <body> <h1>This Page has Moved</h1> <p> The page you have requested has moved to another location. </p> <p> If you are not automatically redirected to <a href=" <?= $ url ?> ">the page's new location</a>, please click <a href=" <?= $ url ?> ">here</a> to do so manually.<br> If you keep seeing this message, or are otherwise unable to reach the new location, please return to <a href="/">our homepage</a> and attempt to reach the page from there. </p> </body> </html> <?php }
Redirect the browser to the provided path .
23,787
public static function normaliseURL ( $ url , array & $ components = [ ] ) { $ url = filter_var ( trim ( $ url ) , FILTER_SANITIZE_URL ) ; $ components = @ parse_url ( $ url ) ; if ( ! $ components || ! isset ( $ components [ 'host' ] ) ) { return '' ; } if ( ! preg_match ( '/https*/i' , $ components [ 'scheme' ] ) ) { switch ( $ components [ 'port' ] ) { case 443 : $ components [ 'scheme' ] = 'https' ; break ; case 80 : default : $ components [ 'scheme' ] = 'http' ; break ; } } if ( ! empty ( $ components [ 'port' ] ) ) { if ( $ components [ 'scheme' ] == 'http' && $ components [ 'port' ] == 80 ) { unset ( $ components [ 'port' ] ) ; } elseif ( $ components [ 'scheme' ] == 'https' && $ components [ 'port' ] == 443 ) { unset ( $ components [ 'port' ] ) ; } } if ( substr ( $ components [ 'host' ] , - 1 ) == '.' ) { $ components [ 'host' ] = substr ( $ components [ 'host' ] , 0 , - 1 ) ; } $ normalised = strtolower ( "{$components['scheme']}://{$components['host']}/" ) ; if ( isset ( $ components [ 'port' ] ) ) { $ normalised = substr ( $ normalised , 0 , - 1 ) . ":{$components['port']}/" ; } if ( isset ( $ components [ 'path' ] ) ) { $ components [ 'path' ] = str_replace ( [ '\\' , '/./' ] , '/' , $ components [ 'path' ] ) ; $ components [ 'path' ] = preg_replace ( '/[\/]+/' , '/' , $ components [ 'path' ] ) ; $ normalised .= ltrim ( $ components [ 'path' ] , '/' ) ; } if ( isset ( $ components [ 'query' ] ) ) { $ normalised .= "?{$components['query']}" ; } if ( isset ( $ components [ 'fragment' ] ) ) { $ normalised .= "#{$components['fragment']}" ; } return $ normalised ; }
Normalise a URL .
23,788
public static function getBaseURL ( $ url ) { $ parsed_url = parse_url ( $ url ) ; if ( $ parsed_url === false ) { throw new ErrorException ( 'Malformed URL.' ) ; } $ base_url = [ ] ; if ( empty ( $ parsed_url [ 'scheme' ] ) ) { throw new ErrorException ( 'Malformed URL, no scheme.' ) ; } $ base_url [ ] = $ parsed_url [ 'scheme' ] ; $ base_url [ ] = '://' ; $ base_url [ ] = $ parsed_url [ 'host' ] ; $ path = $ parsed_url [ 'path' ] ; $ path_parts = explode ( '/' , $ path ) ; array_shift ( $ path_parts ) ; $ base = array_shift ( $ path_parts ) ; if ( strpos ( $ base , '~' ) !== false ) { $ base_url [ ] = '/' . $ base ; } ; $ base_url [ ] = '/' ; return implode ( '' , $ base_url ) ; }
Get the base URL for a given site URL .
23,789
public static function parsedURLToString ( $ parsed_url ) { $ components = [ ] ; if ( ! empty ( $ parsed_url [ 'scheme' ] ) ) { $ components [ 'scheme' ] = $ parsed_url [ 'scheme' ] . '://' ; } $ components [ 'user' ] = '' ; $ components [ 'pass' ] = '' ; if ( ! empty ( $ parsed_url [ 'user' ] ) ) { $ components [ 'user' ] = $ parsed_url [ 'user' ] ; } if ( ! empty ( $ parsed_url [ 'pass' ] ) ) { $ components [ 'pass' ] = ':' . $ parsed_url [ 'pass' ] ; } if ( $ components [ 'user' ] || $ components [ 'pass' ] ) { $ components [ 'pass' ] = $ components [ 'pass' ] . '@' ; } if ( ! empty ( $ parsed_url [ 'host' ] ) ) { $ components [ 'host' ] = $ parsed_url [ 'host' ] ; } if ( ! empty ( $ parsed_url [ 'port' ] ) ) { $ components [ 'port' ] = ':' . $ parsed_url [ 'port' ] ; } if ( ! empty ( $ parsed_url [ 'path' ] ) ) { $ components [ 'path' ] = $ parsed_url [ 'path' ] ; } if ( ! empty ( $ parsed_url [ 'query' ] ) ) { $ components [ 'query' ] = '?' . $ parsed_url [ 'query' ] ; } if ( ! empty ( $ parsed_url [ 'fragment' ] ) ) { $ components [ 'fragment' ] = '#' . $ parsed_url [ 'fragment' ] ; } return implode ( '' , $ components ) ; }
Convert a parsed URL back to a string .
23,790
public static function cleanPath ( $ path ) { $ path = str_replace ( [ '\\' , '/./' ] , '/' , $ path ) ; $ path = preg_replace ( '/[\/]+/' , '/' , $ path ) ; $ path = rtrim ( $ path , '/' ) ; $ path = preg_replace ( '/[^a-z0-9 \-\/]+/i' , '' , $ path ) ; $ path = preg_replace ( '/[ \-]+/' , '-' , $ path ) ; return $ path ; }
Strictly clean a URL - path from any unwanted characters .
23,791
public function clear ( $ what = [ ] ) { $ defaults = [ 'criteria' => [ ] , 'offset' => 0 , 'limit' => 0 , 'orderby' => [ ] , ] ; $ what = ( array ) $ what ; if ( empty ( $ what ) ) $ what = array_keys ( $ defaults ) ; foreach ( $ what as $ k ) { $ this -> $ k = $ defaults [ $ k ] ; } return $ this ; }
Remove all existing criteria from the filter .
23,792
public function orderBy ( $ field , $ dir = Filter :: SORT_ASC ) { $ field = trim ( $ field ) ; if ( empty ( $ field ) ) throw new \ InvalidArgumentException ( 'No field specified' ) ; $ modifier = substr ( $ field , 0 , 1 ) ; if ( in_array ( $ modifier , [ '+' , '-' ] ) ) { $ dir = ( $ modifier == '+' ) ; $ field = substr ( $ field , 1 ) ; } $ this -> orderby [ $ field ] = $ dir ; return $ this ; }
Specify a field to order the results by . Multiple levels of ordering can be specified by calling this method multiple times .
23,793
public function toQuery ( Query $ query , array $ columns = [ ] , $ alias = '' ) { foreach ( $ this -> criteria as $ column => $ criteria ) { if ( ! $ column = $ this -> getColumnName ( $ columns , $ column , $ alias ) ) continue ; foreach ( $ criteria as $ operator => $ value ) { $ query -> where ( $ column , $ operator , $ value ) ; } } foreach ( $ this -> getOrder ( ) as $ column => $ ascending ) { $ column = $ this -> getColumnName ( $ columns , $ column , $ alias ) ; if ( ! $ column ) continue ; $ query -> orderBy ( $ column , $ ascending ) ; } if ( $ this -> offset ) $ query -> offset ( $ this -> offset ) ; if ( $ this -> limit ) $ query -> limit ( $ this -> limit ) ; return $ query ; }
Apply the filter to a database Query
23,794
protected function addCriteria ( $ field , $ operator , $ value ) { $ field = trim ( $ field ) ; if ( ! isset ( $ this -> criteria [ $ field ] ) ) $ this -> criteria [ $ field ] = [ ] ; $ this -> criteria [ $ field ] [ $ operator ] = $ value ; return $ this ; }
Add a criteria item to the filter .
23,795
public static function start ( $ skipConfiguration = false ) { if ( self :: $ instance !== null ) { throw new LogException ( "Logger already started!" ) ; } self :: $ instance = new Writer ( ) ; if ( ! $ skipConfiguration && Configuration :: get ( 'app.log' , true ) ) { $ logPath = Configuration :: get ( 'app.logPath' ) ; if ( $ logPath === null ) { throw new ConfigurationException ( "app.logPath is not valid!" ) ; } if ( ! file_exists ( $ logPath ) ) { if ( ! mkdir ( $ logPath ) ) { throw new PermissionDeniedException ( "Could not create directory '" . $ logPath . "'!" ) ; } } self :: $ files = Configuration :: get ( 'app.logFile' , [ 'app.log' => self :: ERROR ] ) ; self :: $ path = $ logPath ; foreach ( self :: $ files as $ file => $ minimumLevel ) { self :: $ instance -> addHandler ( new StreamHandler ( $ logPath . $ file , $ minimumLevel ) ) ; } } ExceptionHandler :: register ( ) ; }
Start function will be called from the bootstrap file .
23,796
public static function clearLog ( $ level = null ) { foreach ( self :: $ files as $ fileName => $ fileLevel ) { if ( $ level === null || $ level === $ fileLevel ) { $ fileName = self :: $ path . $ fileName ; if ( file_exists ( $ fileName ) ) { @ unlink ( $ fileName ) ; } continue ; } } self :: $ instance = null ; self :: start ( ) ; }
Clear and delete log files .
23,797
public function setView ( $ view ) { if ( class_exists ( $ view ) ) { $ values = [ ] ; if ( isset ( $ this -> view ) && $ this -> view instanceof View ) { $ values = $ this -> view -> getDataArray ( ) ; $ layout = $ this -> view -> getLayout ( ) ; $ this -> view = $ this -> loadView ( $ view , $ values ) ; if ( ! empty ( $ layout ) ) { $ this -> view -> setLayout ( $ layout ) ; } } return $ this ; } else if ( is_string ( $ view ) ) { $ this -> response -> addContent ( $ view ) ; return $ this ; } return false ; }
Sets the view for this controller action
23,798
public function render ( View $ view = null ) { if ( $ this -> rendered ) { return true ; } $ onRender = new Event ( 'Controller.beforeRender' , $ this ) ; $ this -> observer -> trigger ( $ onRender ) ; if ( $ onRender -> isStopped ( ) ) { $ this -> autoRender = false ; return $ this -> response ; } $ view = ! is_null ( $ view ) ? $ view : $ this -> getView ( ) ; $ this -> response -> addContent ( $ view -> render ( ) ) ; $ this -> rendered = true ; return true ; }
Renders the Controller - > Response ;
23,799
public function invokeAction ( $ action , $ params = [ ] ) { $ method = new ReflectionMethod ( $ this , $ action ) ; if ( ! $ method -> isPublic ( ) ) { throw new Exception ( 'Attempting to call a private method' ) ; } return $ method -> invokeArgs ( $ this , $ params ) ; }
Checks that the method is callable ;