idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
51,700
public function removeJugglable ( $ attributes ) { if ( ! is_array ( $ attributes ) ) { $ attributes = func_get_args ( ) ; } $ attributes = array_flip ( $ attributes ) ; $ jugglables = array_diff_key ( $ this -> getJugglable ( ) , $ attributes ) ; $ this -> setJugglable ( $ jugglables ) ; }
Remove an attribute or several attributes from the jugglable array .
51,701
public function isJuggleType ( $ type ) { $ method = $ this -> buildJuggleMethod ( $ type ) ; if ( ! method_exists ( $ this , $ method ) ) { return false ; } return true ; }
Returns whether the type is a type that can be juggled to .
51,702
public function buildJuggleMethod ( $ type ) { $ type = lcfirst ( studly_case ( $ type ) ) ; switch ( $ type ) { case 'bool' : case 'boolean' : $ normalizedType = 'boolean' ; break ; case 'int' : case 'integer' : $ normalizedType = 'integer' ; break ; case 'float' : case 'double' : $ normalizedType = 'float' ; break ; case 'datetime' : case 'dateTime' : $ normalizedType = 'dateTime' ; break ; case 'date' : case 'timestamp' : case 'string' : case 'array' : default : $ normalizedType = $ type ; break ; } return 'juggle' . studly_case ( $ normalizedType ) ; }
Build the method name that the type normalizes to .
51,703
public function juggleAttributes ( ) { foreach ( $ this -> getJugglable ( ) as $ attribute => $ type ) { if ( isset ( $ this -> attributes [ $ attribute ] ) ) { $ this -> juggleAttribute ( $ attribute , $ this -> attributes [ $ attribute ] ) ; } } }
Juggles all attributes that are configured to be juggled .
51,704
public function juggleAttribute ( $ attribute , $ value ) { $ type = $ this -> getJuggleType ( $ attribute ) ; $ this -> attributes [ $ attribute ] = $ this -> juggle ( $ value , $ type ) ; }
Casts a value to the coresponding attribute type and sets it on the attributes array of this model .
51,705
public function juggle ( $ value , $ type ) { if ( ! is_null ( $ value ) ) { if ( $ this -> checkJuggleType ( $ type ) ) { $ method = $ this -> buildJuggleMethod ( $ type ) ; $ value = $ this -> { $ method } ( $ value ) ; } } return $ value ; }
Cast the value to the attribute s type as specified in the juggable array .
51,706
public function purgeAttributes ( ) { $ keys = array_keys ( $ this -> getAttributes ( ) ) ; $ attributes = array_filter ( $ keys , function ( $ key ) { if ( in_array ( $ key , $ this -> getPurgeable ( ) ) ) { return false ; } if ( Str :: endsWith ( $ key , '_confirmation' ) ) { return false ; } if ( Str :: startsWith ( $ key , '_' ) ) { return false ; } return true ; } ) ; $ this -> attributes = array_intersect_key ( $ this -> getAttributes ( ) , array_flip ( $ attributes ) ) ; }
Unset attributes that should be purged .
51,707
protected function setPurgingAndSave ( $ purge ) { $ purging = $ this -> getPurging ( ) ; $ this -> setPurging ( $ purge ) ; $ result = $ this -> save ( ) ; $ this -> setPurging ( $ purging ) ; return $ result ; }
Set purging state and then save and then reset it .
51,708
public static function initPattern ( $ optionName ) { if ( ! isset ( self :: $ store [ "patternSpecific" ] ) ) { self :: $ store [ "patternSpecific" ] = array ( ) ; } if ( ( ! isset ( self :: $ store [ "patternSpecific" ] [ $ optionName ] ) ) || ( ! is_array ( self :: $ store [ "patternSpecific" ] [ $ optionName ] ) ) ) { self :: $ store [ "patternSpecific" ] [ $ optionName ] = array ( ) ; } }
Initialize a pattern specific data store under the patternSpecific option
51,709
public static function setOptionLink ( $ optionName , $ optionValue ) { if ( ! isset ( self :: $ store [ "link" ] ) ) { self :: $ store [ "link" ] = array ( ) ; } self :: $ store [ "link" ] [ $ optionName ] = $ optionValue ; }
Set an option on a sub element of the data array
51,710
public static function setPatternData ( $ optionName , $ optionValue ) { if ( isset ( self :: $ store [ "patternSpecific" ] [ $ optionName ] ) ) { self :: $ store [ "patternSpecific" ] [ $ optionName ] [ "data" ] = $ optionValue ; return true ; } return false ; }
Set the pattern data option
51,711
public static function setPatternListItems ( $ optionName , $ optionValue ) { if ( isset ( self :: $ store [ "patternSpecific" ] [ $ optionName ] ) ) { self :: $ store [ "patternSpecific" ] [ $ optionName ] [ "listItems" ] = $ optionValue ; return true ; } return false ; }
Set the pattern listitems option
51,712
public static function underscorize ( $ word ) { $ word = preg_replace ( '/[\'"]/' , '' , $ word ) ; $ word = preg_replace ( '/[^a-zA-Z0-9]+/' , '_' , $ word ) ; $ word = preg_replace ( '/([A-Z\d]+)([A-Z][a-z])/' , '\1_\2' , $ word ) ; $ word = preg_replace ( '/([a-z\d])([A-Z])/' , '\1_\2' , $ word ) ; $ word = trim ( $ word , '_' ) ; $ word = strtolower ( $ word ) ; $ word = str_replace ( 'boleto_simples_' , '' , $ word ) ; return $ word ; }
Undescorize the element name .
51,713
public static function init ( ) { if ( ! Config :: getOption ( "patternExtension" ) ) { Console :: writeError ( "the pattern extension config option needs to be set..." ) ; } if ( ! Config :: getOption ( "styleguideKit" ) ) { Console :: writeError ( "the styleguideKit config option needs to be set..." ) ; } $ patternExtension = Config :: getOption ( "patternExtension" ) ; $ metaDir = Config :: getOption ( "metaDir" ) ; $ styleguideKit = Config :: getOption ( "styleguideKit" ) ; $ styleguideKitPath = Config :: getOption ( "styleguideKitPath" ) ; if ( ! $ styleguideKitPath || ! is_dir ( $ styleguideKitPath ) ) { Console :: writeError ( "your styleguide won't render because i can't find your styleguide files. are you sure they're at <path>" . Console :: getHumanReadablePath ( $ styleguideKitPath ) . "</path>? you can fix this in <path>./config/config.yml</path> by editing styleguideKitPath..." ) ; } $ partialPath = $ styleguideKitPath . DIRECTORY_SEPARATOR . "views" . DIRECTORY_SEPARATOR . "partials" ; $ generalHeaderPath = $ partialPath . DIRECTORY_SEPARATOR . "general-header." . $ patternExtension ; $ generalFooterPath = $ partialPath . DIRECTORY_SEPARATOR . "general-footer." . $ patternExtension ; self :: $ htmlHead = ( file_exists ( $ generalHeaderPath ) ) ? file_get_contents ( $ generalHeaderPath ) : "" ; self :: $ htmlFoot = ( file_exists ( $ generalFooterPath ) ) ? file_get_contents ( $ generalFooterPath ) : "" ; $ patternHeadPath = $ metaDir . DIRECTORY_SEPARATOR . "_00-head." . $ patternExtension ; $ patternFootPath = $ metaDir . DIRECTORY_SEPARATOR . "_01-foot." . $ patternExtension ; self :: $ patternHead = ( file_exists ( $ patternHeadPath ) ) ? file_get_contents ( $ patternHeadPath ) : "" ; self :: $ patternFoot = ( file_exists ( $ patternFootPath ) ) ? file_get_contents ( $ patternFootPath ) : "" ; $ patternEngineBasePath = PatternEngine :: getInstance ( ) -> getBasePath ( ) ; $ filesystemLoaderClass = $ patternEngineBasePath . "\Loaders\FilesystemLoader" ; $ options = array ( ) ; $ options [ "templatePath" ] = $ styleguideKitPath . DIRECTORY_SEPARATOR . "views" ; $ options [ "partialsPath" ] = $ options [ "templatePath" ] . DIRECTORY_SEPARATOR . "partials" ; self :: $ filesystemLoader = new $ filesystemLoaderClass ( $ options ) ; $ stringLoaderClass = $ patternEngineBasePath . "\Loaders\StringLoader" ; self :: $ stringLoader = new $ stringLoaderClass ( ) ; }
Set - up default vars
51,714
public function validate ( $ authTokenPayload ) { if ( $ authTokenPayload == null ) { return false ; } $ tokenResponse = $ this -> tokens -> find ( $ authTokenPayload ) ; if ( $ tokenResponse == null ) { return false ; } $ user = $ this -> users -> retrieveByID ( $ tokenResponse -> getAuthIdentifier ( ) ) ; if ( $ user == null ) { return false ; } return $ user ; }
Validates a public auth token . Returns User object on success otherwise false .
51,715
public function attempt ( array $ credentials ) { $ user = $ this -> users -> retrieveByCredentials ( $ credentials ) ; if ( $ user instanceof UserInterface && $ this -> users -> validateCredentials ( $ user , $ credentials ) ) { return $ this -> create ( $ user ) ; } return false ; }
Attempt to create an AuthToken from user credentials .
51,716
public function create ( UserInterface $ user ) { $ this -> tokens -> purge ( $ user ) ; return $ this -> tokens -> create ( $ user ) ; }
Create auth token for user .
51,717
public function isHashed ( $ attribute ) { if ( ! array_key_exists ( $ attribute , $ this -> attributes ) ) { return false ; } $ info = password_get_info ( $ this -> attributes [ $ attribute ] ) ; return ( bool ) ( $ info [ 'algo' ] !== 0 ) ; }
Returns whether the attribute is hashed .
51,718
public function hashAttributes ( ) { foreach ( $ this -> getHashable ( ) as $ attribute ) { $ this -> setHashingAttribute ( $ attribute , $ this -> getAttribute ( $ attribute ) ) ; } }
Hash attributes that should be hashed .
51,719
public function setHashingAttribute ( $ attribute , $ value ) { $ this -> attributes [ $ attribute ] = $ value ; if ( ! empty ( $ value ) && ( $ this -> isDirty ( $ attribute ) || ! $ this -> isHashed ( $ attribute ) ) ) { $ this -> attributes [ $ attribute ] = $ this -> hash ( $ value ) ; } }
Set a hashed value for a hashable attribute .
51,720
protected function setHashingAndSave ( $ hash ) { $ hashing = $ this -> getHashing ( ) ; $ this -> setHashing ( $ hash ) ; $ result = $ this -> save ( ) ; $ this -> setHashing ( $ hashing ) ; return $ result ; }
Set hashing state and then save and then reset it .
51,721
public function getRuleset ( $ ruleset , $ mergeWithSaving = false ) { $ rulesets = $ this -> getRulesets ( ) ; if ( array_key_exists ( $ ruleset , $ rulesets ) ) { if ( $ mergeWithSaving ) { return $ this -> mergeRulesets ( [ 'saving' , $ ruleset ] ) ; } return $ rulesets [ $ ruleset ] ; } elseif ( $ mergeWithSaving ) { return $ this -> getDefaultRules ( ) ; } }
Get a ruleset and merge it with saving if required .
51,722
public function addRules ( array $ rules , $ ruleset = null ) { if ( $ ruleset ) { $ newRules = array_merge ( $ this -> getRuleset ( $ ruleset ) , $ rules ) ; $ this -> setRuleset ( $ newRules , $ ruleset ) ; } else { $ newRules = array_merge ( $ this -> getRules ( ) , $ rules ) ; $ this -> setRules ( $ newRules ) ; } }
Add rules to the existing rules or ruleset overriding any existing .
51,723
public function removeRules ( $ keys , $ ruleset = null ) { $ keys = is_array ( $ keys ) ? $ keys : func_get_args ( ) ; $ rules = $ ruleset ? $ this -> getRuleset ( $ ruleset ) : $ this -> getRules ( ) ; array_forget ( $ rules , $ keys ) ; if ( $ ruleset ) { $ this -> setRuleset ( $ rules , $ ruleset ) ; } else { $ this -> setRules ( $ rules ) ; } }
Remove rules from the existing rules or ruleset .
51,724
public function mergeRulesets ( $ keys ) { $ keys = is_array ( $ keys ) ? $ keys : func_get_args ( ) ; $ rulesets = [ ] ; foreach ( $ keys as $ key ) { $ rulesets [ ] = ( array ) $ this -> getRuleset ( $ key , false ) ; } return array_filter ( call_user_func_array ( 'array_merge' , $ rulesets ) ) ; }
Helper method to merge rulesets with later rules overwriting earlier ones .
51,725
public function isValid ( $ ruleset = null , $ mergeWithSaving = true ) { $ rules = is_array ( $ ruleset ) ? $ ruleset : $ this -> getRuleset ( $ ruleset , $ mergeWithSaving ) ? : $ this -> getDefaultRules ( ) ; return $ this -> performValidation ( $ rules ) ; }
Returns whether the model is valid or not .
51,726
public function updateRulesetUniques ( $ ruleset = null ) { $ rules = $ this -> getRuleset ( $ ruleset ) ; $ this -> setRuleset ( $ ruleset , $ this -> injectUniqueIdentifierToRules ( $ rules ) ) ; }
Update the unique rules of the given ruleset to include the model identifier .
51,727
public function spawn ( $ commands = array ( ) , $ quiet = false ) { $ processes = array ( ) ; if ( ! empty ( $ commands ) ) { foreach ( $ commands as $ command ) { $ processes [ ] = $ this -> buildProcess ( $ command ) ; } } foreach ( $ this -> pluginProcesses as $ pluginProcess ) { $ processes [ ] = $ this -> buildProcess ( $ pluginProcess ) ; } if ( ! empty ( $ processes ) ) { foreach ( $ processes as $ process ) { $ process [ "process" ] -> start ( ) ; } while ( true ) { foreach ( $ processes as $ process ) { try { if ( $ process [ "process" ] -> isRunning ( ) ) { $ process [ "process" ] -> checkTimeout ( ) ; if ( ! $ quiet && $ process [ "output" ] ) { print $ process [ "process" ] -> getIncrementalOutput ( ) ; $ cmd = $ process [ "process" ] -> getCommandLine ( ) ; if ( strpos ( $ cmd , "router.php" ) != ( strlen ( $ cmd ) - 10 ) ) { print $ process [ "process" ] -> getIncrementalErrorOutput ( ) ; } } } } catch ( ProcessTimedOutException $ e ) { if ( $ e -> isGeneralTimeout ( ) ) { Console :: writeError ( "pattern lab processes should never time out. yours did..." ) ; } else if ( $ e -> isIdleTimeout ( ) ) { Console :: writeError ( "pattern lab processes automatically time out if their is no command line output in 30 minutes..." ) ; } } } usleep ( 100000 ) ; } } }
Spawn the passed commands and those collected from plugins
51,728
protected function buildProcess ( $ commandOptions ) { if ( is_string ( $ commandOptions ) ) { $ process = new Process ( escapeshellcmd ( ( string ) $ commandOptions ) ) ; return array ( "process" => $ process , "output" => true ) ; } else if ( is_array ( $ commandOptions ) ) { $ commandline = escapeshellcmd ( ( string ) $ commandOptions [ "command" ] ) ; $ cwd = isset ( $ commandOptions [ "cwd" ] ) ? $ commandOptions [ "cwd" ] : null ; $ env = isset ( $ commandOptions [ "env" ] ) ? $ commandOptions [ "env" ] : null ; $ input = isset ( $ commandOptions [ "input" ] ) ? $ commandOptions [ "input" ] : null ; $ timeout = isset ( $ commandOptions [ "timeout" ] ) ? $ commandOptions [ "timeout" ] : null ; $ options = isset ( $ commandOptions [ "options" ] ) ? $ commandOptions [ "options" ] : array ( ) ; $ idle = isset ( $ commandOptions [ "idle" ] ) ? $ commandOptions [ "idle" ] : null ; $ output = isset ( $ commandOptions [ "output" ] ) ? $ commandOptions [ "output" ] : true ; $ process = new Process ( $ commandline , $ cwd , $ env , $ input , $ timeout , $ options ) ; if ( ! empty ( $ idle ) ) { $ process -> setIdleTimeout ( $ idle ) ; } return array ( "process" => $ process , "output" => $ output ) ; } }
Build the process from the given commandOptions
51,729
public function saving ( Model $ model ) { if ( ! $ model -> getRuleset ( 'creating' ) && ! $ model -> getRuleset ( 'updating' ) ) { return $ this -> performValidation ( $ model , 'saving' ) ; } }
Register the validation event for saving the model . Saving validation should only occur if creating and updating validation does not .
51,730
private function getOption ( ) { $ searchOption = Console :: findCommandOptionValue ( "get" ) ; $ optionValue = Config :: getOption ( $ searchOption ) ; if ( ! $ optionValue ) { Console :: writeError ( "the --get value you provided, <info>" . $ searchOption . "</info>, does not exists in the config..." ) ; } else { $ optionValue = ( is_array ( $ optionValue ) ) ? implode ( ", " , $ optionValue ) : $ optionValue ; $ optionValue = ( ! $ optionValue ) ? "false" : $ optionValue ; Console :: writeInfo ( $ searchOption . ": <ok>" . $ optionValue . "</ok>" ) ; } }
Get the given option and return its value
51,731
private function listOptions ( ) { $ options = Config :: getOptions ( ) ; ksort ( $ options ) ; $ this -> lengthLong = 0 ; foreach ( $ options as $ optionName => $ optionValue ) { $ this -> lengthLong = ( strlen ( $ optionName ) > $ this -> lengthLong ) ? strlen ( $ optionName ) : $ this -> lengthLong ; } $ this -> writeOutOptions ( $ options ) ; }
List out of the options available in the config
51,732
protected function setOption ( ) { $ updateOption = Console :: findCommandOptionValue ( "set" ) ; $ updateOptionBits = explode ( "=" , $ updateOption ) ; if ( count ( $ updateOptionBits ) == 1 ) { Console :: writeError ( "the --set value should look like <info>optionName=\"optionValue\"</info>. nothing was updated..." ) ; } $ updateName = $ updateOptionBits [ 0 ] ; $ updateValue = ( ( $ updateOptionBits [ 1 ] [ 0 ] == "\"" ) || ( $ updateOptionBits [ 1 ] [ 0 ] == "'" ) ) ? substr ( $ updateOptionBits [ 1 ] , 1 , strlen ( $ updateOptionBits [ 1 ] ) - 1 ) : $ updateOptionBits [ 1 ] ; $ currentValue = Config :: getOption ( $ updateName ) ; if ( ! $ currentValue ) { Console :: writeError ( "the --set option you provided, <info>" . $ updateName . "</info>, does not exists in the config. nothing will be updated..." ) ; } else { Config :: updateConfigOption ( $ updateName , $ updateValue ) ; Console :: writeInfo ( "config option updated..." ) ; } }
Set the given option to the given value
51,733
private function writeOutOptions ( $ options , $ pre = "" ) { foreach ( $ options as $ optionName => $ optionValue ) { if ( is_array ( $ optionValue ) && ( count ( $ optionValue ) > 0 ) && ! isset ( $ optionValue [ 0 ] ) ) { $ this -> writeOutOptions ( $ optionValue , $ optionName . "." ) ; } else { $ optionValue = ( is_array ( $ optionValue ) && isset ( $ optionValue [ 0 ] ) ) ? implode ( ", " , $ optionValue ) : $ optionValue ; $ optionValue = ( ! $ optionValue ) ? "false" : $ optionValue ; $ spacer = Console :: getSpacer ( $ this -> lengthLong , strlen ( $ pre . $ optionName ) ) ; Console :: writeLine ( "<info>" . $ pre . $ optionName . ":</info>" . $ spacer . $ optionValue ) ; } } }
Write out the given options . Check to see if it s a nested sequential or associative array
51,734
public static function init ( ) { $ found = false ; $ patternExtension = Config :: getOption ( "patternExtension" ) ; self :: loadRules ( ) ; foreach ( self :: $ rules as $ rule ) { if ( $ rule -> test ( $ patternExtension ) ) { self :: $ instance = $ rule ; $ found = true ; break ; } } if ( ! $ found ) { Console :: writeError ( "the supplied pattern extension didn't match a pattern loader rule. check your config..." ) ; } }
Load a new instance of the Pattern Loader
51,735
public static function loadRules ( ) { $ configDir = Config :: getOption ( "configDir" ) ; if ( file_exists ( $ configDir . "/patternengines.json" ) ) { $ patternEngineList = json_decode ( file_get_contents ( $ configDir . "/patternengines.json" ) , true ) ; foreach ( $ patternEngineList [ "patternengines" ] as $ patternEngineName ) { self :: $ rules [ ] = new $ patternEngineName ( ) ; } } else { Console :: writeError ( "The pattern engines list isn't available in <path>" . $ configDir . "</path>..." ) ; } }
Load all of the rules related to Pattern Engines . They re located in the plugin dir
51,736
public static function check ( $ text = "" ) { if ( empty ( self :: $ startTime ) ) { Console :: writeError ( "the timer wasn't started..." ) ; } if ( empty ( self :: $ checkTime ) ) { self :: $ checkTime = self :: $ startTime ; } $ insert = "" ; if ( ! empty ( $ text ) ) { $ insert = "<info>" . $ text . " >> </info>" ; } $ checkTime = self :: getTime ( ) ; $ totalTime = ( $ checkTime - self :: $ startTime ) ; $ mem = round ( ( memory_get_peak_usage ( true ) / 1024 ) / 1024 , 2 ) ; $ timeTag = "info" ; if ( ( $ checkTime - self :: $ checkTime ) > 0.2 ) { $ timeTag = "error" ; } else if ( ( $ checkTime - self :: $ checkTime ) > 0.1 ) { $ timeTag = "warning" ; } self :: $ checkTime = $ checkTime ; Console :: writeLine ( $ insert . "currently taken <" . $ timeTag . ">" . $ totalTime . "</" . $ timeTag . "> seconds and used <info>" . $ mem . "MB</info> of memory..." ) ; }
Check the current timer
51,737
public static function checkPatternOption ( $ patternStoreKey , $ optionName ) { if ( isset ( self :: $ store [ $ patternStoreKey ] ) ) { return isset ( self :: $ store [ $ patternStoreKey ] [ $ optionName ] ) ; } return false ; }
Return if a specific option for a pattern is set
51,738
public static function getOption ( $ optionName ) { if ( isset ( self :: $ store [ $ optionName ] ) ) { return self :: $ store [ $ optionName ] ; } return false ; }
Get a specific item from the store
51,739
public static function getRule ( $ ruleName ) { if ( isset ( self :: $ rules [ $ ruleName ] ) ) { return self :: $ rules [ $ ruleName ] ; } return false ; }
Get a particular rule
51,740
public function serializeToken ( AuthToken $ token ) { $ payload = $ this -> encrypter -> encrypt ( array ( 'id' => $ token -> getAuthIdentifier ( ) , 'key' => $ token -> getPublicKey ( ) ) ) ; $ payload = str_replace ( array ( '+' , '/' , '\r' , '\n' , '=' ) , array ( '-' , '_' ) , $ payload ) ; return $ payload ; }
Returns serialized token .
51,741
public function deserializeToken ( $ payload ) { try { $ payload = str_replace ( array ( '-' , '_' ) , array ( '+' , '/' ) , $ payload ) ; $ data = $ this -> encrypter -> decrypt ( $ payload ) ; } catch ( DecryptException $ e ) { return null ; } if ( empty ( $ data [ 'id' ] ) || empty ( $ data [ 'key' ] ) ) { return null ; } $ token = $ this -> generateAuthToken ( $ data [ 'key' ] ) ; $ token -> setAuthIdentifier ( $ data [ 'id' ] ) ; return $ token ; }
Deserializes token .
51,742
public static function updateConfigOption ( $ optionName , $ optionValue , $ force = false ) { if ( is_string ( $ optionValue ) && strpos ( $ optionValue , "<prompt>" ) !== false ) { $ options = "" ; $ default = "" ; $ prompt = str_replace ( "</prompt>" , "" , str_replace ( "<prompt>" , "" , $ optionValue ) ) ; if ( strpos ( $ prompt , "<default>" ) !== false ) { $ default = explode ( "<default>" , $ prompt ) ; $ default = explode ( "</default>" , $ default [ 1 ] ) ; $ default = $ default [ 0 ] ; } $ input = Console :: promptInput ( $ prompt , $ options , $ default , false ) ; self :: writeUpdateConfigOption ( $ optionName , $ input ) ; Console :: writeTag ( "ok" , "config option " . $ optionName . " updated..." , false , true ) ; } else if ( ! isset ( self :: $ options [ $ optionName ] ) || ( self :: $ options [ "overrideConfig" ] == "a" ) || $ force ) { self :: writeUpdateConfigOption ( $ optionName , $ optionValue ) ; } else if ( self :: $ options [ "overrideConfig" ] == "q" ) { $ currentOption = self :: getOption ( $ optionName ) ; $ currentOptionValue = $ currentOption ; $ newOptionValue = $ optionValue ; $ optionNameOutput = $ optionName ; if ( $ optionName == "plugins" ) { $ optionValue = array_replace_recursive ( $ currentOption , $ newOptionValue ) ; reset ( $ newOptionValue ) ; $ newOptionKey = key ( $ newOptionValue ) ; if ( ! array_key_exists ( $ newOptionKey , $ currentOptionValue ) ) { self :: writeUpdateConfigOption ( $ optionName , $ optionValue ) ; return ; } else { if ( $ newOptionValue [ $ newOptionKey ] == $ currentOptionValue [ $ newOptionKey ] ) { return ; } else { $ optionNameOutput = $ optionName . "." . $ newOptionKey ; } } } if ( $ currentOptionValue != $ newOptionValue ) { if ( is_array ( $ currentOptionValue ) ) { $ prompt = "update the config option <desc>" . $ optionNameOutput . "</desc> with the value from the package install?" ; } else { $ prompt = "update the config option <desc>" . $ optionNameOutput . " (" . $ currentOptionValue . ")</desc> with the value <desc>" . $ newOptionValue . "</desc>?" ; } $ options = "Y/n" ; $ input = Console :: promptInput ( $ prompt , $ options , "Y" ) ; if ( $ input == "y" ) { self :: writeUpdateConfigOption ( $ optionName , $ optionValue ) ; Console :: writeInfo ( "config option " . $ optionNameOutput . " updated..." , false , true ) ; } else { Console :: writeWarning ( "config option <desc>" . $ optionNameOutput . "</desc> not updated..." , false , true ) ; } } } }
Update a single config option based on a change in composer . json
51,743
protected static function writeUpdateConfigOption ( $ optionName , $ optionValue ) { try { $ options = Yaml :: parse ( file_get_contents ( self :: $ userConfigPath ) ) ; } catch ( ParseException $ e ) { Console :: writeError ( "Config parse error in <path>" . self :: $ userConfigPath . "</path>: " . $ e -> getMessage ( ) ) ; } self :: setOption ( $ optionName , $ optionValue ) ; $ arrayFinder = new ArrayFinder ( $ options ) ; $ arrayFinder -> set ( $ optionName , $ optionValue ) ; $ options = $ arrayFinder -> get ( ) ; $ configOutput = Yaml :: dump ( $ options , 3 ) ; file_put_contents ( self :: $ userConfigPath , $ configOutput ) ; }
Write out the new config option value
51,744
public function say ( ) { $ colors = array ( "ok" , "options" , "info" , "warning" ) ; $ randomNumber = rand ( 0 , count ( $ colors ) - 1 ) ; $ color = ( isset ( $ colors [ $ randomNumber ] ) ) ? $ colors [ $ randomNumber ] : "desc" ; $ randomNumber = rand ( 0 , ( count ( $ this -> sayings ) - 1 ) * 3 ) ; if ( isset ( $ this -> sayings [ $ randomNumber ] ) ) { Console :: writeLine ( "<" . $ color . ">" . $ this -> sayings [ $ randomNumber ] . "...</" . $ color . ">" ) ; } }
Randomly prints a saying after the generate is complete
51,745
public function handleQuery ( HTTPRequest $ request ) { $ model = $ request -> param ( 'ModelReference' ) ; $ modelMap = Config :: inst ( ) -> get ( self :: class , 'models' ) ; if ( array_key_exists ( $ model , $ modelMap ) ) { $ model = $ modelMap [ $ model ] ; } $ id = $ request -> param ( 'ID' ) ; $ response = false ; $ queryParams = $ this -> parseQueryParameters ( $ request -> getVars ( ) ) ; if ( $ model ) { $ model = $ this -> deSerializer -> unformatName ( $ model ) ; if ( ! class_exists ( $ model ) ) { return new RESTfulAPIError ( 400 , "Model does not exist. Received '$model'." ) ; } else { $ this -> requestedData [ 'model' ] = $ model ; } } else { return new RESTfulAPIError ( 400 , "Missing Model parameter." ) ; } if ( ! RESTfulAPI :: api_access_control ( $ model , $ request -> httpMethod ( ) ) ) { return new RESTfulAPIError ( 403 , "API access denied." ) ; } if ( ( $ request -> isPUT ( ) || $ request -> isDELETE ( ) ) && ! is_numeric ( $ id ) ) { return new RESTfulAPIError ( 400 , "Invalid or missing ID. Received '$id'." ) ; } elseif ( $ id !== null && ! is_numeric ( $ id ) ) { return new RESTfulAPIError ( 400 , "Invalid ID. Received '$id'." ) ; } else { $ this -> requestedData [ 'id' ] = $ id ; } if ( $ queryParams ) { $ this -> requestedData [ 'params' ] = $ queryParams ; } switch ( $ request -> httpMethod ( ) ) { case 'GET' : return $ this -> findModel ( $ model , $ id , $ queryParams , $ request ) ; break ; case 'POST' : return $ this -> createModel ( $ model , $ request ) ; break ; case 'PUT' : return $ this -> updateModel ( $ model , $ id , $ request ) ; break ; case 'DELETE' : return $ this -> deleteModel ( $ model , $ id , $ request ) ; break ; default : return new RESTfulAPIError ( 403 , "HTTP method mismatch." ) ; break ; } }
All requests pass through here and are redirected depending on HTTP verb and params
51,746
public function getCommand ( ) { $ options = $ this -> getOptions ( ) ; $ arguments = $ this -> getArguments ( ) ; $ to = null ; $ from = $ arguments [ 'from' ] ; if ( true === isset ( $ arguments [ 'to' ] ) ) { $ to = $ arguments [ 'to' ] ; } array_walk ( $ options , function ( & $ option ) { $ option = '--' . $ option ; } ) ; array_walk ( $ arguments , function ( & $ value , $ argument ) { $ value = '--' . $ argument . '=' . $ value ; } ) ; return trim ( sprintf ( '%s %s %s' , $ this -> getBaseCommand ( ) , $ this -> getRange ( $ from , $ to ) , join ( ' ' , $ options ) ) ) ; }
Returns the compiled VCS log command .
51,747
protected function splitHeader ( $ header ) { list ( $ name , $ value ) = explode ( ':' , $ header , 2 ) ; return [ trim ( $ name ) , trim ( $ value ) , strtolower ( trim ( $ name ) ) ] ; }
Split a header string in name and value
51,748
protected function withHeaderLogic ( $ name , $ value , $ add ) { $ this -> assertHeaderName ( $ name ) ; $ this -> assertHeaderValue ( $ value ) ; $ this -> assertHeadersNotSent ( ) ; foreach ( ( array ) $ value as $ val ) { $ this -> header ( "{$name}: {$val}" , ! $ add ) ; } return $ this ; }
Abstraction for withHeader and withAddedHeader
51,749
protected function reset ( ) { $ this -> protocolVersion = null ; $ this -> headers = null ; $ this -> requestTarget = null ; $ this -> method = null ; $ this -> uri = null ; }
Remove all set and cached values
51,750
protected function dereferenceProperty ( ... $ properties ) { foreach ( ( array ) $ properties as $ property ) { if ( ! property_exists ( $ this , $ property ) ) { continue ; } $ value = $ this -> $ property ; unset ( $ this -> $ property ) ; $ this -> $ property = $ value ; } }
Remove referencing from properties
51,751
protected function buildGlobalEnvironment ( ) { $ request = clone $ this ; $ request -> serverParams = & $ _SERVER ; $ request -> cookies = & $ _COOKIE ; $ request -> queryParams = & $ _GET ; $ request -> setPostData ( $ _POST ) ; $ request -> setUploadedFiles ( $ _FILES ) ; $ request -> body = Stream :: open ( 'php://input' , 'r' ) ; $ request -> reset ( ) ; $ request -> isStale = false ; return $ request ; }
Build the global environment
51,752
public function withoutGlobalEnvironment ( ) { if ( $ this -> isStale !== false ) { return $ this ; } $ request = clone $ this ; $ request -> copy ( ) ; $ request -> isStale = null ; return $ request ; }
Return object that is disconnected from superglobals
51,753
protected function copy ( ) { if ( $ this -> isStale ) { throw new \ BadMethodCallException ( "Unable to modify a stale server request object" ) ; } $ request = clone $ this ; if ( $ this -> isStale === false ) { $ this -> dereferenceProperty ( 'serverParams' , 'cookies' , 'queryParams' , 'postData' , 'uploadedFiles' ) ; $ this -> isStale = true ; } return $ request ; }
Clone the server request . Turn stale if the request is bound to the global environment .
51,754
public function revive ( ) { if ( $ this -> isStale !== true ) { return $ this ; } $ request = $ this -> buildGlobalEnvironment ( ) ; return $ request -> withServerParams ( $ this -> getServerParams ( ) ) -> withCookieParams ( $ this -> getCookieParams ( ) ) -> withQueryParams ( $ this -> getQueryParams ( ) ) -> withParsedBody ( $ this -> getParsedBody ( ) ) -> withBody ( clone $ this -> getBody ( ) ) -> withUploadedFiles ( $ this -> getUploadedFiles ( ) ) ; }
Revive a stale server request
51,755
public function invoke ( ServerRequestInterface $ request , RouteParams $ params ) { $ callable = $ this -> callable ; if ( $ this -> isControllerAction ( ) ) { $ callable = call_user_func ( $ this -> callable ) ; } if ( $ this -> invoker ) { return $ this -> invoker -> setRequest ( $ request ) -> call ( $ callable , $ params -> toArray ( ) ) ; } else { return call_user_func ( $ callable , $ params ) ; } }
Invoke the action
51,756
private function createCallableFromAction ( $ action ) : callable { if ( ! is_callable ( $ action ) && is_string ( $ action ) ) { return $ this -> convertClassStringToFactory ( $ action ) ; } return $ action ; }
If the action is a Controller string a factory callable is returned to allow for lazy loading
51,757
private function getController ( ) { if ( empty ( $ this -> controllerName ) ) { return null ; } if ( isset ( $ this -> controller ) ) { return $ this -> controller ; } $ this -> controller = $ this -> createControllerFromClassName ( $ this -> controllerName ) ; return $ this -> controller ; }
Get the Controller for this action . The Controller will only be created once
51,758
private function createControllerFromClassName ( $ className ) { if ( $ this -> invoker ) { return $ this -> invoker -> getContainer ( ) -> get ( $ className ) ; } return new $ className ; }
Instantiate a Controller object from the provided class name
51,759
private function providesMiddleware ( ) : bool { $ controller = $ this -> getController ( ) ; if ( $ controller && ( $ controller instanceof ProvidesControllerMiddleware ) ) { return true ; } return false ; }
Can this action provide Middleware
51,760
public function getMiddleware ( ) : array { if ( ! $ this -> providesMiddleware ( ) ) { return [ ] ; } $ allControllerMiddleware = array_filter ( $ this -> getController ( ) -> getControllerMiddleware ( ) , function ( ControllerMiddleware $ middleware ) { return ! $ middleware -> excludedForMethod ( $ this -> controllerMethod ) ; } ) ; return array_map ( function ( $ controllerMiddleware ) { return $ controllerMiddleware -> middleware ( ) ; } , $ allControllerMiddleware ) ; }
Get an array of Middleware
51,761
private function convertClassStringToFactory ( $ string ) : Closure { $ this -> controllerName = null ; $ this -> controllerMethod = null ; @ list ( $ className , $ method ) = explode ( '@' , $ string ) ; if ( ! isset ( $ className ) || ! isset ( $ method ) ) { throw new RouteClassStringParseException ( 'Could not parse route controller from string: `' . $ string . '`' ) ; } if ( ! class_exists ( $ className ) ) { throw new RouteClassStringControllerNotFoundException ( 'Could not find route controller class: `' . $ className . '`' ) ; } if ( ! method_exists ( $ className , $ method ) ) { throw new RouteClassStringMethodNotFoundException ( 'Route controller class: `' . $ className . '` does not have a `' . $ method . '` method' ) ; } $ this -> controllerName = $ className ; $ this -> controllerMethod = $ method ; return function ( ) { $ controller = $ this -> getController ( ) ; $ method = $ this -> controllerMethod ; if ( $ this -> invoker ) { return [ $ controller , $ method ] ; } return function ( $ params = null ) use ( $ controller , $ method ) { return $ controller -> $ method ( $ params ) ; } ; } ; }
Create a factory Closure for the given Controller string
51,762
public function getActionName ( ) { $ callableName = null ; if ( $ this -> isControllerAction ( ) ) { return $ this -> controllerName . '@' . $ this -> controllerMethod ; } if ( is_callable ( $ this -> callable , false , $ callableName ) ) { list ( $ controller , $ method ) = explode ( '::' , $ callableName ) ; if ( $ controller === 'Closure' ) { return $ controller ; } return $ controller . '@' . $ method ; } }
Get the human readable name of this action
51,763
protected function assertTmpFile ( ) { if ( empty ( $ this -> tmpName ) ) { throw new \ RuntimeException ( "There is no tmp_file for " . $ this -> getDesc ( ) . ": " . $ this -> getErrorDescription ( ) ) ; } if ( ! file_exists ( $ this -> tmpName ) ) { throw new \ RuntimeException ( "The " . $ this -> getDesc ( ) . " no longer exists or is already moved" ) ; } if ( $ this -> assertIsUploadedFile && ! $ this -> isUploadedFile ( $ this -> tmpName ) ) { throw new \ RuntimeException ( "The specified tmp_name for " . $ this -> getDesc ( ) . " doesn't appear" . " to be uploaded via HTTP POST" ) ; } }
Assert that the temp file exists and is an uploaded file
51,764
public function getErrorDescription ( ) { if ( $ this -> error === UPLOAD_ERR_OK ) { return null ; } $ descs = static :: ERROR_DESCRIPTIONS ; return isset ( $ descs [ $ this -> error ] ) ? $ descs [ $ this -> error ] : $ descs [ - 1 ] ; }
Retrieve the description of the error associated with the uploaded file .
51,765
public function generate ( ) { if ( true === empty ( $ this -> log ) ) { return array ( ) ; } $ log = array ( ) ; foreach ( $ this -> log as $ header => & $ entries ) { $ log [ ] = sprintf ( "\n#### %s" , $ header ) ; foreach ( $ entries as & $ line ) { $ message = explode ( VCS :: MSG_SEPARATOR , $ line ) ; $ log [ ] = sprintf ( "* %s" , trim ( $ message [ 0 ] ) ) ; if ( true === isset ( $ message [ 1 ] ) ) { $ log [ ] = sprintf ( "\n %s" , trim ( $ message [ 1 ] ) ) ; } } } return array_merge ( array ( "## {$this->release}" , "*({$this->date->format('Y-m-d')})*" ) , $ log , array ( "\n---\n" ) ) ; }
Returns a write - ready log .
51,766
protected function serverParamKeyToHeaderName ( $ key ) { $ name = null ; if ( \ Jasny \ str_starts_with ( $ key , 'HTTP_' ) ) { $ name = $ this -> headerCase ( substr ( $ key , 5 ) ) ; } elseif ( in_array ( $ key , [ 'CONTENT_TYPE' , 'CONTENT_LENGTH' ] ) ) { $ name = $ this -> headerCase ( $ key ) ; } return $ name ; }
Turn a server parameter key to a header name
51,767
protected function determineHeaders ( ) { $ params = $ this -> getServerParams ( ) ; $ headers = [ ] ; foreach ( $ params as $ key => $ value ) { $ name = $ this -> serverParamKeyToHeaderName ( $ key ) ; if ( isset ( $ name ) && is_string ( $ value ) ) { $ headers [ $ name ] = [ $ value ] ; } } return $ headers ; }
Determine the headers based on the server parameters
51,768
public function deserialize ( $ json ) { $ data = json_decode ( $ json , true ) ; $ error = RESTfulAPIError :: get_json_error ( ) ; if ( $ error !== false ) { return new RESTfulAPIError ( 400 , $ error ) ; } if ( $ data ) { $ data = $ this -> unformatPayloadData ( $ data ) ; } else { return new RESTfulAPIError ( 400 , "No data received." ) ; } return $ data ; }
Convert client JSON data to an array of data ready to be consumed by SilverStripe
51,769
public function parse ( $ arrAttributes = null ) { $ basicTextOptions = array ( 'text' => array ( 'formatProgress' , 'failUpload' , 'waitingForResponse' , 'paused' , ) , 'messages' => array ( 'typeError' , 'sizeError' , 'minSizeError' , 'emptyError' , 'noFilesError' , 'tooManyItemsError' , 'maxHeightImageError' , 'maxWidthImageError' , 'minHeightImageError' , 'minWidthImageError' , 'retryFailTooManyItems' , 'onLeave' , 'unsupportedBrowserIos8Safari' , ) , 'retry' => array ( 'autoRetryNote' , ) , 'deleteFile' => array ( 'confirmMessage' , 'deletingStatusText' , 'deletingFailedText' , ) , 'paste' => array ( 'namePromptMessage' , ) ) ; $ config = array ( ) ; foreach ( $ basicTextOptions as $ category => $ messages ) { foreach ( $ messages as $ message ) { if ( isset ( $ GLOBALS [ 'TL_LANG' ] [ 'MSC' ] [ 'fineuploader_trans' ] [ $ category ] [ $ message ] ) ) { $ config [ $ category ] [ $ message ] = $ GLOBALS [ 'TL_LANG' ] [ 'MSC' ] [ 'fineuploader_trans' ] [ $ category ] [ $ message ] ; } } } if ( isset ( $ this -> arrConfiguration [ 'uploaderConfig' ] ) && $ this -> arrConfiguration [ 'uploaderConfig' ] !== '' ) { $ this -> arrConfiguration [ 'uploaderConfig' ] = json_decode ( '{' . $ this -> arrConfiguration [ 'uploaderConfig' ] . '}' , true ) ; } $ this -> config = json_encode ( array_merge ( $ config , ( array ) $ this -> arrConfiguration [ 'uploaderConfig' ] ) ) ; $ labels = array ( 'drop' , 'upload' , 'processing' , 'cancel' , 'retry' , 'delete' , 'close' , 'yes' , 'no' , ) ; $ preparedLabels = array ( ) ; foreach ( $ labels as $ label ) { $ preparedLabels [ $ label ] = $ GLOBALS [ 'TL_LANG' ] [ 'MSC' ] [ 'fineuploader_' . $ label ] ; } if ( $ this -> uploadButtonLabel ) { $ preparedLabels [ 'upload' ] = $ this -> uploadButtonLabel ; } $ this -> labels = $ preparedLabels ; return parent :: parse ( $ arrAttributes ) ; }
Add the labels and messages .
51,770
protected function getDestinationFolder ( ) { $ destination = \ Config :: get ( 'uploadPath' ) ; $ folder = null ; if ( isset ( $ this -> arrConfiguration [ 'uploadFolder' ] ) ) { $ folder = $ this -> arrConfiguration [ 'uploadFolder' ] ; } if ( $ this -> arrConfiguration [ 'useHomeDir' ] && FE_USER_LOGGED_IN ) { $ user = FrontendUser :: getInstance ( ) ; if ( $ user -> assignDir && $ user -> homeDir ) { $ folder = $ user -> homeDir ; } } if ( $ folder !== null && \ Validator :: isUuid ( $ folder ) ) { $ folderModel = \ FilesModel :: findByUuid ( $ folder ) ; if ( $ folderModel !== null ) { $ destination = $ folderModel -> path ; } } else { $ destination = $ folder ; } return $ destination ; }
Get the destination folder
51,771
protected function validatorSingle ( $ varFile , $ strDestination ) { if ( ! \ Validator :: isStringUuid ( $ varFile ) && is_file ( TL_ROOT . '/' . $ varFile ) ) { $ varFile = $ this -> moveTemporaryFile ( $ varFile , $ strDestination ) ; } if ( \ Validator :: isStringUuid ( $ varFile ) ) { $ varFile = \ StringUtil :: uuidToBin ( $ varFile ) ; } return $ varFile ; }
Validate a single file .
51,772
protected function moveTemporaryFile ( $ strFile , $ strDestination ) { if ( ! is_file ( TL_ROOT . '/' . $ strFile ) ) { return '' ; } if ( ! $ this -> arrConfiguration [ 'storeFile' ] ) { return $ strFile ; } if ( stripos ( $ strFile , $ this -> strTemporaryPath ) === false ) { return $ strFile ; } $ strNew = $ strDestination . '/' . basename ( $ strFile ) ; if ( $ this -> arrConfiguration [ 'doNotOverwrite' ] ) { $ strNew = $ strDestination . '/' . $ this -> getFileName ( basename ( $ strFile ) , $ strDestination ) ; } $ blnRename = \ Files :: getInstance ( ) -> rename ( $ strFile , $ strNew ) ; \ Files :: getInstance ( ) -> chmod ( $ strNew , \ Config :: get ( 'defaultFileChmod' ) ) ; if ( $ this -> arrConfiguration [ 'addToDbafs' ] && $ blnRename ) { $ objModel = \ Dbafs :: addResource ( $ strNew ) ; if ( $ objModel !== null ) { $ strNew = $ objModel -> uuid ; } } return $ strNew ; }
Move the temporary file to its destination
51,773
protected function getFileName ( $ strFile , $ strFolder ) { if ( ! file_exists ( TL_ROOT . '/' . $ strFolder . '/' . $ strFile ) ) { return $ strFile ; } $ offset = 1 ; $ pathinfo = pathinfo ( $ strFile ) ; $ name = $ pathinfo [ 'filename' ] ; $ arrAll = scan ( TL_ROOT . '/' . $ strFolder ) ; $ arrFiles = preg_grep ( '/^' . preg_quote ( $ name , '/' ) . '.*\.' . preg_quote ( $ pathinfo [ 'extension' ] , '/' ) . '/' , $ arrAll ) ; foreach ( $ arrFiles as $ file ) { if ( preg_match ( '/__[0-9]+\.' . preg_quote ( $ pathinfo [ 'extension' ] , '/' ) . '$/' , $ file ) ) { $ file = str_replace ( '.' . $ pathinfo [ 'extension' ] , '' , $ file ) ; $ intValue = intval ( substr ( $ file , ( strrpos ( $ file , '_' ) + 1 ) ) ) ; $ offset = max ( $ offset , $ intValue ) ; } } return str_replace ( $ name , $ name . '__' . ++ $ offset , $ strFile ) ; }
Get the new file name if it already exists in the folder
51,774
protected function generateFileItem ( $ strPath ) { if ( ! is_file ( TL_ROOT . '/' . $ strPath ) ) { return '' ; } $ imageSize = $ this -> getImageSize ( ) ; $ objFile = new \ File ( $ strPath , true ) ; $ strInfo = $ strPath . ' <span class="tl_gray">(' . \ System :: getReadableSize ( $ objFile -> size ) . ( $ objFile -> isGdImage ? ', ' . $ objFile -> width . 'x' . $ objFile -> height . ' px' : '' ) . ')</span>' ; $ allowedDownload = trimsplit ( ',' , strtolower ( $ GLOBALS [ 'TL_CONFIG' ] [ 'allowedDownload' ] ) ) ; $ strReturn = '' ; if ( ! $ this -> blnIsGallery && ! $ this -> blnIsDownloads ) { if ( $ objFile -> isGdImage ) { $ strReturn = \ Image :: getHtml ( \ Image :: get ( $ strPath , $ imageSize [ 0 ] , $ imageSize [ 1 ] , $ imageSize [ 2 ] ) , '' , 'class="gimage" title="' . specialchars ( $ strInfo ) . '"' ) ; } else { $ strReturn = \ Image :: getHtml ( $ objFile -> icon ) . ' ' . $ strInfo ; } } else { if ( $ this -> blnIsGallery ) { if ( $ objFile -> isGdImage ) { $ strReturn = \ Image :: getHtml ( \ Image :: get ( $ strPath , $ imageSize [ 0 ] , $ imageSize [ 1 ] , $ imageSize [ 2 ] ) , '' , 'class="gimage" title="' . specialchars ( $ strInfo ) . '"' ) ; } } else { if ( in_array ( $ objFile -> extension , $ allowedDownload ) && ! preg_match ( '/^meta(_[a-z]{2})?\.txt$/' , $ objFile -> basename ) ) { $ strReturn = \ Image :: getHtml ( $ objFile -> icon ) . ' ' . $ strPath ; } } } return $ strReturn ; }
Generate a file item and return it as HTML string
51,775
public static function get_json_error ( ) { $ error = 'JSON - ' ; switch ( json_last_error ( ) ) { case JSON_ERROR_NONE : $ error = false ; break ; case JSON_ERROR_DEPTH : $ error .= 'The maximum stack depth has been exceeded.' ; break ; case JSON_ERROR_STATE_MISMATCH : $ error .= 'Invalid or malformed JSON.' ; break ; case JSON_ERROR_CTRL_CHAR : $ error .= 'Control character error, possibly incorrectly encoded.' ; break ; case JSON_ERROR_SYNTAX : $ error .= 'Syntax error.' ; break ; default : $ error .= 'Unknown error (' . json_last_error ( ) . ').' ; break ; } return $ error ; }
Check for the latest JSON parsing error and return the message if any
51,776
protected function setScheme ( $ scheme ) { $ scheme = strtolower ( $ scheme ) ; if ( $ scheme !== '' && ! $ this -> isSupportedScheme ( $ scheme ) ) { throw new \ InvalidArgumentException ( "Invalid or unsupported scheme '$scheme'" ) ; } $ this -> scheme = $ scheme ; }
Set the scheme
51,777
public function withLocalScope ( ) { if ( $ this -> isClosed ( ) ) { throw new \ RuntimeException ( "The stream is closed" ) ; } if ( ! $ this -> isGlobal ( ) ) { return $ this ; } $ stream = clone $ this ; fwrite ( $ stream -> handle , ( string ) $ this ) ; return $ stream ; }
Get this stream in a local scope . If the stream is global it will create a temp stream and copy the contents .
51,778
public function login ( HTTPRequest $ request ) { $ response = array ( ) ; if ( $ this -> tokenConfig [ 'owner' ] === Member :: class ) { $ email = $ request -> requestVar ( 'email' ) ; $ pwd = $ request -> requestVar ( 'pwd' ) ; $ member = false ; if ( $ email && $ pwd ) { $ member = Injector :: inst ( ) -> get ( MemberAuthenticator :: class ) -> authenticate ( array ( 'Email' => $ email , 'Password' => $ pwd , ) , $ request ) ; if ( $ member ) { $ tokenData = $ this -> generateToken ( ) ; $ tokenDBColumn = $ this -> tokenConfig [ 'DBColumn' ] ; $ expireDBColumn = $ this -> tokenConfig [ 'expireDBColumn' ] ; $ member -> { $ tokenDBColumn } = $ tokenData [ 'token' ] ; $ member -> { $ expireDBColumn } = $ tokenData [ 'expire' ] ; $ member -> write ( ) ; $ member -> login ( ) ; } } if ( ! $ member ) { $ response [ 'result' ] = false ; $ response [ 'message' ] = 'Authentication fail.' ; $ response [ 'code' ] = self :: AUTH_CODE_LOGIN_FAIL ; } else { $ response [ 'result' ] = true ; $ response [ 'message' ] = 'Logged in.' ; $ response [ 'code' ] = self :: AUTH_CODE_LOGGED_IN ; $ response [ 'token' ] = $ tokenData [ 'token' ] ; $ response [ 'expire' ] = $ tokenData [ 'expire' ] ; $ response [ 'userID' ] = $ member -> ID ; } } return $ response ; }
Login a user into the Framework and generates API token Only works if the token owner is a Member
51,779
public function logout ( HTTPRequest $ request ) { $ email = $ request -> requestVar ( 'email' ) ; $ member = Member :: get ( ) -> filter ( array ( 'Email' => $ email ) ) -> first ( ) ; if ( $ member ) { $ member -> logout ( ) ; if ( $ this -> tokenConfig [ 'owner' ] === Member :: class ) { $ tokenData = $ this -> generateToken ( true ) ; $ tokenDBColumn = $ this -> tokenConfig [ 'DBColumn' ] ; $ expireDBColumn = $ this -> tokenConfig [ 'expireDBColumn' ] ; $ member -> { $ tokenDBColumn } = $ tokenData [ 'token' ] ; $ member -> { $ expireDBColumn } = $ tokenData [ 'expire' ] ; $ member -> write ( ) ; } } }
Logout a user from framework and update token with an expired one if token owner class is a Member
51,780
public function lostPassword ( HTTPRequest $ request ) { $ email = Convert :: raw2sql ( $ request -> requestVar ( 'email' ) ) ; $ member = DataObject :: get_one ( Member :: class , "\"Email\" = '{$email}'" ) ; if ( $ member ) { $ token = $ member -> generateAutologinTokenAndStoreHash ( ) ; $ link = Security :: lost_password_url ( ) ; $ lostPasswordHandler = new LostPasswordHandler ( $ link ) ; $ lostPasswordHandler -> sendEmail ( $ member , $ token ) ; } return array ( 'done' => true ) ; }
Sends password recovery email
51,781
public function getToken ( $ id ) { if ( $ id ) { $ ownerClass = $ this -> tokenConfig [ 'owner' ] ; $ owner = DataObject :: get_by_id ( $ ownerClass , $ id ) ; if ( $ owner ) { $ tokenDBColumn = $ this -> tokenConfig [ 'DBColumn' ] ; return $ owner -> { $ tokenDBColumn } ; } else { user_error ( "API Token owner '$ownerClass' not found with ID = $id" , E_USER_WARNING ) ; } } else { user_error ( "TokenAuthenticator::getToken() requires an ID as argument." , E_USER_WARNING ) ; } }
Return the stored API token for a specific owner
51,782
private function generateToken ( $ expired = false ) { $ life = $ this -> tokenConfig [ 'life' ] ; if ( ! $ expired ) { $ expire = time ( ) + $ life ; } else { $ expire = time ( ) - ( $ life * 2 ) ; } $ generator = new RandomGenerator ( ) ; $ tokenString = $ generator -> randomToken ( ) ; $ e = PasswordEncryptor :: create_for_algorithm ( 'blowfish' ) ; $ salt = $ e -> salt ( $ tokenString ) ; $ token = $ e -> encrypt ( $ tokenString , $ salt ) ; return array ( 'token' => substr ( $ token , 7 ) , 'expire' => $ expire , ) ; }
Generates an encrypted random token and an expiry date
51,783
public function getOwner ( HTTPRequest $ request ) { $ owner = null ; $ token = $ request -> getHeader ( $ this -> tokenConfig [ 'header' ] ) ; if ( ! $ token ) { $ token = $ request -> requestVar ( $ this -> tokenConfig [ 'queryVar' ] ) ; } if ( $ token ) { $ SQLToken = Convert :: raw2sql ( $ token ) ; $ owner = DataObject :: get_one ( $ this -> tokenConfig [ 'owner' ] , "\"" . $ this -> tokenConfig [ 'DBColumn' ] . "\"='" . $ SQLToken . "'" , false ) ; if ( ! $ owner ) { $ owner = null ; } } return $ owner ; }
Returns the DataObject related to the token that sent the authenticated request
51,784
public function authenticate ( HTTPRequest $ request ) { $ token = $ request -> getHeader ( $ this -> tokenConfig [ 'header' ] ) ; if ( ! $ token ) { $ token = $ request -> requestVar ( $ this -> tokenConfig [ 'queryVar' ] ) ; } if ( $ token ) { return $ this -> validateAPIToken ( $ token , $ request ) ; } else { return new RESTfulAPIError ( 403 , 'Token invalid.' , array ( 'message' => 'Token invalid.' , 'code' => self :: AUTH_CODE_TOKEN_INVALID , ) ) ; } }
Checks if a request to the API is authenticated Gets API Token from HTTP Request and return Auth result
51,785
private function validateAPIToken ( $ token , $ request ) { $ SQL_token = Convert :: raw2sql ( $ token ) ; $ tokenColumn = $ this -> tokenConfig [ 'DBColumn' ] ; $ tokenOwner = DataObject :: get_one ( $ this -> tokenConfig [ 'owner' ] , "\"" . $ this -> tokenConfig [ 'DBColumn' ] . "\"='" . $ SQL_token . "'" , false ) ; if ( $ tokenOwner ) { $ tokenExpire = $ tokenOwner -> { $ this -> tokenConfig [ 'expireDBColumn' ] } ; $ now = time ( ) ; $ life = $ this -> tokenConfig [ 'life' ] ; if ( $ tokenExpire > ( $ now - $ life ) ) { if ( $ this -> tokenConfig [ 'autoRefresh' ] ) { $ tokenOwner -> setField ( $ this -> tokenConfig [ 'expireDBColumn' ] , $ now + $ life ) ; $ tokenOwner -> write ( ) ; } if ( is_a ( $ tokenOwner , Member :: class ) ) { Config :: nest ( ) ; Config :: modify ( ) -> set ( Member :: class , 'session_regenerate_id' , true ) ; $ identityStore = Injector :: inst ( ) -> get ( IdentityStore :: class ) ; $ identityStore -> logIn ( $ tokenOwner , false , $ request ) ; Config :: unnest ( ) ; } return true ; } else { return new RESTfulAPIError ( 403 , 'Token expired.' , array ( 'message' => 'Token expired.' , 'code' => self :: AUTH_CODE_TOKEN_EXPIRED , ) ) ; } } else { return new RESTfulAPIError ( 403 , 'Token invalid.' , array ( 'message' => 'Token invalid.' , 'code' => self :: AUTH_CODE_TOKEN_INVALID , ) ) ; } }
Validate the API token
51,786
protected function jsonify ( $ data ) { $ json = json_encode ( $ data ) ; $ error = RESTfulAPIError :: get_json_error ( ) ; if ( $ error !== false ) { return new RESTfulAPIError ( 400 , $ error ) ; } return $ json ; }
Convert data into a JSON string
51,787
protected function formatDataList ( DataList $ dataList ) { $ formattedDataListMap = array ( ) ; foreach ( $ dataList as $ dataObject ) { $ formattedDataObjectMap = $ this -> formatDataObject ( $ dataObject ) ; if ( $ formattedDataObjectMap ) { array_push ( $ formattedDataListMap , $ formattedDataObjectMap ) ; } } return $ formattedDataListMap ; }
Format a DataList into a formatted array ready to be turned into JSON
51,788
protected function getEmbedData ( DataObject $ record , $ relationName ) { if ( $ record -> hasMethod ( $ relationName ) ) { $ relationData = $ record -> $ relationName ( ) ; if ( $ relationData instanceof RelationList ) { return $ this -> formatDataList ( $ relationData ) ; } else { return $ this -> formatDataObject ( $ relationData ) ; } } return null ; }
Returns a DataObject relation s data formatted and ready to embed .
51,789
protected function isEmbeddable ( $ model , $ relation ) { if ( array_key_exists ( $ model , $ this -> embeddedRecords ) ) { return is_array ( $ this -> embeddedRecords [ $ model ] ) && in_array ( $ relation , $ this -> embeddedRecords [ $ model ] ) ; } return false ; }
Checks if a speicific model s relation should have its records embedded .
51,790
protected function assertMethod ( $ method ) { if ( ! is_string ( $ method ) ) { $ type = ( is_object ( $ method ) ? get_class ( $ method ) . ' ' : '' ) . gettype ( $ method ) ; throw new \ InvalidArgumentException ( "Method should be a string, not a $type" ) ; } if ( preg_match ( '/[^a-z\-]/i' , $ method ) ) { $ type = ( is_object ( $ method ) ? get_class ( $ method ) . ' ' : '' ) . gettype ( $ method ) ; throw new \ InvalidArgumentException ( "Invalid method '$method': " . "Method may only contain letters and dashes" ) ; } }
Assert method is valid
51,791
public function withStatus ( $ code , $ reasonPhrase = '' ) { $ status = clone $ this ; $ status -> setStatus ( $ code , $ reasonPhrase ) ; return $ status ; }
Create a new response status object with the specified code and phrase .
51,792
public function requireDefaultRecords ( ) { $ readersGroup = DataObject :: get ( Group :: class ) -> filter ( array ( 'Code' => 'restfulapi-readers' , ) ) ; if ( ! $ readersGroup -> count ( ) ) { $ readerGroup = new Group ( ) ; $ readerGroup -> Code = 'restfulapi-readers' ; $ readerGroup -> Title = 'RESTful API Readers' ; $ readerGroup -> Sort = 0 ; $ readerGroup -> write ( ) ; Permission :: grant ( $ readerGroup -> ID , 'RESTfulAPI_VIEW' ) ; } $ editorsGroup = DataObject :: get ( Group :: class ) -> filter ( array ( 'Code' => 'restfulapi-editors' , ) ) ; if ( ! $ editorsGroup -> count ( ) ) { $ editorGroup = new Group ( ) ; $ editorGroup -> Code = 'restfulapi-editors' ; $ editorGroup -> Title = 'RESTful API Editors' ; $ editorGroup -> Sort = 0 ; $ editorGroup -> write ( ) ; Permission :: grant ( $ editorGroup -> ID , 'RESTfulAPI_VIEW' ) ; Permission :: grant ( $ editorGroup -> ID , 'RESTfulAPI_EDIT' ) ; Permission :: grant ( $ editorGroup -> ID , 'RESTfulAPI_CREATE' ) ; } $ adminsGroup = DataObject :: get ( Group :: class ) -> filter ( array ( 'Code' => 'restfulapi-administrators' , ) ) ; if ( ! $ adminsGroup -> count ( ) ) { $ adminGroup = new Group ( ) ; $ adminGroup -> Code = 'restfulapi-administrators' ; $ adminGroup -> Title = 'RESTful API Administrators' ; $ adminGroup -> Sort = 0 ; $ adminGroup -> write ( ) ; Permission :: grant ( $ adminGroup -> ID , 'RESTfulAPI_VIEW' ) ; Permission :: grant ( $ adminGroup -> ID , 'RESTfulAPI_EDIT' ) ; Permission :: grant ( $ adminGroup -> ID , 'RESTfulAPI_CREATE' ) ; Permission :: grant ( $ adminGroup -> ID , 'RESTfulAPI_DELETE' ) ; } }
Create the default Groups and add default admin to admin group
51,793
public function loadAssets ( $ table ) { if ( TL_MODE !== 'BE' || ! is_array ( $ GLOBALS [ 'TL_DCA' ] [ $ table ] [ 'fields' ] ) ) { return ; } foreach ( $ GLOBALS [ 'TL_DCA' ] [ $ table ] [ 'fields' ] as $ field ) { if ( $ field [ 'inputType' ] === 'fineUploader' ) { FineUploaderWidget :: includeAssets ( ) ; break ; } } }
Load the widget assets if they are needed . Load them here so the widget in subpalette can work as well .
51,794
protected function validator ( $ varInput ) { $ varReturn = parent :: validator ( $ varInput ) ; $ arrReturn = array_filter ( ( array ) $ varReturn ) ; $ intCount = 0 ; foreach ( $ arrReturn as $ varFile ) { if ( \ Validator :: isUuid ( $ varFile ) ) { $ objModel = \ FilesModel :: findByUuid ( $ varFile ) ; if ( $ objModel === null ) { continue ; } $ varFile = $ objModel -> path ; } $ objFile = new \ File ( $ varFile , true ) ; $ _SESSION [ 'FILES' ] [ $ this -> strName . '_' . $ intCount ++ ] = array ( 'name' => $ objFile -> name , 'type' => $ objFile -> mime , 'tmp_name' => TL_ROOT . '/' . $ objFile -> path , 'error' => 0 , 'size' => $ objFile -> size , 'uploaded' => true , 'uuid' => ( $ objModel !== null ) ? \ StringUtil :: binToUuid ( $ objModel -> uuid ) : '' ) ; } return $ varReturn ; }
Store the file information in the session
51,795
protected function mapUriPartsFromServerParams ( array $ params ) { $ parts = [ ] ; $ map = [ 'PHP_AUTH_USER' => 'user' , 'PHP_AUTH_PWD' => 'password' , 'HTTP_HOST' => 'host' , 'SERVER_PORT' => 'port' , 'REQUEST_URI' => 'path' , 'QUERY_STRING' => 'query' ] ; foreach ( $ map as $ param => $ key ) { if ( isset ( $ params [ $ param ] ) ) { $ parts [ $ key ] = $ params [ $ param ] ; } } return $ parts ; }
Map server params for URI
51,796
protected function determineUri ( ) { $ params = $ this -> getServerParams ( ) ; $ parts = $ this -> mapUriPartsFromServerParams ( $ params ) ; if ( isset ( $ params [ 'SERVER_PROTOCOL' ] ) && \ Jasny \ str_starts_with ( strtoupper ( $ params [ 'SERVER_PROTOCOL' ] ) , 'HTTP/' ) ) { $ parts [ 'scheme' ] = ! empty ( $ params [ 'HTTPS' ] ) && $ params [ 'HTTPS' ] !== 'off' ? 'https' : 'http' ; } if ( isset ( $ parts [ 'host' ] ) ) { list ( $ parts [ 'host' ] ) = explode ( ':' , $ parts [ 'host' ] , 2 ) ; } if ( isset ( $ parts [ 'path' ] ) ) { $ parts [ 'path' ] = parse_url ( $ parts [ 'path' ] , PHP_URL_PATH ) ; } return new UriObject ( $ parts ) ; }
Determine the URI base on the server parameters
51,797
public function getParser ( ) { if ( true === empty ( $ this -> parser ) ) { $ typeParserClassName = sprintf ( '\ReadmeGen\Vcs\Type\%s' , ucfirst ( $ this -> config [ 'vcs' ] ) ) ; if ( false === class_exists ( $ typeParserClassName ) ) { throw new \ InvalidArgumentException ( sprintf ( 'Class "%s" does not exist' , $ typeParserClassName ) ) ; } $ this -> parser = new Parser ( new $ typeParserClassName ( ) ) ; } return $ this -> parser ; }
Returns the parser .
51,798
public function extractMessages ( array $ log = null ) { if ( true === empty ( $ log ) ) { return array ( ) ; } $ this -> extractor -> setMessageGroups ( $ this -> config [ 'message_groups' ] ) ; return $ this -> extractor -> setLog ( $ log ) -> extract ( ) ; }
Returns messages extracted from the log .
51,799
public function getDecoratedMessages ( array $ log = null ) { if ( true === empty ( $ log ) ) { return array ( ) ; } return $ this -> decorator -> setLog ( $ log ) -> setIssueTrackerUrlPattern ( $ this -> config [ 'issue_tracker_pattern' ] ) -> decorate ( ) ; }
Returns decorated log messages .