idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
41,600
public function addByElement ( $ element , array $ styles ) { $ this -> elements [ $ element ] = array_merge_recursive ( $ this -> getByElement ( $ element ) , $ styles ) ; }
Add style by element name
41,601
protected static function fe ( ) { if ( ! empty ( ZN :: upgrade ( ) ) ) { $ status = self :: $ lang [ 'upgradeSuccess' ] ; } else { $ status = self :: $ lang [ 'alreadyVersion' ] ; if ( $ upgradeError = ZN :: upgradeError ( ) ) { $ status = $ upgradeError ; } } return $ status ; }
Protected upgrade FE
41,602
protected static function eip ( $ tag = 'znframework' ) { if ( $ return = Restful :: useragent ( true ) -> get ( 'https://api.github.com/repos/znframework/' . $ tag . '/tags' ) ) { if ( ! isset ( $ return -> message ) ) { usort ( $ return , function ( $ data1 , $ data2 ) { return strcmp ( $ data1 -> name , $ data2 -> name ) ; } ) ; rsort ( $ return ) ; $ lastest = $ return [ 0 ] ; $ lastVersionData = $ lastest -> name ?? ZN_VERSION ; $ open = popen ( 'composer update 2>&1' , 'r' ) ; $ result = fread ( $ open , 2048 ) ; pclose ( $ open ) ; if ( empty ( $ result ) ) { $ status = self :: $ lang [ 'composerUpdate' ] ; } else { if ( ZN_VERSION !== $ lastVersionData ) { File :: replace ( DIRECTORY_INDEX , ZN_VERSION , $ lastVersionData ) ; $ status = self :: $ lang [ 'upgradeSuccess' ] ; } else { $ status = self :: $ lang [ 'alreadyVersion' ] ; } } } else { $ status = $ return -> message ; } return $ status ; } }
Proteted upgrade EIP
41,603
public function cached ( $ public = true , $ expires = '+1 year' ) { if ( ! is_int ( $ expires ) ) { $ expires = strtotime ( $ expires ) ; } $ maxAge = $ expires - time ( ) ; $ pragma = $ public ? 'public' : 'private' ; $ cache = $ pragma . ', max-age=' . $ maxAge ; $ response = clone $ this ; $ response -> setHeader ( 'Expires' , Message :: date ( $ expires ) ) ; $ response -> setHeader ( 'Pragma' , $ pragma ) ; $ response -> setHeader ( 'Cache-Control' , $ cache ) ; return $ response ; }
Set cache settings .
41,604
public static function file ( $ path , $ type = null ) { $ response = new self ( Status :: OK , new PhpStream ( $ path , 'rb' ) ) ; if ( isset ( $ type ) ) { $ response -> setHeader ( 'Content-Type' , $ type ) ; } return $ response ; }
Create a file response .
41,605
public function registerPlugin ( array $ plugin ) { if ( ! isset ( $ plugin [ 'name' ] ) ) return ; $ this -> getContainer ( ) -> addPlugin ( $ plugin [ 'name' ] ) ; if ( isset ( $ plugin [ 'commands' ] ) ) { $ this -> registerCommands ( $ plugin [ 'name' ] , $ plugin [ 'commands' ] ) ; } if ( isset ( $ plugin [ 'procedures' ] ) ) { $ this -> registerProcedures ( $ plugin [ 'name' ] , $ plugin [ 'procedures' ] , $ plugin [ 'path' ] ) ; } if ( isset ( $ plugin [ 'settings' ] ) ) { $ this -> registerSettings ( $ plugin [ 'name' ] , $ plugin [ 'settings' ] ) ; } }
Register a plugin found in manifest file
41,606
public function registerProcedures ( string $ plugin , array $ procedures , string $ path ) { array_walk ( $ procedures , function ( & $ procedure ) use ( $ path ) { $ procedure = "$path/$procedure" ; } ) ; $ factory = new ProcedureFactory ( $ this , $ procedures ) ; foreach ( $ factory -> getNames ( ) as $ name ) { $ procedure = $ factory -> create ( $ name ) ; $ this -> add ( $ procedure ) ; } }
Register all procedures for a given plugin
41,607
public function registerCommands ( string $ plugin , array $ commands ) { $ newCommands = [ ] ; foreach ( $ commands as $ commandClass ) { $ command = new $ commandClass ( $ plugin ) ; $ command = CommandFactory :: setNamespace ( $ command ) ; $ this -> add ( $ command ) ; $ newCommands [ ] = $ command ; } return $ newCommands ; }
Register all commands for a given plugin
41,608
public function missingSettings ( ) { $ missing = [ ] ; foreach ( $ this -> recommendedSettings ( ) as $ plugin => $ settings ) { foreach ( $ settings as $ setting ) { $ value = $ _ENV [ $ setting ] ?? null ; if ( is_null ( $ value ) ) $ missing [ $ plugin ] [ ] = $ setting ; } } return $ missing ; }
Get an array of plugins and their settings that are not defined in env
41,609
public function flushBuffer ( ) { $ content = $ this -> format ( $ this -> buffer -> flush ( ) ) ; if ( ! $ this -> is ( OutputVerbosity :: SILENT ) ) { fwrite ( $ this -> getOutputStream ( ) , $ content ) ; } }
Manually flush buffered output .
41,610
public function add ( Job $ job ) { $ jobClass = new \ ReflectionClass ( $ job ) ; $ name = $ jobClass -> getName ( ) ; $ object = serialize ( $ job ) ; $ jobId = $ this -> broker -> put ( [ 'object' => $ object , 'class' => $ name ] ) ; $ this -> broker -> setStatus ( $ jobId , [ 'status' => Job :: STATUS_QUEUED , 'queued' => date ( DATE_RFC3339_EXTENDED ) ] ) ; return $ jobId ; }
Add a job to the job queue .
41,611
public static function indent ( $ str , $ spaces = 4 , $ level = 1 ) { return str_repeat ( " " , $ spaces * $ level ) . str_replace ( "\n" , "\n" . str_repeat ( " " , $ spaces * $ level ) , $ str ) ; }
Inserts N spaces to the left of a string
41,612
public function moveCursorRel ( $ x , $ y ) { $ yChar = ( $ y < 0 ) ? "A" : "B" ; $ xChar = ( $ x < 0 ) ? "D" : "C" ; fwrite ( STDOUT , "\e[" . abs ( $ x ) . $ xChar ) ; fwrite ( STDOUT , "\e[" . abs ( $ y ) . $ yChar ) ; }
Moves cursor relatively to its current position
41,613
function getEndpoint ( ) { $ this -> api -> curl_header = array ( 'Authorization: OAuth ' . $ this -> api -> access_token , ) ; $ data = $ this -> api -> get ( $ this -> metadata_url ) ; if ( ! isset ( $ data -> api_endpoint ) ) { throw new Exception ( "Endpoint request failed! {$this->providerId} returned an invalid response." , 6 ) ; } return $ data -> api_endpoint ; }
Load the metadata which includes the URL of the API endpoint .
41,614
protected function getPhpInfo ( ) : string { ob_start ( ) ; phpinfo ( ) ; $ result = ob_get_contents ( ) ; ob_end_clean ( ) ; $ result = preg_replace ( '%^.*<body>(.*)</body>.*$%ms' , '$1' , $ result ) ; $ result = preg_replace ( '/,\s*/' , ', ' , $ result ) ; return $ result ; }
Vrati vypis PHP info
41,615
protected function getSystem ( ) : Obj { $ system = new Obj ; $ system -> hostname = $ this -> readFile ( '/etc/hostname' ) ; $ system -> ip = $ this -> getIp ( ) ; $ system -> distribution = Strings :: replace ( $ this -> readCommand ( 'lsb_release -d' ) , '/Description:\s/' ) ; $ system -> kernel = $ this -> readCommand ( 'uname -r' ) . ' ' . $ this -> readCommand ( 'uname -i' ) ; $ uptime = $ this -> readFileAsArray ( '/proc/uptime' , ' ' ) ; if ( $ uptime ) { $ system -> uptime = new Obj ; $ system -> uptime -> days = ( int ) gmdate ( "d" , ( int ) $ uptime [ 0 ] ) - 1 ; $ system -> uptime -> hours = ( int ) gmdate ( "H" , ( int ) $ uptime [ 0 ] ) ; $ system -> uptime -> minutes = ( int ) gmdate ( "i" , ( int ) $ uptime [ 0 ] ) ; } $ system -> users = $ this -> readCommandAsArray ( 'users' , ' ' ) ; $ system -> load = $ this -> getLoad ( ) ; $ system -> processes = new Obj ; $ system -> processes -> total = $ this -> readCommand ( 'ps axo state | wc -l' ) ; $ system -> processes -> running = $ this -> readCommand ( 'ps axo state | grep "R" | wc -l' ) ; $ system -> processes -> sleeping = $ system -> processes -> total - $ system -> processes -> running ; return $ system ; }
Vrati informace o systemu
41,616
protected function getLoad ( ) : ? string { $ load = $ this -> readFileAsArray ( '/proc/loadavg' , ' ' ) ; if ( $ load ) { unset ( $ load [ 3 ] , $ load [ 4 ] ) ; return implode ( ' ' , $ load ) ; } return null ; }
Vrati vytizeni serveru
41,617
protected function getHardware ( ) : Obj { $ hardware = new Obj ; $ product = $ this -> readFile ( '/sys/devices/virtual/dmi/id/product_name' ) ; $ board = $ this -> readFile ( '/sys/devices/virtual/dmi/id/board_name' ) ; $ bios = $ this -> readFile ( '/sys/devices/virtual/dmi/id/bios_version' ) ; $ biosDate = $ this -> readFile ( '/sys/devices/virtual/dmi/id/bios_date' ) ; $ hardware -> server = $ product . ( $ board ? '/' . $ board : null ) . ( $ bios ? ', BIOS ' . $ bios : null ) . ( $ biosDate ? ' ' . $ biosDate : null ) ; $ hardware -> cpu = $ this -> getCpu ( ) ; $ hardware -> scsi = $ this -> getScsi ( ) ; $ hardware -> data = ! empty ( $ hardware -> server ) || ! empty ( $ hardware -> cpu ) || ! empty ( $ hardware -> scsi ) ; return $ hardware ; }
Vrati informace o hardware
41,618
private function getScsi ( ) : array { $ get_type = false ; $ device = null ; $ scsi = [ ] ; $ data = $ this -> readFile ( '/proc/scsi/scsi' ) ; if ( $ data !== null ) { $ bufe = preg_split ( "/\n/" , $ data , - 1 , PREG_SPLIT_NO_EMPTY ) ; foreach ( $ bufe as $ buf ) { if ( preg_match ( '/Vendor: (.*) Model: (.*) Rev: (.*)/i' , $ buf , $ devices ) ) { $ get_type = true ; $ device = $ devices ; continue ; } if ( $ get_type ) { preg_match ( '/Type:\s+(\S+)/i' , $ buf , $ dev_type ) ; $ dev = new Obj ; $ dev -> name = trim ( $ device [ 1 ] ) . ' ' . trim ( $ device [ 2 ] ) ; $ dev -> type = trim ( $ dev_type [ 1 ] ) ; $ scsi [ ] = $ dev ; $ get_type = false ; } } } return $ scsi ; }
Vrati informace o scsi
41,619
protected function getMemory ( ) : ? Obj { $ memory = null ; $ meminfo = $ this -> readFile ( '/proc/meminfo' ) ; if ( $ meminfo ) { $ bufer = preg_split ( "/\n/" , $ meminfo , - 1 , PREG_SPLIT_NO_EMPTY ) ; $ memory = new Obj ; foreach ( $ bufer as $ buf ) { if ( preg_match ( '/^MemTotal:\s+(.*)\s*kB/i' , $ buf , $ ar_buf ) ) { $ memory -> total = ( ( float ) $ ar_buf [ 1 ] ) * 1024 ; } elseif ( preg_match ( '/^MemFree:\s+(.*)\s*kB/i' , $ buf , $ ar_buf ) ) { $ memory -> free = ( ( float ) $ ar_buf [ 1 ] ) * 1024 ; } elseif ( preg_match ( '/^Cached:\s+(.*)\s*kB/i' , $ buf , $ ar_buf ) ) { $ memory -> cache = ( ( float ) $ ar_buf [ 1 ] ) * 1024 ; } elseif ( preg_match ( '/^Buffers:\s+(.*)\s*kB/i' , $ buf , $ ar_buf ) ) { $ memory -> buffer = ( ( float ) $ ar_buf [ 1 ] ) * 1024 ; } } $ memory -> used = $ memory -> total - $ memory -> free ; if ( $ memory -> cache !== null && $ memory -> buffer !== null ) { $ memory -> application = $ memory -> used - $ memory -> cache - $ memory -> buffer ; } $ memory -> swap = [ ] ; $ swaps = preg_split ( "/\n/" , $ this -> readFile ( '/proc/swaps' ) , - 1 , PREG_SPLIT_NO_EMPTY ) ; unset ( $ swaps [ 0 ] ) ; foreach ( $ swaps as $ swap ) { $ ar_buf = preg_split ( '/\s+/' , $ swap , PREG_BAD_UTF8_OFFSET_ERROR ) ; $ swap = new Obj ; $ swap -> mount = $ ar_buf [ 0 ] ; $ swap -> name = 'SWAP' ; $ swap -> total = $ ar_buf [ 2 ] * 1024 ; $ swap -> used = $ ar_buf [ 3 ] * 1024 ; $ swap -> free = $ swap -> total - $ swap -> used ; $ memory -> swap [ ] = $ swap ; } } return $ memory ; }
Vrati informace o pameti
41,620
protected function getFileSystem ( ) : array { $ fileSystem = [ ] ; $ command = $ this -> readCommand ( 'df -T' ) ; if ( $ command ) { $ bufe = preg_split ( "/\n/" , $ command , - 1 , PREG_SPLIT_NO_EMPTY ) ; unset ( $ bufe [ 0 ] ) ; foreach ( $ bufe as $ buf ) { $ data = preg_split ( '/\s+/' , $ buf ) ; $ mounted = new Obj ; $ mounted -> partition = $ data [ 0 ] ; $ mounted -> type = $ data [ 1 ] ; $ mounted -> size = $ data [ 2 ] * 1024 ; $ mounted -> used = $ data [ 3 ] * 1024 ; $ mounted -> free = $ data [ 4 ] * 1024 ; $ mounted -> usage = $ data [ 5 ] ; $ mounted -> mountPoint = $ data [ 6 ] ; $ fileSystem [ ] = $ mounted ; } } return $ fileSystem ; }
Vrati informace o souborovem system
41,621
protected function getNetwork ( ) : array { $ network = [ ] ; $ data = $ this -> readFile ( '/proc/net/dev' ) ; if ( $ data !== null ) { $ bufe = preg_split ( "/\n/" , $ data , - 1 , PREG_SPLIT_NO_EMPTY ) ; unset ( $ bufe [ 0 ] , $ bufe [ 1 ] ) ; foreach ( $ bufe as $ buf ) { list ( $ dev_name , $ stats_list ) = preg_split ( '/:/' , $ buf , 2 ) ; $ stats = preg_split ( '/\s+/' , trim ( $ stats_list ) ) ; $ dev = new Obj ; $ dev -> name = trim ( $ dev_name ) ; $ dev -> recieve = ( int ) $ stats [ 0 ] ; $ dev -> sent = ( int ) $ stats [ 8 ] ; $ dev -> error = ( int ) $ stats [ 2 ] + ( int ) $ stats [ 10 ] ; $ dev -> drop = ( int ) $ stats [ 3 ] + ( int ) $ stats [ 11 ] ; $ ipBuff = preg_split ( "/\n/" , $ this -> readCommand ( 'ip addr show ' . $ dev -> name ) , - 1 , PREG_SPLIT_NO_EMPTY ) ; foreach ( $ ipBuff as $ line ) { if ( preg_match ( '/^\s*link\/ether\s+(.*)\s+brd.*/i' , $ line , $ ar_buf ) ) { $ dev -> mac = $ ar_buf [ 1 ] ; } elseif ( preg_match ( '/^\s*inet6\s+(.*)\/.*/i' , $ line , $ ar_buf ) ) { $ dev -> ip6 = $ ar_buf [ 1 ] ; } elseif ( preg_match ( '/^\s*inet\s+(.*)\/.*/i' , $ line , $ ar_buf ) ) { $ dev -> ip = $ ar_buf [ 1 ] ; } } $ network [ ] = $ dev ; } } return $ network ; }
Vrati informace o siti
41,622
public function attemptConfirmation ( $ code ) { $ token = Token :: find ( ) -> where ( [ 'userId' => $ this -> id , 'code' => $ code , 'type' => Token :: TYPE_CONFIRMATION , ] ) -> one ( ) ; if ( $ token instanceof Token && ! $ token -> isExpired ) { $ token -> delete ( ) ; if ( ( $ success = $ this -> confirm ( ) ) ) { Yii :: $ app -> user -> login ( $ this , $ this -> module -> rememberFor ) ; $ message = Yii :: t ( 'users' , 'Thank you, registration is now complete.' ) ; } else { $ message = Yii :: t ( 'users' , 'Something went wrong and your account has not been confirmed.' ) ; } } else { $ success = false ; $ message = Yii :: t ( 'users' , 'The confirmation link is invalid or expired. Please try requesting a new one.' ) ; } Yii :: $ app -> session -> setFlash ( $ success ? 'success' : 'danger' , $ message ) ; return $ success ; }
Attempts user confirmation .
41,623
public function assignRoles ( ) { $ auth = Yii :: $ app -> authManager ; $ auth -> assign ( $ auth -> getRole ( Access :: ROLE_USER ) , $ this -> id ) ; }
Assign roles to new user Overwrite this method for own purposes
41,624
public static function mul ( Vector $ vector , $ value ) : Vector { $ type = get_class ( $ vector ) ; $ out = new $ type ( ) ; $ count = count ( $ out ) ; if ( $ value instanceof Vector === false ) { $ value = new $ type ( ... array_fill ( 0 , $ count , $ value ) ) ; } for ( $ i = $ count ; $ i -- > 0 ; ) { $ out [ $ i ] = $ vector [ $ i ] * $ value [ $ i ] ; } return $ out ; }
Vector multiplication .
41,625
public static function cross ( Vector3D $ value1 , Vector3D $ value2 ) : Vector3D { return new Vector3D ( ( $ value1 -> getY ( ) * $ value2 -> getZ ( ) ) - ( $ value1 -> getZ ( ) * $ value2 -> getY ( ) ) , - ( ( $ value1 -> getX ( ) * $ value2 -> getZ ( ) ) - ( $ value1 -> getZ ( ) * $ value2 -> getX ( ) ) ) , ( $ value1 -> getX ( ) * $ value2 -> getY ( ) ) - ( $ value1 -> getY ( ) * $ value2 -> getX ( ) ) ) ; }
Cross product of two vectors .
41,626
private function executeComposerInstall ( $ host ) { $ ssh = $ host -> getSshClient ( ) ; $ ssh -> exec ( array ( sprintf ( 'cd %s;' , $ host -> getWorkingDirectory ( ) ) , 'stat composer.phar' ) ) ; if ( $ ssh -> getExitCode ( ) ) { $ this -> installComposer ( $ host ) ; } $ ssh = $ host -> getSshClient ( ) ; $ ssh -> exec ( array ( sprintf ( 'cd %s;' , $ host -> getWorkingDirectory ( ) ) , 'php composer.phar install --no-dev' ) , null , self :: TIMEOUT_MAX_RUNTIME_COMPOSER_INSTALL ) ; if ( $ ssh -> getExitCode ( ) ) { throw new SynchronisationException ( $ host -> getName ( ) , sprintf ( 'Unable to execute composer install: "%s".' , $ ssh -> getErrorOutput ( ) ) ) ; } }
Execute composer install from the host s working directory . Install composer to the working directory if it isn t already installed there .
41,627
public function invoke ( $ route ) { if ( $ route instanceof IRoute ) { return $ this -> invokeRoute ( $ route ) ; } return new HttpResponse ( HttpStatusCode :: NOT_FOUND ) ; }
Invoke given route . If the route is null returns a 404 response .
41,628
public function sendRequest ( ApiKey $ apiKey , RestRequest $ request ) { $ hmac = $ this -> generateHmac ( $ apiKey -> getPrivateKey ( ) , $ request -> getEndpoint ( ) , array_merge ( $ request -> getQueryData ( ) , $ request -> getPostData ( ) ) ) ; $ client = new Client ( [ 'base_uri' => $ request -> getHost ( ) ] ) ; $ args = [ 'auth' => [ $ apiKey -> getPublicKey ( ) , $ hmac ] , 'headers' => [ 'Accept' => 'application/json' ] ] ; if ( $ request -> getRequestMethod ( ) === 'POST' ) { $ args [ 'form_params' ] = $ request -> getPostData ( ) ; } else { $ args [ 'query' ] = $ request -> getQueryData ( ) ; } try { $ responseRaw = $ client -> request ( $ request -> getRequestMethod ( ) , $ request -> getEndpoint ( ) , $ args ) ; } catch ( RequestException $ e ) { if ( ! $ e -> hasResponse ( ) ) { throw new Exception ( 'Cannot send REST request.' , 0 , $ e ) ; } $ responseRaw = $ e -> getResponse ( ) ; } return $ this -> prepareResponse ( $ responseRaw , $ request ) ; }
Sends the RestRequest to the endpoint
41,629
protected function prepareResponse ( $ responseRaw , RestRequest $ request ) { $ body = ( string ) $ responseRaw -> getBody ( ) ; $ parsedResult = json_decode ( $ body ) ; if ( $ parsedResult == false ) { $ parsedResult = new \ stdClass ( ) ; } $ response = new RestResponse ( $ responseRaw -> getStatusCode ( ) , $ body , $ parsedResult , $ request ) ; return $ response ; }
Prepares the response object for the given raw response object
41,630
protected function fillXml ( \ SimpleXMLElement $ element , $ data ) { foreach ( $ data as $ key => $ value ) { if ( is_array ( $ value ) || is_object ( $ value ) ) { if ( ! is_numeric ( $ key ) ) { $ child = $ element -> addChild ( $ key ) ; } else { $ child = $ element ; } $ this -> fillXml ( $ child , $ value ) ; } else { $ element -> addChild ( $ key , $ value ) ; } } }
Builds a xml string out of the given array
41,631
protected function generateHmac ( $ privateKey , $ requestedRoute , $ data ) { $ completeString = $ requestedRoute . json_encode ( $ data ) ; return hash_hmac ( 'sha256' , $ completeString , $ privateKey ) ; }
Generates the hmac for the given data
41,632
protected function _createTransitionerException ( $ message = null , $ code = null , RootException $ previous = null , $ transitioner = null ) { return new TransitionerException ( $ message , $ code , $ previous , $ transitioner ) ; }
Creates a new transitioner exception .
41,633
public function chmodR ( $ path , $ filemode ) { if ( ! $ this -> isFolder ( $ path ) ) { return $ this -> chmod ( $ path , $ filemode ) ; } $ dirh = @ opendir ( $ path ) ; while ( $ file = readdir ( $ dirh ) ) { if ( $ file != '.' && $ file != '..' ) { $ fullpath = $ path . '/' . $ file ; if ( ! $ this -> isFolder ( $ fullpath ) ) { if ( ! $ this -> chmod ( $ fullpath , $ filemode ) ) { return false ; } } else { if ( ! $ this -> chmodR ( $ fullpath , $ filemode ) ) { return false ; } } } } closedir ( $ dirh ) ; if ( $ this -> chmod ( $ path , $ filemode ) ) { return true ; } else { return false ; } }
Recursively sets permissions for all files in a folder
41,634
final public function ls ( $ path , $ exclude = array ( ".DS_Store" , ".git" , ".svn" , ".CVS" ) , $ recursive = FALSE , $ recursivelimit = 0 , $ showfiles = FALSE , $ sort = TRUE , $ long = FALSE ) { if ( ! $ this -> is ( $ path ) ) { return array ( ) ; } $ dirh = @ opendir ( $ path ) ; $ found = [ ] ; if ( $ dirh ) { while ( false !== ( $ file = readdir ( $ dirh ) ) ) { if ( $ file == '.' || $ file == '..' || in_array ( $ file , $ exclude ) ) { continue ; } $ recursion = 0 ; $ newPath = $ path . $ file ; if ( $ this -> isFolder ( $ newPath ) && $ recursive && ( $ recursion < $ recursiveLimit ) ) { $ newRecursiveLimit = ( ( int ) $ recursiveLimit > 0 ) ? ( ( int ) $ recursiveLimit - 1 ) : 0 ; $ items = $ this -> list ( $ newPath , $ exclude , $ recursive , $ newRecursiveLimit ) ; $ found = array_merge ( $ items , $ found ) ; } $ found [ ] = $ newPath ; } closedir ( $ dirh ) ; } return $ found ; }
Lists all the files in a directory
41,635
final public function deleteContents ( $ folderpath , $ filterByExtension = [ ] , $ filterByName = [ ] , $ filterExcludeMode = true , $ recursive = true ) { if ( ! $ this -> is ( $ folderpath ) ) { return false ; } $ dirh = @ opendir ( $ folderpath ) ; if ( $ dirh ) { while ( false !== ( $ file = readdir ( $ dirh ) ) ) { if ( $ filterExcludeMode ) { if ( $ file == '.' || $ file == '..' || in_array ( $ file , $ filterByName ) ) { continue ; } if ( ! empty ( $ filterByExtension ) ) { $ fhandler = $ this -> getFile ( ) ; $ extension = $ fhandler -> getExtension ( $ file ) ; if ( in_array ( $ extension , $ filterByExtension ) ) { continue ; } } } $ newPath = $ folderpath . DS . $ file ; if ( $ this -> isFolder ( $ newPath ) && $ recursive ) { $ this -> deleteContents ( $ newPath , $ filterByExtension , $ filterByName , $ filterExcludeMode , $ recursive ) ; } if ( ! static :: delete ( $ newPath ) ) { static :: setError ( "Could not delete {$newPath}" ) ; return false ; } } closedir ( $ dirh ) ; } return true ; }
Method to delete the contents of a folder
41,636
public function GetOutput ( ) { $ numberOfVarsExtracted = extract ( $ this -> variablesList ) ; if ( count ( $ this -> variablesList ) !== $ numberOfVarsExtracted ) { $ errMsg = "Number of variables extracted different from the $vars array" ; throw new \ Exception ( $ errMsg , Codes \ LogicErrors :: UNEXPECTED_VALUE , null ) ; } ob_start ( ) ; include_once $ this -> contentFile ; $ content = ob_get_clean ( ) ; ob_start ( ) ; include_once "APP_ROOT_DIR" . \ Puzzlout \ Framework \ Enums \ FrameworkFolderName :: ViewsFolderName . \ Puzzlout \ Framework \ Enums \ FileNameConst :: LayoutTemplate ; return ob_get_clean ( ) ; }
Computes the html output of send to the client . It extracts the variables first
41,637
public function getMetaTables ( ) { $ stmt = $ this -> query ( self :: META_TABLES_SQL ) ; if ( $ stmt === false ) { return array ( ) ; } $ rows = array ( ) ; foreach ( $ stmt as $ row ) { $ rows [ ] = $ row [ 0 ] ; } return $ rows ; }
Return tables information .
41,638
public function getMetaColumns ( $ tableName ) { $ stmt = $ this -> query ( self :: META_COLUMNS_SQL , array ( $ tableName ) ) ; if ( $ stmt === false ) { return array ( ) ; } $ rows = array ( ) ; foreach ( $ stmt as $ row ) { switch ( $ row [ 1 ] ) { case 'float8' : case 'numeric' : $ type = PDO :: PARAM_STR ; break ; case 'int4' : case 'int8' : $ type = PDO :: PARAM_INT ; break ; case 'bool' : $ type = PDO :: PARAM_BOOL ; break ; default : $ type = PDO :: PARAM_STR ; break ; } $ rows [ $ row [ 0 ] ] = $ type ; } return $ rows ; }
Return columns information .
41,639
public function currval ( $ table , $ pkey ) { $ stmt = $ this -> query ( "SELECT currval('{$table}_{$pkey}_seq')" ) ; if ( ! $ stmt ) return false ; $ ret = $ stmt -> fetch ( PDO :: FETCH_NUM ) ; if ( ! $ ret ) { $ stmt = null ; return false ; } $ stmt = null ; return $ ret [ 0 ] ; }
Return current sequence .
41,640
private function checkCredentials ( array $ args = [ ] ) : bool { if ( empty ( $ args [ 'credentials' ] ) ) { throw new DorcasException ( 'You did not provide the Dorcas client credentials in the configuration.' , $ args ) ; } $ id = data_get ( $ args , 'credentials.id' , null ) ; $ secret = data_get ( $ args , 'credentials.secret' , null ) ; if ( empty ( $ id ) ) { throw new DorcasException ( 'The client "id" key is absent in the credentials configuration.' , $ args ) ; } if ( empty ( $ secret ) ) { throw new DorcasException ( 'The client "secret" key is absent in the credentials configuration.' , $ args ) ; } return true ; }
Checks the credentials configuration to make sure it is valid .
41,641
protected function createResourceClient ( string $ name , array $ options = [ ] ) : ResourceInterface { $ entry = $ this -> manifest -> getResource ( $ name ) ; if ( empty ( $ entry ) ) { throw new ResourceNotFoundException ( 'Could not find the client for the requested resource ' . $ name ) ; } $ resource = $ entry [ 'namespace' ] . '\\' . $ entry [ 'client' ] ; return new $ resource ( $ this , ... $ options ) ; }
Creates a new resource client with the provided options .
41,642
protected function createServiceClient ( string $ name , array $ options = [ ] ) : ServiceInterface { $ entry = $ this -> manifest -> getService ( $ name ) ; if ( empty ( $ entry ) ) { throw new ResourceNotFoundException ( 'Could not find the client for the requested service ' . $ name ) ; } $ service = $ entry [ 'namespace' ] . '\\' . $ entry [ 'client' ] ; return new $ service ( $ this , $ options ) ; }
Creates a new service client with the provided options .
41,643
protected function extractAttributes ( array $ data , EntityMetadata $ metadata ) { $ flattened = [ ] ; if ( ! isset ( $ data [ 'attributes' ] ) || ! is_array ( $ data [ 'attributes' ] ) ) { return $ data [ 'attributes' ] = [ ] ; } $ keyMap = array_flip ( array_keys ( $ data [ 'attributes' ] ) ) ; foreach ( $ metadata -> getProperties ( ) as $ key => $ propMeta ) { if ( ! isset ( $ keyMap [ $ key ] ) ) { continue ; } if ( true === $ metadata -> hasAttribute ( $ key ) || true === $ metadata -> hasEmbed ( $ key ) ) { $ flattened [ $ key ] = $ data [ 'attributes' ] [ $ key ] ; } } return $ flattened ; }
Extracts the model s attributes per JSON API spec .
41,644
protected function extractRelationships ( array $ data , EntityMetadata $ metadata ) { $ flattened = [ ] ; if ( ! isset ( $ data [ 'relationships' ] ) || ! is_array ( $ data [ 'relationships' ] ) ) { return $ flattened ; } foreach ( $ metadata -> getRelationships ( ) as $ key => $ relMeta ) { if ( ! isset ( $ data [ 'relationships' ] [ $ key ] ) ) { continue ; } $ rel = $ data [ 'relationships' ] [ $ key ] ; if ( false === array_key_exists ( 'data' , $ rel ) ) { throw NormalizerException :: badRequest ( sprintf ( 'The "data" member was missing from the payload for relationship "%s"' , $ key ) ) ; } if ( empty ( $ rel [ 'data' ] ) ) { $ flattened [ $ key ] = $ relMeta -> isOne ( ) ? null : [ ] ; continue ; } if ( ! is_array ( $ rel [ 'data' ] ) ) { throw NormalizerException :: badRequest ( sprintf ( 'The "data" member is not valid in the payload for relationship "%s"' , $ key ) ) ; } if ( true === $ relMeta -> isOne ( ) && true === $ this -> isSequentialArray ( $ rel [ 'data' ] ) ) { throw NormalizerException :: badRequest ( sprintf ( 'The data payload for relationship "%s" is malformed. Data types of "one" must be an associative array, sequential found.' , $ key ) ) ; } if ( true === $ relMeta -> isMany ( ) && false === $ this -> isSequentialArray ( $ rel [ 'data' ] ) ) { throw NormalizerException :: badRequest ( sprintf ( 'The data payload for relationship "%s" is malformed. Data types of "many" must be a sequential array, associative found.' , $ key ) ) ; } $ flattened [ $ key ] = $ rel [ 'data' ] ; } return $ flattened ; }
Extracts the model s relationships per JSON API spec .
41,645
public function setClientLocales ( $ clientLocales ) : void { if ( ! $ this -> clientLocales ) $ this -> clientLocales = new LocaleCollection ( ) ; $ this -> clientLocales -> removeAllLocales ( ) ; foreach ( $ clientLocales as $ locale ) { if ( is_string ( $ locale ) ) { $ locale = new Locale ( $ locale ) ; } if ( $ locale instanceof Locale ) { $ this -> clientLocales -> addLocale ( $ locale ) ; } } }
Sets the client locales . You may pass Locale objects or string values .
41,646
public function readClientLocalesFromRequest ( Request $ request ) { $ locales = [ ] ; foreach ( $ request -> getLanguages ( ) as $ client ) { try { $ locale = new Locale ( $ client ) ; $ locales [ ] = $ locale ; } catch ( \ Exception $ e ) { trigger_error ( $ e -> getMessage ( ) , E_USER_NOTICE ) ; } } $ this -> setClientLocales ( $ locales ) ; }
Reads the client locales from the request
41,647
public function getServerLocales ( ) { if ( ! isset ( $ this -> serverLocales ) ) { $ this -> serverLocales = new LocaleCollection ( ) ; foreach ( $ this -> supportedLocaleStrings as $ server ) { try { $ locale = new Locale ( $ server ) ; $ this -> serverLocales -> addLocale ( $ locale ) ; } catch ( \ Exception $ e ) { trigger_error ( $ e -> getMessage ( ) , E_USER_NOTICE ) ; } } } return $ this -> serverLocales -> getLocales ( ) ; }
Returns all possible locales the server can deliver the render result
41,648
public function getBestRenderLocales ( $ ordered = self :: ORDER_LANG ) { $ locales = [ ] ; $ this -> getServerLocales ( ) ; foreach ( $ this -> getClientLocales ( ) as $ locale ) { $ loc = $ this -> serverLocales -> getBestMatchingLocaleForLocale ( $ locale ) ; if ( $ loc && ! in_array ( $ loc , $ locales ) ) { $ locales [ ] = $ loc ; } } if ( count ( $ locales ) == 0 ) { if ( $ this -> defaultLocale ) $ locales [ ] = $ this -> defaultLocale ; else { $ locales [ ] = $ this -> getServerLocales ( ) [ 0 ] ?? NULL ; } } if ( $ ordered & self :: ORDER_STRUCT ) { $ locs = [ ] ; foreach ( $ locales as $ loc ) { $ lang = $ loc -> getLanguage ( ) ; $ locs [ $ lang ] [ ] = $ loc ; } if ( $ ordered & self :: ORDER_LANG ) { foreach ( $ locs as & $ ll ) usort ( $ ll , LocaleCollection :: LANG_SORT_CALLBACK ) ; } elseif ( $ ordered & self :: ORDER_REG ) { foreach ( $ locs as & $ ll ) usort ( $ ll , LocaleCollection :: REG_SORT_CALLBACK ) ; } return $ locs ; } return $ locales ; }
Tries to figure out which locales matching the desired language and the provided language . If no matches can be found the default CMS language will be served .
41,649
public static function installAvooDemoBundle ( InputInterface $ input , OutputInterface $ output , QuestionHelper $ helper ) { $ rootDir = getcwd ( ) ; if ( file_exists ( $ rootDir . '/src/Avoo/DemoBundle' ) ) { return ; } if ( ! getenv ( 'AVOO_DEMO' ) ) { $ question = new ConfirmationQuestion ( 'Would you like to install Avoo Demo bundle? [y/n] ' , true ) ; if ( ! $ helper -> ask ( $ input , $ output , $ question ) ) { return ; } } $ output -> writeln ( '<info>Installing the Avoo Demo bundle.</info>' ) ; $ output -> writeln ( '' ) ; $ kernelFile = $ rootDir . '/app/AppKernel.php' ; $ configFile = $ rootDir . '/app/config/config_dev.yml' ; $ fileSystem = new Filesystem ( ) ; $ fileSystem -> mirror ( __DIR__ . '/../Resources/skeleton/avoo-demo-bundle' , $ rootDir . '/src' , null , array ( 'override' => true ) ) ; $ ref = '$bundles[] = new \Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();' ; $ bundleDeclaration = "\$bundles[] = new \\Avoo\\DemoBundle\\AvooDemoBundle();" ; $ content = file_get_contents ( $ kernelFile ) ; if ( false === strpos ( $ content , $ bundleDeclaration ) ) { $ updatedContent = str_replace ( $ ref , $ bundleDeclaration . "\n " . $ ref , $ content ) ; if ( $ content === $ updatedContent ) { throw new \ RuntimeException ( 'Unable to patch %s.' , $ kernelFile ) ; } $ fileSystem -> dumpFile ( $ kernelFile , $ updatedContent ) ; } $ ref = '- { resource: config.yml }' ; $ configDeclaration = '- { resource: @AvooDemoBundle/Resources/config/config.yml }' ; $ content = file_get_contents ( $ configFile ) ; if ( false === strpos ( $ content , $ bundleDeclaration ) ) { $ updatedContent = str_replace ( $ ref , $ ref . "\n " . $ configDeclaration , $ content ) ; if ( $ content === $ updatedContent ) { throw new \ RuntimeException ( 'Unable to patch %s.' , $ kernelFile ) ; } $ fileSystem -> dumpFile ( $ configFile , $ updatedContent ) ; } self :: patchAvooDemoBundleConfiguration ( $ rootDir , $ fileSystem ) ; }
Avoo demo bundle install
41,650
private static function getApplicationName ( InputInterface $ input , OutputInterface $ output , QuestionHelper $ helper ) { $ question = new Question ( 'Choose your application name: ' ) ; $ question -> setValidator ( function ( $ answer ) { if ( ! preg_match ( '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/' , $ answer ) ) { throw new \ InvalidArgumentException ( 'The application name contains invalid characters.' ) ; } return ucfirst ( strtolower ( $ answer ) ) ; } ) ; return $ helper -> ask ( $ input , $ output , $ question ) ; }
Get application name
41,651
private static function buildCoreFiles ( $ bundleDir , $ applicationName , Filesystem $ filesystem ) { $ filesystem -> setParameters ( array ( 'namespace' => $ applicationName . '\\Bundle\\CoreBundle' , 'applicationName' => $ applicationName , 'rename' => array ( 'Bundle.php.twig' => $ applicationName . 'CoreBundle.php' , 'Extension.php.twig' => $ applicationName . 'CoreExtension.php' , 'app.yml.twig' => strtolower ( $ applicationName ) . '.yml' , ) ) ) ; $ filesystem -> mirror ( __DIR__ . '/../Resources/skeleton/avoo-core-bundle' , $ bundleDir , null , array ( 'override' => true ) ) ; }
Build core files
41,652
private static function buildComponentFiles ( $ bundleDir , $ applicationName , Filesystem $ filesystem ) { $ filesystem -> setParameters ( array ( 'namespace' => $ applicationName , 'applicationName' => $ applicationName , ) ) ; $ filesystem -> mirror ( __DIR__ . '/../Resources/skeleton/avoo-component' , $ bundleDir , null , array ( 'override' => true ) ) ; }
Build component files
41,653
private function buildHost ( UriInterface $ uri ) : string { return $ uri -> getHost ( ) . ( $ uri -> getPort ( ) !== null ? ':' . $ uri -> getPort ( ) : '' ) ; }
Returns the host header .
41,654
public static function generateFilteredKey ( $ definition , $ masterKey ) { $ cipher = mcrypt_module_open ( MCRYPT_RIJNDAEL_128 , '' , MCRYPT_MODE_CBC , '' ) ; $ ivSize = mcrypt_enc_get_iv_size ( $ cipher ) ; $ iv = mcrypt_create_iv ( $ ivSize , MCRYPT_RAND ) ; $ definitionWithPading = self :: _pad ( json_encode ( $ definition ) , 16 ) ; if ( mcrypt_generic_init ( $ cipher , $ masterKey , $ iv ) != - 1 ) { $ cipherText = mcrypt_generic ( $ cipher , $ definitionWithPading ) ; mcrypt_generic_deinit ( $ cipher ) ; $ encrypted = sprintf ( "%s-%s" , bin2hex ( $ iv ) , bin2hex ( $ cipherText ) ) ; return $ encrypted ; } }
Encrypt filtered key for use with the Connect API
41,655
public static function decryptFilteredKey ( $ encryptedKey , $ masterKey ) { $ cipher = mcrypt_module_open ( MCRYPT_RIJNDAEL_128 , '' , MCRYPT_MODE_CBC , '' ) ; $ ivAndFilter = explode ( '-' , $ encryptedKey ) ; $ iv = hex2bin ( $ ivAndFilter [ 0 ] ) ; $ filter = hex2bin ( $ ivAndFilter [ 1 ] ) ; if ( mcrypt_generic_init ( $ cipher , $ masterKey , $ iv ) != - 1 ) { $ decrypted = mdecrypt_generic ( $ cipher , $ filter ) ; mcrypt_generic_deinit ( $ cipher ) ; mcrypt_module_close ( $ cipher ) ; $ decryptedNoPadding = self :: _unpad ( $ decrypted , 16 ) ; return $ decryptedNoPadding ; } }
Decrypt filtered key generated via the encryptFukteredKey function
41,656
private static function _pad ( $ text , $ blocksize ) { $ pad = $ blocksize - ( strlen ( $ text ) % $ blocksize ) ; $ textWithPadding = $ text . str_repeat ( chr ( $ pad ) , $ pad ) ; return $ textWithPadding ; }
Pad an input string for encryption
41,657
private static function _unpad ( $ text , $ blocksize ) { if ( empty ( $ text ) ) { return '' ; } if ( strlen ( $ text ) % $ blocksize !== 0 ) { return false ; } $ pad = ord ( $ text { strlen ( $ text ) - 1 } ) ; if ( $ pad > $ blocksize || $ pad > strlen ( $ text ) || $ pad === 0 ) { return false ; } if ( strspn ( $ text , chr ( $ pad ) , strlen ( $ text ) - $ pad ) != $ pad ) { return false ; } $ textNoPadding = substr ( $ text , 0 , - $ pad ) ; return $ textNoPadding ; }
Unpad an input string
41,658
public function sendActivationMail ( $ user ) { if ( ! $ this -> shouldSend ( $ user ) ) { return trans ( 'HCACL::users.activation.check_email' ) ; } \ DB :: beginTransaction ( ) ; try { $ token = $ this -> createActivation ( $ user ) ; $ user -> sendActivationLinkNotification ( $ token ) ; } catch ( \ Exception $ e ) { \ DB :: rollback ( ) ; throw new \ Exception ( 'Activation code or mail sending failed' ) ; } \ DB :: commit ( ) ; return trans ( 'HCACL::users.activation.resent_activation' ) ; }
Send activation mail
41,659
protected function shouldSend ( $ user ) { $ activation = $ this -> getActivation ( $ user ) ; return $ activation === null || strtotime ( $ activation -> created_at ) + 60 * 60 * $ this -> resendAfter < time ( ) ; }
Check if activation mail should be resent
41,660
private function parseValue ( string $ key , $ value ) : string { if ( is_array ( $ value ) ) { return $ this -> parseArray ( $ key , $ value ) ; } return $ this -> parseScalar ( $ key , $ value ) ; }
Parsea un valor
41,661
public function getRules ( ) { $ action = $ this -> getActionReplaced ( ) ; if ( method_exists ( $ this -> formRequest , $ action ) ) { return call_user_func ( [ $ this -> formRequest , $ action ] ) ; } if ( method_exists ( $ this -> formRequest , 'rules' ) ) { return call_user_func ( [ $ this -> formRequest , 'rules' ] ) ; } return [ ] ; }
Get rules from ActionBasedFormRequest or FormRequest instance .
41,662
public function getRequiredFields ( ) { $ rules = $ this -> getRules ( ) ; $ requiredFields = array_where ( $ rules , function ( $ value , $ key ) { if ( is_array ( $ value ) ) { $ value = implode ( '|' , $ value ) ; } return str_contains ( $ value , [ 'required' , 'sometimes' ] ) ; } ) ; return $ requiredFields ; }
Get required fields .
41,663
private function getTableGateway ( ) { return new TableGateway ( $ this -> tableName , $ this -> dbAdapter , null , new HydratingResultSet ( $ this -> hydrator , $ this -> prototipo ) ) ; }
Obtem o TableGatwey
41,664
public function sendEmail ( EmailType $ type ) { $ builder = $ this -> builder ; $ type -> buildEmail ( $ builder ) ; $ email = $ builder -> build ( new SwiftEmail ( ) ) ; $ this -> mailer -> send ( $ email -> getMessage ( ) ) ; }
Build and send a given type of email .
41,665
public function run ( $ query , $ bind = [ ] ) { try { $ this -> handle = $ this -> prepare ( $ query ) ; $ this -> handle -> execute ( $ bind ) ; if ( preg_match ( '/^(select|describe|pragma)/i' , $ query ) ) { return $ this -> handle -> fetchAll ( ) ; } if ( preg_match ( '/^(delete|insert|update)/i' , $ query ) ) { return $ this -> rowCount ( ) ; } return true ; } catch ( \ PDOException $ e ) { $ this -> error = $ e -> getMessage ( ) ; return false ; } }
Execute any SQL query
41,666
public static function requestHasFiles ( Request $ request ) : bool { return ( $ request && $ request -> allFiles ( ) && count ( $ request -> allFiles ( ) ) > 0 ) ; }
Check if the passed request has at least one file
41,667
public static function isValidCurrentRequestUploadFile ( string $ uploadField , array $ arrMimeType = array ( ) ) : bool { return self :: isValidUploadFile ( $ uploadField , $ arrMimeType , request ( ) ) ; }
Check if uploaded File in current request is valid and has a valid Mime Type . Return true is all ok otherwise return false .
41,668
public static function isValidUploadFile ( string $ uploadField , array $ arrMimeType = array ( ) , Request $ request ) : bool { $ uploadedFile = self :: getFileSafe ( $ uploadField , $ request ) ; if ( ! is_a ( $ uploadedFile , UploadedFile :: class ) ) { return false ; } return UploadedFileHelper :: isValidUploadFile ( $ uploadedFile , $ arrMimeType ) ; }
Check if uploaded File is valid and has a valid Mime Type . Return true is all ok otherwise return false .
41,669
public static function getFileSafe ( string $ uploadField , Request $ request ) { if ( ! $ request ) { return null ; } $ uploadedFile = $ request -> file ( $ uploadField ) ; if ( ! is_a ( $ uploadedFile , UploadedFile :: class ) ) { return null ; } return $ uploadedFile ; }
Return File in passed request if ok otherwise return null
41,670
public static function error ( $ message , $ context = array ( ) , $ extra = null ) { return static :: log ( $ message , LoggingLevels :: ERROR , $ context , $ extra ) ; }
Creates an error log entry
41,671
public static function warning ( $ message , $ context = array ( ) , $ extra = null ) { return static :: log ( $ message , LoggingLevels :: WARNING , $ context , $ extra ) ; }
Creates a warning log entry
41,672
public static function notice ( $ message , $ context = array ( ) , $ extra = null ) { return static :: log ( $ message , LoggingLevels :: NOTICE , $ context , $ extra ) ; }
Creates a notice log entry
41,673
public static function info ( $ message , $ context = array ( ) , $ extra = null ) { return static :: log ( $ message , LoggingLevels :: INFO , $ context , $ extra ) ; }
Creates an info log entry
41,674
public static function debug ( $ message , $ context = array ( ) , $ extra = null ) { return static :: log ( $ message , LoggingLevels :: DEBUG , $ context , $ extra ) ; }
Creates a debug log entry
41,675
protected static function _processMessage ( & $ message ) { $ _newIndent = 0 ; foreach ( static :: $ _indentTokens as $ _key => $ _token ) { if ( $ _token == substr ( $ message , 0 , $ _length = strlen ( $ _token ) ) ) { $ _newIndent = ( false === $ _key ? - 1 : 1 ) ; $ message = substr ( $ message , $ _length ) ; } } return $ _newIndent ; }
Processes the indent level for the messages
41,676
protected static function _getCallingMethod ( ) { $ _backTrace = debug_backtrace ( ) ; $ _thisClass = get_called_class ( ) ; $ _type = $ _class = $ _method = null ; for ( $ _i = 0 , $ _size = sizeof ( $ _backTrace ) ; $ _i < $ _size ; $ _i ++ ) { if ( isset ( $ _backTrace [ $ _i ] [ 'class' ] ) ) { $ _class = $ _backTrace [ $ _i ] [ 'class' ] ; } if ( $ _class == $ _thisClass ) { continue ; } if ( isset ( $ _backTrace [ $ _i ] [ 'method' ] ) ) { $ _method = $ _backTrace [ $ _i ] [ 'method' ] ; } else if ( isset ( $ _backTrace [ $ _i ] [ 'function' ] ) ) { $ _method = $ _backTrace [ $ _i ] [ 'function' ] ; } else { $ _method = 'Unknown' ; } $ _type = $ _backTrace [ $ _i ] [ 'type' ] ; break ; } if ( $ _i >= 0 ) { return str_ireplace ( 'Kisma\\Core\\' , 'Core\\' , $ _class ) . $ _type . $ _method ; } return 'Unknown' ; }
Returns the name of the method that made the call
41,677
public static function formatLogEntry ( array $ entry , $ newline = true ) { $ _level = Option :: get ( $ entry , 'level' ) ; $ _levelName = static :: _getLogLevel ( $ _level ) ; $ _timestamp = Option :: get ( $ entry , 'timestamp' ) ; $ _message = preg_replace ( '/\033\[[\d;]+m/' , null , Option :: get ( $ entry , 'message' ) ) ; $ _context = Option :: get ( $ entry , 'context' ) ; $ _extra = Option :: get ( $ entry , 'extra' ) ; $ _blob = new \ stdClass ( ) ; if ( static :: $ _includeProcessInfo ) { $ _blob -> pid = getmypid ( ) ; $ _blob -> uid = getmyuid ( ) ; $ _blob -> hostname = gethostname ( ) ; } if ( ! empty ( $ _context ) ) { $ _blob -> context = $ _context ; } if ( ! empty ( $ _extra ) ) { $ _context -> extra = $ _extra ; } $ _blob = json_encode ( $ _blob ) ; if ( false === $ _blob || '{}' == $ _blob ) { $ _blob = null ; } $ _replacements = array ( 0 => $ _levelName , 1 => date ( 'M d' , $ _timestamp ) , 2 => date ( 'H:i:s' , $ _timestamp ) , 3 => $ _message , 4 => $ _blob , ) ; return str_ireplace ( array ( '%%level%%' , '%%date%%' , '%%time%%' , '%%message%%' , '%%extra%%' , ) , $ _replacements , static :: $ _logFormat ) . ( $ newline ? PHP_EOL : null ) ; }
Formats the log entry . You can override this method to provide you own formatting . It will strip out any console escape sequences as well
41,678
protected static function _checkLogFile ( ) { if ( null !== static :: $ _logger ) { return static :: $ _logFileValid = true ; } if ( empty ( static :: $ _logFilePath ) ) { static :: $ _logFilePath = ( \ Kisma :: get ( 'app.log_path' , \ Kisma :: get ( 'app.base_path' ) ) ? : dirname ( getcwd ( ) ) ) . '/log' ; } if ( ! is_dir ( static :: $ _logFilePath ) ) { if ( false === @ mkdir ( static :: $ _logFilePath , 0777 , true ) ) { error_log ( 'Unable to create default log directory: ' . static :: $ _logFilePath ) ; return static :: $ _logFileValid = false ; } } if ( empty ( static :: $ _logFileName ) ) { \ Kisma :: set ( 'app.log_file_name' , static :: $ _logFileName = static :: DEFAULT_LOG_FILE_NAME ) ; } static :: $ _defaultLog = static :: $ _logFilePath . '/' . trim ( static :: $ _logFileName , '/' ) ; static :: $ _logger = static :: createLogger ( static :: DEFAULT_CHANNEL_NAME ) ; if ( \ Kisma :: get ( CoreSettings :: DEBUG ) ) { static :: $ _enableChromePhp = static :: $ _enableChromePhp ? : true ; static :: $ _enableFirePhp = static :: $ _enableFirePhp ? : true ; } if ( static :: $ _enableFirePhp ) { static :: $ _logger -> pushHandler ( new FirePHPHandler ( ) ) ; } if ( static :: $ _enableChromePhp ) { static :: $ _logger -> pushHandler ( new ChromePHPHandler ( ) ) ; } return static :: $ _logFileValid = true ; }
Makes sure we have a log file name and path
41,679
public function setNumber ( $ number = null ) { $ this -> number = null !== $ number ? floatval ( $ number ) : null ; return $ this ; }
Sets the number .
41,680
static private function curl ( $ method , $ url , $ data , $ special_options = null ) { $ curl = \ curl_init ( ) ; if ( $ method == 'GET' ) { if ( ! empty ( $ data ) ) { $ url .= '?' . \ http_build_query ( $ data ) ; } } elseif ( ! is_null ( $ special_options ) ) { \ curl_setopt_array ( $ curl , $ special_options ) ; \ curl_setopt ( $ curl , CURLOPT_CUSTOMREQUEST , $ method ) ; \ curl_setopt ( $ curl , CURLOPT_POSTFIELDS , $ data ) ; } else { \ curl_setopt ( $ curl , CURLOPT_CUSTOMREQUEST , $ method ) ; \ curl_setopt ( $ curl , CURLOPT_POSTFIELDS , \ http_build_query ( $ data ) ) ; } \ curl_setopt ( $ curl , CURLOPT_URL , $ url ) ; \ curl_setopt ( $ curl , CURLOPT_SSL_VERIFYHOST , 0 ) ; \ curl_setopt ( $ curl , CURLOPT_SSL_VERIFYPEER , false ) ; \ curl_setopt ( $ curl , CURLOPT_CONNECTTIMEOUT , 10 ) ; \ curl_setopt ( $ curl , CURLOPT_RETURNTRANSFER , true ) ; $ content = \ curl_exec ( $ curl ) ; \ curl_close ( $ curl ) ; return $ content ; }
Requests a specified url using the specified method
41,681
public static function call ( $ method , $ args , $ content_type = null ) { if ( count ( $ args ) == 0 ) { throw new Exception \ InvalidArgsException ( "You need specify at least the URL to call" ) ; } $ method = strtoupper ( $ method ) ; $ url = null ; $ params = null ; $ callback = null ; $ data_type = '' ; if ( ! is_string ( $ args [ 0 ] ) || ! filter_var ( $ args [ 0 ] , FILTER_VALIDATE_URL ) ) { throw new Exception \ InvalidArgsException ( "The URL you specified is not valid." ) ; } else { $ url = \ array_shift ( $ args ) ; } if ( count ( $ args ) > 0 && is_array ( $ args [ 0 ] ) ) { $ params = \ array_shift ( $ args ) ; } if ( count ( $ args ) > 0 && is_callable ( $ args [ 0 ] ) ) { $ callback = \ array_shift ( $ args ) ; } if ( count ( $ args ) > 0 && is_string ( $ args [ 0 ] ) ) { $ data_type = \ array_shift ( $ args ) ; } if ( $ method == 'POST' && $ content_type == 'json' ) { $ data = self :: curl ( $ method , $ url , \ reset ( $ params ) , array ( CURLOPT_HTTPHEADER => array ( 'Content-Type: application/json' ) , CURLOPT_POSTFIELDS => $ params , ) ) ; } else if ( $ method == 'POST' && $ content_type == 'xml' ) { $ data = self :: curl ( $ method , $ url , \ reset ( $ params ) , array ( CURLOPT_HTTPHEADER => array ( 'Content-Type: text/xml' ) , CURLOPT_POSTFIELDS => $ params , ) ) ; } else { $ data = self :: curl ( $ method , $ url , $ params ) ; } $ data = StringParser :: parse ( $ data , $ data_type ) ; if ( ! is_null ( $ callback ) ) { $ data = $ callback ( $ data ) ; } return $ data ; }
Deals with the arguments detection and sets the rigth configs for the method you specify
41,682
public function createConnection ( $ host , $ port , $ password = null ) { $ socket = $ this -> socketFactory -> createClient ( sprintf ( '%s:%s' , $ host , $ port ) ) ; $ conn = new Connection ( $ socket ) ; if ( ! empty ( $ password ) ) { $ conn -> authenticate ( $ password ) ; } return $ conn ; }
Creates a new Connection
41,683
public function parseFuelConfig ( array $ config ) { $ params = array ( ) ; $ params [ 'driver' ] = $ config [ 'type' ] ; if ( $ params [ 'driver' ] === 'pdo' ) { list ( $ type , $ dsn ) = explode ( ':' , $ config [ 'connection' ] [ 'dsn' ] , 2 ) ; $ params [ 'driver' ] .= '_' . $ type ; $ dsn = explode ( ';' , $ dsn ) ; foreach ( $ dsn as $ d ) { list ( $ k , $ v ) = explode ( '=' , $ d ) ; $ params [ $ k ] = $ v ; } } else { $ params [ 'dbname' ] = $ config [ 'connection' ] [ 'database' ] ; $ params [ 'host' ] = $ config [ 'connection' ] [ 'hostname' ] ; $ params [ 'port' ] = Arr :: get ( $ config , 'connection.port' ) ; } $ params [ 'user' ] = Arr :: get ( $ config , 'connection.username' ) ; $ params [ 'password' ] = Arr :: get ( $ config , 'connection.password' ) ; $ params [ 'charset' ] = Arr :: get ( $ config , 'charset' ) ; return $ params ; }
Parses Fuel db config to DBAL compatible configuration
41,684
private function getApp ( ) { $ stack = $ this -> resolve ( 'requeststack' ) ; if ( $ request = $ stack -> top ( ) ) { $ app = $ request -> getApplication ( ) ; } else { $ app = $ this -> resolve ( 'application::__main' ) ; } return $ app ; }
Returns the current application
41,685
protected static function semicolonTerminate ( $ sql ) { $ lines = explode ( "\n" , $ sql ) ; $ lastLineK = null ; foreach ( $ lines as $ k => $ line ) { $ line = trim ( $ line ) ; if ( ! preg_match ( '/^$|^--$|^--\s+/' , $ line ) ) $ lastLineK = $ k ; } if ( $ lastLineK !== null and ! preg_match ( '/;$/' , $ lines [ $ lastLineK ] ) ) { $ lines [ $ lastLineK ] .= ";" ; return implode ( "\n" , $ lines ) ; } else { return $ sql ; } }
Make sure the last non - comment line ends with a semicolon .
41,686
protected function isEntirelyCommented ( $ sql ) { $ lines = explode ( "\n" , $ sql ) ; foreach ( $ lines as $ line ) { if ( preg_match ( self :: COMMENT_LINE_REGEX , $ line ) ) continue ; return false ; } return true ; }
Commented or empty
41,687
protected function getUpgradeLogColumnNames ( ) { $ colNames = array ( ) ; foreach ( array ( 'time' , 'script filename' , 'script file hash' ) as $ attrib ) { $ colNames [ self :: toLowerCamelCase ( $ attrib ) ] = $ this -> toDbObjectName ( $ attrib ) ; } return $ colNames ; }
Returns a map of camelCase = > however the column is spelled in the database of our upgrade table columns
41,688
public function ActivityQuery ( $ Join = TRUE ) { $ this -> SQL -> Select ( 'a.*' ) -> Select ( 't.FullHeadline, t.ProfileHeadline, t.AllowComments, t.ShowIcon, t.RouteCode' ) -> Select ( 't.Name' , '' , 'ActivityType' ) -> From ( 'Activity a' ) -> Join ( 'ActivityType t' , 'a.ActivityTypeID = t.ActivityTypeID' ) ; if ( $ Join ) { $ this -> SQL -> Select ( 'au.Name' , '' , 'ActivityName' ) -> Select ( 'au.Gender' , '' , 'ActivityGender' ) -> Select ( 'au.Photo' , '' , 'ActivityPhoto' ) -> Select ( 'au.Email' , '' , 'ActivityEmail' ) -> Select ( 'ru.Name' , '' , 'RegardingName' ) -> Select ( 'ru.Gender' , '' , 'RegardingGender' ) -> Select ( 'ru.Email' , '' , 'RegardingEmail' ) -> Select ( 'ru.Photo' , '' , 'RegardingPhoto' ) -> Join ( 'User au' , 'a.ActivityUserID = au.UserID' ) -> Join ( 'User ru' , 'a.RegardingUserID = ru.UserID' , 'left' ) ; } $ this -> FireEvent ( 'AfterActivityQuery' ) ; }
Build basis of common activity SQL query .
41,689
public function Delete ( $ ActivityID , $ Options = array ( ) ) { $ Activity = $ this -> GetID ( $ ActivityID ) ; if ( $ Activity ) { $ Log = GetValue ( 'Log' , $ Options ) ; if ( $ Log ) { LogModel :: Insert ( $ Log , 'Activity' , $ Activity ) ; } $ this -> SQL -> Delete ( 'ActivityComment' , array ( 'ActivityID' => $ ActivityID ) ) ; parent :: Delete ( array ( 'ActivityID' => $ ActivityID ) ) ; } }
Delete a particular activity item .
41,690
public function GetWhere ( $ Where , $ Offset = 0 , $ Limit = 30 ) { if ( is_string ( $ Where ) ) { $ Where = array ( $ Where => $ Offset ) ; $ Offset = 0 ; } $ this -> SQL -> Select ( 'a2.*' ) -> Select ( 't.FullHeadline, t.ProfileHeadline, t.AllowComments, t.ShowIcon, t.RouteCode' ) -> Select ( 't.Name' , '' , 'ActivityType' ) -> From ( 'Activity a' ) -> Join ( 'Activity a2' , 'a.ActivityID = a2.ActivityID' ) -> Join ( 'ActivityType t' , 'a2.ActivityTypeID = t.ActivityTypeID' ) ; foreach ( $ Where as $ Key => $ Value ) { if ( strpos ( $ Key , '.' ) === FALSE ) { $ Where [ 'a.' . $ Key ] = $ Value ; unset ( $ Where [ $ Key ] ) ; } } $ Result = $ this -> SQL -> Where ( $ Where ) -> OrderBy ( 'a.DateUpdated' , 'desc' ) -> Limit ( $ Limit , $ Offset ) -> Get ( ) ; self :: GetUsers ( $ Result -> ResultArray ( ) ) ; Gdn :: UserModel ( ) -> JoinUsers ( $ Result -> ResultArray ( ) , array ( 'ActivityUserID' , 'RegardingUserID' ) , array ( 'Join' => array ( 'Name' , 'Email' , 'Gender' , 'Photo' ) ) ) ; $ this -> CalculateData ( $ Result -> ResultArray ( ) ) ; $ this -> EventArguments [ 'Data' ] = & $ Result ; $ this -> FireEvent ( 'AfterGet' ) ; return $ Result ; }
Modifies standard Gdn_Model - > GetWhere to use AcitivityQuery .
41,691
public function Get ( $ NotifyUserID = FALSE , $ Offset = 0 , $ Limit = 30 ) { $ Offset = is_numeric ( $ Offset ) ? $ Offset : 0 ; if ( $ Offset < 0 ) $ Offset = 0 ; $ Limit = is_numeric ( $ Limit ) ? $ Limit : 0 ; if ( $ Limit < 0 ) $ Limit = 30 ; $ this -> ActivityQuery ( FALSE ) ; if ( ! $ NotifyUserID ) { $ NotifyUserID = self :: NOTIFY_PUBLIC ; } $ this -> SQL -> WhereIn ( 'NotifyUserID' , ( array ) $ NotifyUserID ) ; $ this -> FireEvent ( 'BeforeGet' ) ; $ Result = $ this -> SQL -> OrderBy ( 'a.ActivityID' , 'desc' ) -> Limit ( $ Limit , $ Offset ) -> Get ( ) ; Gdn :: UserModel ( ) -> JoinUsers ( $ Result , array ( 'ActivityUserID' , 'RegardingUserID' ) , array ( 'Join' => array ( 'Name' , 'Photo' , 'Email' , 'Gender' ) ) ) ; $ this -> EventArguments [ 'Data' ] = & $ Result ; $ this -> FireEvent ( 'AfterGet' ) ; return $ Result ; }
Modifies standard Gdn_Model - > Get to use AcitivityQuery .
41,692
public function GetCount ( $ UserID = '' ) { $ this -> SQL -> Select ( 'a.ActivityID' , 'count' , 'ActivityCount' ) -> From ( 'Activity a' ) -> Join ( 'ActivityType t' , 'a.ActivityTypeID = t.ActivityTypeID' ) ; if ( $ UserID != '' ) { $ this -> SQL -> BeginWhereGroup ( ) -> Where ( 'a.ActivityUserID' , $ UserID ) -> OrWhere ( 'a.RegardingUserID' , $ UserID ) -> EndWhereGroup ( ) ; } $ Session = Gdn :: Session ( ) ; if ( ! $ Session -> IsValid ( ) || $ Session -> UserID != $ UserID ) $ this -> SQL -> Where ( 't.Public' , '1' ) ; $ this -> FireEvent ( 'BeforeGetCount' ) ; return $ this -> SQL -> Get ( ) -> FirstRow ( ) -> ActivityCount ; }
Get number of activity related to a user .
41,693
public function GetForRole ( $ RoleID = '' , $ Offset = '0' , $ Limit = '50' ) { if ( ! is_array ( $ RoleID ) ) $ RoleID = array ( $ RoleID ) ; $ Offset = is_numeric ( $ Offset ) ? $ Offset : 0 ; if ( $ Offset < 0 ) $ Offset = 0 ; $ Limit = is_numeric ( $ Limit ) ? $ Limit : 0 ; if ( $ Limit < 0 ) $ Limit = 0 ; $ this -> ActivityQuery ( ) ; $ Result = $ this -> SQL -> Join ( 'UserRole ur' , 'a.ActivityUserID = ur.UserID' ) -> WhereIn ( 'ur.RoleID' , $ RoleID ) -> Where ( 't.Public' , '1' ) -> OrderBy ( 'a.DateInserted' , 'desc' ) -> Limit ( $ Limit , $ Offset ) -> Get ( ) ; $ this -> EventArguments [ 'Data' ] = & $ Result ; $ this -> FireEvent ( 'AfterGet' ) ; return $ Result ; }
Get activity related to a particular role .
41,694
public function GetCountForRole ( $ RoleID = '' ) { if ( ! is_array ( $ RoleID ) ) $ RoleID = array ( $ RoleID ) ; return $ this -> SQL -> Select ( 'a.ActivityID' , 'count' , 'ActivityCount' ) -> From ( 'Activity a' ) -> Join ( 'ActivityType t' , 'a.ActivityTypeID = t.ActivityTypeID' ) -> Join ( 'UserRole ur' , 'a.ActivityUserID = ur.UserID' ) -> WhereIn ( 'ur.RoleID' , $ RoleID ) -> Where ( 't.Public' , '1' ) -> Get ( ) -> FirstRow ( ) -> ActivityCount ; }
Get number of activity related to a particular role .
41,695
public function GetID ( $ ActivityID , $ DataType = FALSE ) { $ Activity = parent :: GetID ( $ ActivityID , $ DataType ) ; if ( $ Activity ) { $ this -> CalculateRow ( $ Activity ) ; $ Activities = array ( $ Activity ) ; self :: JoinUsers ( $ Activities ) ; $ Activity = array_pop ( $ Activities ) ; } return $ Activity ; }
Get a particular activity record .
41,696
public function GetNotifications ( $ NotifyUserID , $ Offset = '0' , $ Limit = '30' ) { $ this -> ActivityQuery ( FALSE ) ; $ this -> FireEvent ( 'BeforeGetNotifications' ) ; $ Result = $ this -> SQL -> Where ( 'NotifyUserID' , $ NotifyUserID ) -> Limit ( $ Limit , $ Offset ) -> OrderBy ( 'a.ActivityID' , 'desc' ) -> Get ( ) ; $ Result -> DatasetType ( DATASET_TYPE_ARRAY ) ; self :: GetUsers ( $ Result -> ResultArray ( ) ) ; Gdn :: UserModel ( ) -> JoinUsers ( $ Result -> ResultArray ( ) , array ( 'ActivityUserID' , 'RegardingUserID' ) , array ( 'Join' => array ( 'Name' , 'Photo' , 'Email' , 'Gender' ) ) ) ; $ this -> CalculateData ( $ Result -> ResultArray ( ) ) ; return $ Result ; }
Get notifications for a user .
41,697
public function GetNotificationsSince ( $ UserID , $ LastActivityID , $ FilterToActivityTypeIDs = '' , $ Limit = '5' ) { $ this -> ActivityQuery ( ) ; $ this -> FireEvent ( 'BeforeGetNotificationsSince' ) ; if ( is_array ( $ FilterToActivityTypeIDs ) ) $ this -> SQL -> WhereIn ( 'a.ActivityTypeID' , $ FilterToActivityTypeIDs ) ; else $ this -> SQL -> Where ( 't.Notify' , '1' ) ; $ Result = $ this -> SQL -> Where ( 'RegardingUserID' , $ UserID ) -> Where ( 'a.ActivityID >' , $ LastActivityID ) -> Limit ( $ Limit , 0 ) -> OrderBy ( 'a.ActivityID' , 'desc' ) -> Get ( ) ; return $ Result ; }
Get notifications for a user since designated ActivityID .
41,698
public function GetComments ( $ ActivityIDs ) { $ Result = $ this -> SQL -> Select ( 'c.*' ) -> From ( 'ActivityComment c' ) -> WhereIn ( 'c.ActivityID' , $ ActivityIDs ) -> OrderBy ( 'c.ActivityID, c.DateInserted' ) -> Get ( ) -> ResultArray ( ) ; Gdn :: UserModel ( ) -> JoinUsers ( $ Result , array ( 'InsertUserID' ) , array ( 'Join' => array ( 'Name' , 'Photo' , 'Email' ) ) ) ; return $ Result ; }
Get comments related to designated activity items .
41,699
public function Add ( $ ActivityUserID , $ ActivityType , $ Story = NULL , $ RegardingUserID = NULL , $ CommentActivityID = NULL , $ Route = NULL , $ SendEmail = '' ) { static $ ActivityTypes = array ( ) ; $ ActivityTypeRow = self :: GetActivityType ( $ ActivityType ) ; if ( $ ActivityTypeRow !== FALSE ) { $ ActivityTypeID = $ ActivityTypeRow [ 'ActivityTypeID' ] ; $ Notify = ( bool ) $ ActivityTypeRow [ 'Notify' ] ; } else { trigger_error ( ErrorMessage ( sprintf ( 'Activity type could not be found: %s' , $ ActivityType ) , 'ActivityModel' , 'Add' ) , E_USER_ERROR ) ; } $ Activity = array ( 'ActivityUserID' => $ ActivityUserID , 'ActivityType' => $ ActivityType , 'Story' => $ Story , 'RegardingUserID' => $ RegardingUserID , 'Route' => $ Route ) ; $ QueueEmail = FALSE ; if ( $ SendEmail === 'Only' ) { $ SendEmail = '' ; $ AddActivity = FALSE ; } else if ( $ SendEmail === 'QueueOnly' ) { $ SendEmail = '' ; $ QueueEmail = TRUE ; $ AddActivity = TRUE ; $ Notify = TRUE ; } else { $ AddActivity = TRUE ; } if ( $ SendEmail === FALSE || $ SendEmail === TRUE ) $ Notify = $ SendEmail ; $ Preference = FALSE ; if ( ( $ ActivityTypeRow [ 'Notify' ] || ! $ ActivityTypeRow [ 'Public' ] ) && $ RegardingUserID ) { $ Activity [ 'NotifyUserID' ] = $ Activity [ 'RegardingUserID' ] ; $ Preference = $ ActivityType ; } else { $ Activity [ 'NotifyUserID' ] = self :: NOTIFY_PUBLIC ; } if ( $ SendEmail == 'Force' || $ Notify ) { $ Activity [ 'Emailed' ] = self :: SENT_PENDING ; } elseif ( $ Notify ) { $ Activity [ 'Emailed' ] = self :: SENT_PENDING ; } elseif ( $ SendEmail === FALSE ) { $ Activity [ 'Emailed' ] = self :: SENT_ARCHIVE ; } $ Activity = $ this -> Save ( $ Activity , $ Preference ) ; return GetValue ( 'ActivityID' , $ Activity ) ; }
Add a new activity item .