idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
26,000
public static function ip ( ) { if ( getenv ( "HTTP_CLIENT_IP" ) ) { $ ip = getenv ( "HTTP_CLIENT_IP" ) ; } elseif ( getenv ( "HTTP_X_FORWARDED_FOR" ) ) { $ ip = getenv ( "HTTP_X_FORWARDED_FOR" ) ; if ( strstr ( $ ip , ',' ) ) { $ tmp = explode ( ',' , $ ip ) ; $ ip = trim ( $ tmp [ 0 ] ) ; } } else { $ ip = getenv ( "REMOTE_ADDR" ) ; } return $ ip ; }
return the user ip
26,001
protected function registerDebugger ( ) { if ( $ this -> config [ 'debugger' ] ) { $ builder = $ this -> getContainerBuilder ( ) ; if ( ! $ builder -> hasDefinition ( self :: TRACY_PANEL ) ) { $ builder -> addDefinition ( self :: TRACY_PANEL ) -> setClass ( LoadPanel :: class ) ; } $ builder -> getDefinition ( self :: TRACY_PANEL ) -> addSetup ( 'addCompiler' , [ $ this -> name , "@sw2load.compiler.{$this->name}" ] ) ; } }
Add debug panel if needed .
26,002
public function afterCompile ( Nette \ PhpGenerator \ ClassType $ class ) { $ initialize = $ class -> getMethod ( 'initialize' ) ; $ builder = $ this -> getContainerBuilder ( ) ; if ( $ builder -> parameters [ 'debugMode' ] && $ builder -> hasDefinition ( self :: TRACY_PANEL ) ) { $ initialize -> addBody ( $ builder -> formatPhp ( '?;' , [ new Nette \ DI \ Statement ( '@Tracy\Bar::addPanel' , [ '@' . self :: TRACY_PANEL , self :: TRACY_PANEL ] ) , ] ) ) ; } }
Adjusts DI container compiled to PHP class . Intended to be overridden by descendant .
26,003
public function resolveArguments ( $ callable , array $ context ) { $ resolve_arg = $ this -> resolve_arg ; $ rf = $ this -> callableToReflectionFunctionAbstract ( $ callable ) ; $ args = [ ] ; foreach ( $ rf -> getParameters ( ) as $ i => $ arg_meta ) { $ arg = $ resolve_arg ( $ arg_meta , $ context ) ; if ( ! count ( $ arg ) && $ arg_meta -> isOptional ( ) ) { continue ; } else if ( ! count ( $ arg ) ) { throw new Exception \ ResolutionException ( $ arg_meta ) ; } $ args [ ] = $ arg [ 0 ] ; } return $ args ; }
resolves the arguments for the callable and returns the array of args
26,004
public static function forge ( $ name = 'default' , $ config = array ( ) ) { empty ( static :: $ instances ) and \ Config :: load ( 'db' , true ) ; if ( ! ( $ conf = \ Config :: get ( 'db.redis.' . $ name ) ) ) { throw new \ RedisException ( 'Invalid instance name given.' ) ; } $ config = \ Arr :: merge ( $ conf , $ config ) ; static :: $ instances [ $ name ] = new static ( $ config ) ; return static :: $ instances [ $ name ] ; }
create an instance of the Redis class
26,005
public function execute ( ) { foreach ( $ this -> queue as $ command ) { for ( $ written = 0 ; $ written < strlen ( $ command ) ; $ written += $ fwrite ) { $ fwrite = fwrite ( $ this -> connection , substr ( $ command , $ written ) ) ; if ( $ fwrite === false ) { throw new \ RedisException ( 'Failed to write entire command to stream' ) ; } } } $ responses = array ( ) ; for ( $ i = 0 ; $ i < count ( $ this -> queue ) ; $ i ++ ) { $ responses [ ] = $ this -> readResponse ( ) ; } $ this -> queue = array ( ) ; if ( $ this -> pipelined ) { $ this -> pipelined = false ; return $ responses ; } else { return $ responses [ 0 ] ; } }
Flushes the commands in the pipeline queue to Redis and returns the responses .
26,006
public function psubscribe ( $ pattern , $ callback ) { $ args = array ( 'PSUBSCRIBE' , $ pattern ) ; $ command = sprintf ( '*%d%s%s%s' , 2 , CRLF , implode ( array_map ( function ( $ arg ) { return sprintf ( '$%d%s%s' , strlen ( $ arg ) , CRLF , $ arg ) ; } , $ args ) , CRLF ) , CRLF ) ; for ( $ written = 0 ; $ written < strlen ( $ command ) ; $ written += $ fwrite ) { $ fwrite = fwrite ( $ this -> connection , substr ( $ command , $ written ) ) ; if ( $ fwrite === false ) { throw new \ RedisException ( 'Failed to write entire command to stream' ) ; } } while ( ! feof ( $ this -> connection ) ) { try { $ response = $ this -> readResponse ( ) ; $ callback ( $ response ) ; } catch ( \ RedisException $ e ) { \ Log :: warning ( $ e -> getMessage ( ) , 'Redis_Db::readResponse' ) ; } } }
Alias for the redis PSUBSCRIBE command . It allows you to listen and have the callback called for every response .
26,007
protected function _fetch ( ) { if ( $ this -> _select === NULL ) { return false ; } $ this -> _data = $ this -> _select -> fetchAllAsItems ( ) ; return true ; }
Fetch MySQL results .
26,008
public function load ( array $ pArgs = array ( ) ) { $ select = new Select ( $ this -> _dbContainer ) ; if ( isset ( $ pArgs [ DbInterface :: FILTER_LIMIT ] ) ) { $ select -> limit ( $ pArgs [ DbInterface :: FILTER_LIMIT ] ) ; } if ( isset ( $ pArgs [ DbInterface :: FILTER_ORDER ] ) ) { $ select -> addOrder ( $ pArgs [ DbInterface :: FILTER_ORDER ] ) ; } else { $ select -> addOrder ( array ( $ this -> _dbContainer . ItemInterface :: PREFIX_SEPARATOR . ItemInterface :: IDFIELD => Db :: ORDER_DESC ) ) ; } if ( isset ( $ pArgs [ DbInterface :: FILTER_CONDITIONS ] ) and $ pArgs [ DbInterface :: FILTER_CONDITIONS ] instanceof Conditions ) { $ select -> loadConditions ( $ pArgs [ DbInterface :: FILTER_CONDITIONS ] ) ; } $ select -> find ( ) ; $ this -> _count = $ select -> count ( ) ; $ this -> _select = $ select ; $ this -> _fetch ( ) ; return $ this ; }
Load all the collection s items with optional filters .
26,009
public function countAll ( $ pConditions = NULL ) { $ count = new Count ( $ this -> _dbContainer ) ; if ( $ pConditions instanceof Conditions ) { $ count -> loadConditions ( $ pConditions ) ; } return $ count -> commit ( ) ; }
Count a collection without loading items .
26,010
public function deleteItems ( $ pWithChilds = false ) { foreach ( $ this as $ item ) { if ( $ item -> getId ( ) ) { $ item -> delete ( $ pWithChilds ) ; } } return $ this ; }
Delete all items from the database and reset the collection .
26,011
protected function realPath ( $ path ) { $ path = trim ( str_replace ( '\\' , '/' , $ path ) , '/' ) ; $ path = str_replace ( '/./' , '/' , $ path ) ; $ path = preg_replace ( '#[^/]+/\\.\\./#' , '/' , $ path ) ; $ path = preg_replace ( '#/?\\.\\.?/#' , '' , $ path ) ; $ path = preg_replace ( '#/+#' , '/' , $ path ) ; $ path = trim ( $ path , '/' ) ; if ( $ path == '.' || $ path == '..' ) { $ path = '' ; } return $ path ; }
Get real path
26,012
public function createDir ( $ path ) { if ( empty ( $ path ) ) { return false ; } $ path = $ this -> validPath ( $ path ) ; $ base = $ this -> baseUrl . '/' . $ path ; $ full = $ this -> baseDir . '/' . $ base ; if ( ! is_dir ( $ full ) && ! is_file ( $ full ) ) { $ rights = $ this -> rights ( $ path ) ; if ( $ rights -> write && @ mkdir ( $ full , 0777 , true ) ) { return $ path ; } } return false ; }
Create a dir
26,013
protected function _copy ( $ path , $ to ) { if ( is_file ( $ to ) ) { return false ; } $ iterator = new RecursiveIteratorIterator ( new RecursiveDirectoryIterator ( $ path , RecursiveDirectoryIterator :: CURRENT_AS_FILEINFO | RecursiveDirectoryIterator :: SKIP_DOTS ) , RecursiveIteratorIterator :: SELF_FIRST ) ; $ result = is_dir ( $ to ) ? true : @ mkdir ( $ to ) ; foreach ( $ iterator as $ info ) { $ toPath = $ to . '/' . $ iterator -> getSubPathName ( ) ; switch ( true ) { case $ info -> isFile ( ) : $ result = $ result && @ copy ( $ info -> getPathname ( ) , $ toPath ) ; break ; case $ info -> isDir ( ) : $ result = $ result && @ mkdir ( $ toPath , 0777 ) ; break ; } } return $ result ; }
Copy entire dir
26,014
public function uploaded ( $ temp , $ to ) { if ( null === $ this -> identity ) { return false ; } if ( is_array ( $ temp ) || is_object ( $ temp ) || is_array ( $ to ) || is_object ( $ to ) ) { if ( ( ! is_array ( $ temp ) && ! is_object ( $ temp ) ) || ( ! is_array ( $ to ) && ! is_object ( $ to ) ) ) { return false ; } $ result = array ( ) ; foreach ( $ temp as $ key => $ p ) { foreach ( $ to as $ toKey => $ t ) { if ( $ key == $ toKey ) { $ result [ $ key ] = $ this -> uploaded ( $ p , $ t ) ; } } } return $ result ; } $ to = $ this -> secureFile ( $ this -> validPath ( $ this -> realPath ( $ to ) ) ) ; $ base = $ this -> baseDir . self :: UPLOADS_TEMP ; $ full = realpath ( $ base . '/' . $ temp ) ; $ toBase = $ this -> baseUrl . '/' . $ to ; $ toFull = $ this -> baseDir . '/' . $ toBase ; if ( ! empty ( $ to ) && ! is_dir ( dirname ( $ toFull ) ) ) { $ ba = '/' . basename ( $ to ) ; $ to = $ this -> createDir ( dirname ( $ to ) ) ; if ( ! $ to ) { return false ; } $ to = $ to . $ ba ; $ toBase = $ this -> baseUrl . '/' . $ to ; $ toFull = $ this -> baseDir . '/' . $ toBase ; } if ( is_file ( $ full ) && is_dir ( dirname ( $ toFull ) ) ) { if ( $ this -> rights ( $ to ) -> write ) { if ( @ rename ( $ full , $ toFull ) ) { return $ to ; } } } return false ; }
Handle uploaded file
26,015
public function addAjax ( ) { $ this -> request -> allowMethod ( [ 'ajax' ] ) ; $ data [ 'group_or_user' ] = $ this -> request -> data [ 'group_or_user' ] ; $ data [ 'group_or_user_id' ] = $ this -> request -> data [ 'group_or_user_id' ] ; $ permissions = json_decode ( $ this -> request -> data [ 'permissions' ] ) ; foreach ( $ permissions as $ permission ) { $ data [ 'permission_id' ] = $ permission -> id ; $ data [ 'allow' ] = $ permission -> allow ; $ userGroupPermission = $ this -> UserGroupPermission -> findUserGroupPermission ( [ 'id' ] , $ data [ 'group_or_user_id' ] , $ data [ 'group_or_user' ] , $ data [ 'permission_id' ] ) -> first ( ) ; if ( ! is_null ( $ userGroupPermission ) ) { $ this -> UserGroupPermission -> get ( $ userGroupPermission -> id ) ; $ userGroupPermission -> allow = $ data [ 'allow' ] ; } else { $ userGroupPermission = $ this -> UserGroupPermission -> newEntity ( ) ; $ userGroupPermission = $ this -> UserGroupPermission -> patchEntity ( $ userGroupPermission , $ data ) ; } $ this -> UserGroupPermission -> save ( $ userGroupPermission ) ; } $ this -> Flash -> success ( __ ( 'The user group permission has been updated.' ) ) ; $ this -> set ( compact ( 'response' ) ) ; $ this -> set ( '_serialize' , [ 'response' ] ) ; $ this -> render ( 'Acl.Ajax/ajax_response' , false ) ; }
Add by ajax
26,016
public function getPermission ( ) { $ this -> request -> allowMethod ( [ 'ajax' ] ) ; $ group_or_user = isset ( $ this -> request -> data [ 'group_or_user' ] ) ? $ this -> request -> data [ 'group_or_user' ] : null ; $ group_or_user_id = isset ( $ this -> request -> data [ 'group_or_user_id' ] ) ? $ this -> request -> data [ 'group_or_user_id' ] : null ; $ ugp = $ this -> UserGroupPermission -> find ( ) -> select ( [ 'permission_id' , 'allow' ] ) -> where ( [ 'group_or_user_id' => $ group_or_user_id , 'group_or_user' => $ group_or_user ] ) -> toArray ( ) ; $ response = ( ! empty ( $ ugp ) && ! is_null ( $ ugp ) ) ? $ ugp : 'fail' ; $ this -> set ( compact ( 'response' ) ) ; $ this -> set ( '_serialize' , [ 'response' ] ) ; $ this -> render ( 'Acl.Ajax/ajax_response' , false ) ; }
Get all permissions by ajax
26,017
public function filterByThumbUrl ( $ thumbUrl = null , $ comparison = null ) { if ( null === $ comparison ) { if ( is_array ( $ thumbUrl ) ) { $ comparison = Criteria :: IN ; } elseif ( preg_match ( '/[\%\*]/' , $ thumbUrl ) ) { $ thumbUrl = str_replace ( '*' , '%' , $ thumbUrl ) ; $ comparison = Criteria :: LIKE ; } } return $ this -> addUsingAlias ( PictureTableMap :: COL_THUMB_URL , $ thumbUrl , $ comparison ) ; }
Filter the query on the thumb_url column
26,018
public function filterBySkillId ( $ skillId = null , $ comparison = null ) { if ( is_array ( $ skillId ) ) { $ useMinMax = false ; if ( isset ( $ skillId [ 'min' ] ) ) { $ this -> addUsingAlias ( PictureTableMap :: COL_SKILL_ID , $ skillId [ 'min' ] , Criteria :: GREATER_EQUAL ) ; $ useMinMax = true ; } if ( isset ( $ skillId [ 'max' ] ) ) { $ this -> addUsingAlias ( PictureTableMap :: COL_SKILL_ID , $ skillId [ 'max' ] , Criteria :: LESS_EQUAL ) ; $ useMinMax = true ; } if ( $ useMinMax ) { return $ this ; } if ( null === $ comparison ) { $ comparison = Criteria :: IN ; } } return $ this -> addUsingAlias ( PictureTableMap :: COL_SKILL_ID , $ skillId , $ comparison ) ; }
Filter the query on the skill_id column
26,019
public function filterByPhotographer ( $ photographer = null , $ comparison = null ) { if ( null === $ comparison ) { if ( is_array ( $ photographer ) ) { $ comparison = Criteria :: IN ; } elseif ( preg_match ( '/[\%\*]/' , $ photographer ) ) { $ photographer = str_replace ( '*' , '%' , $ photographer ) ; $ comparison = Criteria :: LIKE ; } } return $ this -> addUsingAlias ( PictureTableMap :: COL_PHOTOGRAPHER , $ photographer , $ comparison ) ; }
Filter the query on the photographer column
26,020
public function filterByPhotographerId ( $ photographerId = null , $ comparison = null ) { if ( is_array ( $ photographerId ) ) { $ useMinMax = false ; if ( isset ( $ photographerId [ 'min' ] ) ) { $ this -> addUsingAlias ( PictureTableMap :: COL_PHOTOGRAPHER_ID , $ photographerId [ 'min' ] , Criteria :: GREATER_EQUAL ) ; $ useMinMax = true ; } if ( isset ( $ photographerId [ 'max' ] ) ) { $ this -> addUsingAlias ( PictureTableMap :: COL_PHOTOGRAPHER_ID , $ photographerId [ 'max' ] , Criteria :: LESS_EQUAL ) ; $ useMinMax = true ; } if ( $ useMinMax ) { return $ this ; } if ( null === $ comparison ) { $ comparison = Criteria :: IN ; } } return $ this -> addUsingAlias ( PictureTableMap :: COL_PHOTOGRAPHER_ID , $ photographerId , $ comparison ) ; }
Filter the query on the photographer_id column
26,021
public function filterByAthlete ( $ athlete = null , $ comparison = null ) { if ( null === $ comparison ) { if ( is_array ( $ athlete ) ) { $ comparison = Criteria :: IN ; } elseif ( preg_match ( '/[\%\*]/' , $ athlete ) ) { $ athlete = str_replace ( '*' , '%' , $ athlete ) ; $ comparison = Criteria :: LIKE ; } } return $ this -> addUsingAlias ( PictureTableMap :: COL_ATHLETE , $ athlete , $ comparison ) ; }
Filter the query on the athlete column
26,022
public function setData ( $ data ) { if ( ! empty ( $ data ) ) { foreach ( $ data as $ key => $ value ) { $ this -> _data [ $ key ] = $ value ; } } else { $ this -> _data = array ( ) ; } }
Set data for current instance
26,023
public function getArray ( $ key = null ) { if ( ! is_null ( $ key ) ) { return $ this -> getDeepValue ( $ key ) ; } else { return $ this -> _data ; } }
Return Array with all data
26,024
public static function create ( string $ msg , int $ exitCode , array $ output , string $ cmd , array $ arguments = [ ] ) : self { $ e = new self ( $ msg , $ exitCode ) ; $ e -> setOutput ( $ output ) -> setCmd ( $ cmd ) -> setArguments ( $ arguments ) ; return $ e ; }
Creates an instance of this exception .
26,025
public function initialize ( ) { parent :: initialize ( ) ; $ this -> data -> installmentCount = 1 ; $ this -> data -> fundingInstrument = new stdClass ( ) ; $ this -> data -> fundingInstrument -> method = self :: METHOD_CREDIT_CARD ; }
Initialize a resource
26,026
public function execute ( ) { $ this -> client -> setResource ( $ this -> order -> getResource ( ) ) ; return $ this -> client -> post ( '/{order_id}/payments' , [ $ this -> order -> id ] , $ this -> data ) -> getResults ( ) ; }
Execute a payment
26,027
public function setCreditCard ( CreditCard $ creditCard ) { $ creditCard -> setContext ( Moip :: PAYMENT ) ; $ this -> data -> fundingInstrument -> method = self :: METHOD_CREDIT_CARD ; $ this -> data -> fundingInstrument -> creditCard = $ creditCard -> getData ( ) ; return $ this ; }
Set a credit card
26,028
public function setCreditCardHash ( $ hash , Customers $ holder ) { $ this -> data -> fundingInstrument -> method = self :: METHOD_CREDIT_CARD ; $ this -> data -> fundingInstrument -> creditCard = new stdClass ( ) ; $ this -> data -> fundingInstrument -> creditCard -> hash = $ hash ; $ this -> setCreditCardHolder ( $ holder ) ; return $ this ; }
Set credit card hash .
26,029
public function setBoleto ( Boleto $ boleto ) { $ boleto -> setContext ( Moip :: PAYMENT ) ; $ this -> data -> fundingInstrument -> method = self :: METHOD_BOLETO ; $ this -> data -> fundingInstrument -> boleto = $ boleto -> getData ( ) ; return $ this ; }
Set boleto payment method
26,030
public function Initialize ( ) { parent :: Initialize ( ) ; Gdn_Theme :: Section ( 'Dashboard' ) ; if ( $ this -> Menu ) $ this -> Menu -> HighlightRoute ( '/dashboard/authentication' ) ; $ this -> EnableSlicing ( $ this ) ; $ Authenticators = Gdn :: Authenticator ( ) -> GetAvailable ( ) ; $ this -> ChooserList = array ( ) ; $ this -> ConfigureList = array ( ) ; foreach ( $ Authenticators as $ AuthAlias => $ AuthConfig ) { $ this -> ChooserList [ $ AuthAlias ] = $ AuthConfig [ 'Name' ] ; $ Authenticator = Gdn :: Authenticator ( ) -> AuthenticateWith ( $ AuthAlias ) ; $ ConfigURL = ( is_a ( $ Authenticator , "Gdn_Authenticator" ) && method_exists ( $ Authenticator , 'AuthenticatorConfiguration' ) ) ? $ Authenticator -> AuthenticatorConfiguration ( $ this ) : FALSE ; $ this -> ConfigureList [ $ AuthAlias ] = $ ConfigURL ; } $ this -> CurrentAuthenticationAlias = Gdn :: Authenticator ( ) -> AuthenticateWith ( 'default' ) -> GetAuthenticationSchemeAlias ( ) ; }
Highlight route and do authenticator setup .
26,031
public function Choose ( $ AuthenticationSchemeAlias = NULL ) { $ this -> Permission ( 'Garden.Settings.Manage' ) ; $ this -> AddSideMenu ( 'dashboard/authentication' ) ; $ this -> Title ( T ( 'Authentication' ) ) ; $ this -> AddCssFile ( 'authentication.css' ) ; $ PreFocusAuthenticationScheme = NULL ; if ( ! is_null ( $ AuthenticationSchemeAlias ) ) $ PreFocusAuthenticationScheme = $ AuthenticationSchemeAlias ; if ( $ this -> Form -> AuthenticatedPostback ( ) ) { $ NewAuthSchemeAlias = $ this -> Form -> GetValue ( 'Garden.Authentication.Chooser' ) ; $ AuthenticatorInfo = Gdn :: Authenticator ( ) -> GetAuthenticatorInfo ( $ NewAuthSchemeAlias ) ; if ( $ AuthenticatorInfo !== FALSE ) { $ CurrentAuthenticatorAlias = Gdn :: Authenticator ( ) -> AuthenticateWith ( 'default' ) -> GetAuthenticationSchemeAlias ( ) ; $ AuthenticatorDisableEvent = "DisableAuthenticator" . ucfirst ( $ CurrentAuthenticatorAlias ) ; $ this -> FireEvent ( $ AuthenticatorDisableEvent ) ; $ AuthenticatorEnableEvent = "EnableAuthenticator" . ucfirst ( $ NewAuthSchemeAlias ) ; $ this -> FireEvent ( $ AuthenticatorEnableEvent ) ; $ PreFocusAuthenticationScheme = $ NewAuthSchemeAlias ; $ this -> CurrentAuthenticationAlias = Gdn :: Authenticator ( ) -> AuthenticateWith ( 'default' ) -> GetAuthenticationSchemeAlias ( ) ; } } $ this -> SetData ( 'AuthenticationConfigureList' , $ this -> ConfigureList ) ; $ this -> SetData ( 'PreFocusAuthenticationScheme' , $ PreFocusAuthenticationScheme ) ; $ this -> Render ( ) ; }
Select Authentication method .
26,032
public function Configure ( $ AuthenticationSchemeAlias = NULL ) { $ Message = T ( "Please choose an authenticator to configure." ) ; if ( ! is_null ( $ AuthenticationSchemeAlias ) ) { $ AuthenticatorInfo = Gdn :: Authenticator ( ) -> GetAuthenticatorInfo ( $ AuthenticationSchemeAlias ) ; if ( $ AuthenticatorInfo !== FALSE ) { $ this -> AuthenticatorChoice = $ AuthenticationSchemeAlias ; if ( array_key_exists ( $ AuthenticationSchemeAlias , $ this -> ConfigureList ) && $ this -> ConfigureList [ $ AuthenticationSchemeAlias ] !== FALSE ) { echo Gdn :: Slice ( $ this -> ConfigureList [ $ AuthenticationSchemeAlias ] ) ; return ; } else $ Message = sprintf ( T ( "The %s Authenticator does not have any custom configuration options." ) , $ AuthenticatorInfo [ 'Name' ] ) ; } } $ this -> SetData ( 'ConfigureMessage' , $ Message ) ; $ this -> Render ( ) ; }
Configure authentication method .
26,033
public static function byteFormat ( int $ bytes = 0 , int $ decimals = 0 ) { $ quant = [ 'TB' => 1099511627776 , 'GB' => 1073741824 , 'MB' => 1048576 , 'KB' => 1024 , 'B ' => 1 , ] ; foreach ( $ quant as $ unit => $ mag ) { if ( doubleval ( $ bytes ) >= $ mag ) { return sprintf ( '%01.' . $ decimals . 'f' , ( $ bytes / $ mag ) ) . ' ' . $ unit ; } } return false ; }
Converts a number of bytes to a human readable number by taking the number of that unit that the bytes will go into it .
26,034
public static function convertToBytes ( string $ size = null ) : float { $ size = trim ( ( string ) $ size ) ; $ accepted = implode ( '|' , array_keys ( Number :: $ byte_units ) ) ; $ pattern = '/^([0-9]+(?:\.[0-9]+)?)(' . $ accepted . ')?$/Di' ; if ( ! preg_match ( $ pattern , $ size , $ matches ) ) { throw new \ RuntimeException ( 'The byte unit size, "' . $ size . '", is improperly formatted.' ) ; } $ size = ( float ) $ matches [ 1 ] ; $ unit = Arr :: get ( $ matches , 2 , 'B' ) ; $ bytes = $ size * pow ( 2 , Number :: $ byte_units [ $ unit ] ) ; return $ bytes ; }
Converts a file size number to a byte value .
26,035
public function getCallbacks ( $ name ) { return isset ( $ this -> registry [ $ name ] ) ? $ this -> registry [ $ name ] : null ; }
Returns all the callbacks registered for a callback type .
26,036
public function invoke ( $ model , $ name , $ mustExist = true ) { if ( $ mustExist && ! array_key_exists ( $ name , $ this -> registry ) ) { throw new ActiveRecordException ( "No callbacks were defined for: $name on " . get_class ( $ model ) ) ; } if ( ! array_key_exists ( $ name , $ this -> registry ) ) { $ registry = array ( ) ; } else { $ registry = $ this -> registry [ $ name ] ; } if ( preg_match ( '/^(?<when>after|before)(?<action>Create|Update)$/' , $ name , $ matches ) ) { $ temporalSave = $ matches [ 'when' ] . "Save" ; if ( ! isset ( $ this -> registry [ $ temporalSave ] ) ) $ this -> registry [ $ temporalSave ] = array ( ) ; $ registry = array_merge ( $ this -> registry [ $ temporalSave ] , $ registry ? $ registry : array ( ) ) ; } if ( $ registry ) { foreach ( $ registry as $ method ) { $ ret = ( $ method instanceof Closure ? $ method ( $ model ) : $ model -> $ method ( ) ) ; if ( false === $ ret && $ first === 'before' ) return false ; } } return true ; }
Invokes a callback .
26,037
public function register ( $ name , $ closure = null , $ options = array ( ) ) { $ options = array_merge ( array ( 'prepend' => false ) , $ options ) ; if ( ! $ closure ) { $ closure = $ name ; } if ( ! in_array ( $ name , self :: $ validCallbacks ) ) { throw new ActiveRecordException ( "Invalid callback: $name" ) ; } if ( ! ( $ closure instanceof Closure ) ) { if ( ! isset ( $ this -> publicMethods ) ) { $ this -> publicMethods = get_class_methods ( $ this -> klass -> getName ( ) ) ; } if ( ! in_array ( $ closure , $ this -> publicMethods ) ) { if ( $ this -> klass -> hasMethod ( $ closure ) ) { throw new ActiveRecordException ( "Callback methods need to be public (or anonymous closures). " . "Please change the visibility of " . $ this -> klass -> getName ( ) . "->" . $ closure . "()" ) ; } else { throw new ActiveRecordException ( "Unknown method for callback: $name" . ( is_string ( $ closure ) ? ": #$closure" : "" ) ) ; } } } if ( ! isset ( $ this -> registry [ $ name ] ) ) { $ this -> registry [ $ name ] = array ( ) ; } if ( $ options [ 'prepend' ] ) { array_unshift ( $ this -> registry [ $ name ] , $ closure ) ; } else { $ this -> registry [ $ name ] [ ] = $ closure ; } }
Register a new callback .
26,038
public function createV3Client ( $ username , $ password ) { return new HubV3Client ( $ username , $ password , $ this -> hubUrl , $ this -> requestHeaders , $ this -> tlsCertVerification ) ; }
Get a client for the v3 Hub API .
26,039
public function createV4Client ( $ username , $ password ) { if ( ! $ this -> userbaseUrl ) { throw new RuntimeException ( 'In order to createV4Client you need to have previsously called ApiClientFactory::setUserbaseJwtAuthenticatorUrl' ) ; } $ authenticator = new UserbaseJwtAuthenticatorClient ( $ this -> userbaseUrl , $ this -> tlsCertVerification ) ; try { $ token = $ authenticator -> authenticate ( $ username , $ password ) ; } catch ( AuthenticationFailureException $ e ) { throw new ClientCreationException ( 'Failed to create a v4 API client because of a failure during authentication with UserBase.' , null , $ e ) ; } $ httpClient = new GuzzleClient ( [ 'base_uri' => $ this -> hubUrl , 'verify' => $ this -> tlsCertVerification , 'headers' => array_replace ( [ 'User-Agent' => 'HubV4Client (Guzzle)' ] , $ this -> requestHeaders , [ 'X-Authorization' => "Bearer {$token}" ] ) , ] ) ; return new HubV4Client ( $ httpClient ) ; }
Get a client for the v4 Hub API .
26,040
public static function _encryptAESPKCS7 ( $ str , $ key = _CryptConfig :: AES_KEY , $ cipher = _CryptConfig :: CIPHER , $ mode = _CryptConfig :: MODE ) { $ key = self :: _chopKeyForAES ( $ key ) ; $ block = mcrypt_get_block_size ( $ cipher , $ mode ) ; $ pad = $ block - ( strlen ( $ str ) % $ block ) ; $ str .= str_repeat ( chr ( $ pad ) , $ pad ) ; $ iv = mcrypt_create_iv ( mcrypt_get_iv_size ( $ cipher , $ mode ) , MCRYPT_DEV_URANDOM ) ; $ encrypted = mcrypt_encrypt ( $ cipher , $ key , $ str , $ mode , $ iv ) ; $ ret = base64_encode ( $ iv ) . base64_encode ( $ encrypted ) ; return $ ret ; }
Encrypts a string using AES encryption with PKCS7 padding . Random IV is used
26,041
public static function _decryptAESPKCS7 ( $ str , $ key = _CryptConfig :: AES_KEY , $ cipher = _CryptConfig :: CIPHER , $ mode = _CryptConfig :: MODE ) { $ key = self :: _chopKeyForAES ( $ key ) ; $ ivLength = self :: _getBase64IVLength ( $ cipher , $ mode ) ; $ iv = substr ( $ str , 0 , $ ivLength - 1 ) ; $ iv = base64_decode ( $ iv ) ; $ str = substr ( $ str , $ ivLength - 1 ) ; $ str = base64_decode ( $ str ) ; $ str = mcrypt_decrypt ( $ cipher , $ key , $ str , $ mode , $ iv ) ; $ block = mcrypt_get_block_size ( $ cipher , $ mode ) ; $ pad = ord ( $ str [ ( $ len = strlen ( $ str ) ) - 1 ] ) ; return substr ( $ str , 0 , strlen ( $ str ) - $ pad ) ; }
Decrypts a string using AES encryption with PKCS7 padding .
26,042
private static function _createIV ( $ cipher , $ mode ) { $ size = self :: _getIVSize ( $ cipher , $ mode ) ; return mcrypt_create_iv ( $ size , MCRYPT_DEV_RANDOM ) ; }
Generates an initialization vector based on cipher and mode
26,043
protected function parseAuthorizationString ( $ authorizationString ) { if ( strpos ( $ authorizationString , 'Basic' ) !== false ) { $ authorizationString = trim ( substr ( $ authorizationString , 6 ) ) ; } $ decoded = base64_decode ( $ authorizationString ) ; $ delimiterPos = strpos ( $ decoded , ':' ) ; return array ( 'publicKey' => substr ( $ decoded , 0 , $ delimiterPos ) , 'hmac' => substr ( $ decoded , $ delimiterPos + 1 ) ) ; }
Parses the authorization string and returns an array with the public key and the hmac
26,044
public function startDebug ( $ listener = null , $ type = "" ) { if ( ! Text :: isEmpty ( $ type ) && ! in_array ( $ type , [ "exec" , "query" ] ) ) { throw new DbException ( "Invalid filter type. Valid filter types are 'exec' and 'query'" ) ; } $ this -> _debugListener = $ listener !== null ? $ listener : function ( $ sql ) { echo "$sql\n" ; } ; $ types = Text :: isEmpty ( $ type ) ? [ "exec" , "query" ] : [ $ type ] ; foreach ( $ types as $ type ) { $ this -> _debugger -> on ( $ type , $ this -> _debugListener ) ; } }
Starts the debugger mechanism .
26,045
public function stopDebug ( $ type = "" ) { if ( ! Text :: isEmpty ( $ type ) && ! in_array ( $ type , [ "exec" , "query" ] ) ) { throw new DbException ( "Invalid filter type. Valid filter types are 'exec' and 'query'" ) ; } $ types = Text :: isEmpty ( $ type ) ? [ "exec" , "query" ] : [ $ type ] ; foreach ( $ types as $ type ) { $ this -> _debugger -> off ( $ type , $ this -> _debugListener ) ; } }
Stops the debugger mechanism .
26,046
public function addDebugListener ( $ listener , $ type = "" ) { if ( ! Text :: isEmpty ( $ type ) && ! in_array ( $ type , [ "exec" , "query" ] ) ) { throw new DbException ( "Invalid filter type. Valid filter types are 'exec' and 'query'" ) ; } $ types = Text :: isEmpty ( $ type ) ? [ "exec" , "query" ] : [ $ type ] ; foreach ( $ types as $ type ) { $ this -> _debugger -> on ( $ type , $ listener ) ; } }
Adds a debug listener .
26,047
public function query ( $ sql , $ arguments = array ( ) ) { $ this -> _debugger -> trigger ( "query" , [ $ sql , $ arguments ] ) ; $ ret = new DbSource ( $ this , $ sql , $ arguments ) ; return $ ret ; }
Executes a DDL statement .
26,048
public function fetchRows ( $ sql , $ arguments = array ( ) ) { $ ret = array ( ) ; $ result = $ this -> _exec ( $ sql , $ arguments ) ; while ( $ row = $ result -> fetch_array ( ) ) { array_push ( $ ret , $ row ) ; } $ result -> close ( ) ; return $ ret ; }
Executes a DDL statement and returns all rows .
26,049
private function _replaceArguments ( $ sql , $ arguments ) { if ( ! is_array ( $ arguments ) ) { $ arguments = array ( $ arguments ) ; } $ stringSegments = [ ] ; if ( preg_match_all ( '/(["\'`])((?:\\\\\1|.)*?)\1/' , $ sql , $ matches , PREG_OFFSET_CAPTURE ) ) { foreach ( $ matches [ 2 ] as $ match ) { $ startPos = $ match [ 1 ] ; $ endPos = $ startPos + strlen ( $ match [ 0 ] ) ; array_push ( $ stringSegments , [ $ startPos , $ endPos ] ) ; } } $ argsPos = [ ] ; preg_match_all ( '/\?/' , $ sql , $ matches , PREG_OFFSET_CAPTURE ) ; foreach ( $ matches [ 0 ] as $ match ) { array_push ( $ argsPos , $ match [ 1 ] ) ; } $ matchCount = 0 ; $ argCount = 0 ; return preg_replace_callback ( '/\?/' , function ( $ matches ) use ( & $ argCount , & $ matchCount , $ arguments , $ argsPos , $ stringSegments ) { $ ret = $ matches [ 0 ] ; if ( $ argCount < count ( $ arguments ) ) { $ argPos = $ argsPos [ $ matchCount ] ; $ isInsideQuotedString = false ; foreach ( $ stringSegments as $ segment ) { if ( $ argPos >= $ segment [ 0 ] && $ argPos < $ segment [ 1 ] ) { $ isInsideQuotedString = true ; break ; } } if ( ! $ isInsideQuotedString ) { $ ret = $ this -> quote ( $ arguments [ $ argCount ++ ] ) ; } } $ matchCount ++ ; return $ ret ; } , $ sql ) ; }
Replaces arguments in an SQL statement .
26,050
public function getDeliveryAddress ( ) : ? string { if ( ! $ this -> hasDeliveryAddress ( ) ) { $ this -> setDeliveryAddress ( $ this -> getDefaultDeliveryAddress ( ) ) ; } return $ this -> deliveryAddress ; }
Get delivery address
26,051
private function init_whoops ( ) { $ whoops = new Run ; $ general = new General ( ) ; $ whoops -> pushHandler ( $ general -> get_handler ( ) ) ; $ whoops -> pushHandler ( new Ajax ( ) ) ; $ whoops -> pushHandler ( new Rest_Api ( ) ) ; $ whoops -> register ( ) ; \ ob_start ( ) ; Container :: add_instance ( $ whoops ) ; }
Register the Whoops service into the service container .
26,052
public function getAmount ( $ baseAmount = null ) { if ( is_numeric ( $ this -> getFixedAmount ( ) ) ) { return $ this -> getFixedAmount ( ) ; } if ( null === $ baseAmount ) { $ baseAmount = $ this -> getBaseAmount ( ) ; } return round ( $ baseAmount * $ this -> getRate ( ) / 100 , 2 ) ; }
Get tax amount from a given base amount
26,053
private function InitArticles ( ) { $ this -> archive = Archive :: Schema ( ) -> ByPage ( $ this -> CurrentPage ( ) ) ; if ( $ this -> archive ) { $ this -> InitArchiveArticles ( ) ; return ; } $ this -> category = Category :: Schema ( ) -> ByPage ( $ this -> CurrentPage ( ) ) ; if ( $ this -> category ) { $ this -> archive = $ this -> category -> GetArchive ( ) ; $ this -> InitCategoryArticles ( ) ; } }
Initializes the article array
26,054
private function InitArchiveArticles ( ) { $ sql = Access :: SqlBuilder ( ) ; $ tblArticle = Article :: Schema ( ) -> Table ( ) ; $ tblCategory = Category :: Schema ( ) -> Table ( ) ; $ join = $ sql -> Join ( $ tblCategory ) ; $ joinCond = $ sql -> Equals ( $ tblArticle -> Field ( 'Category' ) , $ tblCategory -> Field ( 'ID' ) ) ; $ orderBy = $ sql -> OrderList ( $ sql -> OrderDesc ( $ tblArticle -> Field ( 'Created' ) ) ) ; $ where = $ this -> PublishedCondition ( ) -> And_ ( $ sql -> Equals ( $ tblCategory -> Field ( 'Archive' ) , $ sql -> Value ( $ this -> archive -> GetID ( ) ) ) ) ; $ this -> articles = Article :: Schema ( ) -> Fetch ( false , $ where , $ orderBy , null , $ this -> ArticleOffset ( ) , $ this -> ArticleCount ( ) , $ join , Sql \ JoinType :: Inner ( ) , $ joinCond ) ; $ this -> articlesTotal = Article :: Schema ( ) -> Count ( false , $ where , null , $ join , Sql \ JoinType :: Inner ( ) , $ joinCond ) ; }
Initializes article array for a page assigned archive
26,055
private function InitCategoryArticles ( ) { $ sql = Access :: SqlBuilder ( ) ; $ tblArticle = Article :: Schema ( ) -> Table ( ) ; $ orderBy = $ sql -> OrderList ( $ sql -> OrderDesc ( $ tblArticle -> Field ( 'Created' ) ) ) ; $ where = $ this -> PublishedCondition ( ) -> And_ ( $ sql -> Equals ( $ tblArticle -> Field ( 'Category' ) , $ sql -> Value ( $ this -> category -> GetID ( ) ) ) ) ; $ this -> articles = Article :: Schema ( ) -> Fetch ( false , $ where , $ orderBy ) ; $ this -> articlesTotal = Article :: Schema ( ) -> Count ( false , $ where ) ; }
Initializes article array for a page assigned category
26,056
private function PublishedCondition ( ) { $ sql = Access :: SqlBuilder ( ) ; $ sqlNow = $ sql -> Value ( Date :: Now ( ) ) ; $ tblArticle = Article :: Schema ( ) -> Table ( ) ; return $ sql -> Equals ( $ tblArticle -> Field ( 'Publish' ) , $ sql -> Value ( true ) ) -> And_ ( $ sql -> IsNull ( $ tblArticle -> Field ( 'PublishFrom' ) ) -> Or_ ( $ sql -> LTE ( $ tblArticle -> Field ( 'PublishFrom' ) , $ sqlNow ) ) ) -> And_ ( $ sql -> IsNull ( $ tblArticle -> Field ( 'PublishTo' ) ) -> Or_ ( $ sql -> GTE ( $ tblArticle -> Field ( 'PublishTo' ) , $ sqlNow ) ) ) ; }
The condition to retreive published articles only
26,057
private function ArticleOffset ( ) { $ page = max ( 1 , ( int ) Request :: GetData ( 'page' ) ) ; return ( $ page - 1 ) * $ this -> archive -> GetItemsPerPage ( ) ; }
The offset for the database limit
26,058
public static function fromRaw ( $ raw ) { $ response = new Response ( ) ; $ header_end_offset = strpos ( $ raw , "\r\n\r\n" ) ; $ raw_head = substr ( $ raw , 0 , $ header_end_offset ) ; $ raw_body = substr ( $ raw , $ header_end_offset + 4 ) ; $ raw_headers = explode ( "\r\n" , $ raw_head ) ; $ status_head = array_shift ( $ raw_headers ) ; $ status_segments = explode ( " " , $ status_head ) ; $ status = new stdClass ( ) ; $ status -> protocol = $ status_segments [ 0 ] ; $ status -> code = ( int ) $ status_segments [ 1 ] ; $ status -> message = $ status_segments [ 2 ] ; $ headers = array ( ) ; foreach ( $ raw_headers as $ header ) { $ segments = explode ( ": " , $ header , 2 ) ; $ headers [ $ segments [ 0 ] ] = $ segments [ 1 ] ; } $ response -> status = $ status ; $ response -> headers = $ headers ; $ response -> body = $ raw_body ; return $ response ; }
Parse a raw HTTP response
26,059
protected function getValidPasswordReset ( $ token ) { $ passwordResets = $ this -> passwordResetData -> listEntries ( [ 'token' => $ token ] ) ; if ( count ( $ passwordResets ) !== 1 ) { return null ; } $ passwordReset = $ passwordResets [ 0 ] ; $ createdAt = $ passwordReset -> get ( 'created_at' ) ; if ( strtotime ( $ createdAt . ' UTC' ) < time ( ) - 2 * 24 * 60 * 60 || $ passwordReset -> get ( 'reset' ) ) { return null ; } return $ passwordReset ; }
Gets the password reset of a token but only if it is younger than 48h .
26,060
public function requestPasswordReset ( $ identifyingField , $ identifyingValue ) { $ users = $ this -> userData -> listEntries ( [ $ identifyingField => $ identifyingValue ] ) ; if ( count ( $ users ) !== 1 ) { return null ; } $ user = $ users [ 0 ] ; $ userSetup = new UserSetup ( ) ; do { $ token = $ userSetup -> getSalt ( 32 ) ; $ tokenFound = $ this -> passwordResetData -> countBy ( $ this -> passwordResetData -> getDefinition ( ) -> getTable ( ) , [ 'token' => $ token ] , [ 'token' => '=' ] , true ) === 0 ; } while ( ! $ tokenFound ) ; $ passwordReset = $ this -> passwordResetData -> createEmpty ( ) ; $ passwordReset -> set ( 'user' , $ user -> get ( 'id' ) ) ; $ passwordReset -> set ( 'token' , $ token ) ; $ this -> passwordResetData -> create ( $ passwordReset ) ; return $ token ; }
Creates a password reset request .
26,061
public function resetPassword ( $ token , $ newPassword ) { $ passwordReset = $ this -> getValidPasswordReset ( $ token ) ; if ( $ passwordReset === null ) { return false ; } $ user = $ passwordReset -> get ( 'user' ) ; $ user = $ this -> userData -> get ( $ user [ 'id' ] ) ; $ user -> set ( 'password' , $ newPassword ) ; $ this -> userData -> update ( $ user ) ; $ reset = gmdate ( 'Y-m-d H:i:s' ) ; $ passwordReset -> set ( 'reset' , $ reset ) ; $ this -> passwordResetData -> update ( $ passwordReset ) ; return true ; }
Resets the password of an user belonging to the given password reset token .
26,062
public function authenticate ( $ username , $ password ) { $ client = $ this -> getClient ( ) ; $ parameters = $ this -> getAuthParams ( ) ; $ endpoint = $ this -> getEndpoint ( ) ; $ code = NULL ; $ response = $ client -> get ( $ endpoint , [ 'query' => $ parameters , 'auth' => [ $ username , $ password ] ] ) ; $ code = $ response -> getStatusCode ( ) ; $ this -> setLastResponse ( $ response ) ; switch ( $ code ) { case '200' : $ body = $ response -> getBody ( ) ; $ json = json_decode ( $ body -> getContents ( ) ) ; if ( empty ( $ json ) ) { throw new \ Exception ( "Could not get JSON from body." ) ; } $ this -> setAuthApiToken ( $ json -> access_token ) ; $ this -> setAuthApiTokenExpires ( $ json -> expires_in ) ; break ; } return $ this ; }
Authenticates a username and password with the CAP API .
26,063
public function toDocument ( ) { $ doc = new Document ( ) ; $ doc -> data = $ this -> data ; $ doc -> defaults = $ this -> defaultData ; return $ doc ; }
Convert to document .
26,064
public function getSubset ( $ key ) { if ( isset ( $ this -> emptySubset ) ) { $ this -> createTrueSubset ( ) ; } $ doc = $ this -> createEmpty ( ) ; if ( ! isset ( $ this -> data [ $ key ] ) or ! is_array ( $ this -> data [ $ key ] ) ) { $ doc -> data = null ; $ doc -> emptySubset = $ key ; } else { $ doc -> data = & $ this -> data [ $ key ] ; } if ( ! $ this -> saveDefaults ) { if ( ! isset ( $ this -> defaultData [ $ key ] ) or ! is_array ( $ this -> defaultData [ $ key ] ) ) { $ this -> defaultData [ $ key ] = array ( ) ; } $ doc -> defaultData = & $ this -> defaultData [ $ key ] ; } $ doc -> parent = $ this ; $ doc -> root = $ this -> root ; return $ doc ; }
Get a subdocument .
26,065
protected function createTrueSubset ( ) { $ this -> parent -> data [ $ this -> emptySubset ] = array ( ) ; $ this -> data = & $ this -> parent -> data [ $ this -> emptySubset ] ; $ this -> emptySubset = null ; }
Create actual subset .
26,066
public function set ( $ key , $ value ) { Assume :: that ( is_scalar ( $ key ) ) ; if ( isset ( $ this -> emptySubset ) ) { $ this -> createTrueSubset ( ) ; } $ oldValue = null ; if ( isset ( $ this -> data [ $ key ] ) ) { $ oldValue = $ this -> data [ $ key ] ; } if ( isset ( $ key ) and isset ( $ value ) and $ key !== '' ) { $ this -> data [ $ key ] = $ value ; } else { $ this -> data [ $ key ] = null ; } if ( ! $ this -> root -> updated and $ oldValue !== $ value ) { $ this -> root -> updated = true ; $ this -> root -> update ( ) ; } }
Update a document key .
26,067
public function setRecursive ( $ key , $ value ) { if ( ! is_array ( $ value ) ) { $ this -> set ( $ key , $ value ) ; return ; } $ subset = $ this -> getSubset ( $ key ) ; $ array = $ value ; foreach ( $ array as $ key => $ value ) { $ subset -> setRecursive ( $ key , $ value ) ; } }
Update a subdocument recursively .
26,068
public function get ( $ key , $ default = null ) { if ( isset ( $ this -> data [ $ key ] ) ) { $ value = $ this -> data [ $ key ] ; } else { if ( isset ( $ default ) ) { $ this -> setDefault ( $ key , $ default ) ; } elseif ( isset ( $ this -> defaultData [ $ key ] ) ) { $ default = $ this -> defaultData [ $ key ] ; } return $ default ; } if ( isset ( $ default ) ) { if ( gettype ( $ default ) !== gettype ( $ value ) ) { $ this -> setDefault ( $ key , $ default ) ; return $ default ; } } return $ value ; }
Retreive value of a document key . Returns the default value if the key is not found or if the type of the found value does not match the type of the defuault value .
26,069
public function autoVar ( $ default = null ) { $ backtrace = debug_backtrace ( ) ; $ name = '' ; if ( isset ( $ backtrace [ 1 ] [ 'class' ] ) ) { $ name = $ backtrace [ 1 ] [ 'class' ] . '::' ; } $ name .= $ backtrace [ 1 ] [ 'function' ] ; $ name .= '(' . $ backtrace [ 1 ] [ 'line' ] . ')' ; $ var = new DocumentVar ( $ this , $ name ) ; if ( isset ( $ default ) ) { $ var -> setDefault ( $ default ) ; } return $ var ; }
Create a persistent variable using this document .
26,070
public function updateOrCreateRelations ( Request $ request , Model $ model ) { $ parameterBag = $ request -> request ; foreach ( $ parameterBag -> all ( ) as $ name => $ attributes ) { if ( is_array ( $ request -> { $ name } ) ) { $ this -> _checkRelationExists ( $ model , $ name ) ; $ relation = $ model -> { $ name } ( ) ; $ this -> handleRelations ( $ attributes , $ model , $ relation ) ; } } }
Update or create relations handling array type request data .
26,071
protected function handleRelations ( array $ fillable , Model $ model , Relation $ relation ) { switch ( true ) { case $ relation instanceof HasOne || $ relation instanceof MorphOne : $ this -> updateOrCreateHasOne ( $ fillable , $ model , $ relation ) ; break ; case $ relation instanceof BelongsTo : $ this -> updateOrCreateBelongsToOne ( $ fillable , $ model , $ relation ) ; break ; case $ relation instanceof HasMany || $ relation instanceof MorphMany : $ this -> updateOrCreateHasMany ( $ fillable , $ model , $ relation ) ; break ; case $ relation instanceof BelongsToMany || $ relation instanceof MorphToMany : $ this -> updateOrCreateBelongsToMany ( $ fillable , $ model , $ relation ) ; break ; } }
Handle relations .
26,072
protected function updateOrCreateHasOne ( array $ fillable , Model $ model , Relation $ relation ) { $ id = '' ; if ( array_key_exists ( 'id' , $ fillable ) ) { $ id = $ fillable [ 'id' ] ; } if ( array_except ( $ fillable , [ 'id' ] ) ) { if ( property_exists ( $ this , 'pruneHasOne' ) && $ this -> pruneHasOne !== false ) { $ relation -> update ( $ fillable ) ; } return $ relation -> updateOrCreate ( [ 'id' => $ id ] , $ fillable ) ; } return null ; }
HasOne relation updateOrCreate logic .
26,073
protected function updateOrCreateBelongsToOne ( array $ fillable , Model $ model , Relation $ relation ) { $ related = $ relation -> getRelated ( ) ; if ( array_except ( $ fillable , [ 'id' ] ) ) { if ( ! $ relation -> first ( ) ) { $ record = $ relation -> associate ( $ related -> create ( $ fillable ) ) ; $ model -> save ( ) ; } else { $ record = $ relation -> update ( $ fillable ) ; } return $ record ; } return null ; }
BelongsToOne relation updateOrCreate logic .
26,074
protected function updateOrCreateHasMany ( array $ fillable , Model $ model , Relation $ relation ) { $ keys = [ ] ; $ id = '' ; $ records = [ ] ; foreach ( $ fillable as $ fields ) { if ( is_array ( $ fields ) ) { if ( array_key_exists ( 'id' , $ fields ) ) { $ id = $ fields [ 'id' ] ; } if ( array_except ( $ fields , [ 'id' ] ) ) { $ record = $ relation -> updateOrCreate ( [ 'id' => $ id ] , $ fields ) ; array_push ( $ keys , $ record -> id ) ; array_push ( $ records , $ record ) ; } } else { if ( array_except ( $ fillable , [ 'id' ] ) ) { $ record = $ relation -> updateOrCreate ( [ 'id' => $ id ] , $ fillable ) ; array_push ( $ keys , $ record -> id ) ; array_push ( $ records , $ record ) ; } } } if ( $ keys && ( property_exists ( $ this , 'pruneHasMany' ) && $ this -> pruneHasMany !== false ) ) { $ notIn = $ relation -> getRelated ( ) -> whereNotIn ( 'id' , $ keys ) -> get ( ) ; foreach ( $ notIn as $ record ) { $ record -> delete ( ) ; } } return $ records ; }
HasMany relation updateOrCreate logic .
26,075
protected function updateOrCreateBelongsToMany ( array $ fillable , Model $ model , Relation $ relation ) { $ keys = [ ] ; $ records = [ ] ; $ related = $ relation -> getRelated ( ) ; foreach ( $ fillable as $ fields ) { if ( array_key_exists ( 'id' , $ fields ) ) { $ id = $ fields [ 'id' ] ; array_push ( $ keys , $ id ) ; } else { $ id = '' ; } if ( array_except ( $ fields , [ 'id' ] ) ) { $ record = $ related -> updateOrCreate ( [ 'id' => $ id ] , $ fields ) ; array_push ( $ keys , $ record -> id ) ; array_push ( $ records , $ record ) ; } } $ relation -> sync ( $ keys ) ; return $ records ; }
BelongsToMany relation updateOrCreate logic .
26,076
private function _checkRelationExists ( Model $ model , string $ relationName ) { if ( ! method_exists ( $ model , $ relationName ) || ! $ model -> { $ relationName } ( ) instanceof Relation ) { if ( Lang :: has ( 'resource-controller.data2relationinexistent' ) ) { $ message = trans ( 'resource-controller.data2relationinexistent' , [ 'relationName' => $ relationName ] ) ; } else { $ message = "Array type request data '{$relationName}' must be named after an existent relation." ; } throw new MassAssignmentException ( $ message ) ; } }
Throw an exception if array type request data is not named after an existent Eloquent relation .
26,077
protected function getRecoveryFileContent ( ) : array { $ content = file_get_contents ( $ this -> consumerRecoveryFile ) ; if ( ! empty ( $ content ) ) { return json_decode ( $ content , TRUE ) ; } elseif ( $ content === FALSE ) { throw new ConsumerRecoveryException ( 'Error reading Consumer recovery data at ' . $ this -> consumerRecoveryFile ) ; } return [ ] ; }
Gets the recovery file contents .
26,078
public function get ( $ key ) { $ get = $ this -> getParam ( $ key , $ this -> get ) ; if ( $ get !== null ) { return $ get ; } $ post = $ this -> getParam ( $ key , $ this -> post ) ; if ( $ post !== null ) { return $ post ; } return $ this -> getParam ( $ key , $ this -> files ) ; }
Returns a parameter given via url variables or post variables . If a key exists both in url an in post variables the url variable will be returned .
26,079
public function setContentType ( $ mimes ) { if ( strpos ( $ mimes , '/' ) === FALSE ) { $ extension = ltrim ( $ mimes , '.' ) ; if ( isset ( $ this -> mimes [ $ extension ] ) ) { $ mime_type = & $ this -> mimes [ $ extension ] ; if ( is_array ( $ mime_type ) ) { $ mime_type = current ( $ mime_type ) ; } } } $ header = 'Content-Type: ' . $ mime_type ; $ this -> headers [ ] = array ( $ header , TRUE ) ; return $ this ; }
set Content Type
26,080
public function getViewHelperConfig ( ) { return [ 'aliases' => [ 'h1' => H1 :: class , 'date' => Date :: class , 'bootstrapForm' => BootstrapForm :: class , 'bootstrapMenu' => BootstrapMenu :: class , 'bootstrapFlashMessenger' => BootstrapFlashMessenger :: class , ] , 'factories' => [ H1 :: class => InvokableFactory :: class , Date :: class => InvokableFactory :: class , BootstrapForm :: class => InvokableFactory :: class , BootstrapMenu :: class => InvokableFactory :: class , BootstrapFlashMessenger :: class => BootstrapFlashMessengerFactory :: class , ] , ] ; }
Get view helper configuration
26,081
public function log ( $ priority , $ message , $ extra = array ( ) ) { if ( ! is_int ( $ priority ) || ( $ priority < 0 ) || ( $ priority >= count ( $ this -> priorities ) ) ) { throw new Exception \ InvalidArgumentException ( sprintf ( '$priority must be an integer > 0 and < %d; received %s' , count ( $ this -> priorities ) , var_export ( $ priority , 1 ) ) ) ; } if ( ! is_array ( $ extra ) && ! $ extra instanceof Traversable ) { throw new Exception \ InvalidArgumentException ( '$extra must be an array or implement Traversable' ) ; } else if ( $ extra instanceof Traversable ) { $ extra = ArrayUtils :: iteratorToArray ( $ extra ) ; } if ( $ this -> writers -> count ( ) === 0 ) { throw new Exception \ RuntimeException ( 'No log writer specified' ) ; } $ timestamp = new DateTime ( ) ; if ( is_array ( $ message ) ) { $ message = var_export ( $ message , true ) ; } foreach ( $ this -> writers -> toArray ( ) as $ writer ) { $ writer -> write ( array ( 'timestamp' => $ timestamp , 'priority' => ( int ) $ priority , 'priorityName' => $ this -> priorities [ $ priority ] , 'message' => $ message , 'extra' => $ extra ) ) ; } return $ this ; }
Add a message as a log entry
26,082
public function isSubdomainAvailable ( $ subdomain , $ params = array ( ) ) { $ params = ( object ) $ params ; return ! $ this -> getMapper ( ) -> isSubdomainExists ( $ subdomain , empty ( $ params -> id ) ? null : $ params -> id ) ; }
Return true if subdomain is available
26,083
protected function Init ( ) { $ select = ContentSelect :: Schema ( ) -> ByContent ( $ this -> Content ( ) ) ; $ disableValidation = $ select -> GetDisableFrontendValidation ( ) ; $ this -> label = $ select -> GetLabel ( ) ; $ this -> name = $ select -> GetName ( ) ; $ this -> required = $ disableValidation ? false : $ select -> GetRequired ( ) ; $ this -> value = $ this -> Value ( $ this -> name , $ select -> GetValue ( ) ) ; $ this -> id = $ this -> CssID ( ) ? $ this -> CssID ( ) : $ this -> name ; $ list = new SelectListProvider ( $ select ) ; $ this -> options = $ list -> ToArray ( ) ; $ this -> RealizeField ( $ this -> name ) ; return parent :: Init ( ) ; }
Initializes the select content
26,084
public function BackendName ( ) { $ name = parent :: BackendName ( ) ; if ( ! $ this -> Content ( ) ) { return $ name ; } $ select = ContentSelect :: Schema ( ) -> ByContent ( $ this -> Content ( ) ) ; $ name .= ' : ' . $ select -> GetName ( ) ; return $ name ; }
Gets the name for backend views
26,085
public function logSuccess ( ) { $ user = $ this -> tokenStorage -> getToken ( ) -> getUser ( ) ; if ( $ user instanceof \ XM \ SecurityBundle \ Entity \ User ) { $ user -> incrementLoginCount ( ) ; $ this -> userManager -> updateUser ( $ user ) ; $ this -> addLogSuccess ( $ user ) ; } }
Logs the successful login . Event will be passed but we don t use it or care what it is .
26,086
public function logFailure ( AuthenticationFailureEvent $ event ) { $ request = $ this -> requestStack -> getCurrentRequest ( ) ; $ exception = $ event -> getAuthenticationException ( ) -> getPrevious ( ) ; if ( null === $ exception ) { $ exception = $ event -> getAuthenticationException ( ) ; } $ authLog = $ this -> createAuthLog ( ) ; $ authLog -> setSuccess ( false ) ; $ authLog -> setUsername ( $ request -> request -> get ( '_username' ) ) ; $ authLog -> setMessage ( $ exception -> getMessage ( ) ) ; $ this -> em -> persist ( $ authLog ) ; $ this -> em -> flush ( ) ; }
Logs a failed login .
26,087
protected function createAuthLog ( ) { $ request = $ this -> requestStack -> getCurrentRequest ( ) ; $ authLog = new $ this -> authLogClass ( ) ; $ authLog -> setDatetime ( new \ DateTimeImmutable ( ) ) ; $ authLog -> setUserAgent ( $ request -> headers -> get ( 'User-Agent' ) ) ; $ authLog -> setIpAddress ( $ request -> getClientIp ( ) ) ; return $ authLog ; }
Creates the auth log entity with the User Agent and client IP .
26,088
protected function addLogSuccess ( UserInterface $ user ) { $ this -> userManager -> updateUser ( $ user ) ; $ authLog = $ this -> createAuthLog ( ) ; $ authLog -> setSuccess ( true ) ; $ authLog -> setUser ( $ user ) ; $ authLog -> setUsername ( $ user -> getUsername ( ) ) ; $ this -> em -> persist ( $ authLog ) ; $ this -> em -> flush ( ) ; }
Add successful log .
26,089
public function getBirthday ( ) { if ( isset ( $ this -> _userInfo [ 'birthday' ] ) ) { $ this -> _userInfo [ 'birthday' ] = str_replace ( '0000' , date ( 'Y' ) , $ this -> _userInfo [ 'birthday' ] ) ; $ result = date ( 'd.m.Y' , strtotime ( $ this -> _userInfo [ 'birthday' ] ) ) ; } else { $ result = null ; } return $ result ; }
Get user birthday or null if it is not set
26,090
public function groupAppend ( $ groupName , $ groupName2OrArray , $ replace = true ) { $ this -> load ( $ groupName ) ; $ data = [ ] ; if ( is_array ( $ groupName2OrArray ) ) { $ data = $ groupName2OrArray ; } else { $ this -> load ( $ groupName2OrArray ) ; $ data = $ this -> langs [ $ groupName2OrArray ] ; } if ( ! empty ( $ data ) ) { foreach ( $ data as $ k => $ v ) { if ( isset ( $ this -> langs [ $ groupName ] [ $ k ] ) ) { if ( $ replace == true ) { $ this -> langs [ $ groupName ] [ $ k ] = $ v ; } } else { $ this -> langs [ $ groupName ] [ $ k ] = $ v ; } } } }
append a group or array to the group
26,091
public function defaultValue ( ) { if ( $ this -> default === null ) { return null ; } $ default = $ this -> default ; if ( strstr ( $ this -> default , '{{' ) && strstr ( $ this -> default , '}}' ) ) { $ default = str_replace ( "{{CURRENT_TIME}}" , date ( 'c' , time ( ) ) , $ default ) ; } return $ default ; }
Parse and return default value of column .
26,092
private function deleteDailyBackups ( ) { try { $ date = strtotime ( '-2 months' ) ; if ( ( int ) date ( 'j' , $ date ) !== 1 ) { $ this -> filesystem -> deleteDir ( date ( "Y/m/d" , $ date ) ) ; } } catch ( \ Exception $ e ) { $ this -> event -> fire ( 'MonasheeBackupError' , 'Error trying to delete directory on AWS S3' ) ; } }
Delete AWS S3 directory of 2 months ago but keep 1st of the month
26,093
public function delete ( $ key ) { $ permission = $ this -> findByKey ( $ key ) ; if ( ! isset ( $ permission ) ) { return true ; } return $ permission -> delete ( ) ; }
Delete a permission
26,094
public function findNotInRole ( RoleInterface $ role ) { $ callback = function ( $ permission ) use ( $ role ) { return $ role -> hasnt ( $ permission -> key ) ; } ; return array_filter ( $ this -> findAll ( ) , $ callback ) ; }
Find permission not in a role
26,095
public static function handle ( $ errLevel , $ errMessage ) { if ( $ errLevel === E_RECOVERABLE_ERROR ) { if ( $ explode = explode ( ' ' , $ errMessage ) ) { if ( $ explode [ 0 ] === 'Argument' && $ explode [ 2 ] === 'passed' && $ explode [ 3 ] === 'to' && $ explode [ 5 ] === 'must' && $ explode [ 20 ] === 'defined' ) { $ arg = $ explode [ 1 ] - 1 ; $ mustType = $ explode [ 10 ] ; $ back = debug_backtrace ( ) [ 1 ] ; $ explode = explode ( '\\' , $ mustType ) ; $ end = end ( $ explode ) ; $ getLastType = rtrim ( $ end , ',' ) ; $ args = $ back [ 'args' ] ; $ arg = $ args [ $ arg ] ; if ( gettype ( $ arg ) != $ getLastType ) { if ( call_user_func ( static :: $ types [ $ getLastType ] , $ arg ) ) { return true ; } else { return false ; } } else { return true ; } } else { return false ; } } } else { return false ; } }
handle the error
26,096
public function indexAction ( Request $ request ) { $ query = $ request -> get ( 'query' ) ; $ limit = $ request -> get ( 'limit' , 8 ) ; $ start = $ request -> get ( 'start' , 0 ) ; $ search = $ this -> get ( 'phlexible_search.search' ) ; $ results = $ search -> search ( $ query ) ; return new JsonResponse ( [ 'totalCount' => count ( $ results ) , 'results' => array_slice ( $ results , $ start , $ limit ) , ] ) ; }
Return search results .
26,097
public static final function values ( ) { $ calledClass = get_called_class ( ) ; if ( empty ( self :: $ cachedValues [ $ calledClass ] ) ) { $ class = new \ ReflectionClass ( $ calledClass ) ; self :: $ cachedValues [ $ calledClass ] = $ class -> getConstants ( ) ; } return self :: $ cachedValues [ $ calledClass ] ; }
Returns a list of values this Enum can take . The keys are the defined constants and the values are their respective values .
26,098
public final function equals ( $ e ) { if ( is_object ( $ e ) ) { if ( ! ( $ e instanceof static ) ) { return false ; } return $ this -> value === $ e -> value ; } return $ this -> value === $ e ; }
Helper function to compare an Enum instance to another Enum instance or a scalar value .
26,099
public function values ( $ values ) { if ( is_array ( $ values ) ) $ this -> value = $ values ; else $ this -> valueList = func_get_args ( ) ; return $ this ; }
Sets the values to insert as a list