idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
18,800
public function xmlToArray ( $ string ) { $ doc = new DOMDocument ( ) ; $ doc -> loadXML ( $ string ) ; $ root = $ doc -> documentElement ; return $ this -> DomNodeToArray ( $ root ) ; }
convert XML response to array
18,801
public function stripBom ( $ body ) { if ( substr ( $ body , 0 , 3 ) === "\xef\xbb\xbf" ) { $ body = substr ( $ body , 3 ) ; } else { if ( substr ( $ body , 0 , 4 ) === "\xff\xfe\x00\x00" || substr ( $ body , 0 , 4 ) === "\x00\x00\xfe\xff" ) { $ body = substr ( $ body , 4 ) ; } else { if ( substr ( $ body , 0 , 2 ) === "\xff\xfe" || substr ( $ body , 0 , 2 ) === "\xfe\xff" ) { $ body = substr ( $ body , 2 ) ; } } } return $ body ; }
Remove null byte from body
18,802
public static function withSecure ( $ amount , Currency $ currency = null ) { if ( ! is_long ( $ amount ) ) throw new InvalidAmountException ; $ money = self :: withRaw ( 0 , $ currency ) ; $ money -> setFraction ( $ amount / 100 ) ; $ money -> setWhole ( $ amount / 100 ) ; return $ money ; }
Creates a money instance using a complete integer value for both the whole part and the fractional part
18,803
private function setFraction ( $ amount ) { $ doubleFraction = $ amount * 100 ; $ intFraction = ( $ this -> round ( abs ( $ doubleFraction ) ) ) % 100 ; if ( $ intFraction < 0 ) $ intFraction = - $ intFraction ; $ this -> fraction = $ intFraction ; }
Sets the fractional part of the money
18,804
public function add ( Money $ money ) { $ sum = $ this -> getAmount ( ) + $ money -> getAmount ( ) ; $ this -> setWhole ( $ sum ) ; $ this -> setFraction ( $ sum ) ; return $ this ; }
Adds given money to this money
18,805
public function subtract ( Money $ money ) { $ diff = new Money ( $ this -> getAmount ( ) - $ money -> getAmount ( ) ) ; $ this -> setWhole ( $ diff -> getAmount ( ) ) ; $ this -> setFraction ( $ diff -> getAmount ( ) ) ; return $ this ; }
Subtracts the given money from this money
18,806
public function times ( $ factor ) { $ totalFactor = $ factor * $ this -> getAmount ( ) ; $ this -> setWhole ( $ totalFactor ) ; $ this -> setFraction ( $ totalFactor ) ; return $ this ; }
Scales this money by the provided factor
18,807
public function formatFile ( $ filename , $ lexer = null , array $ options = array ( ) ) { if ( ! $ this -> fs -> exists ( $ filename ) ) { throw new \ InvalidArgumentException ( sprintf ( 'the file %s doesn\'t exists' , $ filename ) ) ; } $ this -> subject = $ filename ; $ this -> lexer = null === $ lexer ? $ this -> binary -> guessLexer ( $ filename ) : $ lexer ; $ this -> format = 'html' ; return $ this -> binary -> execute ( $ this , array_merge ( $ this -> options , $ options ) ) ; }
format a file by its name
18,808
public function format ( $ content , $ originalFilename ) { $ pathInfo = pathinfo ( $ originalFilename ) ; $ filename = sys_get_temp_dir ( ) . '/pygmentize_' . sha1 ( uniqid ( ) ) . ( isset ( $ pathInfo [ 'extension' ] ) ? '.' . $ pathInfo [ 'extension' ] : '' ) ; $ this -> fs -> touch ( $ filename ) ; $ h = fopen ( $ filename , 'w' ) ; fwrite ( $ h , $ content ) ; fclose ( $ h ) ; return $ this -> formatFile ( $ filename , $ this -> binary -> guessLexer ( $ filename ) ) ; }
format a string of content
18,809
public function pay ( ) { if ( ! Settings :: first ( ) -> ready ( ) ) { return false ; } if ( $ this -> ammount != 0 ) { try { Charge :: create ( [ 'amount' => $ this -> ammount , 'currency' => $ this -> currency , 'source' => $ this -> source , 'description' => $ this -> description , ] ) ; } catch ( Exception $ e ) { $ this -> error = $ e ; return false ; } } return true ; }
Execute the payment and return true if succeeded .
18,810
public function prepare ( ) { if ( is_array ( $ this -> viewData ) ) { foreach ( $ this -> viewData as $ _token => $ _value ) { if ( is_object ( $ _value ) && is_subclass_of ( $ _value , __CLASS__ ) ) { $ $ _token = $ _value -> prepare ( ) ; } else { $ $ _token = $ _value ; } } } if ( is_file ( $ this -> filePath ) ) { ob_start ( ) ; require ( $ this -> filePath ) ; return ob_get_clean ( ) ; } else { throw new ViewFileNotFoundException ( 'No such view: ' . $ this -> filePath ) ; } }
Returns string of template pointed to by file with data passed to it .
18,811
public function unsetData ( $ field = null ) { if ( $ field ) { unset ( $ this -> viewData [ $ field ] ) ; } else { $ this -> viewData = array ( ) ; } return $ this ; }
Unsets data either by field or all fields
18,812
public function addCache ( CacheInterface $ cache , $ priority = 0 ) { $ this -> caches [ spl_object_hash ( $ cache ) ] = array ( 'cache' => $ cache , 'priority' => $ priority ) ; $ this -> sortedCaches = null ; }
Add cache to storage
18,813
public function getRouteMatch ( ) { if ( null === $ this -> routeMatch ) { $ this -> routeMatch = $ this -> getEvent ( ) -> getRouteMatch ( ) ; } return $ this -> routeMatch ; }
Return matched route .
18,814
public static function forge ( $ custom = array ( ) ) { $ custom = ! is_array ( $ custom ) ? array ( 'driver' => $ custom ) : $ custom ; $ config = \ Config :: get ( 'auth.' . $ custom [ 'driver' ] . '_config' , array ( ) ) ; $ config = array_merge ( $ config , $ custom ) ; if ( empty ( $ config [ 'driver' ] ) || ! is_string ( $ config [ 'driver' ] ) ) { throw new \ AuthException ( 'No auth driver given.' ) ; } $ driver = \ Auth_Login_Driver :: forge ( $ config ) ; $ id = $ driver -> get_id ( ) ; if ( isset ( static :: $ _instances [ $ id ] ) ) { $ class = get_class ( $ driver ) ; if ( ! static :: $ _instances [ $ id ] instanceof $ class ) { throw new \ AuthException ( 'You can not instantiate two different login drivers using the same id "' . $ id . '"' ) ; } } else { static :: $ _instances [ $ id ] = $ driver ; } if ( count ( static :: $ _instances ) > 1 ) { static :: $ _verify_multiple = \ Config :: get ( 'auth.verify_multiple_logins' , false ) ; } return static :: $ _instances [ $ id ] ; }
Load a login driver to the array of loaded drivers
18,815
public static function check ( $ specific = null ) { $ drivers = $ specific === null ? static :: $ _instances : ( array ) $ specific ; foreach ( $ drivers as $ i ) { if ( ! static :: $ _verify_multiple && ! empty ( static :: $ _verified ) ) { return true ; } $ i = $ i instanceof Auth_Login_Driver ? $ i : static :: instance ( $ i ) ; if ( ! array_key_exists ( $ i -> get_id ( ) , static :: $ _verified ) ) { $ i -> check ( ) ; } if ( $ specific ) { if ( array_key_exists ( $ i -> get_id ( ) , static :: $ _verified ) ) { return true ; } } } return $ specific === null && ! empty ( static :: $ _verified ) ; }
Check login drivers for validated login
18,816
public static function verified ( $ driver = null ) { if ( $ driver === null ) { return static :: $ _verified ; } if ( ! array_key_exists ( $ driver , static :: $ _verified ) ) { return false ; } return static :: $ _verified [ $ driver ] ; }
Get verified driver or all verified drivers returns false when specific driver has not validated when all were requested and none validated an empty array is returned
18,817
public static function register_driver_type ( $ type , $ check_method ) { $ driver_exists = ! is_string ( $ type ) || array_key_exists ( $ type , static :: $ _drivers ) || method_exists ( get_called_class ( ) , $ check_method ) || in_array ( $ type , array ( 'login' , 'group' , 'acl' ) ) ; $ method_exists = ! is_string ( $ type ) || array_search ( $ check_method , static :: $ _drivers ) || method_exists ( get_called_class ( ) , $ type ) ; if ( $ driver_exists && static :: $ _drivers [ $ type ] == $ check_method ) { return true ; } if ( $ driver_exists || $ method_exists ) { \ Error :: notice ( 'Cannot add driver type, its name conflicts with another driver or method.' ) ; return false ; } static :: $ _drivers [ $ type ] = $ check_method ; return true ; }
Register a new driver type
18,818
public static function unregister_driver_type ( $ type ) { if ( in_array ( $ type , array ( 'login' , 'group' , 'acl' ) ) ) { \ Error :: notice ( 'Cannot remove driver type, included drivers login, group and acl cannot be removed.' ) ; return false ; } unset ( static :: $ _drivers [ $ type ] ) ; return true ; }
Unregister a driver type
18,819
public function setQuery ( string $ query , ? PDO $ db = null ) { if ( $ db == null ) { $ db = MDbConnection :: getDbConnection ( ) ; } if ( $ db instanceof \ PDO ) { $ this -> query = new MPDOQuery ( $ query , $ db ) ; } else { throw new \ Exception ( "Database connection not supported." ) ; } $ this -> query -> exec ( ) ; }
Returns the QSqlQuery associated with this model .
18,820
public function logout ( $ destroy = false ) { if ( $ destroy === true ) { $ this -> _session -> destroy ( ) ; } else { $ this -> _session -> delete ( $ this -> sessionKey ( ) ) ; $ this -> _session -> regenerate ( ) ; } return ( ! $ this -> loggedIn ( ) ) ; }
Log out a user by removing the related session variables .
18,821
public function comeBack ( ) { $ initial_user = $ this -> _session -> get ( $ this -> _sessionKeyInitUser ) ; if ( $ initial_user ) { $ this -> logout ( ) ; return $ this -> _completeLogin ( $ initial_user ) ; } return false ; }
Come back to initial user
18,822
public function addLogger ( LoggerInterface $ logger , $ level = null , $ key = null ) { if ( $ logger instanceof AggregateLogger ) { throw new \ InvalidArgumentException ( "You cannot chain AggregateLoggers." , 500 ) ; } $ level = $ level ?? self :: DEBUG ; $ key = $ key ?? spl_object_hash ( $ logger ) ; $ this -> loggers [ $ key ] = [ 'logger' => $ logger , 'priority' => static :: levelPriority ( $ level ) , 'key' => $ key , 'enabled' => true ] ; return $ this ; }
Add a new logger to observe messages .
18,823
public function removeLogger ( string $ key , $ trigger = true ) { if ( $ trigger && ! $ this -> has ( $ key ) ) { trigger_error ( "Logger $key was removed without being added." ) ; } unset ( $ this -> loggers [ $ key ] ) ; return $ this ; }
Remove a logger by passing in its key .
18,824
public function removeLoggerByInstance ( $ logger , $ trigger = true ) { foreach ( $ this -> loggers as $ key => $ addedLogger ) { if ( $ addedLogger [ 0 ] === $ logger ) { unset ( $ this -> loggers [ $ key ] ) ; return $ this ; } } if ( $ trigger ) { $ class = get_class ( $ logger ) ; trigger_error ( "Logger $class was removed without being added." ) ; } return $ this ; }
Remove a logger by passing in its instance .
18,825
public function event ( $ event , $ level , $ message , $ context = [ ] ) { $ context [ 'event' ] = $ event ; $ this -> log ( $ level , $ message , $ context ) ; }
Log an event .
18,826
public function log ( $ level , $ message , array $ context = [ ] ) { $ levelPriority = self :: levelPriority ( $ level ) ; if ( $ levelPriority > LOG_DEBUG ) { throw new \ Psr \ Log \ InvalidArgumentException ( "Invalid log level: $level." ) ; } static $ inCall = false ; if ( $ inCall ) { return ; } $ inCall = true ; foreach ( $ this -> loggers as $ logger ) { if ( ! $ logger [ 'enabled' ] ) { continue ; } if ( $ logger [ 'priority' ] >= $ levelPriority ) { try { $ logger [ 'logger' ] -> log ( $ level , $ message , $ context ) ; } catch ( \ Exception $ ex ) { $ inCall = false ; throw $ ex ; } } } $ inCall = false ; }
Log with an arbitrary level .
18,827
public function getMediaContext ( $ context_id = null ) { if ( is_null ( $ context_id ) ) { $ context_id = $ this -> getMediaContextId ( ) ; } $ context = $ this -> getClassificationContextManager ( ) -> find ( $ context_id ) ; if ( is_null ( $ context ) ) { $ context = $ this -> getClassificationContextManager ( ) -> create ( ) ; $ context -> setId ( $ context_id ) ; $ context -> setName ( $ context_id ) ; $ context -> setEnabled ( true ) ; $ context -> setCreatedAt ( new \ Datetime ( ) ) ; $ context -> setUpdatedAt ( new \ Datetime ( ) ) ; $ this -> getEntityManager ( ) -> persist ( $ context ) ; $ this -> getEntityManager ( ) -> flush ( $ context ) ; $ defaultCategory = $ this -> getClassificationCategoryManager ( ) -> create ( ) ; $ defaultCategory -> setContext ( $ context ) ; $ defaultCategory -> setName ( $ context -> getId ( ) . '_default' ) ; $ defaultCategory -> setEnabled ( true ) ; $ defaultCategory -> setCreatedAt ( new \ Datetime ( ) ) ; $ defaultCategory -> setUpdatedAt ( new \ Datetime ( ) ) ; $ defaultCategory -> setSlug ( $ context -> getId ( ) . '_default' ) ; $ defaultCategory -> setDescription ( $ context -> getId ( ) . '_default' ) ; $ this -> getEntityManager ( ) -> persist ( $ defaultCategory ) ; $ this -> getEntityManager ( ) -> flush ( $ defaultCategory ) ; } return $ context ; }
Obtiene el contexto de medias
18,828
public function setSuccessRedirect ( \ Zend \ Mvc \ Controller \ Plugin \ Redirect $ redirect , $ route , $ params = [ ] ) { $ this -> redirect = $ redirect ; $ this -> redirectRoute = $ route ; $ this -> params = $ params ; }
Set the redirect that will be used if data is saved successfully
18,829
protected function create ( ... $ arguments ) { $ response = null ; while ( $ method = $ this -> methods -> next ( $ response ) ) { $ response = call_user_func ( $ method , ... $ arguments ) ; } return $ response ; }
Crea un valor para ser devuelto
18,830
public function GetPluginKey ( $ Key , $ Default = NULL ) { return GetValue ( $ Key , Gdn :: PluginManager ( ) -> GetPluginInfo ( get_class ( $ this ) , Gdn_PluginManager :: ACCESS_CLASSNAME ) , $ Default ) ; }
Get a specific keyvalue from the plugin info array
18,831
protected function TrimMetaKey ( $ FullyQualifiedUserKey ) { $ Key = explode ( '.' , $ FullyQualifiedUserKey ) ; if ( $ Key [ 0 ] == 'Plugin' && sizeof ( $ Key ) >= 3 ) { return implode ( '.' , array_slice ( $ Key , 2 ) ) ; } return $ FullyQualifiedUserKey ; }
This method trims the plugin prefix from a fully qualified MetaKey .
18,832
public function AutoToggle ( $ Sender , $ Redirect = NULL ) { $ PluginName = $ this -> GetPluginIndex ( ) ; $ EnabledKey = "Plugins.{$PluginName}.Enabled" ; $ CurrentConfig = C ( $ EnabledKey , FALSE ) ; $ PassedKey = GetValue ( 1 , $ Sender -> RequestArgs ) ; if ( $ Sender -> Form -> AuthenticatedPostBack ( ) || Gdn :: Session ( ) -> ValidateTransientKey ( $ PassedKey ) ) { $ CurrentConfig = ! $ CurrentConfig ; SaveToConfig ( $ EnabledKey , $ CurrentConfig ) ; } if ( $ Sender -> Form -> AuthenticatedPostBack ( ) ) $ this -> Controller_Index ( $ Sender ) ; else { if ( $ Redirect === FALSE ) return $ CurrentConfig ; if ( is_null ( $ Redirect ) ) Redirect ( 'plugin/' . strtolower ( $ PluginName ) ) ; else Redirect ( $ Redirect ) ; } return $ CurrentConfig ; }
Automatically handle the toggle effect
18,833
public function Render ( $ ViewName ) { $ PluginFolder = $ this -> GetPluginFolder ( FALSE ) ; $ this -> Sender -> Render ( $ ViewName , '' , $ PluginFolder ) ; }
Passthru render request to sender
18,834
public function toArray ( ) { $ data = [ 'name' => $ this -> getName ( ) , 'text' => $ this -> getText ( ) , 'type' => $ this -> getType ( ) , 'style' => $ this -> getStyle ( ) , ] ; if ( $ this -> getUrl ( ) ) $ data [ 'url' ] = $ this -> getUrl ( ) ; if ( $ this -> getValue ( ) ) $ data [ 'value' ] = $ this -> getValue ( ) ; if ( $ this -> getConfirm ( ) ) $ data [ 'confirm' ] = $ this -> getConfirm ( ) -> toArray ( ) ; if ( $ this -> getOptions ( ) ) $ data [ 'options' ] = $ this -> getOptions ( ) ; if ( $ this -> getOptionGroups ( ) ) $ data [ 'option_groups' ] = $ this -> getOptionGroups ( ) ; if ( $ this -> getDataSource ( ) ) $ data [ 'data_source' ] = $ this -> getDataSource ( ) ; if ( $ this -> getSelectedOptions ( ) ) $ data [ 'selected_options' ] = $ this -> getSelectedOptions ( ) ; if ( $ this -> getMinQueryLength ( ) ) $ data [ 'min_query_length' ] = $ this -> getMinQueryLength ( ) ; return $ data ; }
Get the array representation of this attachment action
18,835
public static function checkAuthentication ( $ redirect = true ) { if ( static :: isAuthenticated ( ) ) { return ; } if ( $ redirect ) { Http \ Server :: getInstance ( ) -> redirect ( RouteCollection :: getInstance ( ) -> get ( 'login' ) -> getUri ( ) ) ; } else { throw new LoginException ( ) ; } }
Check for authentication & redirect if not logged in .
18,836
protected static function restoreFromSession ( ) { $ session = Http \ Session :: getInstance ( ) ; try { $ mapper = new UserMapper ( Database :: get ( ) ) ; $ user = $ mapper -> findFromSession ( $ session ) ; } catch ( \ Exception $ exception ) { $ user = new Data \ User \ User ( ) ; } static :: $ user = $ user ; }
Try to restore user from data in session .
18,837
public function serialize ( ) { $ list = [ ] ; foreach ( $ this as $ index => $ value ) { $ list [ $ index ] = $ value ; } return serialize ( $ list ) ; }
serializing the data fo current object
18,838
public function unserialize ( $ serialized ) { $ list = unserialize ( $ serialized ) ; if ( is_array ( $ list ) ) { foreach ( $ list as $ index => $ value ) { $ this [ $ index ] = $ value ; } } }
unserialize and serialized array and make this object base on that
18,839
public static function toCamelCase ( $ string ) { static $ canUse = null ; if ( is_null ( $ canUse ) ) { $ canUse = method_exists ( Strings :: class , 'firstLower' ) ; } $ pascal = self :: toPascalCase ( $ string ) ; return $ canUse ? Strings :: firstLower ( $ pascal ) : Strings :: lower ( Strings :: substring ( $ pascal , 0 , 1 ) ) . Strings :: substring ( $ pascal , 1 ) ; }
Converts the given string to camelCase .
18,840
public function rateLimitReached ( ) { if ( $ this -> isIpWhitelisted ( ) ) { return false ; } if ( $ this -> isIpBlacklisted ( ) ) { return true ; } $ rateLimit = $ this -> config -> get ( 'BlockThreshold' , 0 ) ; if ( $ rateLimit < 1 ) { return false ; } $ rc = LoginRateControlEntity :: find ( [ 'ip' => $ this -> ip ] , [ '-timestamp' ] , 1 , $ rateLimit ) ; if ( ! $ rc ) { return false ; } $ blockTtl = $ this -> config -> get ( 'BlockTimelimit' , 1 ) * 60 ; if ( ( time ( ) - $ blockTtl ) > 60 ) { return false ; } return true ; }
Check if current IP should be blocked from login page
18,841
public function generateDeviceValidationToken ( $ username ) { $ this -> username = $ username ; $ validationToken = $ this -> crypt ( ) -> generateRandomString ( 6 , '0123456789' ) ; $ devices = $ this -> getMeta ( ) -> allowedDevices ; $ devices [ ] = [ 'device' => $ this -> getDeviceFingerprint ( ) , 'created' => 0 , 'token' => '' , 'validationToken' => $ validationToken , 'confirmed' => false ] ; $ this -> getMeta ( ) -> allowedDevices = $ devices ; $ this -> getMeta ( ) -> save ( ) ; return $ validationToken ; }
Generates a unique token to authenticate the current device for the given username .
18,842
public function validateDeviceConfirmationToken ( $ username , $ token ) { $ this -> username = $ username ; if ( $ this -> rateLimitReached ( ) ) { throw new LoginException ( 'The current user session is block from login page.' , 1 ) ; } $ allowedList = $ this -> getMeta ( ) -> allowedDevices -> val ( ) ; if ( ! is_array ( $ allowedList ) ) { return false ; } $ newAllowedList = $ allowedList ; $ deviceId = $ this -> getDeviceFingerprint ( ) ; $ i = 0 ; foreach ( $ allowedList as $ al ) { if ( $ al [ 'confirmed' ] == false && $ al [ 'device' ] == $ deviceId && $ token == $ al [ 'validationToken' ] ) { $ token = $ this -> crypt ( ) -> generateUserReadableString ( 32 ) ; $ newAllowedList [ $ i ] [ 'confirmed' ] = true ; $ newAllowedList [ $ i ] [ 'created' ] = time ( ) ; $ newAllowedList [ $ i ] [ 'token' ] = $ token ; $ this -> getMeta ( ) -> allowedDevices = $ newAllowedList ; $ this -> getMeta ( ) -> save ( ) ; return $ token ; } $ i ++ ; } $ newAllowedList = [ ] ; foreach ( $ allowedList as $ al ) { if ( $ al [ 'confirmed' ] != false ) { $ newAllowedList [ ] = $ al ; } } $ this -> getMeta ( ) -> allowedDevices = $ newAllowedList ; $ this -> getMeta ( ) -> save ( ) ; $ this -> incrementLoginAttempts ( ) ; return false ; }
Checks if the provided token matches a device validation token in the database for the given username . If token matches the given device is now allowed access .
18,843
public function setUserBlockedStatus ( $ username , $ blocked = true ) { $ this -> username = $ username ; $ this -> getMeta ( ) -> blocked = $ blocked ; $ this -> getMeta ( ) -> save ( ) ; }
Change the blocked user account status flag .
18,844
public function setUserAccountConfirmationStatus ( $ username , $ confirmed = true ) { $ this -> username = $ username ; $ this -> getMeta ( ) -> confirmed = $ confirmed ; $ this -> getMeta ( ) -> save ( ) ; }
Change the confirmed user account status flag .
18,845
public function getUser ( $ authToken , $ deviceToken = '' ) { $ user = null ; $ this -> security ( $ this -> fwName ) -> getToken ( ) -> setTokenString ( $ authToken ) ; try { $ user = $ this -> security ( $ this -> fwName ) -> getUser ( ) ; } catch ( TokenException $ e ) { if ( $ e -> getCode ( ) === TokenException :: TOKEN_EXPIRED ) { throw new LoginException ( 'The current auth session is no longer valid.' , 7 ) ; } } if ( ! $ user -> isAuthenticated ( ) ) { throw new LoginException ( 'User is not authenticated' , 6 ) ; } $ this -> username = $ user -> getUsername ( ) ; if ( $ this -> isAccountBlocked ( $ this -> username ) ) { $ this -> security -> firewall ( $ this -> fwName ) -> processLogout ( ) ; throw new LoginException ( 'User account is blocked.' , 2 ) ; } if ( ! $ this -> isAccountActive ( $ this -> username ) ) { $ this -> security -> firewall ( $ this -> fwName ) -> processLogout ( ) ; throw new LoginException ( 'User hasn\'t confirmed his account.' , 4 ) ; } if ( $ this -> config -> get ( 'ValidateDevice' , false ) ) { if ( ! $ this -> isDeviceSessionValid ( $ deviceToken ) ) { $ this -> security -> firewall ( $ this -> fwName ) -> processLogout ( ) ; throw new LoginException ( 'The device session is no longer valid.' , 8 ) ; } } if ( ! $ this -> isSessionValid ( $ authToken ) ) { $ this -> security -> firewall ( $ this -> fwName ) -> processLogout ( ) ; throw new LoginException ( 'The current auth session is no longer valid.' , 7 ) ; } return $ user ; }
Returns User object for the provided auth token and device token . If user is not found or session is invalid an exception is thrown .
18,846
private function getDeviceFingerprint ( ) { $ server = $ this -> httpRequest ( ) -> server ( ) ; $ did = '' ; $ did .= '|' . $ server -> httpAcceptLanguage ( ) ; if ( empty ( $ server -> httpUserAgent ( ) ) ) { throw new LoginException ( 'Unable to process the request without a user agent' , 100 ) ; } $ platform = 'unknown' ; $ ub = 'unknown' ; $ ua = $ server -> httpUserAgent ( ) ; if ( preg_match ( '/linux/i' , $ ua ) ) { $ platform = 'linux' ; } elseif ( preg_match ( '/macintosh|mac os x/i' , $ ua ) ) { $ platform = 'mac' ; } elseif ( preg_match ( '/windows|win32/i' , $ ua ) ) { $ platform = 'windows' ; } if ( preg_match ( '/MSIE/i' , $ ua ) && ! preg_match ( '/Opera/i' , $ ua ) ) { $ ub = "MSIE" ; } elseif ( preg_match ( '/Firefox/i' , $ ua ) ) { $ ub = "Firefox" ; } elseif ( preg_match ( '/Chrome/i' , $ ua ) ) { $ ub = "Chrome" ; } elseif ( preg_match ( '/Safari/i' , $ ua ) ) { $ ub = "Safari" ; } elseif ( preg_match ( '/Opera/i' , $ ua ) ) { $ ub = "Opera" ; } elseif ( preg_match ( '/Netscape/i' , $ ua ) ) { $ ub = "Netscape" ; } $ did .= '|' . $ platform ; $ did .= '|' . $ ub ; return md5 ( $ did ) ; }
Generates a device fingerprint .
18,847
private function isSessionValid ( $ session ) { $ sessions = $ this -> getMeta ( ) -> sessions ; $ sessionTtl = $ this -> getSessionTtl ( ) ; foreach ( $ sessions as $ s ) { if ( $ s [ 'sid' ] == $ session && ( $ s [ 'created' ] + $ sessionTtl ) > time ( ) ) { return true ; } } return false ; }
Checks if the given session is still valid .
18,848
private function isDeviceSessionValid ( $ deviceToken ) { $ devices = $ this -> getMeta ( ) -> allowedDevices ; $ deviceTtl = $ this -> config -> get ( 'DeviceTtl' , $ this -> defaultDeviceTtl ) ; $ currentDeviceFingerprint = $ this -> getDeviceFingerprint ( ) ; foreach ( $ devices as $ d ) { if ( $ d [ 'token' ] == $ deviceToken && ( $ d [ 'created' ] + ( 86400 * $ deviceTtl ) ) > time ( ) && $ d [ 'device' ] == $ currentDeviceFingerprint ) { return true ; } } return false ; }
Check if the given device token is still valid .
18,849
private function incrementLoginAttempts ( ) { $ rc = new LoginRateControlEntity ( ) ; $ rc -> ip = $ this -> ip ; $ rc -> username = $ this -> username ; $ rc -> timestamp = time ( ) ; $ rc -> save ( ) ; }
Increments the number of login attempts for the current username and IP .
18,850
private function resetRateLimit ( ) { LoginRateControlEntity :: find ( [ 'ip' => $ this -> ip , 'username' => $ this -> username ] ) -> delete ( ) ; $ ts = time ( ) - ( 30 * 86400 ) ; LoginRateControlEntity :: find ( [ 'timestamp' => [ '$lt' => [ $ ts ] ] ] ) -> delete ( ) ; }
Resets the rate limit for the current ip and username . It also clears the records that are older than 30 days .
18,851
private function isIpWhitelisted ( ) { $ whitelist = $ this -> config -> get ( 'RateLimitWhitelist' , [ ] , true ) ; if ( in_array ( $ this -> ip , $ whitelist ) ) { return true ; } return false ; }
Checks if the current ip is whitelisted .
18,852
private function isIpBlacklisted ( ) { $ blacklist = $ this -> config -> get ( 'RateLimitBlacklist' , [ ] , true ) ; if ( in_array ( $ this -> ip , $ blacklist ) ) { return true ; } return false ; }
Checks if the current ip is black listed .
18,853
private function storeUserSession ( $ session ) { $ sessions = $ this -> getMeta ( ) -> sessions -> val ( ) ; if ( ! is_array ( $ sessions ) ) { $ sessions = [ ] ; } $ newSessions = [ ] ; $ ttl = $ this -> getSessionTtl ( ) ; foreach ( $ sessions as $ s ) { if ( ( $ s [ 'created' ] + $ ttl ) > time ( ) ) { $ newSessions [ ] = $ s ; } } $ newSessions [ ] = [ 'sid' => $ session , 'created' => time ( ) , 'ip' => $ this -> ip ] ; $ this -> getMeta ( ) -> lastLogin = time ( ) ; $ this -> getMeta ( ) -> loginAttempts [ ] = [ 'ip' => $ this -> ip , 'timestamp' => time ( ) ] ; $ this -> getMeta ( ) -> sessions = $ newSessions ; $ this -> getMeta ( ) -> save ( ) ; }
Stores a new active session for the current user .
18,854
public static function set ( $ namespace , $ path ) { $ namespace = trim ( $ namespace , '\\' ) ; $ path = rtrim ( $ path , '/' ) ; if ( ! isset ( self :: $ _namespace_list [ $ namespace ] ) ) { self :: $ _namespace_list [ $ namespace ] = [ ] ; } self :: $ _namespace_list [ $ namespace ] [ ] = $ path ; }
Set Command Path
18,855
public static function getId ( $ reference = null , $ base_id = null ) { if ( empty ( $ reference ) ) { $ reference = uniqid ( ) ; } if ( isset ( self :: $ dom_id_register [ $ reference ] ) ) { return self :: $ dom_id_register [ $ reference ] ; } return self :: getNewId ( $ reference , $ base_id ) ; }
Get a DOM unique ID
18,856
public static function getNewId ( $ reference = null , $ base_id = null ) { if ( empty ( $ reference ) ) { $ reference = uniqid ( ) ; } if ( true === $ base_id ) { $ base_id = $ reference ; } if ( ! is_null ( $ base_id ) ) { $ new_id = $ base_id ; while ( in_array ( $ new_id , self :: $ dom_id_register ) ) { $ new_id = $ base_id . '_' . uniqid ( ) ; } } else { $ new_id = uniqid ( ) ; while ( in_array ( $ new_id , self :: $ dom_id_register ) ) { $ new_id = uniqid ( ) ; } } self :: $ dom_id_register [ $ reference ] = $ new_id ; return $ new_id ; }
Create and get a new DOM unique ID
18,857
public static function writeHtmlTag ( $ tag_name , $ content = '' , $ attrs = array ( ) , $ intag_close = false ) { $ str = '<' . $ tag_name . self :: parseAttributes ( $ attrs ) ; if ( empty ( $ content ) && true === $ intag_close ) { $ str .= self :: $ html_tag_closure ; } else { $ str .= '>' . ( is_string ( $ content ) ? $ content : '' ) . '</' . $ tag_name . '>' ; } return $ str ; }
Build an HTML string for a specific tag with attributes
18,858
public static function parseAttributes ( array $ attrs = array ( ) ) { $ str = '' ; foreach ( $ attrs as $ var => $ val ) { $ str .= ' ' . $ var . '="' . ( is_array ( $ val ) ? join ( ' ' , $ val ) : $ val ) . '"' ; } return $ str ; }
Build an attributes HTML string from an array like variable = > value pairs
18,859
public static function javascriptProtect ( $ str = '' , $ protect_quotes = false ) { $ str = preg_replace ( '/\s\s+/' , ' ' , $ str ) ; $ str = htmlentities ( $ str ) ; if ( true === $ protect_quotes ) { $ str = str_replace ( "'" , "\'" , $ str ) ; $ str = str_replace ( '"' , '\"' , $ str ) ; } return $ str ; }
Build an HTML string to use in javascripts attributes or functions
18,860
public function getMacAddress ( ) : ? string { if ( ! $ this -> hasMacAddress ( ) ) { $ this -> setMacAddress ( $ this -> getDefaultMacAddress ( ) ) ; } return $ this -> macAddress ; }
Get mac address
18,861
public function setFetchMode ( $ mode , $ complement_info = null , array $ ctor_args = array ( ) ) { $ fetchMode = new FetchMode ( $ mode , $ complement_info , $ ctor_args ) ; $ this -> attributes [ DB :: ATTR_DEFAULT_FETCH_MODE ] = serialize ( $ fetchMode ) ; }
Sets default fetch mode
18,862
protected function canDelete ( $ record ) { if ( empty ( $ record -> id ) || $ record -> published != - 2 ) { return false ; } return JFactory :: getUser ( ) -> authorise ( 'core.delete' , $ record -> extension . '.category.' . ( int ) $ record -> id ) ; }
Method to test whether a record can be deleted .
18,863
protected function canEditState ( $ record ) { $ user = JFactory :: getUser ( ) ; if ( ! empty ( $ record -> id ) ) { return $ user -> authorise ( 'core.edit.state' , $ record -> extension . '.category.' . ( int ) $ record -> id ) ; } if ( ! empty ( $ record -> parent_id ) ) { return $ user -> authorise ( 'core.edit.state' , $ record -> extension . '.category.' . ( int ) $ record -> parent_id ) ; } return $ user -> authorise ( 'core.edit.state' , $ record -> extension ) ; }
Method to test whether a record can have its state changed .
18,864
protected function populateState ( ) { $ app = JFactory :: getApplication ( 'administrator' ) ; $ parentId = $ app -> input -> getInt ( 'parent_id' ) ; $ this -> setState ( 'category.parent_id' , $ parentId ) ; $ pk = $ app -> input -> getInt ( 'id' ) ; $ this -> setState ( $ this -> getName ( ) . '.id' , $ pk ) ; $ extension = $ app -> input -> get ( 'extension' , 'com_content' ) ; $ this -> setState ( 'category.extension' , $ extension ) ; $ parts = explode ( '.' , $ extension ) ; $ this -> setState ( 'category.component' , $ parts [ 0 ] ) ; $ this -> setState ( 'category.section' , ( count ( $ parts ) > 1 ) ? $ parts [ 1 ] : null ) ; $ params = JComponentHelper :: getParams ( 'com_categories' ) ; $ this -> setState ( 'params' , $ params ) ; }
Auto - populate the model state .
18,865
public function getItem ( $ pk = null ) { if ( $ result = parent :: getItem ( $ pk ) ) { if ( empty ( $ result -> id ) ) { $ result -> parent_id = $ this -> getState ( 'category.parent_id' ) ; $ result -> extension = $ this -> getState ( 'category.extension' ) ; } $ registry = new Registry ; $ registry -> loadString ( $ result -> metadata ) ; $ result -> metadata = $ registry -> toArray ( ) ; $ tz = new DateTimeZone ( JFactory :: getApplication ( ) -> get ( 'offset' ) ) ; if ( ( int ) $ result -> created_time ) { $ date = new JDate ( $ result -> created_time ) ; $ date -> setTimezone ( $ tz ) ; $ result -> created_time = $ date -> toSql ( true ) ; } else { $ result -> created_time = null ; } if ( ( int ) $ result -> modified_time ) { $ date = new JDate ( $ result -> modified_time ) ; $ date -> setTimezone ( $ tz ) ; $ result -> modified_time = $ date -> toSql ( true ) ; } else { $ result -> modified_time = null ; } } $ assoc = $ this -> getAssoc ( ) ; if ( $ assoc ) { if ( $ result -> id != null ) { $ result -> associations = ArrayHelper :: toInteger ( CategoriesHelper :: getAssociations ( $ result -> id , $ result -> extension ) ) ; } else { $ result -> associations = array ( ) ; } } return $ result ; }
Method to get a category .
18,866
public function getForm ( $ data = array ( ) , $ loadData = true ) { $ extension = $ this -> getState ( 'category.extension' ) ; $ jinput = JFactory :: getApplication ( ) -> input ; if ( empty ( $ extension ) && isset ( $ data [ 'extension' ] ) ) { $ extension = $ data [ 'extension' ] ; $ parts = explode ( '.' , $ extension ) ; $ this -> setState ( 'category.extension' , $ extension ) ; $ this -> setState ( 'category.component' , $ parts [ 0 ] ) ; $ this -> setState ( 'category.section' , @ $ parts [ 1 ] ) ; } $ form = $ this -> loadForm ( 'com_categories.category' . $ extension , 'category' , array ( 'control' => 'jform' , 'load_data' => $ loadData ) ) ; if ( empty ( $ form ) ) { return false ; } if ( empty ( $ data [ 'extension' ] ) ) { $ data [ 'extension' ] = $ extension ; } $ user = JFactory :: getUser ( ) ; if ( ! $ user -> authorise ( 'core.edit.state' , $ extension . '.category.' . $ jinput -> get ( 'id' ) ) ) { $ form -> setFieldAttribute ( 'ordering' , 'disabled' , 'true' ) ; $ form -> setFieldAttribute ( 'published' , 'disabled' , 'true' ) ; $ form -> setFieldAttribute ( 'ordering' , 'filter' , 'unset' ) ; $ form -> setFieldAttribute ( 'published' , 'filter' , 'unset' ) ; } return $ form ; }
Method to get the row form .
18,867
protected function loadFormData ( ) { $ app = JFactory :: getApplication ( ) ; $ data = $ app -> getUserState ( 'com_categories.edit.' . $ this -> getName ( ) . '.data' , array ( ) ) ; if ( empty ( $ data ) ) { $ data = $ this -> getItem ( ) ; if ( ! $ data -> id ) { $ extension = substr ( $ app -> getUserState ( 'com_categories.categories.filter.extension' ) , 4 ) ; $ filters = ( array ) $ app -> getUserState ( 'com_categories.categories.' . $ extension . '.filter' ) ; $ data -> set ( 'published' , $ app -> input -> getInt ( 'published' , ( ( isset ( $ filters [ 'published' ] ) && $ filters [ 'published' ] !== '' ) ? $ filters [ 'published' ] : null ) ) ) ; $ data -> set ( 'language' , $ app -> input -> getString ( 'language' , ( ! empty ( $ filters [ 'language' ] ) ? $ filters [ 'language' ] : null ) ) ) ; $ data -> set ( 'access' , $ app -> input -> getInt ( 'access' , ( ! empty ( $ filters [ 'access' ] ) ? $ filters [ 'access' ] : JFactory :: getConfig ( ) -> get ( 'access' ) ) ) ) ; } } $ this -> preprocessData ( 'com_categories.category' , $ data ) ; return $ data ; }
Method to get the data that should be injected in the form .
18,868
public function publish ( & $ pks , $ value = 1 ) { if ( parent :: publish ( $ pks , $ value ) ) { $ dispatcher = JEventDispatcher :: getInstance ( ) ; $ extension = JFactory :: getApplication ( ) -> input -> get ( 'extension' ) ; JPluginHelper :: importPlugin ( 'content' ) ; $ dispatcher -> trigger ( 'onCategoryChangeState' , array ( $ extension , $ pks , $ value ) ) ; return true ; } }
Method to change the published state of one or more records .
18,869
public function rebuild ( ) { $ table = $ this -> getTable ( ) ; if ( ! $ table -> rebuild ( ) ) { $ this -> setError ( $ table -> getError ( ) ) ; return false ; } $ this -> cleanCache ( ) ; return true ; }
Method rebuild the entire nested set tree .
18,870
public function saveorder ( $ idArray = null , $ lft_array = null ) { $ table = $ this -> getTable ( ) ; if ( ! $ table -> saveorder ( $ idArray , $ lft_array ) ) { $ this -> setError ( $ table -> getError ( ) ) ; return false ; } $ this -> cleanCache ( ) ; return true ; }
Method to save the reordered nested set tree . First we save the new order values in the lft values of the changed ids . Then we invoke the table rebuild to implement the new ordering .
18,871
protected function cleanCache ( $ group = null , $ client_id = 0 ) { $ extension = JFactory :: getApplication ( ) -> input -> get ( 'extension' ) ; switch ( $ extension ) { case 'com_content' : parent :: cleanCache ( 'com_content' ) ; parent :: cleanCache ( 'mod_articles_archive' ) ; parent :: cleanCache ( 'mod_articles_categories' ) ; parent :: cleanCache ( 'mod_articles_category' ) ; parent :: cleanCache ( 'mod_articles_latest' ) ; parent :: cleanCache ( 'mod_articles_news' ) ; parent :: cleanCache ( 'mod_articles_popular' ) ; break ; default : parent :: cleanCache ( $ extension ) ; break ; } }
Custom clean the cache of com_content and content modules
18,872
protected function generateNewTitle ( $ parent_id , $ alias , $ title ) { $ table = $ this -> getTable ( ) ; while ( $ table -> load ( array ( 'alias' => $ alias , 'parent_id' => $ parent_id ) ) ) { $ title = JString :: increment ( $ title ) ; $ alias = JString :: increment ( $ alias , 'dash' ) ; } return array ( $ title , $ alias ) ; }
Method to change the title & alias .
18,873
public function getAssoc ( ) { static $ assoc = null ; if ( ! is_null ( $ assoc ) ) { return $ assoc ; } $ extension = $ this -> getState ( 'category.extension' ) ; $ assoc = JLanguageAssociations :: isEnabled ( ) ; $ extension = explode ( '.' , $ extension ) ; $ component = array_shift ( $ extension ) ; $ cname = str_replace ( 'com_' , '' , $ component ) ; if ( ! $ assoc || ! $ component || ! $ cname ) { $ assoc = false ; } else { $ hname = $ cname . 'HelperAssociation' ; JLoader :: register ( $ hname , JPATH_SITE . '/components/' . $ component . '/helpers/association.php' ) ; $ assoc = class_exists ( $ hname ) && ! empty ( $ hname :: $ category_association ) ; } return $ assoc ; }
Method to determine if a category association is available .
18,874
public function getMainTemplateFile ( ) { $ main = $ this -> getPath ( ) . '/main.ss' ; if ( file_exists ( $ main ) ) { return $ main ; } $ main = ( string ) $ this -> getConfiguration ( ) -> main_template ; if ( $ main ) { return SSViewer :: getTemplateFileByType ( $ main , 'main' ) ; } return false ; }
Gets the absolute path to the main template file
18,875
public function getDataSource ( ) { foreach ( self :: $ data_file_names as $ name ) { $ path = $ this -> getPath ( ) . '/' . $ name ; if ( file_exists ( $ path ) ) { return new DataSource ( $ path ) ; } } return false ; }
Gets the data source as an object
18,876
public function loadRequirements ( ) { foreach ( $ this -> getStylesheets ( ) as $ css ) { Requirements :: css ( $ this -> getRelativePath ( ) . '/' . basename ( $ css ) ) ; } foreach ( $ this -> getJavascripts ( ) as $ js ) { Requirements :: javascript ( $ this -> getRelativePath ( ) . '/' . basename ( $ js ) ) ; } }
Loads all of the JS and CSS
18,877
public static function instance ( $ instance = null ) { if ( $ instance === true ) { return static :: $ _instances ; } elseif ( $ instance !== null ) { if ( ! array_key_exists ( $ instance , static :: $ _instances ) ) { return false ; } return static :: $ _instances [ $ instance ] ; } return static :: $ _instance ; }
Return a specific driver or the default instance
18,878
public function check ( $ ability , $ arguments = [ ] ) { if ( ! is_array ( $ arguments ) ) { $ arguments = [ $ arguments ] ; } array_unshift ( $ arguments , $ ability ) ; return call_user_func_array ( [ $ this -> gatekeeper , 'check' ] , $ arguments ) ; }
Determine if the given ability should be granted .
18,879
protected function setFlash ( $ key , $ value ) { $ flashbag = Session :: getFlashBag ( ) ; $ flashbag -> set ( $ key , $ value ) ; }
Sets the flash variable to the session flashbag .
18,880
protected function assignFlash ( $ key , $ viewKey ) { if ( count ( $ msg = $ this -> getFlash ( $ key ) ) > 0 ) { $ this -> set ( $ viewKey , implode ( ", " , $ msg ) ) ; } }
Sets the flash message from the flashbag to a variable available in the view .
18,881
protected function __getLoopsId ( $ refkey = NULL ) { $ classname = get_class ( $ this ) ; if ( $ refkey ) { $ reflection = new ReflectionClass ( $ classname ) ; if ( $ reflection -> hasProperty ( $ refkey ) ) { $ classname = $ reflection -> getProperty ( $ refkey ) -> getDeclaringClass ( ) -> getName ( ) ; } } if ( $ page_parameter = $ this -> parameter ) { $ parts = $ newparts = explode ( "\\" , $ classname ) ; while ( $ parameter = array_shift ( $ page_parameter ) ) { $ pos = array_search ( "_" , $ parts ) ; if ( $ pos == FALSE ) { break ; } $ parts [ $ pos ] = "" ; $ newparts [ $ pos ] = $ parameter ; } $ loopsid = implode ( "-" , $ newparts ) ; } else { $ loopsid = str_replace ( "\\" , "-" , $ classname ) ; } return $ loopsid ; }
Take page element inheritance into account when generating the loopsid .
18,882
public function writeCachedContent ( $ content ) { if ( $ this -> source -> recompiled || ! ( $ this -> caching == Smarty :: CACHING_LIFETIME_CURRENT || $ this -> caching == Smarty :: CACHING_LIFETIME_SAVED ) ) { return false ; } $ this -> properties [ 'cache_lifetime' ] = $ this -> cache_lifetime ; $ this -> properties [ 'unifunc' ] = 'content_' . str_replace ( '.' , '_' , uniqid ( '' , true ) ) ; $ content = $ this -> createTemplateCodeFrame ( $ content , true ) ; $ _smarty_tpl = $ this ; eval ( "?>" . $ content ) ; $ this -> cached -> valid = true ; $ this -> cached -> processed = true ; return $ this -> cached -> write ( $ this , $ content ) ; }
Writes the cached template output
18,883
public function toArray ( ) { $ connections = array ( ) ; foreach ( $ this as $ key => $ connection ) { $ connections [ $ key ] = $ connection -> config ( ) ; } return $ connections ; }
Only returns connection configs indexed by dbname
18,884
public function addDependencyRetriever ( Retriever $ dependencyRetriever ) { if ( ! array_key_exists ( $ dependencyRetriever -> getName ( ) , $ this -> dependencyRetrievers ) ) { $ this -> dependencyRetrievers [ $ dependencyRetriever -> getName ( ) ] = $ dependencyRetriever ; } }
Adds another dependency retriever .
18,885
public function arg ( $ key ) { return isset ( $ this -> args -> $ key ) ? $ this -> args -> $ key : null ; }
Get arg value for this field
18,886
public static function parseType ( $ fieldName , $ desc ) { if ( is_array ( $ desc ) ) { $ typeDesc = $ desc [ 'type' ] ; } else { $ typeDesc = $ desc ; $ desc = array ( ) ; } $ parse = EntityDescriptor :: parseType ( $ fieldName , $ typeDesc ) ; $ field = new static ( $ fieldName , $ parse -> type ) ; $ TYPE = $ field -> getType ( ) ; $ field -> args = $ TYPE -> parseArgs ( $ parse -> args ) ; $ field -> default = $ parse -> default ; $ field -> writable = $ TYPE -> isWritable ( ) ; $ field -> nullable = $ TYPE -> isNullable ( ) ; if ( ! isset ( $ field -> writable ) ) { $ field -> writable = true ; } if ( ! isset ( $ field -> nullable ) ) { $ field -> nullable = false ; } if ( isset ( $ desc [ 'writable' ] ) ) { $ field -> writable = ! empty ( $ desc [ 'writable' ] ) ; } else if ( $ field -> writable ) { $ field -> writable = ! in_array ( 'readonly' , $ parse -> flags ) ; } else { $ field -> writable = in_array ( 'writable' , $ parse -> flags ) ; } if ( isset ( $ desc [ 'nullable' ] ) ) { $ field -> nullable = ! empty ( $ desc [ 'nullable' ] ) ; } else if ( $ field -> nullable ) { $ field -> nullable = ! in_array ( 'notnull' , $ parse -> flags ) ; } else { $ field -> nullable = in_array ( 'nullable' , $ parse -> flags ) ; } return $ field ; }
Parse field type configuration from file string
18,887
public static function buildIDField ( $ name ) { $ field = new static ( $ name , 'ref' ) ; $ TYPE = $ field -> getType ( ) ; $ field -> args = $ TYPE -> parseArgs ( array ( ) ) ; $ field -> default = null ; $ field -> writable = false ; $ field -> nullable = false ; return $ field ; }
Build ID field for an entity
18,888
public static function extend ( $ method ) { if ( is_array ( $ method ) ) { if ( count ( $ method ) == 2 && method_exists ( $ method [ 0 ] , $ method [ 1 ] ) ) { array_push ( self :: $ _extends , [ 'class' => $ method [ 0 ] , 'method' => $ method [ 1 ] ] ) ; } else { throw new MissingTemplateException ( 'You c\'ant extend the template engine with the method : "' . $ method [ 0 ] . '"' ) ; } } else { $ trace = debug_backtrace ( ) ; if ( isset ( $ trace [ 1 ] ) ) { array_push ( self :: $ _extends , [ 'class' => '\\' . $ trace [ 1 ] [ 'class' ] , 'method' => $ method ] ) ; } else { throw new MissingTemplateException ( 'Can\'t reach the method "' . $ method . '"' ) ; } } }
permit to extend the template engine with custom functions
18,889
protected function _compile ( $ content , $ type = self :: TPL_COMPILE_ALL ) { switch ( $ type ) { case self :: TPL_COMPILE_ALL : return $ this -> _parser -> parse ( $ content ) ; break ; case self :: TPL_COMPILE_INCLUDE : return $ this -> _parser -> parseNoTemplate ( $ content ) ; break ; case self :: TPL_COMPILE_LANG : return $ this -> _parser -> parseLang ( $ content ) ; break ; } return '' ; }
compile the template instance
18,890
public function mount ( Info $ info ) : PDO { $ trouble = false ; $ pdo = null ; switch ( $ info -> getDsn ( ) ) { case "mysql" : $ pdo = ( new MySql ( ) ) -> connect ( $ info ) ; break ; default : $ trouble = true ; break ; } if ( $ trouble ) { Lang :: addRoot ( Environment :: PACKAGE , Environment :: PATH ) ; throw new Exception ( Lang :: get ( "database:database:invalid" , "helionogueir/database" ) ) ; } return $ pdo ; }
- Mount database by object
18,891
public function updateIndexes ( $ timeout = null ) { foreach ( $ this -> metadataFactory -> getAllMetadata ( ) as $ class ) { if ( $ class -> isMappedSuperclass || $ class -> isEmbeddedDocument ) { continue ; } $ this -> updateDocumentIndexes ( $ class -> name , $ timeout ) ; } }
Ensure indexes exist for all mapped document classes .
18,892
public function deleteIndexes ( ) { foreach ( $ this -> metadataFactory -> getAllMetadata ( ) as $ class ) { if ( $ class -> isMappedSuperclass || $ class -> isEmbeddedDocument ) { continue ; } $ this -> deleteDocumentIndexes ( $ class -> name ) ; } }
Delete indexes for all documents that can be loaded with the metadata factory .
18,893
public function dropCollections ( ) { foreach ( $ this -> metadataFactory -> getAllMetadata ( ) as $ class ) { if ( $ class -> isMappedSuperclass || $ class -> isEmbeddedDocument ) { continue ; } $ this -> dropDocumentCollection ( $ class -> name ) ; } }
Drop all the mapped document collections in the metadata factory .
18,894
public function dropDatabases ( ) { foreach ( $ this -> metadataFactory -> getAllMetadata ( ) as $ class ) { if ( $ class -> isMappedSuperclass || $ class -> isEmbeddedDocument ) { continue ; } $ this -> dropDocumentDatabase ( $ class -> name ) ; } }
Drop all the mapped document databases in the metadata factory .
18,895
public function createDatabases ( ) { foreach ( $ this -> metadataFactory -> getAllMetadata ( ) as $ class ) { if ( $ class -> isMappedSuperclass || $ class -> isEmbeddedDocument ) { continue ; } $ this -> createDocumentDatabase ( $ class -> name ) ; } }
Create all the mapped document databases in the metadata factory .
18,896
public function createDocumentDatabase ( $ documentName ) { $ class = $ this -> dm -> getClassMetadata ( $ documentName ) ; if ( $ class -> isMappedSuperclass || $ class -> isEmbeddedDocument ) { throw new \ InvalidArgumentException ( 'Cannot delete document indexes for mapped super classes or embedded documents.' ) ; } $ this -> dm -> getDocumentDatabase ( $ documentName ) -> execute ( "function() { return true; }" ) ; }
Create the document database for a mapped class .
18,897
public function onRoute ( $ e ) { $ request = $ e -> getRequest ( ) ; $ router = $ e -> getRouter ( ) ; $ routeMatch = $ router -> match ( $ request ) ; if ( ! $ routeMatch instanceof RouteMatch ) throw new RouteNotFoundException ( ) ; $ e -> setRouteMatch ( $ routeMatch ) ; return $ routeMatch ; }
Listen to the route event and attempt to route the request
18,898
public function execute ( $ statement , $ params = array ( ) ) { $ preparedStmt = null ; $ result = false ; try { $ preparedStmt = $ this -> getConnection ( ) -> prepare ( $ statement ) ; } catch ( PDOException $ e ) { throw new ClientException ( 'Failed to prepare MySQL statement.' , null , $ e ) ; } foreach ( $ params as $ name => $ paramInfo ) { if ( is_string ( $ paramInfo ) ) { $ preparedStmt -> bindValue ( $ name , $ paramInfo , PDO :: PARAM_STR ) ; } elseif ( is_array ( $ paramInfo ) ) { list ( $ value , $ type ) = $ paramInfo ; $ preparedStmt -> bindValue ( $ name , $ value , $ type ) ; } } try { $ result = $ preparedStmt -> execute ( ) ; } catch ( PDOException $ e ) { throw new ClientException ( 'Failed to execute MySQL statement.' , null , $ e ) ; } return $ result ; }
Execute a statement returning boolean true on success .
18,899
public function getSingleResult ( $ statement , $ params = array ( ) ) { $ result = $ this -> getResults ( $ statement , $ params ) ; if ( ! sizeof ( $ result ) ) { return null ; } return $ result [ 0 ] ; }
Execute a statement returning one row of results or null .