idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
59,600
public static function register_js ( $ path , $ prefix = '' , $ version = null , $ footer = true ) { $ function = function ( ) use ( $ path , $ prefix , $ version , $ footer ) { foreach ( self :: parse_dir ( $ path , 'js' , $ prefix ) as $ handle => $ data ) { if ( is_null ( $ version ) ) { $ this_version = filemtime ( $ data [ 'path' ] ) ; } else { $ this_version = $ version ; } wp_register_script ( $ handle , $ data [ 'url' ] , $ data [ 'deps' ] , $ this_version , $ footer ) ; } } ; if ( did_action ( 'init' ) ) { $ function ( ) ; } else { add_action ( 'init' , $ function ) ; } }
Bulk register javascripts .
59,601
public static function register_styles ( $ path , $ prefix = '' , $ version = null , $ screen = 'all' ) { $ function = function ( ) use ( $ path , $ prefix , $ version , $ screen ) { foreach ( self :: parse_dir ( $ path , 'css' , $ prefix ) as $ handle => $ data ) { if ( is_null ( $ version ) ) { $ this_version = filemtime ( $ data [ 'path' ] ) ; } else { $ this_version = $ version ; } wp_register_style ( $ handle , $ data [ 'url' ] , $ data [ 'deps' ] , $ this_version , $ screen ) ; } } ; if ( did_action ( 'init' ) ) { $ function ( ) ; } else { add_action ( 'init' , $ function ) ; } }
Register all style .
59,602
public static function grab_deps ( $ file ) { if ( ! file_exists ( $ file ) ) { return [ ] ; } $ fp = fopen ( $ file , 'r' ) ; $ file_header = fread ( $ fp , 8192 ) ; fclose ( $ fp ) ; $ file_header = str_replace ( "\r" , "\n" , $ file_header ) ; $ regexp = '#wpdeps=(.*)$#um' ; if ( ! preg_match_all ( $ regexp , $ file_header , $ matches ) ) { return [ ] ; } else { list ( $ match , $ deps ) = $ matches ; $ deps = [ ] ; foreach ( $ matches [ 1 ] as $ dep ) { foreach ( array_map ( 'trim' , explode ( ',' , $ dep ) ) as $ d ) { if ( $ d ) { $ deps [ ] = $ d ; } } } return $ deps ; } }
Path to file .
59,603
public static function parse_dir ( $ path , $ extension , $ prefix = '' ) { $ extension = ltrim ( $ extension , '.' ) ; $ regexp = '#/([^._][^/]*)\.' . $ extension . '$#u' ; if ( ! is_dir ( $ path ) ) { return [ ] ; } $ files = [ ] ; $ finder = new Finder ( ) ; foreach ( $ finder -> in ( $ path ) -> name ( "*.{$extension}" ) -> files ( ) as $ file ) { $ file_path = $ file -> getPathname ( ) ; if ( ! preg_match ( $ regexp , $ file_path , $ match ) ) { continue ; } $ handle = $ prefix . $ match [ 1 ] ; $ deps = self :: grab_deps ( $ file_path ) ; $ url = str_replace ( ABSPATH , home_url ( '/' ) , $ file_path ) ; $ files [ $ handle ] = [ 'path' => $ file_path , 'deps' => $ deps , 'url' => $ url , ] ; } return $ files ; }
Grab directory and retrieve file .
59,604
public static function register_js_var_files ( $ dir ) { if ( ! is_dir ( $ dir ) ) { return [ ] ; } $ finder = new Finder ( ) ; $ registered = [ ] ; foreach ( $ finder -> in ( $ dir ) -> name ( '*.php' ) -> files ( ) as $ file ) { $ path = $ file -> getPathname ( ) ; $ file_name = basename ( $ path ) ; if ( preg_match ( '#^[_.]#u' , $ file_name ) ) { continue ; } $ handle = str_replace ( '.php' , '' , $ file_name ) ; $ var_name = self :: camelize ( $ handle ) ; $ vars = include $ path ; if ( ! is_array ( $ vars ) ) { continue ; } $ vars = apply_filters ( 'wp_enqueue_manager_vars' , $ vars , $ handle ) ; wp_localize_script ( $ handle , $ var_name , $ vars ) ; $ registered [ $ handle ] = [ 'name' => $ var_name , 'vars' => $ vars , ] ; } return $ registered ; }
Parse directory and fetch vars .
59,605
public static function createLog ( ) { list ( $ route , $ params ) = Yii :: $ app -> getRequest ( ) -> resolve ( ) ; if ( strpos ( $ route , 'debug/default/toolbar' ) !== false ) return ; $ route = Url :: to ( ) ; $ description = '' ; $ userId = ( int ) Yii :: $ app -> user -> id ; $ userIP = Yii :: $ app -> request -> userIP ; $ model = new Log ( ) ; $ data = [ 'route' => $ route , 'description' => $ description , 'user_id' => $ userId , 'user_ip' => $ userIP , 'created_at' => time ( ) , ] ; $ model -> setAttributes ( $ data ) ; $ model -> save ( false ) ; }
Creates a log .
59,606
public static function getRegisteredRoutes ( ) { if ( self :: $ _routes === null ) { self :: $ _routes = [ ] ; $ manager = Configs :: authManager ( ) ; foreach ( $ manager -> getPermissions ( ) as $ item ) { if ( $ item -> name [ 0 ] === Configs :: instance ( ) -> routePrefix ) { self :: $ _routes [ $ item -> name ] = $ item -> name ; } } } return self :: $ _routes ; }
Get registered routes
59,607
public function calculate ( GeoDataProvider $ provider , $ date , array $ inputValues = [ ] ) { $ this -> resetData ( ) ; $ fields = array_keys ( $ this -> fields ) ; foreach ( $ fields as $ field ) { $ this -> calculateField ( $ provider , $ field , $ date , $ inputValues ) ; } return $ this -> fields ; }
Calculates target values .
59,608
public function guessOptions ( $ class , $ fieldName ) { $ optionGuesses = array ( ) ; foreach ( $ this -> guessers as $ guesser ) { $ guesses = $ guesser -> guessOptions ( $ class , $ fieldName ) ; foreach ( $ guesses as $ guess ) { $ optionGuesses [ $ guess -> getOptionName ( ) ] [ ] = $ guess ; } } $ options = array ( ) ; foreach ( $ optionGuesses as $ name => $ guesses ) { $ value = null ; $ confidence = 0 ; foreach ( $ guesses as $ guess ) { if ( $ guess -> getConfidence ( ) >= $ confidence ) { $ value = $ guess -> getOptionValue ( ) ; $ confidence = $ guess -> getConfidence ( ) ; } } $ options [ $ name ] = $ value ; } return $ options ; }
Guesses option for a class and field .
59,609
public function create ( $ pointer ) { $ pointer = PointerFormat :: normalize ( $ pointer , $ this -> context ) ; $ instance = Builder :: build ( $ pointer , $ this -> context ) ; Validator :: validate ( $ instance , $ this -> context ) ; return $ instance ; }
Creates an object by the pointer
59,610
final public function blockCreate ( array $ block ) { $ result = [ ] ; foreach ( $ block as $ k => $ pointer ) { $ result [ $ k ] = $ this -> create ( $ pointer ) ; } return $ result ; }
Creates a block of objects
59,611
public static function isParity ( $ value , array $ params , Template $ template ) { if ( empty ( $ params ) || count ( $ params ) < 1 || ! isset ( $ params [ 'then' ] ) ) { throw new TemplateException ( TemplateException :: UNKNOWN_PARAM_FILTER , [ 'name' => __METHOD__ ] ) ; } $ params [ 'else' ] = isset ( $ params [ 'else' ] ) ? $ params [ 'else' ] : null ; $ template = clone $ template ; $ placeholders = [ ] ; $ placeholders [ 'output' ] = $ value ; return NumericHelper :: isParity ( $ value ) ? $ template -> replace ( $ params [ 'then' ] , $ placeholders ) : $ template -> replace ( $ params [ 'else' ] , $ placeholders ) ; }
Check numeric is parity .
59,612
public static function formula ( $ value , array $ params = [ ] ) { if ( empty ( $ params [ 'operator' ] ) || ! isset ( $ params [ 'operand' ] ) ) { return $ value ; } switch ( trim ( $ params [ 'operator' ] ) ) { case '*' : return $ value * $ params [ 'operand' ] ; case '/' : return $ value / $ params [ 'operand' ] ; case '+' : return $ value + $ params [ 'operand' ] ; case '-' : return $ value - $ params [ 'operand' ] ; case '**' : return pow ( $ value , $ params [ 'operand' ] ) ; case 'mod' : case '%' : return $ value % $ params [ 'operand' ] ; case '|' : return $ value | $ params [ 'operand' ] ; case '&' : return $ value & $ params [ 'operand' ] ; case '^' : case 'xor' : return $ value ^ $ params [ 'operand' ] ; case '<<' : return $ value << $ params [ 'operand' ] ; case '>>' : return $ value >> $ params [ 'operand' ] ; } throw new TemplateException ( "Unknown operator: {$params['operator']}" ) ; }
The value is calculated by the formula
59,613
public function register ( Application $ app ) { $ app [ 'social-login.controller' ] = $ app -> share ( function ( $ app ) { $ config = $ app [ 'config' ] -> load ( 'social-login' ) ; $ controller = new SocialLoginController ; $ controller -> setSocialLoginService ( $ app [ 'social-login.service' ] ) -> setConfig ( $ config ) -> setServiceFactory ( new ServiceFactory ( ) ) -> setSession ( $ app [ 'session' ] ) ; return $ controller ; } ) ; $ app [ 'social-login.mapper' ] = $ app -> share ( function ( $ app ) { return new SocialLoginMapper ( $ app [ 'db' ] , new SocialLoginEntity ) ; } ) ; $ app [ 'social-login.service' ] = $ app -> share ( function ( $ app ) { $ service = new SocialLoginService ; $ service -> setUserService ( $ app [ 'user.service' ] ) -> setSocialLoginMapper ( $ app [ 'social-login.mapper' ] ) -> setOAuthStorage ( $ app [ 'oauth.storage' ] ) ; return $ service ; } ) ; $ app -> get ( '/social-login/{provider}' , 'social-login.controller:login' ) -> bind ( 'social-login-auth' ) ; $ app -> get ( '/social-login/{provider}/link' , 'social-login.controller:link' ) -> bind ( 'social-link-auth' ) ; $ app -> get ( '/social-login/{provider}/callback' , 'social-login.controller:callback' ) -> bind ( 'social-login-callback' ) ; $ this -> setFirewalls ( $ app ) ; }
Register social login services
59,614
protected function setFirewalls ( Application $ app ) { $ app -> extend ( 'security.firewalls' , function ( $ firewalls , $ app ) { $ socialLoginLink = new RequestMatcher ( '^/social-login/[a-z]+/link' , null , [ 'GET' ] ) ; $ socialLogin = new RequestMatcher ( '^/social-login' , null , [ 'GET' ] ) ; $ socialFirewalls = [ 'social-login-link' => [ 'pattern' => $ socialLoginLink , 'oauth' => true , ] , 'social-login' => [ 'pattern' => $ socialLogin , 'anonymous' => true , ] , ] ; return array_merge ( $ socialFirewalls , $ firewalls ) ; } ) ; }
Set social login related firewalls
59,615
public function validate ( $ group , Constraint $ constraint ) { $ check = $ this -> container -> get ( 'admin.configuration.configgroup_manager' ) -> getRepository ( ) -> findOneBySectionAndGroupName ( $ group -> getConfigSection ( ) -> getName ( ) , $ group -> getName ( ) ) ; if ( $ check && $ check -> getId ( ) != $ group -> getId ( ) ) { $ message = $ this -> container -> get ( 'translator' ) -> trans ( $ constraint -> message , array ( '%group%' => $ group -> getName ( ) , '%section%' => $ group -> getConfigSection ( ) -> getName ( ) ) , 'VinceTAdminConfigurationBundle' ) ; $ this -> context -> addViolation ( $ message ) ; } }
Validate the group
59,616
protected function register ( $ method , $ route , $ handler ) { if ( $ route == '/' ) { return ; } if ( is_array ( $ method ) ) { foreach ( $ method as $ http ) { $ routeCollection = new Route ( $ http , $ route , new RouteHandler ( $ handler ) ) ; array_push ( $ this -> routeCollections , $ routeCollection ) ; } return ; } $ routeCollection = new Route ( $ method , $ route , new RouteHandler ( $ handler ) ) ; array_push ( $ this -> routeCollections , $ routeCollection ) ; return $ this -> routeCollections [ sizeof ( $ this -> routeCollections ) - 1 ] ; }
Register a route with the router .
59,617
public function isValueValidType ( $ value ) { switch ( $ this -> getType ( ) ) { case self :: TYPE_BOOLEAN : $ isValid = is_bool ( $ value ) ; break ; case self :: TYPE_DATE : case self :: TYPE_DATETIME : $ isValid = is_object ( $ value ) and get_class ( $ value ) == 'DateTime' ; break ; case self :: TYPE_NUMBER : $ isValid = is_numeric ( $ value ) ; break ; case self :: TYPE_STRING : $ isValid = is_string ( $ value ) ; break ; default : $ isValid = false ; } return $ isValid ; }
Determines if the supplied value is of the correct type
59,618
public function prePersist ( LifecycleEventArgs $ args ) : void { $ entity = $ args -> getEntity ( ) ; if ( $ entity instanceof CreatedInterface ) { $ entity -> setCreatedAt ( new \ DateTime ( ) ) ; } }
Modify an entity before persist
59,619
public function preUpdate ( LifecycleEventArgs $ args ) : void { $ entity = $ args -> getEntity ( ) ; if ( $ entity instanceof UpdatedInterface ) { $ entity -> setUpdatedAt ( new \ DateTime ( ) ) ; } }
Modify an entity before update
59,620
public function getDriver ( ) : string { $ driver = $ this -> getConfig ( 'driver' ) ; try { if ( ! \ is_string ( $ driver ) ) { throw new Exception ( 'Wrong type of "driver" item in config, must be a string' ) ; } if ( ! \ in_array ( $ driver , self :: ALLOWED_DRIVERS , false ) ) { $ allowed = implode ( ',' , self :: ALLOWED_DRIVERS ) ; throw new Exception ( "Driver \"$driver\" is not in allowed list [" . $ allowed . ']' ) ; } } catch ( Exception $ e ) { } return __NAMESPACE__ . '\\Drivers\\' . ucfirst ( strtolower ( $ driver ) ) ; }
Get driver of current database
59,621
public function getConfig ( string $ name = null ) { return ( null !== $ name ) ? $ this -> _config -> get ( $ name ) : $ this -> _config ; }
Get database configuration object or array with single database
59,622
protected function getFilterFromApiCriteria ( \ Magento \ Framework \ Api \ Search \ SearchCriteriaInterface $ criteria ) { $ result = new \ Flancer32 \ Lib \ Repo \ Data \ ClauseSet \ Filter ( ) ; $ entriesRepoTop = [ ] ; $ groupsApi = $ criteria -> getFilterGroups ( ) ; foreach ( $ groupsApi as $ groupApi ) { $ entriesRepo = [ ] ; $ processed = [ ] ; foreach ( $ groupApi -> getFilters ( ) as $ item ) { $ field = $ item -> getField ( ) ; $ condType = $ item -> getConditionType ( ) ; $ value = $ item -> getValue ( ) ; $ hash = "$field|$condType|$value" ; if ( ! isset ( $ processed [ $ hash ] ) ) { $ condition = new \ Flancer32 \ Lib \ Repo \ Data \ ClauseSet \ Filter \ Condition ( ) ; $ condition -> alias = $ field ; $ func = $ this -> mapApiCondToRepoFunc ( $ condType ) ; $ condition -> func = $ func ; $ condition -> value = $ value ; $ entriesRepo [ ] = $ condition ; $ processed [ $ hash ] = true ; } } $ groupRepo = new \ Flancer32 \ Lib \ Repo \ Data \ ClauseSet \ Filter \ Group ( ) ; $ groupRepo -> entries = $ entriesRepo ; $ groupRepo -> with = \ Flancer32 \ Lib \ Repo \ Data \ ClauseSet \ Filter \ Group :: OP_AND ; $ entriesRepoTop [ ] = $ groupRepo ; } $ groupRepoTop = new \ Flancer32 \ Lib \ Repo \ Data \ ClauseSet \ Filter \ Group ( ) ; $ groupRepoTop -> entries = $ entriesRepoTop ; $ groupRepoTop -> with = \ Flancer32 \ Lib \ Repo \ Data \ ClauseSet \ Filter \ Group :: OP_AND ; $ result -> group = $ groupRepoTop ; return $ result ; }
Convert Magento API filter to Flancer32 Repo filter .
59,623
public function HashValue ( $ dynamicSalt , $ data , $ hashLength = null ) { $ separator = "$%*{//}*%$" ; return is_null ( $ hashLength ) && is_int ( $ hashLength ) ? substr ( sha1 ( $ this -> hashSalt . $ separator . $ dynamicSalt . $ separator . $ data ) , 0 , $ hashLength ) : sha1 ( $ this -> hashSalt . $ separator . $ dynamicSalt . $ separator . $ data ) ; }
Hash some data using Sha1 method with the encryption key . A dynamic salt generated at the request is used to create the hash .
59,624
public function Encrypt ( $ noncryptedData ) { $ encrypted = mcrypt_encrypt ( $ this -> encryptionType , $ this -> encryptionKey , $ noncryptedData , $ this -> encryptionMode , $ this -> iv ) ; $ encoded = base64_encode ( $ encrypted ) ; return $ encoded ; }
Encrypt a string using the MCRYPT_RIJNDAEL_128 encryption and MCRYPT_MODE_CBC and encode the result in a base64 string so it can be stored in a database or file without the hassle of encoding .
59,625
public function Decrypt ( $ encryptedData ) { $ decoded = base64_decode ( $ encryptedData , true ) ; $ decrypted = mcrypt_decrypt ( $ this -> encryptionType , $ this -> encryptionKey , $ decoded , $ this -> encryptionMode , $ this -> iv ) ; return $ decrypted ; }
Decrypt a encoded base64 string using the MCRYPT_RIJNDAEL_128 encryption and MCRYPT_MODE_CBC
59,626
public function restoreValue ( Method $ method , $ sanitize = true ) { $ v = $ method -> getValue ( $ this -> getName ( ) , $ this -> getRestoreDefault ( ) ) ; if ( $ this -> isMultiple ( ) && is_array ( $ v ) ) { foreach ( $ v as & $ value ) $ value = $ this -> importValue ( $ value ) ; } else { $ v = $ this -> importValue ( $ v ) ; } if ( $ sanitize ) foreach ( $ this -> sanitizers as $ s ) $ v = $ s -> sanitize ( $ v ) ; $ this -> value = $ v ; $ this -> restored = true ; }
Restores the value from the provided method
59,627
public function getValue ( ) { return $ this -> isMultiple ( ) && is_array ( $ this -> value ) ? $ this -> condenseMultiple ( $ this -> value ) : $ this -> value ; }
Whether to condense multiple values into a single string
59,628
static public function postvar ( $ name , $ isint = false ) { if ( ! empty ( $ _POST [ $ name ] ) && is_array ( $ _POST [ $ name ] ) ) { return ( array ) $ _POST [ $ name ] ; } $ response = ( isset ( $ _POST [ $ name ] ) ? filter_var ( $ _POST [ $ name ] , FILTER_SANITIZE_STRING ) : "" ) ; return ( ( boolean ) $ isint ? ( int ) $ response : ( string ) $ response ) ; }
Prevent undefined post variables
59,629
static public function getvar ( $ name , $ isint = false ) { if ( ! empty ( $ _GET [ $ name ] ) && is_array ( $ _GET [ $ name ] ) ) { return ( array ) $ _GET [ $ name ] ; } $ response = ( isset ( $ _GET [ $ name ] ) ? filter_var ( $ _GET [ $ name ] , FILTER_SANITIZE_STRING ) : "" ) ; return ( ( boolean ) $ isint ? ( int ) $ response : ( string ) $ response ) ; }
Prevent undefined get variables
59,630
static public function sessionvar ( $ name , $ isint = false ) { if ( ! empty ( $ _SESSION [ $ name ] ) && is_array ( $ _SESSION [ $ name ] ) ) { return ( array ) $ _SESSION [ $ name ] ; } $ response = ( isset ( $ _SESSION [ $ name ] ) ? $ _SESSION [ $ name ] : "" ) ; return ( ( boolean ) $ isint ? ( int ) $ response : ( string ) $ response ) ; }
Prevent undefined session variables
59,631
static public function cookievar ( $ name , $ isint = false ) { if ( ! empty ( $ _COOKIE [ $ name ] ) && is_array ( $ _COOKIE [ $ name ] ) ) { return ( array ) $ _COOKIE [ $ name ] ; } $ response = ( isset ( $ _COOKIE [ $ name ] ) ? $ _COOKIE [ $ name ] : "" ) ; return ( ( boolean ) $ isint ? ( int ) $ response : ( string ) $ response ) ; }
Prevent undefined cookie variables
59,632
static public function servervar ( $ name , $ isint = false ) { if ( ! empty ( $ _SERVER [ $ name ] ) && is_array ( $ _SERVER [ $ name ] ) ) { return ( array ) $ _SERVER [ $ name ] ; } $ response = ( isset ( $ _SERVER [ $ name ] ) ? $ _SERVER [ $ name ] : "" ) ; return ( ( boolean ) $ isint ? ( int ) $ response : ( string ) $ response ) ; }
Prevent undefined server variables
59,633
static public function getvar_default ( $ field_name , $ default_val = "" ) { return ( strlen ( self :: getvar ( $ field_name ) ) ? self :: getvar ( $ field_name ) : $ default_val ) ; }
Return getvar with a default when blank .
59,634
static public function postvar_default ( $ field_name , $ default_val = "" ) { return ( strlen ( self :: postvar ( $ field_name ) ) ? self :: postvar ( $ field_name ) : $ default_val ) ; }
Return postvar with a default when blank .
59,635
static public function right ( $ str , $ howManyCharsFromRight ) { $ strLen = strlen ( $ str ) ; return ( string ) substr ( $ str , $ strLen - $ howManyCharsFromRight , $ strLen ) ; }
Return characters from the right
59,636
static public function mid ( $ str , $ start , $ howManyChars = 0 ) { $ start -- ; if ( ( int ) $ howManyChars === 0 ) { $ howManyChars = ( int ) strlen ( $ str ) - ( int ) $ start ; } return ( string ) substr ( $ str , ( int ) $ start , ( int ) $ howManyChars ) ; }
Return x many characters from the starting point
59,637
static public function truncate ( $ num , $ digits = 0 ) { $ shift = pow ( 10 , $ digits ) ; return ( ( floor ( $ num * $ shift ) ) / $ shift ) ; }
Return truncated number .
59,638
static public function multi_stripslashes ( & $ arr ) { foreach ( $ arr as $ k => $ v ) { if ( is_array ( $ v ) ) { self :: multi_stripslashes ( $ arr [ $ k ] ) ; } else { $ arr [ $ k ] = stripslashes ( $ v ) ; } } }
Return array stripslasshes recursive .
59,639
static public function numberToRoman ( $ num ) { $ numr = intval ( $ num ) ; $ result = '' ; $ lookup = array ( 'M' => 1000 , 'CM' => 900 , 'D' => 500 , 'CD' => 400 , 'C' => 100 , 'XC' => 90 , 'L' => 50 , 'XL' => 40 , 'X' => 10 , 'IX' => 9 , 'V' => 5 , 'IV' => 4 , 'I' => 1 ) ; foreach ( $ lookup as $ roman => $ value ) { $ matches = intval ( $ numr / $ value ) ; $ result .= str_repeat ( $ roman , $ matches ) ; $ numr = $ numr % $ value ; } return ( string ) $ result ; }
Return roman numeral .
59,640
static public function duration ( $ secs ) { $ vals = array ( 'w' => ( int ) ( $ secs / 86400 / 7 ) , 'd' => $ secs / 86400 % 7 , 'h' => $ secs / 3600 % 24 , 'm' => $ secs / 60 % 60 , 's' => $ secs % 60 ) ; $ ret = array ( ) ; $ added = false ; foreach ( $ vals as $ k => $ v ) { if ( $ v > 0 || $ added ) { $ added = true ; $ ret [ ] = $ v . $ k ; } } return ( string ) join ( ' ' , $ ret ) ; }
Return duration from seconds .
59,641
static public function xml2array ( $ xmlstring ) { $ xml = simplexml_load_string ( $ xmlstring ) ; $ json = json_encode ( $ xml ) ; return json_decode ( $ json , true ) ; }
Return an array from xml string .
59,642
static public function escape ( $ inp ) { if ( ! empty ( $ inp ) && is_string ( $ inp ) ) { return ( string ) str_replace ( array ( '\\' , "\0" , "\n" , "\r" , "'" , '"' , "\x1a" ) , array ( '\\\\' , '\\0' , '\\n' , '\\r' , "\\'" , '\\"' , '\\Z' ) , $ inp ) ; } return ( string ) $ inp ; }
Escape a string just like mysql_escape_string which is now depreciated .
59,643
public function totalAction ( Request $ request ) { $ this -> checkAccess ( 'FUNCTIONS_TOTAL' , null ) ; $ count = $ this -> getResourceManager ( ) -> getCountElements ( ) ; $ view = $ this -> view ( array ( 'total' => intval ( $ count ) ) , \ FOS \ RestBundle \ Util \ Codes :: HTTP_OK ) ; return $ view ; }
Get quantity for all resources .
59,644
public function paginatedAction ( Request $ request , ParamFetcherInterface $ paramFetcher ) { $ this -> checkAccess ( 'FUNCTIONS_PAGINATED' , null ) ; $ page = $ paramFetcher -> get ( 'page' , 1 ) ; $ limit = $ paramFetcher -> get ( 'limit' , 32 ) ; $ pager = $ this -> getResourceManager ( ) -> createPagerfantaPaginator ( $ page , $ limit ) ; $ pagerfantaFactory = new PagerfantaFactory ( ) ; $ paginatedCollection = $ pagerfantaFactory -> createRepresentation ( $ pager , new \ Hateoas \ Configuration \ Route ( $ this -> getPaginatedActionRouteName ( ) , array ( ) , true ) ) ; $ view = $ this -> view ( $ paginatedCollection , \ FOS \ RestBundle \ Util \ Codes :: HTTP_OK ) ; return $ this -> handleView ( $ view ) ; }
List all resources paginated .
59,645
public static function set ( $ key , $ value ) { $ parts = explode ( '.' , $ key ) ; $ config = [ ] ; $ current = & $ config ; foreach ( $ parts as $ part ) { $ current [ $ part ] = [ ] ; $ current = & $ current [ $ part ] ; } $ current = $ value ; Application :: $ instance -> appendConfiguration ( $ config ) ; }
Set configuration value
59,646
static function load ( $ class_name ) { if ( stream_resolve_include_path ( "modules/archi/includes/" . $ class_name . ".class.php" ) ) { include_once "modules/archi/includes/" . $ class_name . ".class.php" ; } else if ( stream_resolve_include_path ( __DIR__ . "/frameworkClasses/" . $ class_name . ".class.php" ) ) { include_once __DIR__ . "/frameworkClasses/" . $ class_name . ".class.php" ; } }
Essaie de charger une classe
59,647
public function getMigrations ( ) { if ( count ( $ this -> _migrations ) <= 0 && $ this -> _config !== null ) { $ versions = [ ] ; $ paths = $ this -> _config -> getMigrationPaths ( ) ; foreach ( $ paths as $ path ) { $ files = glob ( $ path . '/*.php' ) ; foreach ( $ files as $ file ) { $ fileName = basename ( $ file ) ; if ( Util :: isValidMigrationFileName ( $ fileName ) ) { $ version = Util :: getVersionFromFileName ( $ fileName ) ; if ( Arr :: key ( $ version , $ versions ) ) { throw new \ InvalidArgumentException ( __d ( 'extensions' , 'Duplicate migration - "%s" has the same version as "%s"' , $ file , $ versions [ $ version ] -> getVersion ( ) ) ) ; } $ class = Util :: mapFileNameToClassName ( $ fileName ) ; require_once $ file ; if ( ! class_exists ( $ class ) ) { throw new \ InvalidArgumentException ( __d ( 'extensions' , 'Could not find class "%s" in file "%s"' , $ class , $ file ) ) ; } $ migration = new $ class ( $ version ) ; if ( ! ( $ migration instanceof AbstractMigration ) ) { throw new \ InvalidArgumentException ( __d ( 'extensions' , 'The class "%s" in file "%s" must extend \Phinx\Migration\AbstractMigration' , $ class , $ file ) ) ; } $ versions [ $ version ] = $ migration ; } } } ksort ( $ versions ) ; $ this -> _migrations = $ versions ; } return $ this -> _migrations ; }
Get plugin migrations .
59,648
public function hasMigration ( ) { $ migrations = array_keys ( $ this -> getMigrations ( ) ) ; if ( count ( $ migrations ) ) { foreach ( $ migrations as $ version ) { if ( ! $ this -> isMigrated ( $ version ) ) { return true ; } } } return false ; }
Check need plugin new migration .
59,649
protected function _configuration ( ) { return [ 'default_migration_table' => self :: SCHEMA_TABLE , 'default_database' => $ this -> _connectionConfig -> get ( 'name' ) , $ this -> _connectionConfig -> get ( 'name' ) => [ 'adapter' => $ this -> _adapterName , 'version_order' => Config :: VERSION_ORDER_CREATION_TIME , 'host' => $ this -> _connectionConfig -> get ( 'host' ) , 'port' => $ this -> _connectionConfig -> get ( 'port' ) , 'name' => $ this -> _connectionConfig -> get ( 'database' ) , 'user' => $ this -> _connectionConfig -> get ( 'username' ) , 'pass' => $ this -> _connectionConfig -> get ( 'password' ) , 'charset' => $ this -> _connectionConfig -> get ( 'encoding' ) , 'unix_socket' => $ this -> _connectionConfig -> get ( 'unix_socket' ) ] ] ; }
Setup Phinx configuration .
59,650
protected function _setAdapter ( array $ options ) { $ adapterFactory = AdapterFactory :: instance ( ) ; $ connection = new Connection ( $ this -> _connectionConfig -> getArrayCopy ( ) ) ; $ adapter = $ adapterFactory -> getAdapter ( $ this -> _adapterName , $ options ) ; return new CakeAdapter ( $ adapter , $ connection ) ; }
Get database adapter .
59,651
public function setFiles ( array $ files ) { foreach ( $ files as $ file ) { if ( ! $ file instanceof File ) { throw new ObjectNotAFileException ( $ file . ' is not a file' ) ; } } $ this -> files = $ files ; return $ this ; }
If multiple is set to false make sure to only enter an array with a single value
59,652
public function convertRouteParam ( $ route ) { $ patterns = array ( ':any?' => ':[a-zA-Z0-9\.\-_%=]?+' , ':num?' => ':[0-9]?+' , ':all?' => ':.?*' , ':num' => ':[0-9]+' , ':any' => ':[a-zA-Z0-9\.\-_%=]+' , ':all' => ':.*' , ) ; $ route = str_replace ( array_keys ( $ patterns ) , array_values ( $ patterns ) , $ route ) ; return $ route ; }
Convert shortcode of regex in route .
59,653
public function add ( $ text , $ value ) { $ this -> radios [ ] = array ( $ text , $ value ) ; $ this -> validator -> addPossibility ( $ value ) ; }
Adds a new Radio button to this Element
59,654
public function launch ( $ target , array $ arguments = null ) { if ( null === $ arguments ) { $ arguments = array ( ) ; } $ os = $ this -> isolator ( ) -> php_uname ( 's' ) ; if ( 'win' === strtolower ( substr ( $ os , 0 , 3 ) ) ) { $ this -> launchWindows ( $ target , $ arguments ) ; } elseif ( 'Darwin' === $ os ) { $ this -> launchOsx ( $ target , $ arguments ) ; } else { $ this -> launchUnix ( $ target , $ arguments ) ; } }
Launch a file or URI in its default GUI application .
59,655
protected function launchOsx ( $ target , array $ arguments ) { if ( count ( $ arguments ) > 0 ) { array_unshift ( $ arguments , '--args' ) ; } array_unshift ( $ arguments , $ target ) ; $ this -> launchCommand ( 'open' , $ arguments ) ; }
Launch a file or URI in its default GUI application via the OSX open command .
59,656
protected function launchCommand ( $ command , array $ arguments ) { $ command = implode ( ' ' , array_merge ( array ( $ command ) , array_map ( 'escapeshellarg' , $ arguments ) ) ) ; $ handle = $ this -> isolator ( ) -> proc_open ( $ command , array ( array ( 'pipe' , 'r' ) , array ( 'pipe' , 'w' ) , array ( 'pipe' , 'w' ) , ) , $ pipes ) ; if ( false === $ handle ) { throw new Exception \ LaunchException ( $ arguments [ 0 ] ) ; } foreach ( $ pipes as $ pipe ) { $ this -> isolator ( ) -> fclose ( $ pipe ) ; } $ this -> isolator ( ) -> proc_close ( $ handle ) ; }
Lanuch an arbitrary command .
59,657
public static function responseToJson ( ResponseInterface $ response ) { $ contents = $ response -> getBody ( ) -> getContents ( ) ; if ( empty ( $ contents ) ) { return [ ] ; } return \ GuzzleHttp \ json_decode ( $ contents , true ) ; }
Parse the content of a response .
59,658
public function getCreatedAt ( ) { if ( ! $ this -> createdAt ) { return null ; } else { return $ this -> createdAt -> setTimezone ( new DateTimeZone ( app ( 'config' ) -> timezone ) ) ; } }
get created time of this model
59,659
public function getUpdatedAt ( ) { if ( ! $ this -> updatedAt ) { return null ; } else { return $ this -> updatedAt -> setTimezone ( new DateTimeZone ( app ( 'config' ) -> timezone ) ) ; } }
get updated time of this model
59,660
public function getDeletedAt ( ) { if ( ! $ this -> deletedAt ) { return null ; } else { return $ this -> deletedAt -> setTimezone ( new DateTimeZone ( app ( 'config' ) -> timezone ) ) ; } }
get deleted time of this model
59,661
final public function save ( ) { if ( ! $ this -> createdAt ) { $ this -> createdAt = new DateTime ( ) ; } else { $ this -> updatedAt = new DateTime ( ) ; } try { app ( 'em' ) -> persist ( $ this ) ; app ( 'em' ) -> flush ( ) ; } catch ( \ Exception $ exception ) { throw new HttpForbiddenException ( 'ERROR INSERTING TO DB' ) ; } return $ this ; }
save model to database
59,662
final public function delete ( $ force = false ) { if ( $ force ) { app ( 'em' ) -> remove ( $ this ) ; } else { $ this -> deletedAt = new DateTime ( ) ; app ( 'em' ) -> persist ( $ this ) ; } app ( 'em' ) -> flush ( ) ; return $ this ; }
delete model from database
59,663
final public static function find ( $ id , $ withTrash = false ) { if ( $ id === null ) { return null ; } $ instance = static :: getRepository ( ) -> find ( $ id ) ; if ( $ instance instanceof static ) { if ( $ instance -> getDeletedAt ( ) && ! $ withTrash ) { return null ; } return $ instance ; } else { return null ; } }
get specific model
59,664
final public static function where ( array $ criteria , array $ orderBy = [ 'createdAt' => 'DESC' ] , int $ limit = null , int $ offset = null , bool $ withTrash = false ) { $ criteria = self :: criteriaWithSoftDelete ( $ criteria , $ withTrash ) ; return static :: getRepository ( ) -> findBy ( $ criteria , $ orderBy , $ limit , $ offset ) ; }
get models by some conditions
59,665
final public static function all ( $ orderBy = [ 'createdAt' => 'DESC' ] , bool $ withTrash = false ) { $ criteria = self :: criteriaWithSoftDelete ( [ ] , $ withTrash ) ; return static :: getRepository ( ) -> findBy ( $ criteria , $ orderBy ) ; }
get all models
59,666
public function persist ( CachedSearchResult $ cachedSearchResult ) : void { $ cachedSearchResult = $ this -> entityManager -> merge ( $ cachedSearchResult ) ; $ this -> entityManager -> persist ( $ cachedSearchResult ) ; $ this -> entityManager -> flush ( ) ; }
Persists the specified cached search result into the database .
59,667
public function cleanup ( DateTimeInterface $ maxAge ) : void { $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> delete ( CachedSearchResult :: class , 'r' ) -> andWhere ( 'r.lastSearchTime < :maxAge' ) -> setParameter ( 'maxAge' , $ maxAge ) ; $ queryBuilder -> getQuery ( ) -> execute ( ) ; }
Cleans up no longer needed data .
59,668
public function clear ( ) : void { $ queryBuilder = $ this -> entityManager -> createQueryBuilder ( ) ; $ queryBuilder -> delete ( CachedSearchResult :: class , 'r' ) ; $ queryBuilder -> getQuery ( ) -> execute ( ) ; }
Clears the database table emptying the cache .
59,669
static function select ( \ fenrir \ system \ MysqlDatabaseSignature $ db , $ table , $ constraints = null ) { $ constraints !== null or $ constraints = '1' ; return $ db -> prepare ( " SELECT * FROM `$table` WHERE $constraints " ) -> execute ( ) -> fetch_all ( ) ; }
Performs safe select of entries .
59,670
static function insert ( \ fenrir \ system \ MysqlDatabaseSignature $ db , $ table , array $ values , $ map = null ) { $ map !== null or $ map = [ ] ; isset ( $ map [ 'nums' ] ) or $ map [ 'nums' ] = [ ] ; isset ( $ map [ 'bools' ] ) or $ map [ 'bools' ] = [ ] ; isset ( $ map [ 'dates' ] ) or $ map [ 'dates' ] = [ ] ; $ rawkeys = array_keys ( $ values ) ; $ keys = \ hlin \ Arr :: join ( ', ' , $ rawkeys , function ( $ i , $ key ) { return "`$key`" ; } ) ; $ refs = \ hlin \ Arr :: join ( ', ' , $ rawkeys , function ( $ i , $ key ) { return ":$key" ; } ) ; $ stmt = $ db -> prepare ( "INSERT INTO `$table` ($keys) VALUES ($refs)" ) ; foreach ( $ values as $ key => $ value ) { if ( in_array ( $ key , $ map [ 'nums' ] ) ) { $ stmt -> num ( ":$key" , $ value ) ; } else if ( in_array ( $ key , $ map [ 'bools' ] ) ) { $ stmt -> bool ( ":$key" , $ value ) ; } else if ( in_array ( $ key , $ map [ 'dates' ] ) ) { $ stmt -> date ( ":$key" , $ value ) ; } else { $ stmt -> str ( ":$key" , $ value ) ; } } $ stmt -> execute ( ) ; return $ db -> lastInsertId ( ) ; }
Performs safe insert into table given values and keys . This is a very primitive function which gurantees the integrity of the operation inside the migration .
59,671
static function massinsert ( \ fenrir \ system \ MysqlDatabaseSignature $ db , $ table , array $ values , $ map = null ) { $ db -> begin ( ) ; try { foreach ( $ values as $ value ) { static :: insert ( $ db , $ table , $ value , $ map ) ; } $ db -> commit ( ) ; } catch ( \ Exception $ e ) { $ db -> rollback ( ) ; throw $ e ; } }
Same as insert only values is assumed to be array of arrays .
59,672
static function remove_bindings ( \ fenrir \ system \ MysqlDatabaseSignature $ db , $ table , array $ bindings ) { foreach ( $ bindings as $ key ) { $ db -> prepare ( " ALTER TABLE `$table` DROP FOREIGN KEY `$key` " ) -> execute ( ) ; } }
Remove specified bindings .
59,673
static function processor ( \ fenrir \ system \ MysqlDatabaseSignature $ db , $ table , $ count , $ callback , $ reads = 1000 ) { $ pages = ( ( int ) ( $ count / $ reads ) ) + 1 ; for ( $ page = 1 ; $ page <= $ pages ; ++ $ page ) { $ db -> begin ( ) ; $ entries = $ db -> prepare ( " SELECT * FROM `$table` LIMIT :limit OFFSET :offset " ) -> page ( $ page , $ reads ) -> execute ( ) -> fetch_all ( ) ; foreach ( $ entries as $ entry ) { $ callback ( $ db , $ entry ) ; } $ db -> commit ( ) ; } }
When converting from one database structure to another it is often required to translate one structure to another which involves going though all the entries in a central table ; this method abstracts the procedure for you .
59,674
public function setButtonType ( $ type , $ submitFormOnClick = false ) { $ this -> model -> type = $ type ; if ( $ submitFormOnClick ) { $ this -> model -> addCssClassNames ( "submit-on-click" ) ; } }
Allows changing the HTML input type from default submit
59,675
private static function _magic ( ) { $ magic = ( isset ( $ _SERVER [ 'HTTP_ACCEPT_LANGUAGE' ] ) ? $ _SERVER [ 'HTTP_ACCEPT_LANGUAGE' ] : '*' ) . ( isset ( $ _SERVER [ 'HTTP_ACCEPT' ] ) ? $ _SERVER [ 'HTTP_ACCEPT' ] : '*' ) . ( isset ( $ _SERVER [ 'HTTP_USER_AGENT' ] ) ? $ _SERVER [ 'HTTP_USER_AGENT' ] : '*' ) ; $ req = grab ( 'request' ) ; $ magic .= $ req [ 'remote_addr' ] ; return md5 ( $ magic ) ; }
Magic string to help prevent session hijacking
59,676
public static function startup ( ) { global $ PPHP ; $ sessionSeconds = $ PPHP [ 'config' ] [ 'session' ] [ 'gc_maxlifetime' ] * 60 ; ini_set ( 'session.gc_probability' , 1 ) ; ini_set ( 'session.gc_gc_divisor' , 1000 ) ; ini_set ( 'session.gc_maxlifetime' , $ sessionSeconds ) ; session_save_path ( $ PPHP [ 'dir' ] . '/var/sessions' ) ; ini_set ( 'session.cookie_lifetime' , 0 ) ; ini_set ( 'session.cookie_httponly' , true ) ; session_start ( ) ; if ( isset ( $ _SESSION [ 'magic' ] ) ) { if ( $ _SESSION [ 'magic' ] !== self :: _magic ( ) ) { self :: reset ( ) ; } ; } else { self :: _init ( ) ; } ; }
Discover and initialize session
59,677
public static function login ( $ email , $ password , $ onetime = '' ) { $ oldId = false ; if ( isset ( $ _SESSION [ 'user' ] ) && isset ( $ _SESSION [ 'user' ] [ 'id' ] ) ) { $ oldId = $ _SESSION [ 'user' ] [ 'id' ] ; } ; if ( is_array ( $ user = grab ( 'authenticate' , $ email , $ password , $ onetime ) ) ) { if ( $ oldId !== $ user [ 'id' ] ) { trigger ( 'log' , array ( 'userId' => $ user [ 'id' ] , 'objectType' => 'user' , 'objectId' => $ user [ 'id' ] , 'action' => 'login' ) ) ; self :: reset ( ) ; } ; $ _SESSION [ 'user' ] = $ user ; $ _SESSION [ 'identified' ] = true ; self :: reloadOutbox ( ) ; trigger ( 'newuser' ) ; if ( pass ( 'can' , 'login' ) ) { return true ; } else { self :: reset ( ) ; return false ; } ; } else { return false ; } ; }
Attempt to attach a user to current session
59,678
public static function beginForm ( $ name ) { $ name = self :: _formHash ( $ name ) ; $ token = md5 ( mcrypt_create_iv ( 32 , MCRYPT_DEV_URANDOM ) ) ; $ _SESSION [ $ name ] = $ token ; return '<input type="hidden" name="' . $ name . '" value="' . $ token . '" />' ; }
Generate hidden input for form validation
59,679
public function hasAssociatedIdentity ( $ userId , $ identity ) { $ sql = $ this -> sql ( $ this -> getTableInSchema ( 'user_identity' ) ) ; $ select = $ sql -> select ( ) -> columns ( array ( 'id' ) ) -> where ( array ( 'userId' => ( int ) $ userId , 'identity' => ( string ) $ identity , ) ) -> limit ( 1 ) ; $ result = $ sql -> prepareStatementForSqlObject ( $ select ) -> execute ( ) ; if ( $ result -> getAffectedRows ( ) < 1 ) { return null ; } foreach ( $ result as $ row ) { if ( ! empty ( $ row [ 'id' ] ) ) { return $ row [ 'id' ] ; } } return null ; }
Has associated identity
59,680
public function isEmailExists ( $ email , $ excludeId = null ) { return $ this -> isExists ( empty ( $ excludeId ) ? array ( 'email' => $ email , 'confirmed' => true , new Predicate \ Operator ( 'state' , Predicate \ Operator :: OP_NE , Structure :: STATE_INACTIVE ) , ) : array ( 'email' => $ email , new Predicate \ Operator ( 'id' , Predicate \ Operator :: OP_NE , $ excludeId ) , ) ) ; }
Is email already exists
59,681
public function isEmailTaken ( $ email , $ excludeId = null ) { return $ this -> isExists ( empty ( $ excludeId ) ? array ( 'email' => $ email , ) : array ( 'email' => $ email , new Predicate \ Operator ( 'id' , Predicate \ Operator :: OP_NE , $ excludeId ) , ) ) ; }
Is email already taken
59,682
public function isDisplayNameExists ( $ displayName , $ excludeId = null ) { $ platform = $ this -> getDbAdapter ( ) -> getPlatform ( ) ; $ expr = new Predicate \ Expression ( 'LOWER( ' . $ platform -> quoteIdentifier ( 'displayName' ) . ' ) = LOWER( ? )' , $ displayName ) ; return $ this -> isExists ( empty ( $ excludeId ) ? array ( $ expr , ) : array ( $ expr , new Predicate \ Operator ( 'id' , Predicate \ Operator :: OP_NE , $ excludeId ) , ) ) ; }
Is dsplay name already exists
59,683
public function connection ( $ name = null ) { if ( ! isset ( $ this -> connections [ $ name ] ) ) { $ this -> connections [ $ name ] = $ this -> createConnection ( $ name ) ; } return $ this -> connections [ $ name ] ; }
Get a Mongo connection instance .
59,684
protected function createConnection ( $ name ) { $ config = $ this -> getConfig ( $ name ) ; $ connection = new Client ( $ config ) ; $ connection -> connect ( ) ; return $ connection ; }
Create the given connection by name .
59,685
public function getSlugs ( $ id_language , $ table_name ) { if ( ! array_key_exists ( $ id_language , $ this -> cached_slugs ) ) { $ resources = Resource :: where ( 'id_language' , $ id_language ) -> where ( 'column_name' , 'slug' ) -> where ( 'value' , '!=' , '' ) -> get ( ) ; $ this -> cached_slugs [ $ id_language ] = array ( ) ; foreach ( $ resources as $ resource ) { if ( ! array_key_exists ( $ resource -> table_name , $ this -> cached_slugs [ $ id_language ] ) ) { $ this -> cached_slugs [ $ id_language ] [ $ resource -> table_name ] = array ( ) ; } $ this -> cached_slugs [ $ id_language ] [ $ resource -> table_name ] [ ] = $ resource ; } } return ( array_key_exists ( $ table_name , $ this -> cached_slugs [ $ id_language ] ) ? $ this -> cached_slugs [ $ id_language ] [ $ table_name ] : array ( ) ) ; }
keys are language ids
59,686
public function status ( ) { return array_key_exists ( $ this -> statusCode ( ) , self :: $ statuses ) ? self :: $ statuses [ $ this -> statusCode ( ) ] : 'Unknown' ; }
Get the string representation of the status .
59,687
private function readResponseBodyString ( $ responseBodyString ) { $ responseLines = array_filter ( array_map ( function ( $ value ) { return trim ( $ value ) ; } , explode ( "\n" , $ responseBodyString ) ) ) ; $ result = [ ] ; foreach ( $ responseLines as $ responseLine ) { $ responseParts = explode ( '=' , $ responseLine ) ; $ result [ strtolower ( $ responseParts [ 0 ] ) ] = $ responseParts [ 1 ] ; } $ status = ( int ) $ result [ 'status' ] ; unset ( $ result [ 'status' ] ) ; $ result [ 'success' ] = ( $ status >= 0 ) ? true : false ; $ result [ 'statusCode' ] = $ status ; return $ result ; }
Read the message response body string .
59,688
static public function factory ( $ configs ) { $ config = self :: _parseConfig ( $ config ) ; $ config = array_merge ( array ( 'modelClass' => null , 'columnMap' => null ) , $ config ) ; return new self ( $ config [ 'modelClass' ] , $ config [ 'columnMap' ] ) ; }
Create a new instance of
59,689
public function delete ( $ bean , $ property ) { $ path = APP_PATH . $ property [ 'directory' ] ; $ file = APP_PATH . $ bean -> { $ property [ 'name' ] } ; if ( file_exists ( $ file ) && substr ( $ file , 0 , strlen ( $ path ) ) == $ path ) { unlink ( $ file ) ; } }
The delete method is executed each time a an object with a property with this type is deleted .
59,690
public function & SubmitValidateMaxPostSizeIfNecessary ( ) { if ( $ this -> method != \ MvcCore \ Ext \ Forms \ IForm :: METHOD_POST ) return $ this ; $ contentLength = $ this -> request -> GetContentLength ( ) ; if ( $ contentLength === NULL ) $ this -> AddError ( $ this -> GetDefaultErrorMsg ( \ MvcCore \ Ext \ Forms \ IError :: EMPTY_CONTENT ) ) ; $ maxSize = static :: GetPhpIniSizeLimit ( 'post_max_size' ) ; if ( $ maxSize > 0 && $ maxSize < $ contentLength ) { $ viewClass = $ this -> viewClass ; $ this -> AddError ( $ viewClass :: Format ( $ this -> GetDefaultErrorMsg ( \ MvcCore \ Ext \ Forms \ IError :: MAX_POST_SIZE ) , [ $ maxSize ] ) ) ; } return $ this ; }
Validate maximum posted size in POST request body by Content - Length HTTP header . If there is no Content - Length request header add error . If Content - Length value is bigger than post_max_size from PHP INI add form error .
59,691
private function importFile ( $ file ) { $ template = new Template ( $ this -> include_path . $ file ) ; return $ template -> process ( $ this -> rules , $ this -> data ) ; }
Imports a file in the form of a new Template .
59,692
private function showVariable ( $ name , $ sanitize = false ) { if ( isset ( $ this -> data [ $ name ] ) ) { if ( $ sanitize ) { echo htmlentities ( $ this -> data [ $ name ] ) ; } else { echo $ this -> data [ $ name ] ; } } else { echo '{' . $ name . '}' ; } }
Shows the content of a variable stored in the data .
59,693
private function wrap ( $ element ) { $ this -> stack [ ] = $ this -> data ; foreach ( $ element as $ k => $ v ) { $ this -> data [ $ k ] = $ v ; } }
Wraps the content of the loop into the data array so it can be used
59,694
public function process ( array $ rules , array $ data ) { $ this -> rules [ ] = new Rule ( 'if_boolean' , 'if:(\w+)' , '<?php if (isset($this->data[\'$1\']) && $this->data[\'$1\']): ?>' ) ; $ this -> rules [ ] = new Rule ( 'if_condition' , 'if:(\w+)([!<>=]+)(\w+)' , '<?php if (isset($this->data[\'$1\'])){$base = $this->data[\'$1\'];}else{$base = \'$1\';}; if (isset($this->data[\'$3\'])){$value = $this->data[\'$3\'];}else{$value = \'$3\';}?> <?php if ($base $2 $value): ?>' ) ; $ this -> rules [ ] = new Rule ( 'ifnot' , 'ifnot:(\w+)' , '<?php if (!isset($this->data[\'$1\']) || !$this->data[\'$1\']): ?>' ) ; $ this -> rules [ ] = new Rule ( 'else' , 'else' , '<?php else: ?>' ) ; $ this -> rules [ ] = new Rule ( 'elseif_boolean' , 'else:(\w+)' , '<?php elseif (isset($this->data[\'$1\']) && $this->data[\'$1\']): ?>' ) ; $ this -> rules [ ] = new Rule ( 'elseif_condition' , 'else:(\w+)([!<>=]+)(\w+)' , '<?php elseif (((isset($this->data[\'$1\']) && isset($this->data[\'$3\'])) && $this->data[\'$1\'] $2 $this->data[\'$3\']) || ((isset($this->data[\'$1\']) && !isset($this->data[\'$3\'])) && $this->data[\'$1\'] $2 \'$3\') || ((!isset($this->data[\'$1\']) && isset($this->data[\'$3\'])) && \'$1\' $2 $this->data[\'$3\']) || ((!isset($this->data[\'$1\']) && !isset($this->data[\'$3\'])) && \'$1\' $2 \'$3\')): ?>' ) ; $ this -> rules [ ] = new Rule ( 'endif' , 'endif' , '<?php endif; ?>' ) ; $ this -> rules [ ] = new Rule ( 'loop' , 'loop:(\w+)' , '<?php foreach ($this->data[\'$1\'] as $element): $this->wrap($element); ?>' ) ; $ this -> rules [ ] = new Rule ( 'endloop' , 'endloop' , '<?php $this->unwrap(); endforeach; ?>' ) ; $ this -> rules [ ] = new Rule ( 'import_view' , 'import:(([^\/\s]+\/)?(.*))' , '<?php echo $this->importFile(\'$1\'); ?>' ) ; $ this -> rules [ ] = new Rule ( 'escape_var' , 'escape:(\w+)' , '<?php $this->showVariable(\'$1\', true); ?>' ) ; $ this -> rules = array_merge ( $ this -> rules , $ rules ) ; $ this -> rules [ ] = new Rule ( 'variable' , '(\w+)' , '<?php $this->showVariable(\'$1\'); ?>' ) ; $ this -> rules [ ] = new Rule ( 'variable_array' , '(\w+)\[(\w+)\]' , '<?php echo (isset($this->data[\'$1\'][\'$2\'])) ? $this->data[\'$1\'][\'$2\'] : "&#123;$1[$2]&#125"; ?>' ) ; $ this -> rules [ ] = new Rule ( 'variable_array_escape' , 'escape:(\w+)\[(\w+)\]' , '<?php echo htmlentities($this->showVariable(\'$1\')[\'$2\']); ?>' ) ; $ this -> data = $ data ; $ this -> stack = array ( ) ; foreach ( $ this -> rules as $ rule ) { $ this -> template = preg_replace ( '/\{' . $ rule -> rule ( ) . '\}/' , $ rule -> replacement ( ) , $ this -> template ) ; } $ this -> template = '?>' . $ this -> template ; ob_start ( ) ; eval ( $ this -> template ) ; return ob_get_clean ( ) ; }
Process the Template and convert its variables into values .
59,695
public function tokenExists ( $ token , $ returnQuery = false ) { $ query = $ this -> find ( ) -> where ( [ $ this -> alias ( ) . '.token' => $ token ] ) ; if ( $ returnQuery ) { return $ query ; } return $ query -> first ( ) ; }
Check if a token already exists .
59,696
public function generateToken ( User $ user , $ tokenType ) { if ( ! isset ( $ this -> timeToLive [ $ tokenType ] ) ) { user_error ( 'Please specify a timeToLive for the tokenType "' . $ tokenType . '" at Token::$timeToLive.' , E_USER_ERROR ) ; } do { $ token = md5 ( microtime ( true ) . Configure :: read ( 'Security.salt' ) . $ user -> get ( 'id' ) . $ user -> get ( 'email' ) ) ; } while ( ( bool ) $ this -> tokenExists ( $ token ) ) ; $ this -> save ( new Entity ( [ 'user_id' => $ user -> get ( 'id' ) , 'token' => $ token , 'token_type' => $ tokenType , 'expires' => new DateTime ( $ this -> timeToLive [ $ tokenType ] ) ] ) ) ; return $ token ; }
Generate a new unique token for an existing user .
59,697
public function isValid ( $ token , $ returnQuery = false ) { if ( strlen ( $ token ) !== 32 ) { return false ; } return $ this -> tokenExists ( $ token , $ returnQuery ) ; }
Check if the supplied token is valid and exists in the database .
59,698
public function setCollapsable ( string $ parent , string $ id , bool $ in ) { $ this -> collapse = [ 'parent' => $ parent , 'id' => $ id , 'in' => ( $ in ? ' in' : '' ) ] ; return $ this ; }
Used internally by accordion helper
59,699
protected function _translate ( $ string , $ context = null , $ params = null ) { $ string = parent :: _translate ( $ string , $ context ) ; if ( ! is_null ( $ params ) ) { $ string = $ this -> _interpolateParams ( $ string , $ params ) ; } return $ string ; }
Translates a string format .