idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
52,900
public function resolveFullPath ( $ path ) { if ( is_array ( $ path ) ) { $ paths = array ( ) ; foreach ( $ path as $ p ) { $ paths [ ] = $ this -> resolveFullPath ( $ p ) ; } return $ paths ; } else { if ( strpos ( $ path , $ this -> getRepositoryPath ( ) ) === 0 ) { return $ path ; } $ path = FileSystem :: normalizeDirectorySeparator ( $ path ) ; $ path = ltrim ( $ path , '/' ) ; return $ this -> getRepositoryPath ( ) . '/' . $ path ; } }
Resolves a path relative to the repository into an absolute path
52,901
public function getBuffer ( ) { $ currentPos = $ this -> getPosition ( ) ; $ this -> setPosition ( 0 , SEEK_SET ) ; $ buffer = stream_get_contents ( $ this -> stream ) ; $ this -> setPosition ( $ currentPos , SEEK_SET ) ; return $ buffer ; }
Returns the complete contents of the buffer
52,902
public function getName ( ) { if ( isset ( $ _REQUEST [ 'qqfilename' ] ) ) return $ _REQUEST [ 'qqfilename' ] ; if ( isset ( $ _FILES [ $ this -> inputName ] ) ) return $ _FILES [ $ this -> inputName ] [ 'name' ] ; }
Get the original filename
52,903
protected function getUniqueTargetPath ( $ uploadDirectory , $ filename ) { if ( function_exists ( 'sem_acquire' ) ) { $ lock = sem_get ( ftok ( __FILE__ , 'u' ) ) ; sem_acquire ( $ lock ) ; } $ pathinfo = pathinfo ( $ filename ) ; $ base = $ pathinfo [ 'filename' ] ; $ ext = isset ( $ pathinfo [ 'extension' ] ) ? $ pathinfo [ 'extension' ] : '' ; $ ext = $ ext == '' ? $ ext : '.' . $ ext ; $ unique = $ base ; $ suffix = 0 ; while ( file_exists ( $ uploadDirectory . DIRECTORY_SEPARATOR . $ unique . $ ext ) ) { $ suffix += rand ( 1 , 999 ) ; $ unique = $ base . '-' . $ suffix ; } $ result = $ uploadDirectory . DIRECTORY_SEPARATOR . $ unique . $ ext ; if ( ! touch ( $ result ) ) { $ result = false ; } if ( function_exists ( 'sem_acquire' ) ) { sem_release ( $ lock ) ; } return $ result ; }
Returns a path to use with this upload . Check that the name does not exist and appends a suffix otherwise .
52,904
protected function cleanupChunks ( ) { foreach ( scandir ( $ this -> chunksFolder ) as $ item ) { if ( $ item == "." || $ item == ".." ) continue ; $ path = $ this -> chunksFolder . DIRECTORY_SEPARATOR . $ item ; if ( ! is_dir ( $ path ) ) continue ; if ( time ( ) - filemtime ( $ path ) > $ this -> chunksExpireIn ) { $ this -> removeDir ( $ path ) ; } } }
Deletes all file parts in the chunks folder for files uploaded more than chunksExpireIn seconds ago
52,905
protected function removeDir ( $ dir ) { foreach ( scandir ( $ dir ) as $ item ) { if ( $ item == "." || $ item == ".." ) continue ; if ( is_dir ( $ item ) ) { removeDir ( $ item ) ; } else { unlink ( join ( DIRECTORY_SEPARATOR , array ( $ dir , $ item ) ) ) ; } } rmdir ( $ dir ) ; }
Removes a directory and all files contained inside
52,906
protected function toBytes ( $ str ) { $ val = substr ( trim ( $ str ) , 0 , strlen ( $ str ) - 1 ) ; $ last = strtolower ( $ str [ strlen ( $ str ) - 1 ] ) ; switch ( $ last ) { case 'g' : $ val *= 1024 ; case 'm' : $ val *= 1024 ; case 'k' : $ val *= 1024 ; } return $ val ; }
Converts a given size with units to bytes .
52,907
protected function isInaccessible ( $ directory ) { $ isWin = ( strtoupper ( substr ( PHP_OS , 0 , 3 ) ) === 'WIN' ) ; $ folderInaccessible = ( $ isWin ) ? ! is_writable ( $ directory ) : ( ! is_writable ( $ directory ) && ! is_executable ( $ directory ) ) ; return $ folderInaccessible ; }
Determines whether a directory can be accessed .
52,908
public function doRequest ( Request $ request ) { $ response = $ this -> getIo ( ) -> call ( $ request ) ; if ( ! $ response ) { throw new HttpException ( 'Request failed' ) ; } else if ( isset ( $ response -> data [ 'errors' ] ) ) { $ error = $ response -> data [ 'errors' ] [ 0 ] ; throw new HttpException ( HttpException :: format ( $ error ) , $ error -> error_code ) ; } return $ response ; }
Take request and execute him
52,909
protected function getRepository ( array $ pathInfo ) { if ( $ pathInfo [ 'host' ] === PathInformationInterface :: GLOBAL_PATH_HOST ) { return $ this -> createRepositoryForPath ( $ pathInfo [ 'path' ] ) ; } else { return $ this -> map -> getRepository ( $ pathInfo [ 'host' ] ) ; } }
Returns the repository for the given path information
52,910
public function createPathInformation ( $ streamUrl ) { $ pathInfo = $ this -> parsePath ( $ streamUrl ) ; $ repository = $ this -> getRepository ( $ pathInfo ) ; $ ref = isset ( $ pathInfo [ 'fragment' ] ) ? $ pathInfo [ 'fragment' ] : 'HEAD' ; $ arguments = array ( ) ; if ( isset ( $ pathInfo [ 'query' ] ) ) { parse_str ( $ pathInfo [ 'query' ] , $ arguments ) ; } $ fullPath = $ repository -> resolveFullPath ( $ pathInfo [ 'path' ] ) ; $ url = $ this -> protocol . '://' . $ fullPath . '#' . $ ref . '?' . http_build_query ( $ arguments ) ; return new PathInformation ( $ repository , $ url , $ fullPath , $ ref , $ arguments ) ; }
Returns the path information for a given stream URL
52,911
public function parsePath ( $ streamUrl ) { $ path = str_replace ( array ( '\\' , '/' ) , '/' , $ streamUrl ) ; $ path = preg_replace ( '~^(.+?)(#[^/]+)(.*)$~' , '$1$3$2' , $ path ) ; $ protocol = $ this -> protocol ; if ( strpos ( $ path , $ protocol . ':///' ) === 0 ) { $ path = str_replace ( $ protocol . ':///' , $ protocol . '://' . PathInformationInterface :: GLOBAL_PATH_HOST . '/' , $ path ) ; } $ info = parse_url ( $ path ) ; if ( $ info === false ) { throw new \ InvalidArgumentException ( 'Url "' . $ streamUrl . '" is not a valid path' ) ; } if ( isset ( $ info [ 'path' ] ) && preg_match ( '~^/\w:.+~' , $ info [ 'path' ] ) ) { $ info [ 'path' ] = ltrim ( $ info [ 'path' ] , '/' ) ; } else if ( ! isset ( $ info [ 'path' ] ) ) { $ info [ 'path' ] = '/' ; } return $ info ; }
Returns path information for a given stream path
52,912
public static function check ( $ name ) { if ( empty ( $ name ) ) { return false ; } return Hash :: get ( $ _SESSION , $ name ) !== null ; }
Returns true if given variable is set in session .
52,913
public static function id ( $ id = null ) { if ( $ id ) { static :: $ id = $ id ; session_id ( static :: $ id ) ; } if ( static :: started ( ) ) { return session_id ( ) ; } return static :: $ id ; }
Returns the session id . Calling this method will not auto start the session . You might have to manually assert a started session .
52,914
public static function valid ( ) { if ( static :: start ( ) && static :: read ( 'Config' ) ) { if ( static :: _validAgentAndTime ( ) && static :: $ error === false ) { static :: $ valid = true ; } else { throw new InternalErrorException ( 'Session Highjacking Attempted !!!' ) ; } } return static :: $ valid ; }
Returns true if session is valid .
52,915
public static function open ( $ repositoryPath , $ git = null , $ createIfNotExists = false , $ initArguments = null , $ findRepositoryRoot = true ) { $ git = Binary :: ensure ( $ git ) ; $ repositoryRoot = null ; if ( ! is_string ( $ repositoryPath ) ) { throw new \ InvalidArgumentException ( sprintf ( '"%s" is not a valid path' , $ repositoryPath ) ) ; } if ( $ findRepositoryRoot ) { $ repositoryRoot = self :: findRepositoryRoot ( $ repositoryPath ) ; } if ( $ repositoryRoot === null ) { if ( ! $ createIfNotExists ) { throw new \ InvalidArgumentException ( sprintf ( '"%s" is not a valid path' , $ repositoryPath ) ) ; } else { if ( ! file_exists ( $ repositoryPath ) && ! mkdir ( $ repositoryPath , $ createIfNotExists , true ) ) { throw new \ RuntimeException ( sprintf ( '"%s" cannot be created' , $ repositoryPath ) ) ; } else if ( ! is_dir ( $ repositoryPath ) ) { throw new \ InvalidArgumentException ( sprintf ( '"%s" is not a valid path' , $ repositoryPath ) ) ; } self :: initRepository ( $ git , $ repositoryPath , $ initArguments ) ; $ repositoryRoot = $ repositoryPath ; } } if ( $ repositoryRoot === null ) { throw new \ InvalidArgumentException ( sprintf ( '"%s" is not a valid Git repository' , $ repositoryPath ) ) ; } return new static ( $ repositoryRoot , $ git ) ; }
Opens a Git repository on the file system optionally creates and initializes a new repository
52,916
protected static function initRepository ( Binary $ git , $ path , $ initArguments = null ) { $ initArguments = $ initArguments ? : Array ( ) ; $ result = $ git -> { 'init' } ( $ path , $ initArguments ) ; $ result -> assertSuccess ( sprintf ( 'Cannot initialize a Git repository in "%s"' , $ path ) ) ; }
Initializes a path to be used as a Git repository
52,917
public function showCommit ( $ hash ) { $ result = $ this -> getGit ( ) -> { 'show' } ( $ this -> getRepositoryPath ( ) , array ( '--format' => 'fuller' , $ hash ) ) ; $ result -> assertSuccess ( sprintf ( 'Cannot retrieve commit "%s" from "%s"' , $ hash , $ this -> getRepositoryPath ( ) ) ) ; return $ result -> getStdOut ( ) ; }
Returns a string containing information about the given commit
52,918
public function showFile ( $ file , $ ref = 'HEAD' ) { $ result = $ this -> getGit ( ) -> { 'show' } ( $ this -> getRepositoryPath ( ) , array ( sprintf ( '%s:%s' , $ ref , $ file ) ) ) ; $ result -> assertSuccess ( sprintf ( 'Cannot show "%s" at "%s" from "%s"' , $ file , $ ref , $ this -> getRepositoryPath ( ) ) ) ; return $ result -> getStdOut ( ) ; }
Returns the content of a file at a given version
52,919
public function getStatus ( ) { $ result = $ this -> getGit ( ) -> { 'status' } ( $ this -> getRepositoryPath ( ) , array ( '--short' ) ) ; $ result -> assertSuccess ( sprintf ( 'Cannot retrieve status from "%s"' , $ this -> getRepositoryPath ( ) ) ) ; $ output = rtrim ( $ result -> getStdOut ( ) ) ; if ( empty ( $ output ) ) { return array ( ) ; } $ status = array_map ( function ( $ f ) { $ line = rtrim ( $ f ) ; $ parts = array ( ) ; preg_match ( '/^(?<x>.)(?<y>.)\s(?<f>.+?)(?:\s->\s(?<f2>.+))?$/' , $ line , $ parts ) ; $ status = array ( 'file' => $ parts [ 'f' ] , 'x' => trim ( $ parts [ 'x' ] ) , 'y' => trim ( $ parts [ 'y' ] ) , 'renamed' => ( array_key_exists ( 'f2' , $ parts ) ) ? $ parts [ 'f2' ] : null ) ; return $ status ; } , explode ( "\n" , $ output ) ) ; return $ status ; }
Returns the current status of the working directory and the staging area
52,920
public function getCurrentBranch ( ) { $ result = $ this -> getGit ( ) -> { 'rev-parse' } ( $ this -> getRepositoryPath ( ) , array ( '--symbolic-full-name' , '--abbrev-ref' , 'HEAD' ) ) ; $ result -> assertSuccess ( sprintf ( 'Cannot retrieve current branch from "%s"' , $ this -> getRepositoryPath ( ) ) ) ; return $ result -> getStdOut ( ) ; }
Returns the name of the current branch
52,921
public function getBranches ( $ which = self :: BRANCHES_LOCAL ) { $ which = ( int ) $ which ; $ arguments = array ( '--no-color' ) ; $ local = ( ( $ which & self :: BRANCHES_LOCAL ) == self :: BRANCHES_LOCAL ) ; $ remote = ( ( $ which & self :: BRANCHES_REMOTE ) == self :: BRANCHES_REMOTE ) ; if ( $ local && $ remote ) { $ arguments [ ] = '-a' ; } else if ( $ remote ) { $ arguments [ ] = '-r' ; } $ result = $ this -> getGit ( ) -> { 'branch' } ( $ this -> getRepositoryPath ( ) , $ arguments ) ; $ result -> assertSuccess ( sprintf ( 'Cannot retrieve branch from "%s"' , $ this -> getRepositoryPath ( ) ) ) ; $ output = rtrim ( $ result -> getStdOut ( ) ) ; if ( empty ( $ output ) ) { return array ( ) ; } $ branches = array_map ( function ( $ b ) { $ line = rtrim ( $ b ) ; if ( strpos ( $ line , '* ' ) === 0 ) { $ line = substr ( $ line , 2 ) ; } $ line = ltrim ( $ line ) ; return $ line ; } , explode ( "\n" , $ output ) ) ; return $ branches ; }
Returns a list of the branches in the repository
52,922
public function getCurrentRemote ( ) { $ result = $ this -> getGit ( ) -> { 'remote' } ( $ this -> getRepositoryPath ( ) , array ( '-v' ) ) ; $ result -> assertSuccess ( sprintf ( 'Cannot remote "%s"' , $ this -> getRepositoryPath ( ) ) ) ; $ tmp = $ result -> getStdOut ( ) ; preg_match_all ( '/([a-z]*)\h(.*)\h\((.*)\)/' , $ tmp , $ matches ) ; $ retVar = array ( ) ; foreach ( $ matches [ 0 ] as $ key => $ value ) $ retVar [ $ matches [ 1 ] [ $ key ] ] [ $ matches [ 3 ] [ $ key ] ] = $ matches [ 2 ] [ $ key ] ; return $ retVar ; }
Returns the remote info
52,923
public function afterFilter ( Event $ event ) { if ( Configure :: read ( 'Shim.monitorHeaders' ) && $ this -> name !== 'Error' && PHP_SAPI !== 'cli' ) { if ( headers_sent ( $ filename , $ lineNumber ) ) { $ message = sprintf ( 'Headers already sent in %s on line %s' , $ filename , $ lineNumber ) ; if ( Configure :: read ( 'debug' ) ) { throw new Exception ( $ message ) ; } trigger_error ( $ message ) ; } } }
Hook to monitor headers being sent .
52,924
public static function ensure ( $ binary ) { if ( $ binary === null || is_string ( $ binary ) ) { $ binary = new static ( $ binary ) ; } if ( ! ( $ binary instanceof static ) ) { throw new \ InvalidArgumentException ( sprintf ( 'The $binary argument must either be a TQ\Vcs\Binary instance or a path to the VCS binary (%s given)' , ( is_object ( $ binary ) ) ? get_class ( $ binary ) : gettype ( $ binary ) ) ) ; } return $ binary ; }
Ensures that the given arguments is a valid VCS binary
52,925
public function createCall ( $ path , $ command , array $ arguments ) { if ( ! self :: isWindows ( ) ) { $ binary = escapeshellcmd ( $ this -> path ) ; } else { $ binary = $ this -> path ; } if ( ! empty ( $ command ) ) { $ command = escapeshellarg ( $ command ) ; } list ( $ args , $ files ) = $ this -> sanitizeCommandArguments ( $ arguments ) ; $ cmd = $ this -> createCallCommand ( $ binary , $ command , $ args , $ files ) ; $ call = $ this -> doCreateCall ( $ cmd , $ path ) ; return $ call ; }
Create a call to the VCS binary for later execution
52,926
protected function createCallCommand ( $ binary , $ command , array $ args , array $ files ) { $ cmd = trim ( sprintf ( '%s %s %s' , $ binary , $ command , implode ( ' ' , $ args ) ) ) ; if ( count ( $ files ) > 0 ) { $ cmd .= ' -- ' . implode ( ' ' , $ files ) ; } return $ cmd ; }
Creates the command string to be executed
52,927
protected function sanitizeCommandArgument ( $ key , $ value ) { $ key = ltrim ( $ key , '-' ) ; if ( strlen ( $ key ) == 1 || is_numeric ( $ key ) ) { $ arg = sprintf ( '-%s' , escapeshellarg ( $ key ) ) ; if ( $ value !== null ) { $ arg .= ' ' . escapeshellarg ( $ value ) ; } } else { $ arg = sprintf ( '--%s' , escapeshellarg ( $ key ) ) ; if ( $ value !== null ) { $ arg .= '=' . escapeshellarg ( $ value ) ; } } return $ arg ; }
Sanitizes a command line argument
52,928
protected function sanitizeCommandArguments ( array $ arguments ) { $ args = array ( ) ; $ files = array ( ) ; $ fileMode = false ; foreach ( $ arguments as $ k => $ v ) { if ( $ v === '--' || $ k === '--' ) { $ fileMode = true ; continue ; } if ( is_int ( $ k ) ) { if ( strpos ( $ v , '-' ) === 0 ) { $ args [ ] = $ this -> sanitizeCommandArgument ( $ v , null ) ; } else if ( $ fileMode ) { $ files [ ] = escapeshellarg ( $ v ) ; } else { $ args [ ] = escapeshellarg ( $ v ) ; } } else { if ( strpos ( $ k , '-' ) === 0 ) { $ args [ ] = $ this -> sanitizeCommandArgument ( $ k , $ v ) ; } } } return array ( $ args , $ files ) ; }
Sanitizes a list of command line arguments and splits them into args and files
52,929
protected function extractCallParametersFromMagicCall ( $ method , array $ arguments ) { if ( count ( $ arguments ) < 1 ) { throw new \ InvalidArgumentException ( sprintf ( '"%s" must be called with at least one argument denoting the path' , $ method ) ) ; } $ path = array_shift ( $ arguments ) ; $ args = array ( ) ; $ stdIn = null ; if ( count ( $ arguments ) > 0 ) { $ args = array_shift ( $ arguments ) ; if ( ! is_array ( $ args ) ) { $ args = array ( $ args ) ; } if ( count ( $ arguments ) > 0 ) { $ stdIn = array_shift ( $ arguments ) ; if ( ! is_string ( $ stdIn ) ) { $ stdIn = null ; } } } return array ( $ path , $ method , $ args , $ stdIn ) ; }
Extracts the CLI call parameters from the arguments to a magic method call
52,930
protected function makeRequest ( $ method , $ uri , array $ data = NULL , $ contentType = Http :: CONTENT_JSON ) { $ this -> trigger ( 'onRequest' , [ $ method , $ uri , $ data ] ) ; if ( ! $ this -> client -> hasToken ( ) ) { $ this -> doAuthorization ( ) ; } $ request = new Request ( ) ; $ request -> setUrl ( Gateway :: getFullApiUrl ( $ uri ) ) ; $ headers = [ 'Accept' => 'application/json' , 'Authorization' => 'Bearer ' . $ this -> client -> getToken ( ) -> accessToken , 'Content-Type' => $ contentType , ] ; $ request -> setHeaders ( $ headers ) ; $ request -> setOpts ( $ this -> options ) ; switch ( $ method ) { case HttpClient :: METHOD_GET : $ request -> appendOpts ( [ CURLOPT_HTTPGET => TRUE , ] ) ; break ; case HttpClient :: METHOD_POST : $ request -> appendOpts ( [ CURLOPT_POST => TRUE , CURLOPT_POSTFIELDS => $ contentType === Http :: CONTENT_FORM ? http_build_query ( $ data ) : json_encode ( $ data ) , ] ) ; break ; default : throw new InvalidStateException ( 'Unsupported http method' ) ; } return $ this -> client -> call ( $ request ) ; }
Build request and execute him
52,931
protected function _shimRelations ( ) { if ( ! empty ( $ this -> belongsTo ) ) { foreach ( $ this -> belongsTo as $ k => $ v ) { if ( is_int ( $ k ) ) { $ k = $ v ; $ v = [ ] ; } $ v = $ this -> _parseRelation ( $ v ) ; $ this -> belongsTo ( Inflector :: pluralize ( $ k ) , $ v ) ; } } if ( ! empty ( $ this -> hasOne ) ) { foreach ( $ this -> hasOne as $ k => $ v ) { if ( is_int ( $ k ) ) { $ k = $ v ; $ v = [ ] ; } $ v = $ this -> _parseRelation ( $ v ) ; $ this -> hasOne ( Inflector :: pluralize ( $ k ) , $ v ) ; } } if ( ! empty ( $ this -> hasMany ) ) { foreach ( $ this -> hasMany as $ k => $ v ) { if ( is_int ( $ k ) ) { $ k = $ v ; $ v = [ ] ; } $ v = $ this -> _parseRelation ( $ v ) ; $ this -> hasMany ( Inflector :: pluralize ( $ k ) , $ v ) ; } } if ( ! empty ( $ this -> hasAndBelongsToMany ) ) { foreach ( $ this -> hasAndBelongsToMany as $ k => $ v ) { if ( is_int ( $ k ) ) { $ k = $ v ; $ v = [ ] ; } $ v = $ this -> _parseRelation ( $ v ) ; $ this -> belongsToMany ( Inflector :: pluralize ( $ k ) , $ v ) ; } } }
Shim the 2 . x way of class properties for relations .
52,932
public function validationDefault ( Validator $ validator ) { if ( ! empty ( $ this -> validate ) ) { foreach ( $ this -> validate as $ field => $ rules ) { if ( is_int ( $ field ) ) { $ field = $ rules ; $ rules = [ ] ; } if ( ! $ rules ) { continue ; } $ rules = ( array ) $ rules ; foreach ( $ rules as $ key => $ rule ) { if ( is_string ( $ rule ) ) { $ ruleArray = [ 'rule' => $ rule ] ; $ rules [ $ rule ] = $ ruleArray ; unset ( $ rules [ $ key ] ) ; $ key = $ rule ; $ rule = $ ruleArray ; } if ( isset ( $ rule [ 'required' ] ) ) { $ validator -> requirePresence ( $ field , $ rule [ 'required' ] ) ; unset ( $ rules [ $ key ] [ 'required' ] ) ; } if ( isset ( $ rule [ 'allowEmpty' ] ) ) { $ validator -> allowEmpty ( $ field , $ rule [ 'allowEmpty' ] ) ; unset ( $ rules [ $ key ] [ 'allowEmpty' ] ) ; } if ( isset ( $ rule [ 'message' ] ) ) { if ( is_array ( $ rule [ 'message' ] ) ) { $ name = array_shift ( $ rule [ 'message' ] ) ; $ args = $ this -> _translateArgs ( $ rule [ 'message' ] ) ; $ message = __d ( $ this -> validationDomain , $ name , $ args ) ; } else { $ message = __d ( $ this -> validationDomain , $ rule [ 'message' ] ) ; } $ rules [ $ key ] [ 'message' ] = $ message ; } if ( ! empty ( $ rules [ $ key ] [ 'rule' ] ) && ( $ rules [ $ key ] [ 'rule' ] === 'notEmpty' || $ rules [ $ key ] [ 'rule' ] === [ 'notEmpty' ] ) ) { $ rules [ $ key ] [ 'rule' ] = 'notBlank' ; } if ( ! empty ( $ rules [ $ key ] [ 'rule' ] ) && ( $ rules [ $ key ] [ 'rule' ] === 'isUnique' || $ rules [ $ key ] [ 'rule' ] === [ 'isUnique' ] ) ) { $ rules [ $ key ] [ 'rule' ] = 'validateUnique' ; $ rules [ $ key ] [ 'provider' ] = 'table' ; } } $ validator -> add ( $ field , $ rules ) ; } } return $ validator ; }
Shim the 2 . x way of validate class properties .
52,933
protected function _translateArgs ( $ args ) { foreach ( ( array ) $ args as $ k => $ arg ) { if ( is_string ( $ arg ) ) { $ args [ $ k ] = __d ( $ this -> validationDomain , $ arg ) ; } } return $ args ; }
Applies translations to validator arguments .
52,934
public function beforeFind ( Event $ event , Query $ query , $ options , $ primary ) { $ order = $ query -> clause ( 'order' ) ; if ( ( $ order === null || ! count ( $ order ) ) && ! empty ( $ this -> order ) ) { $ query -> order ( $ this -> order ) ; } return $ query ; }
Sets the default ordering as 2 . x shim .
52,935
public function autoNullConditionsArray ( array $ conditions ) { foreach ( $ conditions as $ k => $ v ) { if ( $ v !== null ) { continue ; } $ conditions [ $ k . ' IS' ] = $ v ; unset ( $ conditions [ $ k ] ) ; } return $ conditions ; }
2 . x shim to allow conditions without explicit IS operator for NULL values .
52,936
protected function _prefixOrderProperty ( ) { if ( is_string ( $ this -> order ) ) { $ this -> order = $ this -> _prefixAlias ( $ this -> order ) ; } if ( is_array ( $ this -> order ) ) { foreach ( $ this -> order as $ key => $ value ) { if ( is_numeric ( $ key ) ) { $ this -> order [ $ key ] = $ this -> _prefixAlias ( $ value ) ; } else { $ newKey = $ this -> _prefixAlias ( $ key ) ; $ this -> order [ $ newKey ] = $ value ; if ( $ newKey !== $ key ) { unset ( $ this -> order [ $ key ] ) ; } } } } }
Prefixes the order property with the actual alias if its a string or array .
52,937
public function setCommitMsg ( $ commitMsg ) { if ( $ commitMsg === null ) { $ this -> commitMsg = null ; } else { $ this -> commitMsg = ( string ) $ commitMsg ; } return $ this ; }
Sets the commit message that will be used when committing the transaction
52,938
public function setAuthor ( $ author ) { if ( $ author === null ) { $ this -> author = null ; } else { $ this -> author = ( string ) $ author ; } return $ this ; }
Sets the author that will be used when committing the transaction
52,939
public function hasCommandHandler ( $ command ) { $ class = get_class ( $ command ) ; if ( isset ( $ this -> handlers [ $ class ] ) ) { return true ; } $ callback = $ this -> mapper ; if ( ! $ callback || method_exists ( $ command , 'handle' ) ) { return false ; } $ this -> handlers [ $ class ] = $ callback ( $ command ) ; return true ; }
Determine if the given command has a handler .
52,940
public static function simpleMapping ( $ command , string $ commandNamespace , string $ handlerNamespace ) { $ command = str_replace ( $ commandNamespace , '' , get_class ( $ command ) ) ; return $ handlerNamespace . '\\' . trim ( $ command , '\\' ) . 'Handler' ; }
Map the command to a handler within a given root namespace .
52,941
public function hasRoleWithName ( string $ role ) : bool { $ this -> compileUserRoles ( ) ; return in_array ( $ role , $ this -> userRoles ) ; }
Check if the current user has a given role .
52,942
public function addRoleByName ( string $ roleName ) { if ( ! $ this -> user ) { throw new UserRequiredException ( ) ; } $ this -> compileUserRoles ( ) ; if ( $ this -> hasRoleWithName ( $ roleName ) ) { return ; } $ role = $ this -> roleProvider -> getRoleWithName ( $ roleName ) ; if ( ! $ role ) { throw new InvalidRoleException ( $ roleName ) ; } $ this -> user -> addRole ( $ role ) ; $ this -> userRoles [ ] = $ roleName ; $ this -> userProvider -> update ( $ this -> user ) ; }
Add a role for the current User
52,943
private function compileUserRoles ( ) { if ( $ this -> userRoles !== null ) { return ; } if ( ! $ this -> user ) { $ this -> userRoles = [ ] ; return ; } $ roleList = [ ] ; $ roleExpansion = [ ] ; foreach ( $ this -> roleProvider -> getAllRoles ( ) as $ role ) { $ roleList [ $ role -> getId ( ) ] = $ role ; } $ userRoles = $ this -> user -> getRoles ( ) ; if ( $ userRoles ) { foreach ( $ userRoles as $ userRole ) { $ roleExpansion [ ] = $ userRole -> getName ( ) ; $ parentRole = $ userRole -> getParent ( ) ; while ( $ parentRole ) { $ roleExpansion [ ] = $ parentRole -> getName ( ) ; $ parentRole = $ parentRole -> getParent ( ) ; } } } $ this -> userRoles = array_unique ( $ roleExpansion ) ; }
Flattens roles using the roleProvider for quick lookup .
52,944
public function getGroupPermissions ( $ resource ) : array { if ( $ resource instanceof ResourceInterface ) { return $ this -> groupPermissions -> getResourcePermissions ( $ resource ) ; } if ( \ is_string ( $ resource ) ) { return $ this -> groupPermissions -> getPermissions ( $ resource ) ; } throw new UnknownResourceTypeException ( \ get_class ( $ resource ) ) ; }
Permissions are an ability to do something with either a string or ResourceInterface as the subject . Some permissions are attributed to roles as defined by your role provider . This method checks to see if the set of roles associated to your user grants access to a specific verb - actions on a resource .
52,945
public function isAllowedUser ( $ resource , string $ action ) : bool { $ permission = $ this -> getUserPermission ( $ resource ) ; return $ permission && $ permission -> can ( $ action ) ; }
Similar to isAllowed this method checks user - rules specifically . If there is no user in session and this method is called directly a UserRequiredException will be thrown .
52,946
public function listAllowedByClass ( $ resourceClass , string $ action = '' ) : array { $ permissions = $ this -> groupPermissions -> getResourcePermissionsByClass ( $ resourceClass ) ; $ permitted = [ ] ; foreach ( $ permissions as $ permission ) { if ( ! $ action || $ permission -> can ( $ action ) ) { $ permitted [ ] = $ permission -> getResourceId ( ) ; } } return array_unique ( $ permitted ) ; }
List allowed resource IDs by class
52,947
public function grantRoleAccess ( RoleInterface $ role , ResourceInterface $ resource , string $ action ) { $ resourcePermissions = $ this -> getGroupPermissions ( $ resource ) ; $ matchedPermission = null ; $ examinedRole = $ role ; while ( $ examinedRole ) { foreach ( $ resourcePermissions as $ permission ) { if ( $ role === $ permission -> getRole ( ) ) { $ matchedPermission = $ permission ; } if ( $ permission -> can ( $ action ) ) { throw new ExistingAccessException ( $ role , $ resource , $ action , $ permission -> getRole ( ) -> getName ( ) ) ; } } $ examinedRole = $ examinedRole -> getParent ( ) ; } if ( ! $ matchedPermission ) { $ newPermission = $ this -> groupPermissions -> create ( $ role , $ resource -> getClass ( ) , $ resource -> getId ( ) , [ $ action ] ) ; $ this -> groupPermissions -> save ( $ newPermission ) ; } else { $ matchedPermission -> addAction ( $ action ) ; $ this -> groupPermissions -> update ( $ matchedPermission ) ; } }
Give a role access to a specific resource
52,948
public function revokeUserAccess ( $ resource , string $ action ) { $ resourceRule = $ this -> getUserPermission ( $ resource ) ; if ( ! $ resourceRule ) { return ; } if ( $ resourceRule && ! ( $ resourceRule instanceof UserPermissionInterface ) ) { throw new PermissionExpectedException ( UserPermissionInterface :: class , \ get_class ( $ resourceRule ) ) ; } if ( $ resourceRule ) { if ( ! \ in_array ( $ action , $ resourceRule -> getActions ( ) , true ) ) { return ; } $ resourceRule -> removeAction ( $ action ) ; $ this -> userPermissions -> update ( $ resourceRule ) ; } }
Revoke access to a resource
52,949
public function authenticate ( string $ username , string $ password ) : User { $ auth = $ this -> authenticationProvider -> findByUsername ( $ username ) ; $ user = null ; if ( ! $ auth && filter_var ( $ username , FILTER_VALIDATE_EMAIL ) ) { if ( $ user = $ this -> userProvider -> findByEmail ( $ username ) ) { $ auth = $ this -> authenticationProvider -> findByUserId ( $ user -> getId ( ) ) ; } } if ( ! $ auth ) { throw new NoSuchUserException ( ) ; } if ( password_verify ( $ password , $ auth -> getHash ( ) ) ) { if ( ! $ user ) { $ user = $ this -> userProvider -> getUser ( $ auth -> getUserId ( ) ) ; } if ( $ user ) { $ this -> resetAuthenticationKey ( $ auth ) ; $ this -> setSessionCookies ( $ auth ) ; $ this -> setIdentity ( $ user ) ; if ( password_needs_rehash ( $ auth -> getHash ( ) , PASSWORD_DEFAULT ) ) { $ auth -> setHash ( password_hash ( $ password , PASSWORD_DEFAULT ) ) ; $ this -> authenticationProvider -> update ( $ auth ) ; } return $ user ; } else { throw new NoSuchUserException ( ) ; } } throw new BadPasswordException ( ) ; }
Passed in by a successful form submission should set proper auth cookies if the identity verifies . The login should work with both username and email address .
52,950
public function changeUsername ( User $ user , string $ newUsername ) : AuthenticationRecordInterface { $ auth = $ this -> authenticationProvider -> findByUserId ( $ user -> getId ( ) ) ; if ( ! $ auth ) { throw new NoSuchUserException ( ) ; } if ( $ otherAuth = $ this -> authenticationProvider -> findByUsername ( $ newUsername ) ) { if ( $ auth == $ otherAuth ) { return $ auth ; } else { throw new UsernameTakenException ( ) ; } } $ auth -> setUsername ( $ newUsername ) ; $ this -> authenticationProvider -> update ( $ auth ) ; return $ auth ; }
Change an auth record username given a user id and a new username . Note - in this case username is email .
52,951
private function setSessionCookies ( AuthenticationRecordInterface $ authentication ) { $ systemKey = new EncryptionKey ( $ this -> systemEncryptionKey ) ; $ sessionKey = new HiddenString ( $ authentication -> getSessionKey ( ) ) ; $ userKey = new EncryptionKey ( $ sessionKey ) ; $ hashCookieName = hash_hmac ( 'sha256' , $ sessionKey . $ authentication -> getUsername ( ) , $ systemKey ) ; $ userTuple = base64_encode ( Crypto :: encrypt ( new HiddenString ( $ authentication -> getUserId ( ) . ':' . $ hashCookieName ) , $ systemKey ) ) ; $ hashCookieContents = base64_encode ( Crypto :: encrypt ( new HiddenString ( time ( ) . ':' . $ authentication -> getUserId ( ) . ':' . $ authentication -> getUsername ( ) ) , $ userKey ) ) ; $ this -> setCookie ( self :: COOKIE_USER , $ userTuple ) ; $ this -> setCookie ( self :: COOKIE_HASH_PREFIX . $ hashCookieName , $ hashCookieContents ) ; $ this -> setCookie ( self :: COOKIE_VERIFY_A , hash_hmac ( 'sha256' , $ userTuple , $ systemKey ) ) ; $ this -> setCookie ( self :: COOKIE_VERIFY_B , hash_hmac ( 'sha256' , $ hashCookieContents , $ userKey ) ) ; }
Set the auth session cookies that can be used to regenerate the session on subsequent visits
52,952
private function setCookie ( string $ name , $ value ) { $ expiry = $ this -> transient ? 0 : ( time ( ) + 2629743 ) ; $ sessionParameters = session_get_cookie_params ( ) ; setcookie ( $ name , $ value , $ expiry , '/' , $ sessionParameters [ 'domain' ] , $ this -> secure , true ) ; }
Set a cookie with values defined by configuration
52,953
public function getIdentity ( ) { if ( $ this -> identity ) { return $ this -> identity ; } if ( ! isset ( $ _COOKIE [ self :: COOKIE_VERIFY_A ] , $ _COOKIE [ self :: COOKIE_VERIFY_B ] , $ _COOKIE [ self :: COOKIE_USER ] ) ) { return null ; } $ systemKey = new EncryptionKey ( $ this -> systemEncryptionKey ) ; $ verificationCookie = $ _COOKIE [ self :: COOKIE_VERIFY_A ] ; $ hashPass = hash_equals ( hash_hmac ( 'sha256' , $ _COOKIE [ self :: COOKIE_USER ] , $ systemKey ) , $ verificationCookie ) ; if ( ! $ hashPass ) { return null ; } try { $ userTuple = Crypto :: decrypt ( base64_decode ( $ _COOKIE [ self :: COOKIE_USER ] ) , $ systemKey ) ; if ( strpos ( $ userTuple , ':' ) === false ) { throw new \ Exception ( ) ; } @ list ( $ cookieUserId , $ hashCookieSuffix ) = @ explode ( ":" , $ userTuple , 2 ) ; if ( ! isset ( $ cookieUserId , $ hashCookieSuffix ) || ! is_numeric ( $ cookieUserId ) || ! trim ( $ hashCookieSuffix ) ) { throw new \ Exception ( ) ; } if ( ! ( $ auth = $ this -> authenticationProvider -> findByUserId ( $ cookieUserId ) ) ) { throw new \ Exception ( ) ; } $ hashCookieName = self :: COOKIE_HASH_PREFIX . $ hashCookieSuffix ; if ( ! isset ( $ _COOKIE [ $ hashCookieName ] ) ) { throw new \ Exception ( ) ; } $ userKey = new EncryptionKey ( new HiddenString ( $ auth -> getSessionKey ( ) ) ) ; $ hashPass = hash_equals ( hash_hmac ( 'sha256' , $ _COOKIE [ $ hashCookieName ] , $ userKey ) , $ _COOKIE [ self :: COOKIE_VERIFY_B ] ) ; if ( ! $ hashPass ) { throw new \ Exception ( ) ; } $ hashedCookieContents = Crypto :: decrypt ( base64_decode ( $ _COOKIE [ $ hashCookieName ] ) , $ userKey ) ; if ( ! substr_count ( $ hashedCookieContents , ':' ) === 2 ) { throw new \ Exception ( ) ; } list ( , $ hashedUserId , $ hashedUsername ) = explode ( ':' , $ hashedCookieContents ) ; if ( $ hashedUserId !== $ cookieUserId ) { throw new \ Exception ( ) ; } if ( $ hashedUsername !== $ auth -> getUsername ( ) ) { throw new \ Exception ( ) ; } $ this -> purgeHashCookies ( $ hashCookieName ) ; $ user = $ this -> userProvider -> getUser ( $ auth -> getUserId ( ) ) ; if ( $ user ) { $ this -> setIdentity ( $ user ) ; return $ this -> identity ; } } catch ( \ Exception $ x ) { $ this -> purgeHashCookies ( ) ; } return null ; }
Rifle through 4 cookies ensuring that all details line up . If they do we accept that the cookies authenticate a specific user .
52,954
private function purgeHashCookies ( string $ skipCookie = null ) { $ sp = session_get_cookie_params ( ) ; foreach ( $ _COOKIE as $ cookieName => $ value ) { if ( $ cookieName !== $ skipCookie && strpos ( $ cookieName , self :: COOKIE_HASH_PREFIX ) !== false ) { setcookie ( $ cookieName , null , null , '/' , $ sp [ 'domain' ] , false , true ) ; } } }
Remove all hash cookies potentially saving one
52,955
public function resetPassword ( User $ user , string $ newPassword ) { $ this -> enforcePasswordStrength ( $ newPassword ) ; $ auth = $ this -> authenticationProvider -> findByUserId ( $ user -> getId ( ) ) ; if ( ! $ auth ) { throw new NoSuchUserException ( ) ; } $ hash = password_hash ( $ newPassword , PASSWORD_DEFAULT ) ; $ auth -> setHash ( $ hash ) ; $ this -> resetAuthenticationKey ( $ auth ) ; $ this -> authenticationProvider -> update ( $ auth ) ; }
Reset this user s password
52,956
public function verifyPassword ( User $ user , string $ password ) : bool { $ this -> enforcePasswordStrength ( $ password ) ; $ auth = $ this -> authenticationProvider -> findByUserId ( $ user -> getId ( ) ) ; if ( ! $ auth ) { throw new NoSuchUserException ( ) ; } return password_verify ( $ password , $ auth -> getHash ( ) ) ; }
Validate user password
52,957
public function create ( User $ user , string $ username , string $ password ) : AuthenticationRecordInterface { $ this -> enforcePasswordStrength ( $ password ) ; $ auth = $ this -> registerAuthenticationRecord ( $ user , $ username , $ password ) ; $ this -> setSessionCookies ( $ auth ) ; $ this -> setIdentity ( $ user ) ; return $ auth ; }
Register a new user into the auth tables and log them in . Essentially calls registerAuthenticationRecord and then stores the necessary cookies and identity into the service .
52,958
public function registerAuthenticationRecord ( User $ user , string $ username , string $ password ) : AuthenticationRecordInterface { if ( ! $ user -> getId ( ) ) { throw new PersistedUserRequiredException ( "Your user must have an ID before you can create auth records with it" ) ; } if ( $ this -> authenticationProvider -> findByUsername ( $ username ) ) { throw new UsernameTakenException ( ) ; } if ( filter_var ( $ username , FILTER_VALIDATE_EMAIL ) ) { if ( $ user -> getEmail ( ) !== $ username ) { throw new MismatchedEmailsException ( ) ; } if ( $ emailUser = $ this -> userProvider -> findByEmail ( $ username ) ) { if ( $ emailUser !== $ user ) { throw new EmailUsernameTakenException ( ) ; } } } $ hash = password_hash ( $ password , PASSWORD_DEFAULT ) ; $ auth = $ this -> authenticationProvider -> create ( $ user -> getId ( ) , $ username , $ hash , KeyFactory :: generateEncryptionKey ( ) -> getRawKeyMaterial ( ) ) ; $ this -> authenticationProvider -> save ( $ auth ) ; return $ auth ; }
Very similar to create except that it won t log the user in . This was created to satisfy circumstances where you are creating users from an admin panel for example . This function is also used by create .
52,959
private function resetAuthenticationKey ( AuthenticationRecordInterface $ auth ) : AuthenticationRecordInterface { $ key = KeyFactory :: generateEncryptionKey ( ) ; $ auth -> setSessionKey ( $ key -> getRawKeyMaterial ( ) ) ; $ this -> authenticationProvider -> update ( $ auth ) ; return $ auth ; }
Resalt a user s authentication table salt
52,960
public function clearIdentity ( ) { if ( $ user = $ this -> getIdentity ( ) ) { $ auth = $ this -> authenticationProvider -> findByUserId ( $ user -> getId ( ) ) ; $ this -> resetAuthenticationKey ( $ auth ) ; } $ sp = session_get_cookie_params ( ) ; foreach ( [ self :: COOKIE_USER , self :: COOKIE_VERIFY_A , self :: COOKIE_VERIFY_B ] as $ cookieName ) { setcookie ( $ cookieName , null , null , '/' , $ sp [ 'domain' ] , false , true ) ; } $ this -> identity = null ; }
Logout . Reset the user authentication key and delete all cookies .
52,961
public function createRecoveryToken ( User $ user ) : UserResetToken { if ( ! $ this -> resetTokenProvider ) { throw new PasswordResetProhibitedException ( 'The configuration currently prohibits the resetting of passwords!' ) ; } $ auth = $ this -> authenticationProvider -> findByUserId ( $ user -> getId ( ) ) ; if ( ! $ auth ) { throw new NoSuchUserException ( ) ; } if ( $ this -> resetTokenProvider -> getRequestCount ( $ auth ) > 5 ) { throw new TooManyRecoveryAttemptsException ( ) ; } $ this -> resetTokenProvider -> invalidateUnusedTokens ( $ auth ) ; $ remote = new RemoteAddress ( ) ; $ remote -> setUseProxy ( true ) ; $ token = new UserResetToken ( $ auth , $ remote -> getIpAddress ( ) ) ; $ this -> resetTokenProvider -> save ( $ token ) ; return $ token ; }
Forgot - password mechanisms are a potential back door ; but they re needed . This only takes care of hash generation .
52,962
public function checkEnvironments ( ) { if ( ! count ( $ this -> config [ 'environments' ] ) ) { return true ; } if ( in_array ( env ( 'APP_ENV' ) , $ this -> config [ 'environments' ] ) ) { return true ; } return false ; }
checkEnvironments function .
52,963
private function getLineInfo ( $ lines , $ line , $ i ) { $ currentLine = $ line + $ i ; $ index = $ currentLine - 1 ; if ( ! array_key_exists ( $ index , $ lines ) ) { return ; } return [ 'line' => '<span class="exception-currentline">' . $ currentLine . '.</span> ' . SyntaxHighlight :: process ( $ lines [ $ index ] ) , 'wrap_left' => $ i ? '' : '<span class="exception-line">' , 'wrap_right' => $ i ? '' : '</span>' , ] ; }
Gets information from the line
52,964
private function addExceptionToSleep ( array $ data ) { $ exceptionString = $ this -> createExceptionString ( $ data ) ; return Cache :: put ( $ exceptionString , $ exceptionString , $ this -> config [ 'sleep' ] ) ; }
addExceptionToSleep function .
52,965
public function url ( $ return = null , $ altRealm = null ) { $ useHttps = ! empty ( $ _SERVER [ 'HTTPS' ] ) || ( ! empty ( $ _SERVER [ 'HTTP_X_FORWARDED_PROTO' ] ) && $ _SERVER [ 'HTTP_X_FORWARDED_PROTO' ] == 'https' ) ; if ( ! is_null ( $ return ) ) { if ( ! $ this -> validateUrl ( $ return ) ) { throw new Exception ( 'The return URL must be a valid URL with a URI Scheme or http or https.' ) ; } } else { if ( $ altRealm == null ) $ return = ( $ useHttps ? 'https' : 'http' ) . '://' . $ _SERVER [ 'HTTP_HOST' ] . $ _SERVER [ 'SCRIPT_NAME' ] ; else $ return = $ altRealm . $ _SERVER [ 'SCRIPT_NAME' ] ; } $ params = array ( 'openid.ns' => 'http://specs.openid.net/auth/2.0' , 'openid.mode' => 'checkid_setup' , 'openid.return_to' => $ return , 'openid.realm' => $ altRealm != null ? $ altRealm : ( ( $ useHttps ? 'https' : 'http' ) . '://' . $ _SERVER [ 'HTTP_HOST' ] ) , 'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select' , 'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select' , ) ; return self :: $ openId . '?' . http_build_query ( $ params ) ; }
Build the Steam login URL
52,966
public function validate ( $ timeout = 30 ) { $ response = null ; try { $ params = array ( 'openid.assoc_handle' => $ _GET [ 'openid_assoc_handle' ] , 'openid.signed' => $ _GET [ 'openid_signed' ] , 'openid.sig' => $ _GET [ 'openid_sig' ] , 'openid.ns' => 'http://specs.openid.net/auth/2.0' , ) ; $ signed = explode ( ',' , $ _GET [ 'openid_signed' ] ) ; foreach ( $ signed as $ item ) { $ val = $ _GET [ 'openid_' . str_replace ( '.' , '_' , $ item ) ] ; $ params [ 'openid.' . $ item ] = get_magic_quotes_gpc ( ) ? stripslashes ( $ val ) : $ val ; } $ params [ 'openid.mode' ] = 'check_authentication' ; $ data = http_build_query ( $ params ) ; $ context = stream_context_create ( array ( 'http' => array ( 'method' => 'POST' , 'header' => "Accept-language: en\r\n" . "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen ( $ data ) . "\r\n" , 'content' => $ data , 'timeout' => $ timeout ) , ) ) ; $ result = file_get_contents ( self :: $ openId , false , $ context ) ; preg_match ( "#^https://steamcommunity.com/openid/id/([0-9]{17,25})#" , $ _GET [ 'openid_claimed_id' ] , $ matches ) ; $ steamID64 = is_numeric ( $ matches [ 1 ] ) ? $ matches [ 1 ] : 0 ; $ response = preg_match ( "#is_valid\s*:\s*true#i" , $ result ) == 1 ? $ steamID64 : null ; } catch ( Exception $ e ) { $ response = null ; } if ( is_null ( $ response ) ) { throw new Exception ( 'The Steam login request timed out or was invalid' ) ; } return $ response ; }
Validates a Steam login request and returns the users Steam Community ID
52,967
public function getRequestCount ( AuthenticationRecordInterface $ authenticationRecord ) : int { $ fiveMinutesAgo = new \ DateTime ( 'now' , new \ DateTimeZone ( 'UTC' ) ) ; $ fiveMinutesAgo -> modify ( '-5 minutes' ) ; $ query = $ this -> getRepository ( ) -> createQueryBuilder ( 'r' ) -> select ( 'COUNT(r.id) AS total' ) -> where ( 'r.authentication = :authentication' ) -> andWhere ( 'r.request_time > :since' ) -> setParameter ( 'authentication' , $ authenticationRecord ) -> setParameter ( 'since' , $ fiveMinutesAgo ) -> getQuery ( ) ; return $ query -> getSingleScalarResult ( ) ; }
Get the count of requests in the last 5 minutes
52,968
public function invalidateUnusedTokens ( AuthenticationRecordInterface $ authenticationRecord ) { $ query = $ this -> getRepository ( ) -> createQueryBuilder ( 'r' ) -> update ( ) -> set ( 'r.status' , UserResetTokenInterface :: STATUS_INVALID ) -> where ( 'r.authentication = :authentication' ) -> andWhere ( 'r.status = :status_unused' ) -> setParameters ( [ 'authentication' => $ authenticationRecord , 'status_unused' => UserResetTokenInterface :: STATUS_UNUSED , ] ) -> getQuery ( ) ; $ query -> execute ( ) ; }
Modify previously created tokens that are not used so that their status is invalid . There should only be one valid token at any time .
52,969
public function dump ( \ Twig_Environment $ env , $ context , ... $ vars ) { if ( ! $ env -> isDebug ( ) ) { return null ; } if ( ! $ vars ) { $ vars = [ ] ; foreach ( $ context as $ key => $ value ) { if ( ! $ value instanceof \ Twig_Template ) { $ vars [ $ key ] = $ value ; } } } ob_start ( ) ; VarDumper :: dump ( $ vars ) ; echo ob_get_clean ( ) ; }
Override dump version of Symfony s VarDumper component
52,970
protected function tokenizeGlobalExclusions ( $ html ) { $ html = ( string ) $ html ; $ _this = $ this ; $ global_exclusions = [ '/\<noscript(?:\s[^>]*)?\>.*?\<\/noscript\>/uis' , ] ; $ html = preg_replace_callback ( $ global_exclusions , function ( $ m ) use ( $ _this ) { $ _this -> current_global_exclusion_tokens [ ] = $ m [ 0 ] ; return '<htmlc-gxt-' . ( count ( $ _this -> current_global_exclusion_tokens ) - 1 ) . ' />' ; } , $ html ) ; return $ html ; }
Global exclusion tokenizer .
52,971
protected function restoreGlobalExclusions ( $ html ) { $ html = ( string ) $ html ; if ( ! $ this -> current_global_exclusion_tokens ) { return $ html ; } if ( mb_strpos ( $ html , '<htmlc-gxt-' ) === false ) { return $ html ; } foreach ( array_reverse ( $ this -> current_global_exclusion_tokens , true ) as $ _token => $ _value ) { $ html = str_replace ( '<htmlc-gxt-' . $ _token . ' />' , $ _value , $ html ) ; } $ this -> current_global_exclusion_tokens = [ ] ; return $ html ; }
Restore global exclusions .
52,972
protected function getLinkCssHref ( array $ tag_frag , $ test_for_css = true ) { if ( $ test_for_css && ! $ this -> isLinkTagFragCss ( $ tag_frag ) ) { return '' ; } if ( preg_match ( '/\shref\s*\=\s*(["\'])(?P<value>.+?)\\1/ui' , $ tag_frag [ 'link_self_closing_tag' ] , $ _m ) ) { return trim ( $ this -> nUrlAmps ( $ _m [ 'value' ] ) ) ; } return '' ; }
Get a CSS link href value from a tag fragment .
52,973
protected function getLinkCssMedia ( array $ tag_frag , $ test_for_css = true ) { if ( $ test_for_css && ! $ this -> isLinkTagFragCss ( $ tag_frag ) ) { return '' ; } if ( preg_match ( '/\smedia\s*\=\s*(["\'])(?P<value>.+?)\\1/ui' , $ tag_frag [ 'link_self_closing_tag' ] , $ _m ) ) { return trim ( mb_strtolower ( $ _m [ 'value' ] ) ) ; } return '' ; }
Get a CSS link media rule from a tag fragment .
52,974
protected function getStyleCssMedia ( array $ tag_frag , $ test_for_css = true ) { if ( $ test_for_css && ! $ this -> isStyleTagFragCss ( $ tag_frag ) ) { return '' ; } if ( preg_match ( '/\smedia\s*\=\s*(["\'])(?P<value>.+?)\\1/ui' , $ tag_frag [ 'style_open_tag' ] , $ _m ) ) { return trim ( mb_strtolower ( $ _m [ 'value' ] ) ) ; } return '' ; }
Get a CSS style media rule from a tag fragment .
52,975
protected function getStyleCss ( array $ tag_frag , $ test_for_css = true ) { if ( empty ( $ tag_frag [ 'style_css' ] ) ) { return '' ; } if ( $ test_for_css && ! $ this -> isStyleTagFragCss ( $ tag_frag ) ) { return '' ; } return trim ( $ tag_frag [ 'style_css' ] ) ; }
Get style CSS from a CSS tag fragment .
52,976
protected function stripExistingCssCharsets ( $ css ) { if ( ! ( $ css = ( string ) $ css ) ) { return $ css ; } $ css = preg_replace ( '/@(?:\-(?:' . $ this -> regex_vendor_css_prefixes . ')\-)?charset(?:\s+[^;]*?)?;/ui' , '' , $ css ) ; return $ css = $ css ? trim ( $ css ) : $ css ; }
Strip existing charset rules from CSS code .
52,977
protected function resolveCssRelatives ( $ css , $ base = '' ) { if ( ! ( $ css = ( string ) $ css ) ) { return $ css ; } $ this -> current_base = $ base ; $ import_without_url_regex = '/(?P<import>@(?:\-(?:' . $ this -> regex_vendor_css_prefixes . ')\-)?import\s*)(?P<open_encap>["\'])(?P<url>.+?)(?P<close_encap>\\2)/ui' ; $ any_url_regex = '/(?P<url_>url\s*)(?P<open_bracket>\(\s*)(?P<open_encap>["\']?)(?P<url>.+?)(?P<close_encap>\\3)(?P<close_bracket>\s*\))/ui' ; $ css = preg_replace_callback ( $ import_without_url_regex , [ $ this , 'resolveCssRelativesImportCb' ] , $ css ) ; $ css = preg_replace_callback ( $ any_url_regex , [ $ this , 'resolveCssRelativesUrlCb' ] , $ css ) ; return $ css ; }
Resolve relative URLs in CSS code .
52,978
protected function forceAbsRelativePathsInCss ( $ css ) { if ( ! ( $ css = ( string ) $ css ) ) { return $ css ; } $ regex = '/(?:[a-z0-9]+\:)?\/\/' . $ this -> pregQuote ( $ this -> currentUrlHost ( ) ) . '\//ui' ; return preg_replace ( $ regex , '/' , $ css ) ; }
Force absolute relative paths in CSS .
52,979
protected function maybeFilterCssUrls ( $ css ) { if ( ! ( $ css = ( string ) $ css ) ) { return $ css ; } if ( ! $ this -> hook_api -> hasFilter ( 'css_url()' ) ) { return $ css ; } $ import_without_url_regex = '/(?P<import>@(?:\-(?:' . $ this -> regex_vendor_css_prefixes . ')\-)?import\s*)(?P<open_encap>["\'])(?P<url>.+?)(?P<close_encap>\\2)/ui' ; $ any_url_regex = '/(?P<url_>url\s*)(?P<open_bracket>\(\s*)(?P<open_encap>["\']?)(?P<url>.+?)(?P<close_encap>\\3)(?P<close_bracket>\s*\))/ui' ; $ css = preg_replace_callback ( $ import_without_url_regex , [ $ this , 'filterCssUrlImportCb' ] , $ css ) ; $ css = preg_replace_callback ( $ any_url_regex , [ $ this , 'filterCssUrlCb' ] , $ css ) ; return $ css ; }
Maybe filter URLs in CSS code .
52,980
protected function filterCssUrlCb ( array $ m ) { if ( mb_stripos ( $ m [ 'url' ] , 'data:' ) === 0 ) { return $ m [ 0 ] ; } return $ m [ 'url_' ] . $ m [ 'open_bracket' ] . $ m [ 'open_encap' ] . $ this -> hook_api -> applyFilters ( 'css_url()' , $ m [ 'url' ] ) . $ m [ 'close_encap' ] . $ m [ 'close_bracket' ] ; }
Callback handler for CSS URL filters .
52,981
protected function maybeCompressCombineHeadJs ( $ html ) { if ( ( $ benchmark = ! empty ( $ this -> options [ 'benchmark' ] ) && $ this -> options [ 'benchmark' ] === 'details' ) ) { $ time = microtime ( true ) ; } $ html = ( string ) $ html ; if ( isset ( $ this -> options [ 'compress_combine_head_js' ] ) ) { if ( ! $ this -> options [ 'compress_combine_head_js' ] ) { $ disabled = true ; } } if ( ! $ html || ! empty ( $ disabled ) ) { goto finale ; } if ( ( $ head_frag = $ this -> getHeadFrag ( $ html ) ) ) { if ( ( $ js_tag_frags = $ this -> getJsTagFrags ( $ head_frag ) ) && ( $ js_parts = $ this -> compileJsTagFragsIntoParts ( $ js_tag_frags , 'head' ) ) ) { $ js_tag_frags_all_compiled = $ this -> compileKeyElementsDeep ( $ js_tag_frags , 'all' ) ; $ html = $ this -> replaceOnce ( $ head_frag [ 'all' ] , '%%htmlc-head%%' , $ html ) ; $ cleaned_head_contents = $ this -> replaceOnce ( $ js_tag_frags_all_compiled , '' , $ head_frag [ 'contents' ] ) ; $ cleaned_head_contents = $ this -> cleanupSelfClosingHtmlTagLines ( $ cleaned_head_contents ) ; $ compressed_js_tags = [ ] ; foreach ( $ js_parts as $ _js_part ) { if ( isset ( $ _js_part [ 'exclude_frag' ] , $ js_tag_frags [ $ _js_part [ 'exclude_frag' ] ] [ 'all' ] ) ) { $ compressed_js_tags [ ] = $ js_tag_frags [ $ _js_part [ 'exclude_frag' ] ] [ 'all' ] ; } else { $ compressed_js_tags [ ] = $ _js_part [ 'tag' ] ; } } $ compressed_js_tags = implode ( "\n" , $ compressed_js_tags ) ; $ compressed_head_parts = [ $ head_frag [ 'open_tag' ] , $ cleaned_head_contents , $ compressed_js_tags , $ head_frag [ 'closing_tag' ] ] ; $ html = $ this -> replaceOnce ( '%%htmlc-head%%' , implode ( "\n" , $ compressed_head_parts ) , $ html ) ; if ( $ benchmark ) { $ this -> benchmark -> addData ( __FUNCTION__ , compact ( 'head_frag' , 'js_tag_frags' , 'js_parts' , 'cleaned_head_contents' , 'compressed_js_tags' , 'compressed_head_parts' ) ) ; } } } finale : if ( $ html ) { $ html = trim ( $ html ) ; } if ( $ benchmark && ! empty ( $ time ) && $ html && empty ( $ disabled ) ) { $ this -> benchmark -> addTime ( __FUNCTION__ , $ time , sprintf ( 'compressing/combining head JS in checksum: `%1$s`' , md5 ( $ html ) ) ) ; } return $ html ; }
Handles possible compression of head JS .
52,982
protected function maybeCompressCombineFooterJs ( $ html ) { if ( ( $ benchmark = ! empty ( $ this -> options [ 'benchmark' ] ) && $ this -> options [ 'benchmark' ] === 'details' ) ) { $ time = microtime ( true ) ; } $ html = ( string ) $ html ; if ( isset ( $ this -> options [ 'compress_combine_footer_js' ] ) ) { if ( ! $ this -> options [ 'compress_combine_footer_js' ] ) { $ disabled = true ; } } if ( ! $ html || ! empty ( $ disabled ) ) { goto finale ; } if ( ( $ footer_scripts_frag = $ this -> getFooterScriptsFrag ( $ html ) ) ) { if ( ( $ js_tag_frags = $ this -> getJsTagFrags ( $ footer_scripts_frag ) ) && ( $ js_parts = $ this -> compileJsTagFragsIntoParts ( $ js_tag_frags , 'foot' ) ) ) { $ js_tag_frags_all_compiled = $ this -> compileKeyElementsDeep ( $ js_tag_frags , 'all' ) ; $ html = $ this -> replaceOnce ( $ footer_scripts_frag [ 'all' ] , '%%htmlc-footer-scripts%%' , $ html ) ; $ cleaned_footer_scripts = $ this -> replaceOnce ( $ js_tag_frags_all_compiled , '' , $ footer_scripts_frag [ 'contents' ] ) ; $ compressed_js_tags = [ ] ; foreach ( $ js_parts as $ _js_part ) { if ( isset ( $ _js_part [ 'exclude_frag' ] , $ js_tag_frags [ $ _js_part [ 'exclude_frag' ] ] [ 'all' ] ) ) { $ compressed_js_tags [ ] = $ js_tag_frags [ $ _js_part [ 'exclude_frag' ] ] [ 'all' ] ; } else { $ compressed_js_tags [ ] = $ _js_part [ 'tag' ] ; } } $ compressed_js_tags = implode ( "\n" , $ compressed_js_tags ) ; $ compressed_footer_script_parts = [ $ footer_scripts_frag [ 'open_tag' ] , $ cleaned_footer_scripts , $ compressed_js_tags , $ footer_scripts_frag [ 'closing_tag' ] ] ; $ html = $ this -> replaceOnce ( '%%htmlc-footer-scripts%%' , implode ( "\n" , $ compressed_footer_script_parts ) , $ html ) ; if ( $ benchmark ) { $ this -> benchmark -> addData ( __FUNCTION__ , compact ( 'footer_scripts_frag' , 'js_tag_frags' , 'js_parts' , 'cleaned_footer_scripts' , 'compressed_js_tags' , 'compressed_footer_script_parts' ) ) ; } } } finale : if ( $ html ) { $ html = trim ( $ html ) ; } if ( $ benchmark && ! empty ( $ time ) && $ html && empty ( $ disabled ) ) { $ this -> benchmark -> addTime ( __FUNCTION__ , $ time , sprintf ( 'compressing/combining footer JS in checksum: `%1$s`' , md5 ( $ html ) ) ) ; } return $ html ; }
Handles possible compression of footer JS .
52,983
protected function isScriptTagFragJson ( array $ tag_frag ) { if ( empty ( $ tag_frag [ 'script_open_tag' ] ) || empty ( $ tag_frag [ 'script_closing_tag' ] ) ) { return false ; } $ type = $ language = '' ; if ( mb_stripos ( $ tag_frag [ 'script_open_tag' ] , 'type' ) !== 0 ) { if ( preg_match ( '/\stype\s*\=\s*(["\'])(?P<value>.+?)\\1/ui' , $ tag_frag [ 'script_open_tag' ] , $ _m ) ) { $ type = $ _m [ 'value' ] ; } } if ( mb_stripos ( $ tag_frag [ 'script_open_tag' ] , 'language' ) !== 0 ) { if ( preg_match ( '/\slanguage\s*\=\s*(["\'])(?P<value>.+?)\\1/ui' , $ tag_frag [ 'script_open_tag' ] , $ _m ) ) { $ language = $ _m [ 'value' ] ; } } if ( ( $ type && mb_stripos ( $ type , 'javascript' ) === false ) || ( $ language && mb_stripos ( $ language , 'javascript' ) === false ) ) { if ( $ type && mb_stripos ( $ type , 'json' ) !== false ) { return true ; } if ( $ language && mb_stripos ( $ language , 'json' ) !== false ) { return true ; } } return false ; }
Test a script tag fragment to see if it s JSON .
52,984
protected function getScriptJsSrc ( array $ tag_frag , $ test_for_js = true ) { if ( $ test_for_js && ! $ this -> isScriptTagFragJs ( $ tag_frag ) ) { return '' ; } if ( preg_match ( '/\ssrc\s*\=\s*(["\'])(?P<value>.+?)\\1/ui' , $ tag_frag [ 'script_open_tag' ] , $ _m ) ) { return trim ( $ this -> nUrlAmps ( $ _m [ 'value' ] ) ) ; } return '' ; }
Get script JS src value from a JS tag fragment .
52,985
protected function getScriptJsAsync ( array $ tag_frag , $ test_for_js = true ) { if ( $ test_for_js && ! $ this -> isScriptTagFragJs ( $ tag_frag ) ) { return '' ; } if ( preg_match ( '/\s(?:async|defer)(?:\>|\s+[^=]|\s*\=\s*(["\'])(?:1|on|yes|true|async|defer)\\1)/ui' , $ tag_frag [ 'script_open_tag' ] , $ _m ) ) { return 'async' ; } return '' ; }
Get script JS async|defer value from a JS tag fragment .
52,986
protected function getScriptJs ( array $ tag_frag , $ test_for_js = true ) { if ( empty ( $ tag_frag [ 'script_js' ] ) ) { return '' ; } if ( $ test_for_js && ! $ this -> isScriptTagFragJs ( $ tag_frag ) ) { return '' ; } return trim ( $ tag_frag [ 'script_js' ] ) ; }
Get script JS from a JS tag fragment .
52,987
protected function getScriptJson ( array $ tag_frag , $ test_for_json = true ) { if ( empty ( $ tag_frag [ 'script_json' ] ) ) { return '' ; } if ( $ test_for_json && ! $ this -> isScriptTagFragJson ( $ tag_frag ) ) { return '' ; } return trim ( $ tag_frag [ 'script_json' ] ) ; }
Get script JSON from a JS tag fragment .
52,988
protected function getHtmlFrag ( $ html ) { if ( ! ( $ html = ( string ) $ html ) ) { return [ ] ; } if ( preg_match ( '/(?P<all>(?P<open_tag>\<html(?:\s+[^>]*?)?\>)(?P<contents>.*?)(?P<closing_tag>\<\/html\>))/uis' , $ html , $ html_frag ) ) { return $ this -> removeNumericKeysDeep ( $ html_frag ) ; } return [ ] ; }
Build an HTML fragment from HTML source code .
52,989
protected function getHeadFrag ( $ html ) { if ( ! ( $ html = ( string ) $ html ) ) { return [ ] ; } if ( preg_match ( '/(?P<all>(?P<open_tag>\<head(?:\s+[^>]*?)?\>)(?P<contents>.*?)(?P<closing_tag>\<\/head\>))/uis' , $ html , $ head_frag ) ) { return $ this -> removeNumericKeysDeep ( $ head_frag ) ; } return [ ] ; }
Build a head fragment from HTML source code .
52,990
protected function getFooterScriptsFrag ( $ html ) { if ( ! ( $ html = ( string ) $ html ) ) { return [ ] ; } if ( preg_match ( '/(?P<all>(?P<open_tag>\<\!\-\-\s*footer[\s_\-]+scripts\s*\-\-\>)(?P<contents>.*?)(?P<closing_tag>(?P=open_tag)))/uis' , $ html , $ head_frag ) ) { return $ this -> removeNumericKeysDeep ( $ head_frag ) ; } return [ ] ; }
Build a footer scripts fragment from HTML source code .
52,991
protected function getTagFragsChecksum ( array $ tag_frags ) { foreach ( $ tag_frags as & $ _frag ) { $ _frag = $ _frag [ 'exclude' ] ? [ 'exclude' => true ] : $ _frag ; } return md5 ( serialize ( $ tag_frags ) ) ; }
Construct a checksum for an array of tag fragments .
52,992
protected function maybeCompressHtmlCode ( $ html ) { if ( ( $ benchmark = ! empty ( $ this -> options [ 'benchmark' ] ) && $ this -> options [ 'benchmark' ] === 'details' ) ) { $ time = microtime ( true ) ; } $ html = ( string ) $ html ; if ( isset ( $ this -> options [ 'compress_html_code' ] ) ) { if ( ! $ this -> options [ 'compress_html_code' ] ) { $ disabled = true ; } } if ( ! $ html || ! empty ( $ disabled ) ) { goto finale ; } if ( ( $ compressed_html = $ this -> compressHtml ( $ html ) ) ) { $ html = $ compressed_html ; } finale : if ( $ html ) { $ html = trim ( $ html ) ; } if ( $ benchmark && ! empty ( $ time ) && $ html && empty ( $ disabled ) ) { $ this -> benchmark -> addTime ( __FUNCTION__ , $ time , sprintf ( 'compressing HTML w/ checksum: `%1$s`' , md5 ( $ html ) ) ) ; } return $ html ; }
Maybe compress HTML code .
52,993
protected function maybeCompressCssCode ( $ css ) { if ( ( $ benchmark = ! empty ( $ this -> options [ 'benchmark' ] ) && $ this -> options [ 'benchmark' ] === 'details' ) ) { $ time = microtime ( true ) ; } $ css = ( string ) $ css ; if ( isset ( $ this -> options [ 'compress_css_code' ] ) ) { if ( ! $ this -> options [ 'compress_css_code' ] ) { $ disabled = true ; } } if ( ! $ css || ! empty ( $ disabled ) ) { goto finale ; } if ( strlen ( $ css ) > 1000000 ) { goto finale ; } try { if ( ! ( $ compressed_css = \ WebSharks \ CssMinifier \ Core :: compress ( $ css ) ) ) { trigger_error ( 'CSS compression failure.' , E_USER_NOTICE ) ; } else { $ css = $ this -> stripUtf8Bom ( $ compressed_css ) ; } } catch ( \ Exception $ exception ) { trigger_error ( $ exception -> getMessage ( ) , E_USER_NOTICE ) ; } finale : if ( $ css ) { $ css = trim ( $ css ) ; } if ( $ benchmark && ! empty ( $ time ) && $ css && empty ( $ disabled ) ) { $ this -> benchmark -> addTime ( __FUNCTION__ , $ time , sprintf ( 'compressing CSS w/ checksum: `%1$s`' , md5 ( $ css ) ) ) ; } return $ css ; }
Maybe compress CSS code .
52,994
protected function maybeCompressJsCode ( $ js ) { if ( ( $ benchmark = ! empty ( $ this -> options [ 'benchmark' ] ) && $ this -> options [ 'benchmark' ] === 'details' ) ) { $ time = microtime ( true ) ; } $ js = ( string ) $ js ; if ( isset ( $ this -> options [ 'compress_js_code' ] ) ) { if ( ! $ this -> options [ 'compress_js_code' ] ) { $ disabled = true ; } } if ( ! $ js || ! empty ( $ disabled ) ) { goto finale ; } if ( strlen ( $ js ) > 1000000 ) { goto finale ; } try { if ( ! ( $ compressed_js = \ WebSharks \ JsMinifier \ Core :: compress ( $ js ) ) ) { trigger_error ( 'JS compression failure.' , E_USER_NOTICE ) ; } else { $ js = $ compressed_js ; } } catch ( \ Exception $ exception ) { trigger_error ( $ exception -> getMessage ( ) , E_USER_NOTICE ) ; } finale : if ( $ js ) { $ js = trim ( $ js ) ; } if ( $ benchmark && ! empty ( $ time ) && $ js && empty ( $ disabled ) ) { $ this -> benchmark -> addTime ( __FUNCTION__ , $ time , sprintf ( 'compressing JS w/ checksum: `%1$s`' , md5 ( $ js ) ) ) ; } return $ js ; }
Maybe compress JS code .
52,995
protected function maybeCompressInlineJsCode ( $ html ) { if ( ( $ benchmark = ! empty ( $ this -> options [ 'benchmark' ] ) && $ this -> options [ 'benchmark' ] === 'details' ) ) { $ time = microtime ( true ) ; } $ html = ( string ) $ html ; if ( isset ( $ this -> options [ 'compress_js_code' ] ) ) { if ( ! $ this -> options [ 'compress_js_code' ] ) { $ disabled = true ; } } if ( isset ( $ this -> options [ 'compress_inline_js_code' ] ) ) { if ( ! $ this -> options [ 'compress_inline_js_code' ] ) { $ disabled = true ; } } if ( ! $ html || ! empty ( $ disabled ) ) { goto finale ; } if ( ( $ html_frag = $ this -> getHtmlFrag ( $ html ) ) && ( $ js_tag_frags = $ this -> getJsTagFrags ( $ html_frag ) ) ) { foreach ( $ js_tag_frags as $ _js_tag_frag_key => $ _js_tag_frag ) { if ( ! $ _js_tag_frag [ 'exclude' ] && $ _js_tag_frag [ 'script_js' ] ) { $ js_tag_frags_script_js_parts [ ] = $ _js_tag_frag [ 'all' ] ; $ js_tag_frags_script_js_part_placeholders [ ] = '%%htmlc-' . $ _js_tag_frag_key . '%%' ; $ js_tag_frags_script_js_part_placeholder_key_replacements [ ] = $ _js_tag_frag_key ; } } if ( isset ( $ js_tag_frags_script_js_parts , $ js_tag_frags_script_js_part_placeholders , $ js_tag_frags_script_js_part_placeholder_key_replacements ) ) { $ html = $ this -> replaceOnce ( $ js_tag_frags_script_js_parts , $ js_tag_frags_script_js_part_placeholders , $ html ) ; foreach ( $ js_tag_frags_script_js_part_placeholder_key_replacements as & $ _js_tag_frag_key_replacement ) { $ _js_tag_frag = $ js_tag_frags [ $ _js_tag_frag_key_replacement ] ; $ _js_tag_frag_key_replacement = $ _js_tag_frag [ 'if_open_tag' ] ; $ _js_tag_frag_key_replacement .= $ _js_tag_frag [ 'script_open_tag' ] ; $ _js_tag_frag_key_replacement .= $ this -> compressInlineJsCode ( $ _js_tag_frag [ 'script_js' ] ) ; $ _js_tag_frag_key_replacement .= $ _js_tag_frag [ 'script_closing_tag' ] ; $ _js_tag_frag_key_replacement .= $ _js_tag_frag [ 'if_closing_tag' ] ; } $ html = $ this -> replaceOnce ( $ js_tag_frags_script_js_part_placeholders , $ js_tag_frags_script_js_part_placeholder_key_replacements , $ html ) ; if ( $ benchmark ) { $ this -> benchmark -> addData ( __FUNCTION__ , compact ( 'js_tag_frags' , 'js_tag_frags_script_js_parts' , 'js_tag_frags_script_js_part_placeholders' , 'js_tag_frags_script_js_part_placeholder_key_replacements' ) ) ; } } } finale : if ( $ html ) { $ html = trim ( $ html ) ; } if ( $ benchmark && ! empty ( $ time ) && $ html && empty ( $ disabled ) ) { $ this -> benchmark -> addTime ( __FUNCTION__ , $ time , sprintf ( 'compressing inline JS in checksum: `%1$s`' , md5 ( $ html ) ) ) ; } return $ html ; }
Maybe compress inline JS code within the HTML source .
52,996
protected function compressInlineJsCode ( $ js ) { if ( ! ( $ js = ( string ) $ js ) ) { return $ js ; } if ( ( $ compressed_js = \ WebSharks \ JsMinifier \ Core :: compress ( $ js ) ) ) { return '/*<![CDATA[*/' . $ compressed_js . '/*]]>*/' ; } return $ js ; }
Helper function ; compress inline JS code .
52,997
protected function maybeCompressInlineJsonCode ( $ html ) { if ( ( $ benchmark = ! empty ( $ this -> options [ 'benchmark' ] ) && $ this -> options [ 'benchmark' ] === 'details' ) ) { $ time = microtime ( true ) ; } $ html = ( string ) $ html ; if ( isset ( $ this -> options [ 'compress_js_code' ] ) ) { if ( ! $ this -> options [ 'compress_js_code' ] ) { $ disabled = true ; } } if ( isset ( $ this -> options [ 'compress_inline_js_code' ] ) ) { if ( ! $ this -> options [ 'compress_inline_js_code' ] ) { $ disabled = true ; } } if ( ! $ html || ! empty ( $ disabled ) ) { goto finale ; } if ( ( $ html_frag = $ this -> getHtmlFrag ( $ html ) ) && ( $ js_tag_frags = $ this -> getJsTagFrags ( $ html_frag ) ) ) { foreach ( $ js_tag_frags as $ _js_tag_frag_key => $ _js_tag_frag ) { if ( ! $ _js_tag_frag [ 'exclude' ] && $ _js_tag_frag [ 'script_json' ] ) { $ js_tag_frags_script_json_parts [ ] = $ _js_tag_frag [ 'all' ] ; $ js_tag_frags_script_json_part_placeholders [ ] = '%%htmlc-' . $ _js_tag_frag_key . '%%' ; $ js_tag_frags_script_json_part_placeholder_key_replacements [ ] = $ _js_tag_frag_key ; } } if ( isset ( $ js_tag_frags_script_json_parts , $ js_tag_frags_script_json_part_placeholders , $ js_tag_frags_script_json_part_placeholder_key_replacements ) ) { $ html = $ this -> replaceOnce ( $ js_tag_frags_script_json_parts , $ js_tag_frags_script_json_part_placeholders , $ html ) ; foreach ( $ js_tag_frags_script_json_part_placeholder_key_replacements as & $ _json_tag_frag_key_replacement ) { $ _js_tag_frag = $ js_tag_frags [ $ _json_tag_frag_key_replacement ] ; $ _json_tag_frag_key_replacement = $ _js_tag_frag [ 'if_open_tag' ] ; $ _json_tag_frag_key_replacement .= $ _js_tag_frag [ 'script_open_tag' ] ; $ _json_tag_frag_key_replacement .= $ this -> compressInlineJsonCode ( $ _js_tag_frag [ 'script_json' ] ) ; $ _json_tag_frag_key_replacement .= $ _js_tag_frag [ 'script_closing_tag' ] ; $ _json_tag_frag_key_replacement .= $ _js_tag_frag [ 'if_closing_tag' ] ; } $ html = $ this -> replaceOnce ( $ js_tag_frags_script_json_part_placeholders , $ js_tag_frags_script_json_part_placeholder_key_replacements , $ html ) ; if ( $ benchmark ) { $ this -> benchmark -> addData ( __FUNCTION__ , compact ( 'js_tag_frags' , 'js_tag_frags_script_json_parts' , 'js_tag_frags_script_json_part_placeholders' , 'js_tag_frags_script_json_part_placeholder_key_replacements' ) ) ; } } } finale : if ( $ html ) { $ html = trim ( $ html ) ; } if ( $ benchmark && ! empty ( $ time ) && $ html && empty ( $ disabled ) ) { $ this -> benchmark -> addTime ( __FUNCTION__ , $ time , sprintf ( 'compressing inline JSON in checksum: `%1$s`' , md5 ( $ html ) ) ) ; } return $ html ; }
Maybe compress inline JSON code within the HTML source .
52,998
protected function compressInlineJsonCode ( $ json ) { if ( ! ( $ json = ( string ) $ json ) ) { return $ json ; } if ( ( $ compressed_json = \ WebSharks \ JsMinifier \ Core :: compress ( $ json ) ) ) { return '/*<![CDATA[*/' . $ compressed_json . '/*]]>*/' ; } return $ json ; }
Helper function ; compress inline JSON code .
52,999
protected function pregQuote ( $ value , $ delimiter = '/' ) { if ( is_array ( $ value ) || is_object ( $ value ) ) { foreach ( $ value as & $ _value ) { $ _value = $ this -> pregQuote ( $ _value , $ delimiter ) ; } return $ value ; } return preg_quote ( ( string ) $ value , ( string ) $ delimiter ) ; }
Escapes regex special chars deeply .