idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
43,700
public static function findIdentities ( $ ids , $ scope = null ) { $ query = static :: find ( ) -> where ( [ 'id' => $ ids ] ) ; if ( $ scope !== null ) { if ( is_array ( $ scope ) ) { foreach ( $ scope as $ value ) { $ query -> $ value ( ) ; } } else { $ query -> $ scope ( ) ; } } return $ query -> all ( ) ; }
Find users by IDs .
43,701
public function delete ( ) { if ( ! ( $ this -> id == 1 && $ this -> module -> cantDeleteRoot == true ) ) { if ( $ this -> status == self :: STATUS_DELETED ) { Yii :: $ app -> authManager -> revokeAll ( $ this -> getId ( ) ) ; parent :: delete ( ) ; } else { $ this -> status = self :: STATUS_DELETED ; $ this -> save ( false ) ; } } }
Deside delete user or just set a deleted status
43,702
public function calculate ( Calculator $ calculator , $ inputValuesGrid ) { $ outputValuesGrid = [ ] ; foreach ( $ inputValuesGrid as $ date => $ inputValues ) { $ outputValuesGrid [ $ date ] = $ calculator -> calculate ( $ this , new \ DateTime ( $ date , $ this -> dataTimeZone ) , $ inputValues ) ; } return $ outputValuesGrid ; }
Returns calculated params time grid .
43,703
public function getProperties ( $ properties ) { $ values = array ( ) ; foreach ( $ properties as $ key ) { $ values [ $ key ] = $ this -> getProperty ( $ key ) ; } return $ values ; }
Retorna un array con todos los valores de las propiedades . Para leer cada propiedad llama al metodo getProperty .
43,704
public function setProperties ( $ properties , $ create = FALSE ) { foreach ( $ properties as $ key => $ value ) { $ this -> setProperty ( $ key , $ value , $ create ) ; } }
Setea las propiedades de un objeto . Para setear cada valor llama al metodo setProperty
43,705
public function configureDependencyInjection ( DependencyInjectionContainer $ dic , array $ moduleConfig , array $ globalConfig ) { $ dic -> alias ( InputProcessor :: class , StandardInputProcessor :: class ) ; $ dic -> alias ( OutputProcessor :: class , StandardOutputProcessor :: class ) ; $ dic -> setClassParameters ( InputProcessor :: class , [ 'server' => $ _SERVER , 'get' => $ _GET , 'post' => $ _POST , 'cookie' => $ _COOKIE ] ) ; }
Configures StandardInputProcessor and StandardOutputProcessor as IO handlers and wires up the input processor to use standard PHP superglobals for input .
43,706
public function dump ( array $ input , string $ outerIndent = '' ) : string { $ this -> indentLength = StringHelper :: lengthUtf8 ( $ this -> indent ) ; return $ this -> dumpArray ( $ input , $ outerIndent , StringHelper :: lengthUtf8 ( $ outerIndent ) ) ; }
Dumps an array to PHP code
43,707
protected function dumpValue ( $ value ) : string { if ( null === $ value ) { return 'null' ; } if ( false === $ value ) { return 'false' ; } if ( true === $ value ) { return 'true' ; } if ( \ is_int ( $ value ) || \ is_float ( $ value ) ) { return ( string ) $ value ; } if ( \ is_string ( $ value ) ) { return StringHelper :: dumpString ( $ value ) ; } throw new \ InvalidArgumentException ( 'Unsupported data type:' . gettype ( $ value ) ) ; }
Dumps a value other then array
43,708
protected function dumpArray ( array $ input , string $ indent , int $ outerLineLength ) : string { if ( ! $ input ) { return '[]' ; } if ( $ outerLineLength < $ this -> lineLength ) { $ dump = $ this -> tryDumpList ( $ input , $ outerLineLength , 1 ) ; if ( null !== $ dump ) { return $ dump ; } } $ next_indent = $ indent . $ this -> indent ; $ next_indent_length = $ outerLineLength + $ this -> indentLength ; $ dump = '[' . $ this -> eol ; $ index = 0 ; $ still_linear = true ; foreach ( $ input as $ key => $ value ) { $ item = $ next_indent ; $ item_outer_length = $ next_indent_length ; if ( $ still_linear && $ key === $ index ) { ++ $ index ; } else { $ still_linear = false ; $ key_dump = $ this -> dumpValue ( $ key ) ; $ item .= $ key_dump . ' => ' ; $ item_outer_length += 4 + StringHelper :: lengthUtf8 ( $ key_dump ) ; } if ( \ is_array ( $ value ) ) { $ value_dump = $ this -> dumpArray ( $ value , $ next_indent , $ item_outer_length + 1 ) ; } else { $ value_dump = $ this -> dumpValue ( $ value ) ; } $ item .= $ value_dump ; $ dump .= $ item . ',' . $ this -> eol ; } $ dump .= $ indent . ']' ; return $ dump ; }
Dumps an array with specific indention
43,709
protected function tryDumpList ( array $ input , int $ outerLineLength , int $ level ) : ? string { if ( $ level > $ this -> listDepthLimit ) { return null ; } $ dump = '[' ; $ total_length = $ outerLineLength + 1 ; $ index = 0 ; foreach ( $ input as $ key => $ value ) { if ( $ key !== $ index ) { return null ; } if ( $ index > 0 ) { $ dump .= ', ' ; $ total_length += 2 ; } if ( $ total_length >= $ this -> lineLength ) { return null ; } ++ $ index ; if ( \ is_array ( $ value ) ) { $ value_dump = $ this -> tryDumpList ( $ value , $ total_length , $ level + 1 ) ; if ( null === $ value_dump ) { return null ; } } else { $ value_dump = $ this -> dumpValue ( $ value ) ; } $ total_length += StringHelper :: lengthUtf8 ( $ value_dump ) ; if ( $ total_length >= $ this -> lineLength ) { return null ; } $ dump .= $ value_dump ; } $ total_length += 1 ; if ( $ total_length > $ this -> lineLength ) { return null ; } $ dump .= ']' ; return $ dump ; }
Dump list if possible
43,710
protected function encodeSingleResource ( \ FreeFW \ Interfaces \ ApiResponseInterface $ p_api_response ) : \ FreeFW \ JsonApi \ V1 \ Model \ ResourceObject { $ resource = new \ FreeFW \ JsonApi \ V1 \ Model \ ResourceObject ( $ p_api_response -> getApiType ( ) , $ p_api_response -> getApiId ( ) ) ; $ fields = $ p_api_response -> getApiAttributes ( ) ; if ( $ fields ) { $ attributes = new \ FreeFW \ JsonApi \ V1 \ Model \ AttributesObject ( $ fields ) ; $ resource -> setAttributes ( $ attributes ) ; } return $ resource ; }
Encode single resource
43,711
public function encode ( \ FreeFW \ Interfaces \ ApiResponseInterface $ p_api_response ) : \ FreeFW \ JsonApi \ V1 \ Model \ Document { $ document = new \ FreeFW \ JsonApi \ V1 \ Model \ Document ( ) ; if ( $ p_api_response -> hasErrors ( ) ) { foreach ( $ p_api_response -> getErrors ( ) as $ idx => $ oneError ) { $ newError = new \ FreeFW \ JsonApi \ V1 \ Model \ ErrorObject ( $ oneError -> getType ( ) , $ oneError -> getMessage ( ) , $ oneError -> getCode ( ) ) ; $ document -> addError ( $ newError ) ; } } else { if ( $ p_api_response instanceof \ Iterator ) { } else { $ resource = $ this -> encodeSingleResource ( $ p_api_response ) ; $ document -> setData ( $ resource ) ; } } return $ document ; }
Encode a ApiResponseInterface
43,712
public function table ( ) { return $ this -> database ? $ this -> laravel [ 'db' ] -> connection ( $ this -> database ) -> table ( config ( 'database.migrations' ) ) : $ this -> laravel [ 'db' ] -> table ( config ( 'database.migrations' ) ) ; }
Get table instance .
43,713
public static function get ( string $ type ) : AbstractReader { if ( ! \ array_key_exists ( $ type , static :: $ invokableClasses ) ) { throw new InvalidArgumentException ( 'Unsupported config file type: ' . $ type ) ; } return new static :: $ invokableClasses [ $ type ] ; }
Returns config reader class
43,714
public function pushAncestor ( $ ancestor ) { if ( is_string ( $ ancestor ) ) { $ ancestor = new $ ancestor ; } if ( ! $ ancestor instanceof AncestorCriteriaInterface ) { throw new RepositoryException ( "Class " . get_class ( $ ancestor ) . " must be an instance of Aruberuto\\Repository\\Contracts\\AncestorCriteriaInterface" ) ; } $ this -> ancestor -> push ( $ ancestor ) ; return $ this ; }
Push Ancestor for filter the query
43,715
public function getByAncestor ( AncestorCriteriaInterface $ ancestor ) { $ this -> model = $ ancestor -> apply ( $ this -> model , $ this ) ; $ results = $ this -> model -> get ( ) ; $ this -> resetModel ( ) ; return $ this -> parserResult ( $ results ) ; }
Find data by Ancestor
43,716
public function getSport ( ConnectionInterface $ con = null ) { if ( $ this -> aSport === null && ( $ this -> sport_id !== null ) ) { $ this -> aSport = ChildSportQuery :: create ( ) -> findPk ( $ this -> sport_id , $ con ) ; } return $ this -> aSport ; }
Get the associated ChildSport object
43,717
public function initSkills ( $ overrideExisting = true ) { if ( null !== $ this -> collSkills && ! $ overrideExisting ) { return ; } $ this -> collSkills = new ObjectCollection ( ) ; $ this -> collSkills -> setModel ( '\gossi\trixionary\model\Skill' ) ; }
Initializes the collSkills collection .
43,718
public function getEndpointAsUrl ( $ port , $ protocol = 'tcp' ) { if ( ! $ this -> hasEndpoint ( $ port , $ protocol ) ) { throw new Exception ( 'Endpoint is not available' ) ; } $ key = $ port . '/' . $ protocol ; return Url :: fromString ( $ this -> endpoints [ $ key ] ) ; }
Try to get a single endpoint as a Url
43,719
public function hasEndpoint ( $ port , $ protocol = 'tcp' ) { $ key = $ port . '/' . $ protocol ; return array_key_exists ( $ key , $ this -> endpoints ) ; }
Return whether or not an endpoint exists
43,720
private function getPathAndParent ( PersistentCollection $ coll ) { $ mapping = $ coll -> getMapping ( ) ; $ fields = array ( ) ; $ parent = $ coll -> getOwner ( ) ; while ( null !== ( $ association = $ this -> uow -> getParentAssociation ( $ parent ) ) ) { list ( $ m , $ owner , $ field ) = $ association ; if ( isset ( $ m [ 'reference' ] ) ) { break ; } $ parent = $ owner ; $ fields [ ] = $ field ; } $ propertyPath = implode ( '.' , array_reverse ( $ fields ) ) ; $ path = $ mapping [ 'name' ] ; if ( $ propertyPath ) { $ path = $ propertyPath . '.' . $ path ; } return array ( $ path , $ parent ) ; }
Gets the parent information for a given PersistentCollection . It will retrieve the top - level persistent Document that the PersistentCollection lives in . We can use this to issue queries when updating a PersistentCollection that is multiple levels deep inside an embedded document .
43,721
public function arrayFilterRecursive ( array $ array ) { foreach ( $ array as & $ value ) { if ( is_array ( $ value ) ) { $ value = count ( $ value ) === 1 && array_key_exists ( 0 , $ value ) && is_string ( $ value [ 0 ] ) && $ this -> variable -> isEmpty ( trim ( $ value [ 0 ] ) ) ? $ value [ 0 ] : $ this -> arrayFilterRecursive ( $ value ) ; } } return array_filter ( $ array , function ( $ value ) { return ! $ this -> variable -> isEmpty ( $ value ) && ! ( is_string ( $ value ) && $ this -> variable -> isEmpty ( trim ( $ value ) ) ) ; } ) ; }
Method to filter empty elements from XML
43,722
public function makePath ( ) { $ path = base_path ( 'src' ) ; if ( ! File :: exists ( $ path ) ) { File :: makeDirectory ( $ path , 0775 , true ) ; } }
Create basic path if doesn t exists
43,723
public function truncatePreservingTags ( $ str , $ textMaxLength , $ postString = '...' , $ encoding = 'UTF-8' ) { $ htmlLength = mb_strlen ( $ str , $ encoding ) ; $ htmlPos = 0 ; $ textLength = 0 ; $ closeTag = array ( ) ; if ( $ htmlLength <= $ textMaxLength ) { return $ str ; } $ inEntity = false ; for ( $ i = $ htmlPos ; $ i < $ htmlLength ; ++ $ i ) { $ char = mb_substr ( $ str , $ i , 1 , $ encoding ) ; if ( $ char === '&' ) { if ( ! $ inEntity ) { $ inEntity = true ; } } elseif ( $ char === ';' ) { if ( $ inEntity ) { $ inEntity = false ; } } elseif ( $ char === '<' ) { $ tagPos = $ i + 1 ; $ tagFirst = $ tagPos ; $ tagSize = 1 ; $ tagName = '' ; $ isTag = true ; $ isClosingTag = false ; for ( $ j = $ tagPos ; $ j < $ htmlLength ; ++ $ j ) { $ charTag = mb_substr ( $ str , $ j , 1 , $ encoding ) ; if ( $ charTag === '<' ) { $ isTag = false ; break ; } elseif ( $ tagFirst === $ j && $ charTag === '>' ) { $ isTag = false ; break ; } elseif ( $ tagFirst === $ j && $ charTag === '/' ) { $ isClosingTag = true ; } elseif ( $ charTag === '>' ) { break ; } else { $ tagName .= $ charTag ; } ++ $ tagSize ; } if ( ! empty ( $ isTag ) ) { if ( ! empty ( $ isClosingTag ) ) { array_pop ( $ closeTag ) ; } else { $ closeTag [ ] = $ tagName ; } $ i = $ i + $ tagSize ; } else { $ textLength = $ textLength + $ tagSize ; $ i = $ i + $ tagSize - 1 ; } } else { ++ $ textLength ; } if ( ! $ inEntity && $ textLength >= $ textMaxLength ) { break ; } } $ htmlPos = $ i + 1 ; $ ret = mb_substr ( $ str , 0 , $ htmlPos , $ encoding ) ; if ( $ textLength >= $ textMaxLength ) { $ ret .= $ postString ; } if ( count ( $ closeTag ) ) { foreach ( array_reverse ( $ closeTag ) as $ tag ) { $ tokens = explode ( ' ' , $ tag ) ; $ ret .= '</' . $ tokens [ 0 ] . '>' ; } } return $ ret ; }
Function truncates a HTML string preserving and closing all tags .
43,724
public function createStreamingResponse ( $ filePath , $ fileName , $ type = 'application/octet-stream' ) { $ response = new StreamedResponse ( ) ; $ this -> setStreamCallBack ( $ response , $ filePath ) ; $ this -> setStreamHeaders ( $ response , $ fileName , $ type ) ; return $ response ; }
Handles creating a streaming response for the given file path and uses the given file name
43,725
public function parse ( $ string ) { $ response = new Response ( ) ; $ filtered = preg_replace ( "/(\n|\r){2,}/" , PHP_EOL , $ string ) ; $ lines = explode ( PHP_EOL , $ filtered ) ; foreach ( $ lines as $ line ) { $ matches = array ( ) ; if ( preg_match ( '/^(\s*)\[(.*)\]$/' , $ line , $ matches ) ) { $ depth = strlen ( $ matches [ 1 ] ) ; $ this -> completeSection ( $ response , $ depth ) ; $ this -> stack [ $ depth ] = new Section ( $ matches [ 2 ] ) ; } else if ( preg_match ( '/^(\s*)(.*)=(.*)$/' , $ line , $ matches ) ) { $ depth = strlen ( $ matches [ 1 ] ) ; if ( isset ( $ this -> stack [ $ depth ] ) ) { $ section = $ this -> stack [ $ depth ] ; $ section -> __set ( $ matches [ 2 ] , self :: cast ( $ matches [ 3 ] ) ) ; } } } $ this -> completeSection ( $ response , 0 ) ; return $ response ; }
Parses the passed response and passes the key - value pairs to references .
43,726
public static function cast ( $ value ) { $ matches = array ( ) ; if ( strtolower ( $ value ) === 'true' ) { $ value = ( bool ) true ; } else if ( strtolower ( $ value ) === 'false' ) { $ value = ( bool ) false ; } else if ( is_numeric ( $ value ) ) { $ value = ( int ) $ value ; } else if ( preg_match ( '/^"(.*)"$/' , $ value , $ matches ) ) { $ value = $ matches [ 1 ] ; } return $ value ; }
Casts the value to the correct datatype .
43,727
public static function forSum ( callable $ num ) : self { return new self ( function ( ) { return 0 ; } , function ( & $ result , $ element ) use ( $ num ) { $ result += $ num ( $ element ) ; } ) ; }
returns a collector to sum up elements
43,728
public static function forAverage ( callable $ num ) : self { return new self ( function ( ) { return [ 0 , 0 ] ; } , function ( & $ result , $ arg ) use ( $ num ) { $ result [ 0 ] += $ num ( $ arg ) ; $ result [ 1 ] ++ ; } , function ( $ result ) { return $ result [ 0 ] / $ result [ 1 ] ; } ) ; }
returns a collector to calculate an average for all the given elements
43,729
public function accumulate ( $ element , $ key ) { $ accumulate = $ this -> accumulator ; $ accumulate ( $ this -> structure , $ element , $ key ) ; }
adds given element and key to result structure
43,730
public function finish ( ) { if ( null === $ this -> finisher ) { return $ this -> structure ; } $ finish = $ this -> finisher ; return $ finish ( $ this -> structure ) ; }
finishes collection of result
43,731
public function import ( $ file ) { if ( ! file_exists ( $ file ) ) { throw new \ InvalidArgumentException ( "Footprint file '$file' does not exist" ) ; } $ content = file_get_contents ( $ file ) ; $ this -> importJson ( $ content ) ; }
Import footprints from json file
43,732
public function importJson ( $ jsonData ) { $ json = json_decode ( $ jsonData , true ) ; if ( $ json === null ) { throw new \ InvalidArgumentException ( "Footprint json is not a valid" ) ; } if ( ! is_array ( $ json ) ) { throw new \ InvalidArgumentException ( "Footprint json data is not a valid" ) ; } $ this -> _data += $ json ; }
Import footprints from json string
43,733
public function get ( $ className ) { if ( isset ( $ this -> _footprints [ $ className ] ) ) { return $ this -> _footprints [ $ className ] ; } if ( isset ( $ this -> _data [ $ className ] ) ) { $ data = $ this -> _data [ $ className ] ; $ footprint = new ClassFootprint ( $ data ) ; } else { $ footprint = new ClassFootprint ( ) ; if ( preg_match ( $ this -> _interfaceRegex , $ className ) ) { $ footprint -> setType ( ClassFootprint :: TYPE_INTERFACE ) ; } } $ this -> addFootprint ( $ className , $ footprint ) ; return $ footprint ; }
Retrieve class footprint
43,734
private function validate ( ) { if ( ! stristr ( self :: CHARACTER_LIST , $ this -> value [ 0 ] ) ) { throw new \ Exception ( 'Invalid first character: ' . $ this -> value [ 0 ] ) ; } if ( ! in_array ( $ this -> value , self :: listForCharacter ( $ this -> value [ 0 ] ) ) ) { throw new \ Exception ( 'Word not in known list of words: ' . $ this -> value ) ; } }
Validate word against list of allowed characters and words
43,735
public static function randomFor ( $ char ) { $ list = self :: listForCharacter ( $ char ) ; $ class = get_called_class ( ) ; return new $ class ( $ list [ rand ( 0 , count ( $ list ) - 1 ) ] ) ; }
Get random string startign with given character
43,736
public static function listForCharacter ( $ char ) { $ file = self :: getDataFolder ( ) . '/' . $ char ; $ data = strtolower ( file_get_contents ( $ file ) ) ; return explode ( "\n" , $ data ) ; }
Get list of available words for given character
43,737
public function firstOrCreate ( array $ attributes = [ ] ) { $ model = $ this -> first ( ) ; if ( ! $ model ) { $ model = $ this -> create ( $ attributes ) ; } return $ model ; }
Find first or create record .
43,738
public function get ( ) { if ( $ this -> value !== null ) return $ this -> value ; if ( $ this -> error !== null ) throw $ this -> error ; throw new \ LogicException ( "Value and error cannot both be null" ) ; }
Returns the value of the result if it is a success
43,739
public static function _try ( callable $ f ) { try { return Result :: success ( $ f ( ) ) ; } catch ( \ Exception $ error ) { return Result :: error ( $ error ) ; } }
Tries to execute the given function and returns a result representing the outcome i . e . if the function returns normally a successful result is returned containing the return value and if the function throws an exception an error result is returned containing the error
43,740
public function addGuestActions ( $ guestActions ) { if ( ! is_array ( $ guestActions ) ) { $ guestActions = [ $ guestActions ] ; } $ this -> _guestActions = Hash :: merge ( $ this -> _guestActions , $ guestActions ) ; }
Add guest actions which don t require a logged in user .
43,741
public function hasAccess ( $ url ) { if ( $ this -> isGuestAction ( $ url ) ) { return true ; } $ path = $ this -> getPathFromUrl ( $ url ) ; $ groupId = $ this -> Auth -> user ( 'group_id' ) ; if ( $ groupId === null ) { return false ; } if ( ! is_array ( $ groupId ) ) { $ groupId = [ $ groupId ] ; } if ( in_array ( 1 , $ groupId ) ) { return true ; } $ user = Wasabi :: user ( ) ; if ( empty ( $ user -> permissions ) ) { Wasabi :: user ( ) -> permissions = $ this -> _getGroupPermissions ( ) -> findAllForGroup ( $ groupId ) ; } if ( array_key_exists ( $ path , Wasabi :: user ( ) -> permissions ) ) { return true ; } return false ; }
Check if the currently logged in user is authorized to access the given url .
43,742
public function isGuestAction ( $ url ) { $ path = $ this -> getPathFromUrl ( $ url ) ; if ( in_array ( $ path , $ this -> _guestActions ) ) { return true ; } return false ; }
Check if the requested action does not require an authenticated user . - > guest action
43,743
public function getPathFromUrl ( $ url ) { $ cacheKey = md5 ( serialize ( $ url ) ) ; return Cache :: remember ( $ cacheKey , function ( ) use ( $ url ) { $ plugin = 'App' ; $ action = 'index' ; $ parsedUrl = ! is_array ( $ url ) ? Router :: parse ( $ url ) : $ url ; if ( isset ( $ parsedUrl [ 'plugin' ] ) && ! empty ( $ parsedUrl [ 'plugin' ] ) ) { $ plugin = $ parsedUrl [ 'plugin' ] ; } $ controller = $ parsedUrl [ 'controller' ] ; if ( isset ( $ parsedUrl [ 'action' ] ) && $ parsedUrl [ 'action' ] !== '' ) { $ action = $ parsedUrl [ 'action' ] ; } return $ plugin . '.' . $ controller . '.' . $ action ; } , 'wasabi/core/guardian_paths' ) ; }
Determine the path for a given url array .
43,744
public function getActionMap ( ) { $ plugins = $ this -> getLoadedPluginPaths ( ) ; $ actionMap = [ ] ; foreach ( $ plugins as $ plugin => $ path ) { $ controllers = $ this -> getControllersForPlugin ( $ plugin , $ path ) ; foreach ( $ controllers as $ controller ) { $ actions = $ this -> introspectController ( $ controller [ 'path' ] ) ; if ( empty ( $ actions ) ) { continue ; } foreach ( $ actions as $ action ) { $ path = "{$plugin}.{$controller['name']}.{$action}" ; if ( in_array ( $ path , $ this -> _guestActions ) ) { continue ; } $ actionMap [ $ path ] = [ 'plugin' => $ plugin , 'controller' => $ controller [ 'name' ] , 'action' => $ action ] ; } } } $ appControllers = $ this -> getControllersForApp ( ) ; foreach ( $ appControllers as $ controller ) { $ actions = $ this -> introspectController ( $ controller [ 'path' ] ) ; if ( empty ( $ actions ) ) { continue ; } foreach ( $ actions as $ action ) { if ( strpos ( $ controller [ 'path' ] , ROOT . DS . 'src' . DS . 'Controller' ) === false ) { $ path = "App.{$controller['name']}.{$action}" ; if ( in_array ( $ path , $ this -> _guestActions ) ) { continue ; } $ actionMap [ $ path ] = [ 'plugin' => 'App' , 'controller' => $ controller [ 'name' ] , 'action' => $ action ] ; } else { $ namespaceParts = explode ( DS , substr ( $ controller [ 'path' ] , strlen ( ROOT . DS . 'src' . DS . 'Controller' ) + 1 ) ) ; array_pop ( $ namespaceParts ) ; $ namespace = join ( '/' , $ namespaceParts ) ; if ( ! empty ( $ namespace ) ) { $ path = "App.{$namespace}/{$controller['name']}.{$action}" ; } else { $ path = "App.{$controller['name']}.{$action}" ; } if ( in_array ( $ path , $ this -> _guestActions ) ) { continue ; } $ actionMap [ $ path ] = [ 'plugin' => 'App' , 'controller' => ! empty ( $ namespace ) ? $ namespace . '/' . $ controller [ 'name' ] : $ controller [ 'name' ] , 'action' => $ action ] ; } } } return $ actionMap ; }
Get a mapped array of all guardable controller actions excluding the provided guest actions .
43,745
public function getLoadedPluginPaths ( ) { $ pluginPaths = [ ] ; $ plugins = Plugin :: loaded ( ) ?? [ ] ; foreach ( $ plugins as $ p ) { if ( in_array ( $ p , [ 'DebugKit' , 'Migrations' ] ) ) { continue ; } $ pluginPaths [ $ p ] = Plugin :: path ( $ p ) ; } return $ pluginPaths ; }
Get the paths of all installed and active plugins .
43,746
public function getControllersForPlugin ( $ plugin , $ pluginPath ) { $ controllers = [ ] ; $ Folder = new Folder ( ) ; $ ctrlFolder = $ Folder -> cd ( $ pluginPath . DS . 'src' . DS . 'Controller' ) ; if ( ! empty ( $ ctrlFolder ) ) { $ files = $ Folder -> find ( '.*Controller\.php$' ) ; $ subLength = strlen ( 'Controller.php' ) ; foreach ( $ files as $ f ) { $ filename = basename ( $ f ) ; if ( $ filename === $ plugin . 'AppController.php' ) { continue ; } $ ctrlName = substr ( $ filename , 0 , strlen ( $ filename ) - $ subLength ) ; $ controllers [ ] = [ 'name' => $ ctrlName , 'path' => $ Folder -> path . DS . $ f ] ; } } return $ controllers ; }
Retrieve all controller names + paths for a given plugin .
43,747
public function getControllersForApp ( ) { $ controllers = [ ] ; $ ctrlFolder = new Folder ( ) ; $ ctrlFolder -> cd ( ROOT . DS . 'src' . DS . 'Controller' ) ; if ( ! empty ( $ ctrlFolder ) ) { $ files = $ ctrlFolder -> find ( '.*Controller\.php$' ) ; $ subLength = strlen ( 'Controller.php' ) ; foreach ( $ files as $ f ) { $ filename = basename ( $ f ) ; if ( $ filename === 'AppController.php' ) { continue ; } $ ctrlName = substr ( $ filename , 0 , strlen ( $ filename ) - $ subLength ) ; $ controllers [ ] = [ 'name' => $ ctrlName , 'path' => $ ctrlFolder -> path . DS . $ f ] ; } $ subFolders = $ ctrlFolder -> read ( true , false , true ) [ 0 ] ; foreach ( $ subFolders as $ subFolder ) { $ ctrlFolder -> cd ( $ subFolder ) ; $ files = $ ctrlFolder -> find ( '.*Controller\.php$' ) ; $ subLength = strlen ( 'Controller.php' ) ; foreach ( $ files as $ f ) { $ filename = basename ( $ f ) ; if ( $ filename === 'AppController.php' ) { continue ; } $ ctrlName = substr ( $ filename , 0 , strlen ( $ filename ) - $ subLength ) ; $ controllers [ ] = [ 'name' => $ ctrlName , 'path' => $ ctrlFolder -> path . DS . $ f ] ; } } } return $ controllers ; }
Retrieve all controller names + paths for the app src .
43,748
public function introspectController ( $ controllerPath ) { $ content = file_get_contents ( $ controllerPath ) ; preg_match_all ( '/public\s+function\s+\&?\s*([^(]+)/' , $ content , $ methods ) ; $ guardableActions = [ ] ; foreach ( $ methods [ 1 ] as $ m ) { if ( in_array ( $ m , [ '__construct' , 'initialize' , 'isAuthorized' , 'setRequest' , 'invokeAction' , 'beforeFilter' , 'beforeRender' , 'beforeRedirect' , 'afterFilter' ] ) ) { continue ; } $ guardableActions [ ] = $ m ; } return $ guardableActions ; }
Retrieve all controller actions from a given controller .
43,749
protected function _getGroupPermissions ( ) { if ( get_class ( $ this -> GroupPermissions ) === 'GroupPermission' ) { return $ this -> GroupPermissions ; } return $ this -> GroupPermissions = TableRegistry :: get ( 'Wasabi/Core.GroupPermissions' ) ; }
Get or initialize an instance of the GroupPermissionsTable .
43,750
public function isValid ( $ id , $ value , $ context = null ) { return $ this -> createRegeneratable ( array ( 'id' => $ id ) ) -> isValid ( $ value , $ context ) ; }
A captcha is valid by id
43,751
protected function isFileMarked ( string $ packageName , string $ file ) : bool { return \ is_file ( $ file ) && \ strpos ( \ file_get_contents ( $ file ) , \ sprintf ( '/** > %s **/' , $ packageName ) ) !== false ; }
Check if file is marked .
43,752
protected function doRequest ( Client $ client , $ url , $ options = array ( ) ) { $ options += array ( 'urlParams' => array ( ) , 'queryParams' => array ( ) , 'method' => static :: METHOD_GET , ) ; $ token = $ client -> getToken ( ) ; $ urlReplacements = $ this -> getParameterReplacements ( $ options [ 'urlParams' ] , $ token ) ; $ url = str_replace ( array_keys ( $ urlReplacements ) , array_values ( $ urlReplacements ) , $ url ) ; $ queryReplacements = $ this -> getParameterReplacements ( $ options [ 'queryParams' ] , $ token ) ; $ queryParams = array_merge ( $ options [ 'queryParams' ] , $ queryReplacements ) ; $ queryParams = $ this -> processQueryParameters ( $ queryParams ) ; $ client -> setUri ( $ this -> credentials -> getEnvironment ( ) -> getBaseUrl ( ) . $ url ) ; switch ( $ options [ 'method' ] ) { case static :: METHOD_POST : $ client -> setParameterPost ( $ queryParams ) ; break ; case static :: METHOD_GET : default : $ client -> setParameterGet ( $ queryParams ) ; break ; } $ client -> setMethod ( $ options [ 'method' ] ) ; $ response = $ client -> send ( ) ; $ statusCode = $ response -> getStatusCode ( ) ; switch ( $ statusCode ) { case 204 : return null ; case 400 : case 401 : case 403 : case 404 : case 421 : case $ statusCode >= 400 : throw new BibException ( $ response -> getReasonPhrase ( ) , $ response -> getStatusCode ( ) ) ; } $ doc = new \ DOMDocument ( ) ; $ doc -> loadXML ( $ response -> getBody ( ) ) ; return $ doc ; }
Executes a request .
43,753
protected function getParameterReplacements ( $ parameters , TokenInterface $ token ) { $ replacements = $ parameters ; foreach ( $ parameters as $ key => $ param ) { if ( strpos ( $ param , '{' ) === 0 && strpos ( $ param , '}' ) === strlen ( $ param ) - 1 ) { $ replacements [ $ key ] = $ token -> getParam ( substr ( $ param , 1 , - 1 ) ) ; } } return $ replacements ; }
Replace values in an array with parameters from a token .
43,754
protected function fetchRequestToken ( ) { $ this -> storage -> delete ( static :: BIB_ACCESS_TOKEN ) ; $ token = $ this -> consumer -> getRequestToken ( ) ; $ this -> storage -> set ( static :: BIB_REQUEST_TOKEN , $ token ) ; return $ this ; }
Fetches the request token .
43,755
protected function fetchAccessToken ( $ queryData , $ retry = true ) { if ( ! $ this -> hasRequestToken ( ) ) { $ this -> consumer -> setCallbackUrl ( $ this -> getCurrentUri ( ) ) ; $ this -> fetchRequestToken ( ) ; $ this -> consumer -> redirect ( array ( 'hint' => $ this -> getHint ( ) ) ) ; } try { $ token = $ this -> consumer -> getAccessToken ( $ queryData , $ this -> getRequestToken ( ) ) ; } catch ( InvalidArgumentException $ e ) { if ( $ retry ) { $ this -> storage -> delete ( static :: BIB_REQUEST_TOKEN ) ; $ this -> storage -> delete ( static :: BIB_ACCESS_TOKEN ) ; return $ this -> fetchAccessToken ( $ queryData , false ) ; } throw $ e ; } $ this -> storage -> delete ( static :: BIB_REQUEST_TOKEN ) ; $ this -> storage -> set ( static :: BIB_ACCESS_TOKEN , $ token ) ; return $ this ; }
Fetches the access token .
43,756
protected function getCurrentUri ( ) { $ uri = isset ( $ _SERVER [ 'REQUEST_URI' ] ) ? $ _SERVER [ 'REQUEST_URI' ] : false ; if ( ! $ uri ) { $ uri = $ _SERVER [ 'SCRIPT_NAME' ] ; if ( isset ( $ _SERVER [ 'argv' ] ) || isset ( $ _SERVER [ 'QUERY_STRING' ] ) ) { $ uri .= '?' ; $ uri .= isset ( $ _SERVER [ 'argv' ] ) ? $ _SERVER [ 'argv' ] [ 0 ] : $ _SERVER [ 'QUERY_STRING' ] ; } } return 'http' . ( isset ( $ _SERVER [ 'HTTPS' ] ) ? 's' : '' ) . '://' . $ _SERVER [ 'HTTP_HOST' ] . '/' . ltrim ( $ uri , '/' ) ; }
Gets the current uri .
43,757
protected function processQueryParameters ( $ queryParams ) { foreach ( $ queryParams as $ name => $ value ) { if ( is_bool ( $ value ) ) { $ queryParams [ $ name ] = $ value ? 'true' : 'false' ; } } return $ queryParams ; }
Processes an array of query parameters to a readable format .
43,758
public function prepare ( Mapper $ mapper ) { if ( $ this -> isPrepared ( ) ) { throw new DataSetPreparationException ( 'DataSet is already prepared' ) ; } $ this -> map ( $ mapper ) -> createInstances ( ) ; $ this -> isPrepared = true ; }
Prepare data to be trained . MUST be called prior to any call
43,759
protected function map ( Mapper $ mapper ) : DataSet { $ this -> mapper = $ mapper ; $ this -> instances = $ this -> inputsMatrix = $ this -> outputsMatrix = [ ] ; foreach ( $ this -> rawData as & $ row ) { list ( $ inputs , $ outputs ) = $ this -> mapper -> map ( $ row ) ; if ( $ inputs && $ outputs ) { $ this -> size ++ ; $ this -> inputsMatrix [ ] = $ inputs ; $ this -> numberOfInputs = $ this -> numberOfInputs ?? count ( $ inputs ) ; $ this -> outputsMatrix [ ] = $ outputs ; $ this -> numberOfOutputs = $ this -> numberOfOutputs ?? count ( $ outputs ) ; } foreach ( $ row as $ key => $ value ) { $ this -> frequency [ $ key ] [ $ value ] = $ this -> frequency [ $ key ] [ $ value ] ?? 0 ; $ this -> frequency [ $ key ] [ $ value ] ++ ; $ this -> rawAverage [ $ key ] = $ this -> rawAverage [ $ key ] ?? 0 ; $ this -> rawAverage [ $ key ] += floatval ( $ value ) / $ this -> rawSize ; } } return $ this ; }
Is called by the prepare method maps the data grabbed by the processor into instances objects
43,760
public function run ( ) { $ this -> init ( ) ; try { $ this -> bootstrap ( ) ; $ this -> route ( ) ; $ this -> dispatch ( ) ; } catch ( Exception $ e ) { if ( APPLICATION_ENV == self :: ENV_DEV ) { var_dump ( $ e ) ; } else { throw $ e ; } } return $ this ; }
bootstrap + route + dispatch
43,761
public function bootstrap ( ) { $ config = Container :: getConfig ( ) ; $ commonConfigFile = APPLICATION_PATH . '/App/' . Router :: getDefaultControllerName ( true ) . '/Config/application.php' ; $ config -> appendConfig ( require $ commonConfigFile ) ; $ bootstrapFile = APPLICATION_PATH . '/App/' . Router :: getDefaultControllerName ( true ) . '/Bootstrap.php' ; if ( ! file_exists ( $ bootstrapFile ) ) { throw new ArchException ( 'Bootstrap file ' . $ bootstrapFile . ' is needed' ) ; } Container :: getBootstrap ( ) -> bootstrap ( ) ; return $ this ; }
Configuration + Bootstraping
43,762
public function route ( ) { PluginManager :: handleApplicationPlugins ( PluginManager :: STEP_BEFORE_ROUTE ) ; Container :: getRouter ( ) -> route ( ) ; self :: debug ( 'Route: ' . Container :: getRouter ( ) -> buildUri ( ) ) ; PluginManager :: handleApplicationPlugins ( PluginManager :: STEP_AFTER_ROUTE ) ; return $ this ; }
Call router before dispatching
43,763
public function dispatch ( ) { $ request = Container :: getRequest ( ) ; $ response = Container :: getResponse ( ) ; PluginManager :: handleApplicationPlugins ( PluginManager :: STEP_BEFORE_DISPATCH_LOOP ) ; while ( ! $ this -> dispatched ) { try { PluginManager :: handleApplicationPlugins ( PluginManager :: STEP_BEFORE_ACTION ) ; $ this -> dispatchProcess ( $ request , $ response ) ; PluginManager :: handleApplicationPlugins ( PluginManager :: STEP_AFTER_ACTION ) ; } catch ( Exception $ e ) { if ( $ request -> getController ( false ) == 'event' && $ request -> getAction ( false ) == 'error' ) { throw $ e ; } Container :: getView ( ) -> addValue ( 'exception' , $ e ) ; $ this -> renderView = true ; $ request -> setController ( 'event' ) -> setAction ( 'error' ) ; $ this -> setDispatched ( false ) ; } } PluginManager :: handleApplicationPlugins ( PluginManager :: STEP_AFTER_DISPATCH_LOOP ) ; self :: debug ( 'End dispatch loop' ) ; if ( $ this -> dispatched && $ this -> renderLayout ) { $ layout = Container :: getConfig ( ) -> getConfig ( 'layout' ) ; if ( $ layout !== null ) { if ( ! file_exists ( $ layout ) ) { throw new ArchException ( 'Layout file ' . $ layout . ' not found' ) ; } $ response -> setBody ( Container :: getLayout ( true ) -> render ( $ layout ) ) ; } } if ( $ this -> renderResponse ) { $ response -> fixHeaders ( ) -> putTypeHeadersInResponse ( ) ; foreach ( $ response -> getHeaders ( ) as $ header ) { header ( $ header ) ; } $ response -> executeCallback ( ) ; if ( $ response -> hasBody ( ) ) { echo $ response -> getBody ( ) ; } } return $ this ; }
Launch the dispatch loop
43,764
private function _applyFilter ( $ chain , $ object ) { foreach ( $ chain as $ filter ) { if ( ! $ object = call_user_func ( $ filter , $ object ) ) throw new Exception ( "Filter returned null" ) ; } return $ object ; }
Apply a chain of filters to an object
43,765
protected function filter ( $ request ) { return $ this -> _applyFilter ( $ this -> _responses , $ this -> _controller -> execute ( $ this -> _applyFilter ( $ this -> _requests , $ request ) ) ) ; }
Filter a request and response and return the response
43,766
public function getMethod ( ) { $ fakeMethod = $ this -> params [ '_method' ] ; if ( $ fakeMethod ) { if ( in_array ( $ fakeMethod , $ this -> acceptedMethods ) ) { return $ fakeMethod ; } throw new Exceptions \ InvalidRequestMethodException ( "'$fakeMethod' is not a valid request method" ) ; } return $ this -> environment [ 'REQUEST_METHOD' ] ; }
Get the request method
43,767
public function create ( $ uri ) { list ( $ scheme , $ host , $ port , $ path , $ query , $ fragment , $ user , $ pass ) = $ this -> parseUrl ( $ uri ) ; return new Uri ( $ scheme , $ host , $ port , $ path , $ query , $ fragment , $ user , $ pass ) ; }
Create new Uri from provided string .
43,768
protected function parseUrl ( $ uri ) { $ parsedUrl = parse_url ( $ uri ) ; return [ isset ( $ parsedUrl [ 'scheme' ] ) ? $ parsedUrl [ 'scheme' ] : '' , isset ( $ parsedUrl [ 'host' ] ) ? $ parsedUrl [ 'host' ] : '' , isset ( $ parsedUrl [ 'port' ] ) ? $ parsedUrl [ 'port' ] : null , isset ( $ parsedUrl [ 'path' ] ) ? $ parsedUrl [ 'path' ] : '/' , isset ( $ parsedUrl [ 'query' ] ) ? $ parsedUrl [ 'query' ] : '' , isset ( $ parsedUrl [ 'fragment' ] ) ? $ parsedUrl [ 'fragment' ] : '' , isset ( $ parsedUrl [ 'user' ] ) ? $ parsedUrl [ 'user' ] : '' , isset ( $ parsedUrl [ 'pass' ] ) ? $ parsedUrl [ 'pass' ] : '' ] ; }
Parse uri to array with individual parts
43,769
protected function sendTextMsgToXmlString ( WxSendTextMsg $ msg ) { $ formatStr = <<<XML<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%d</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>XML ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getFromUserName ( ) , strtotime ( $ msg -> getCreateTime ( ) ) , $ msg -> getMsgType ( ) , $ msg -> getContent ( ) ) ; return $ result ; }
formatter WxSendTextMsg to xml string
43,770
protected function sendImageMsgToXmlString ( WxSendImageMsg $ msg ) { $ formatStr = <<<XML<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%d</CreateTime><MsgType><![CDATA[%s]]></MsgType><Image><MediaId><![CDATA[%s]]></MediaId></Image></xml>XML ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getFromUserName ( ) , strtotime ( $ msg -> getCreateTime ( ) ) , $ msg -> getMsgType ( ) , $ msg -> getMediaId ( ) ) ; return $ result ; }
formatter WxSendImageMsg to xml string
43,771
protected function sendVoiceMsgToXmlString ( WxSendVoiceMsg $ msg ) { $ formatStr = <<<XML<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%d</CreateTime><MsgType><![CDATA[%s]]></MsgType><Voice><MediaId><![CDATA[%s]]></MediaId></Voice></xml>XML ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getFromUserName ( ) , strtotime ( $ msg -> getCreateTime ( ) ) , $ msg -> getMsgType ( ) , $ msg -> getMediaId ( ) ) ; return $ result ; }
formatter WxSendVoiceMsg to xml string
43,772
protected function sendVideoMsgToXmlString ( WxSendVideoMsg $ msg ) { $ formatStr = <<<XML<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%d</CreateTime><MsgType><![CDATA[%s]]></MsgType><Video><MediaId><![CDATA[%s]]></MediaId><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description></Video></xml>XML ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getFromUserName ( ) , strtotime ( $ msg -> getCreateTime ( ) ) , $ msg -> getMsgType ( ) , $ msg -> getMediaId ( ) , $ msg -> getTitle ( ) , $ msg -> getDescription ( ) ) ; return $ result ; }
formatter WxSendVideoMsg to xml string
43,773
protected function sendMusicMsgToXmlString ( WxSendMusicMsg $ msg ) { $ formatStr = <<<XML<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%d</CreateTime><MsgType><![CDATA[%s]]></MsgType><Music><Title><![CDATA[%s]]></Title><Description><![CDATA[%s]]></Description><MusicUrl><![CDATA[%s]]></MusicUrl><HQMusicUrl><![CDATA[%s]]></HQMusicUrl><ThumbMediaId><![CDATA[%s]]></ThumbMediaId></Music></xml>XML ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getFromUserName ( ) , strtotime ( $ msg -> getCreateTime ( ) ) , $ msg -> getMsgType ( ) , $ msg -> getTitle ( ) , $ msg -> getDescription ( ) , $ msg -> getMusicUrl ( ) , $ msg -> getHQMusicUrl ( ) , $ msg -> getThumbMediaId ( ) ) ; return $ result ; }
formatter WxSendMusicMsg to xml string
43,774
protected function sendNewsMsgToXmlString ( WxSendNewsMsg $ msg ) { $ itemArray = $ msg -> getAllArticleItems ( ) ; $ itemStr = '' ; foreach ( $ itemArray as $ item ) { $ itemStr .= $ this -> sendNewsItemToXmlString ( $ item ) ; } $ formatStr = <<<XML<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%d</CreateTime><MsgType><![CDATA[%s]]></MsgType><ArticleCount>%d</ArticleCount><Articles>%s</Articles></xml>XML ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getFromUserName ( ) , strtotime ( $ msg -> getCreateTime ( ) ) , $ msg -> getMsgType ( ) , $ msg -> getArticleCount ( ) , $ itemStr ) ; return $ result ; }
formatter WxSendNewsMsg to xml string
43,775
public function toJsonString ( WxSendMsg $ msg ) { if ( $ msg instanceof WxSendTextMsg ) { return $ this -> sendTextMsgToJsonString ( $ msg ) ; } elseif ( $ msg instanceof WxSendImageMsg ) { return $ this -> sendImageMsgToJsonString ( $ msg ) ; } elseif ( $ msg instanceof WxSendVoiceMsg ) { return $ this -> sendVoiceMsgToJsonString ( $ msg ) ; } elseif ( $ msg instanceof WxSendVideoMsg ) { return $ this -> sendVideoMsgToJsonString ( $ msg ) ; } elseif ( $ msg instanceof WxSendMusicMsg ) { return $ this -> sendMusicMsgToJsonString ( $ msg ) ; } elseif ( $ msg instanceof WxSendNewsMsg ) { return $ this -> sendNewsMsgToJsonString ( $ msg ) ; } throw new \ InvalidArgumentException ( "unknown wx send msg" ) ; }
formatter to json string
43,776
protected function sendTextMsgToJsonString ( WxSendTextMsg $ msg ) { $ formatStr = '{ "touser":"%s", "msgtype":"%s", "text": { "content":"%s" } }' ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getMsgType ( ) , $ msg -> getContent ( ) ) ; return $ result ; }
formatter WxSendTextMsg to Json string
43,777
protected function sendImageMsgToJsonString ( WxSendImageMsg $ msg ) { $ formatStr = '{ "touser":"%s", "msgtype":"%s", "image": { "media_id":"%s" } }' ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getMsgType ( ) , $ msg -> getMediaId ( ) ) ; return $ result ; }
formatter WxSendImageMsg to Json string
43,778
protected function sendVoiceMsgToJsonString ( WxSendVoiceMsg $ msg ) { $ formatStr = '{ "touser":"%s", "msgtype":"%s", "voice": { "media_id":"%s" } }' ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getMsgType ( ) , $ msg -> getMediaId ( ) ) ; return $ result ; }
formatter WxSendVoiceMsg to Json string
43,779
protected function sendVideoMsgToJsonString ( WxSendVideoMsg $ msg ) { $ formatStr = '{ "touser":"%s", "msgtype":"%s", "video": { "media_id":"%s", "thumb_media_id":"%s", "title":"%s", "description":"%s" } }' ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getMsgType ( ) , $ msg -> getMediaId ( ) , $ msg -> getThumbMediaId ( ) , $ msg -> getTitle ( ) , $ msg -> getDescription ( ) ) ; return $ result ; }
formatter WxSendVideoMsg to Json string
43,780
protected function sendMusicMsgToJsonString ( WxSendMusicMsg $ msg ) { $ formatStr = '{ "touser":"%s", "msgtype":"%s", "music": { "title":"%s", "description":"%s", "musicurl":"%s", "hqmusicurl":"%s", "thumb_media_id":"%s" } }' ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getMsgType ( ) , $ msg -> getTitle ( ) , $ msg -> getDescription ( ) , $ msg -> getMusicUrl ( ) , $ msg -> getHQMusicUrl ( ) , $ msg -> getThumbMediaId ( ) ) ; return $ result ; }
formatter WxSendMusicMsg to Json string
43,781
protected function sendNewsMsgToJsonString ( WxSendNewsMsg $ msg ) { $ itemArray = $ msg -> getAllArticleItems ( ) ; $ itemStr = '' ; foreach ( $ itemArray as $ item ) { $ itemStr .= $ this -> sendNewsItemToJsonString ( $ item ) . ',' ; } $ itemStr = substr ( $ itemStr , 0 , - 1 ) ; $ formatStr = '{ "touser":"%s", "msgtype":"%s", "news":{ "articles": [ %s ] } }' ; $ result = sprintf ( $ formatStr , $ msg -> getToUserName ( ) , $ msg -> getMsgType ( ) , $ itemStr ) ; return $ result ; }
formatter WxSendNewsMsg to Json string
43,782
protected function sendNewsItemToJsonString ( WxSendNewsMsgItem $ item ) { $ formatStr = '{ "title":"%s", "description":"%s", "url":"%s", "picurl":"%s" }' ; $ result = sprintf ( $ formatStr , $ item -> getTitle ( ) , $ item -> getDescription ( ) , $ item -> getPicUrl ( ) , $ item -> getUrl ( ) ) ; return $ result ; }
formatter WxSendNewsMsgItem to Json string
43,783
public function load ( ) { if ( ! $ this -> path ) { throw new \ Exception ( 'Unable to load AppConfig from undefined path' ) ; } $ this -> data = json_decode ( file_get_contents ( $ this -> path ) , true ) ; }
Load config from filesystem
43,784
public function getTwig ( \ Twig_Environment $ twig ) { $ this -> functions -> rewind ( ) ; while ( $ this -> functions -> valid ( ) ) { $ function = $ this -> functions -> current ( ) ; $ twig -> addFunction ( new \ Twig_SimpleFunction ( $ function -> getFunctionName ( ) , array ( $ function , 'getFunctionBody' ) ) ) ; $ this -> functions -> next ( ) ; } return $ twig ; }
Adds all the functions into the twig environment
43,785
public function onMapMetaCap ( $ caps , $ cap , $ user_id , $ args ) { $ post_type_object = get_post_type_object ( $ this -> name ) ; if ( is_null ( $ post_type_object ) ) { return $ caps ; } if ( $ post_type_object -> capability_type === 'post' || $ post_type_object -> capability_type === 'page' ) { return $ caps ; } $ edit_post = $ post_type_object -> cap -> edit_post ; $ delete_post = $ post_type_object -> cap -> delete_post ; $ read_post = $ post_type_object -> cap -> read_post ; if ( $ cap === $ edit_post || $ cap === $ delete_post || $ cap === $ read_post ) { $ post = get_post ( $ args [ 0 ] ) ; switch ( $ cap ) { case $ edit_post : return $ this -> onCheckedMapMetaCapEditPost ( $ user_id , $ post , $ post_type_object ) ; case $ delete_post : return $ this -> onCheckedMapMetaCapDeletePost ( $ user_id , $ post , $ post_type_object ) ; case $ read_post : return $ this -> onCheckedMapMetaCapReadPost ( $ user_id , $ post , $ post_type_object ) ; } } return $ caps ; }
map meta cap
43,786
public function save ( $ isNewRecord ) { if ( $ this -> validate ( ) ) { $ user = $ this -> user ; $ data = [ ] ; $ fn = $ user -> formName ( ) ; if ( $ isNewRecord ) { $ data [ $ fn ] [ 'username' ] = $ this -> username ; } $ data [ $ fn ] [ 'email' ] = $ this -> email ; $ data [ $ fn ] [ 'password' ] = $ this -> password_new ; $ data [ $ fn ] [ 'change_auth_key' ] = $ this -> change_auth_key ; $ loaded = $ user -> load ( $ data ) ; if ( $ isNewRecord ) { $ user -> scenario = $ user :: SCENARIO_CREATE ; $ user -> status = $ user :: STATUS_REGISTERED ; $ saved = $ user -> insert ( ) ; } else { $ saved = $ user -> update ( ) ; } if ( $ loaded && $ saved ) { $ this -> auth_key = $ user -> auth_key ; return $ saved ; } else { $ this -> addErrors ( $ user -> errors ) ; } } return false ; }
Edit user s profile .
43,787
public function addData ( array $ data , $ templates = null ) { $ this -> engine -> addData ( $ data , $ templates ) ; return $ this -> engine ; }
Add data to render .
43,788
public function CopyLocal ( $ Name ) { $ Parsed = self :: Parse ( $ Name ) ; $ LocalPath = '' ; $ this -> EventArguments [ 'Parsed' ] = $ Parsed ; $ this -> EventArguments [ 'Path' ] = & $ LocalPath ; $ this -> FireAs ( 'Gdn_Upload' ) -> FireEvent ( 'CopyLocal' ) ; if ( ! $ LocalPath ) { $ LocalPath = PATH_UPLOADS . '/' . $ Parsed [ 'Name' ] ; } return $ LocalPath ; }
Copy an upload locally so that it can be operated on .
43,789
public function Delete ( $ Name ) { $ Parsed = $ this -> Parse ( $ Name ) ; $ this -> EventArguments [ 'Parsed' ] = & $ Parsed ; $ Handled = FALSE ; $ this -> EventArguments [ 'Handled' ] = & $ Handled ; $ this -> FireAs ( 'Gdn_Upload' ) -> FireEvent ( 'Delete' ) ; if ( ! $ Handled ) { $ Path = PATH_UPLOADS . '/' . ltrim ( $ Name , '/' ) ; @ unlink ( $ Path ) ; } }
Delete an uploaded file .
43,790
public static function FormatFileSize ( $ Bytes , $ Precision = 1 ) { $ Units = array ( 'B' , 'K' , 'M' , 'G' , 'T' ) ; $ Bytes = max ( ( int ) $ Bytes , 0 ) ; $ Pow = floor ( ( $ Bytes ? log ( $ Bytes ) : 0 ) / log ( 1024 ) ) ; $ Pow = min ( $ Pow , count ( $ Units ) - 1 ) ; $ Bytes /= pow ( 1024 , $ Pow ) ; $ Result = round ( $ Bytes , $ Precision ) . $ Units [ $ Pow ] ; return $ Result ; }
Format a number of bytes with the largest unit .
43,791
public static function UnformatFileSize ( $ Formatted ) { $ Units = array ( 'B' => 1 , 'K' => 1024 , 'M' => 1024 * 1024 , 'G' => 1024 * 1024 * 1024 , 'T' => 1024 * 1024 * 1024 * 1024 ) ; if ( preg_match ( '/([0-9.]+)\s*([A-Z]*)/i' , $ Formatted , $ Matches ) ) { $ Number = floatval ( $ Matches [ 1 ] ) ; $ Unit = strtoupper ( substr ( $ Matches [ 2 ] , 0 , 1 ) ) ; $ Mult = GetValue ( $ Unit , $ Units , 1 ) ; $ Result = round ( $ Number * $ Mult , 0 ) ; return $ Result ; } else { return FALSE ; } }
Take a string formatted filesize and return the number of bytes .
43,792
public static function Urls ( $ Type = NULL ) { static $ Urls = NULL ; if ( $ Urls === NULL ) { $ Urls = array ( '' => Asset ( '/uploads' , TRUE ) ) ; $ Sender = new stdClass ( ) ; $ Sender -> Returns = array ( ) ; $ Sender -> EventArguments = array ( ) ; $ Sender -> EventArguments [ 'Urls' ] = & $ Urls ; Gdn :: PluginManager ( ) -> CallEventHandlers ( $ Sender , 'Gdn_Upload' , 'GetUrls' ) ; } if ( $ Type === NULL ) return $ Urls ; if ( isset ( $ Urls [ $ Type ] ) ) return $ Urls [ $ Type ] ; return FALSE ; }
Returns the url prefix for a given type . If there is a plugin that wants to store uploads at a different location or in a different way then they register themselves by subscribing to the Gdn_Upload_GetUrls_Handler event . After that they will be available here .
43,793
public function ValidateUpload ( $ InputName , $ ThrowException = TRUE ) { $ Ex = FALSE ; if ( ! array_key_exists ( $ InputName , $ _FILES ) || ( ! is_uploaded_file ( $ _FILES [ $ InputName ] [ 'tmp_name' ] ) && GetValue ( 'error' , $ _FILES [ $ InputName ] , 0 ) == 0 ) ) { $ ContentLength = Gdn :: Request ( ) -> GetValueFrom ( 'server' , 'CONTENT_LENGTH' ) ; $ MaxPostSize = self :: UnformatFileSize ( ini_get ( 'post_max_size' ) ) ; if ( $ ContentLength > $ MaxPostSize ) { $ Ex = sprintf ( T ( 'Gdn_Upload.Error.MaxPostSize' , 'The file is larger than the maximum post size. (%s)' ) , self :: FormatFileSize ( $ MaxPostSize ) ) ; } else { $ Ex = T ( 'The file failed to upload.' ) ; } } else { switch ( $ _FILES [ $ InputName ] [ 'error' ] ) { case 1 : case 2 : $ MaxFileSize = self :: UnformatFileSize ( ini_get ( 'upload_max_filesize' ) ) ; $ Ex = sprintf ( T ( 'Gdn_Upload.Error.PhpMaxFileSize' , 'The file is larger than the server\'s maximum file size. (%s)' ) , self :: FormatFileSize ( $ MaxFileSize ) ) ; break ; case 3 : case 4 : $ Ex = T ( 'The file failed to upload.' ) ; break ; case 6 : $ Ex = T ( 'The temporary upload folder has not been configured.' ) ; break ; case 7 : $ Ex = T ( 'Failed to write the file to disk.' ) ; break ; case 8 : $ Ex = T ( 'The upload was stopped by extension.' ) ; break ; } } $ Foo = self :: FormatFileSize ( $ this -> _MaxFileSize ) ; if ( ! $ Ex && $ this -> _MaxFileSize > 0 && filesize ( $ _FILES [ $ InputName ] [ 'tmp_name' ] ) > $ this -> _MaxFileSize ) { $ Ex = sprintf ( T ( 'Gdn_Upload.Error.MaxFileSize' , 'The file is larger than the maximum file size. (%s)' ) , self :: FormatFileSize ( $ this -> _MaxFileSize ) ) ; } elseif ( ! $ Ex ) { $ Extension = pathinfo ( $ _FILES [ $ InputName ] [ 'name' ] , PATHINFO_EXTENSION ) ; if ( ! InArrayI ( $ Extension , $ this -> _AllowedFileExtensions ) ) $ Ex = sprintf ( T ( 'You cannot upload files with this extension (%s). Allowed extension(s) are %s.' ) , $ Extension , implode ( ', ' , $ this -> _AllowedFileExtensions ) ) ; } if ( $ Ex ) { if ( $ ThrowException ) { throw new Gdn_UserException ( $ Ex ) ; } else { $ this -> Exception = $ Ex ; return FALSE ; } } else { $ this -> _UploadedFile = $ _FILES [ $ InputName ] ; return $ this -> _UploadedFile [ 'tmp_name' ] ; } }
Validates the uploaded file . Returns the temporary name of the uploaded file .
43,794
private function _controllerFor ( $ name ) { if ( isset ( $ this -> _controllers [ $ name ] ) && is_string ( $ this -> _controllers [ $ name ] ) ) { return $ this -> _controllerFor ( $ this -> _controllers [ $ name ] ) ; } else if ( isset ( $ this -> _controllers [ $ name ] ) && is_object ( $ this -> _controllers [ $ name ] ) ) { return $ this -> _controllers [ $ name ] ; } else if ( isset ( $ this -> _controllerFactory ) ) { return $ this -> _controllerFactory -> resolve ( $ name ) ; } else { throw new Exception ( "No controller found for $name" ) ; } }
Gets a controller for a path either from a locally registered controller or one from a controller factory
43,795
public function connect ( $ url , $ name , $ controller = null ) { $ this -> _router -> connect ( $ url , $ name , $ controller ) ; if ( ! is_null ( $ controller ) ) { $ this -> _controllers [ $ name ] = $ controller ; } return $ this ; }
Defines a url a route name and an optional controller
43,796
protected function fequiv_mb_ucfirst ( $ string , $ encoding = 'utf8' ) { return mb_strtoupper ( mb_substr ( $ string , 0 , 1 , $ encoding ) , $ encoding ) . mb_substr ( $ string , 1 , mb_strlen ( $ string , $ encoding ) - 1 , $ encoding ) ; }
Equivalent function to ucfirst with mbstring usage .
43,797
public static function parse ( $ path ) { if ( ! file_exists ( $ path ) ) { throw new \ Exception ( "$path not found" ) ; } $ src = file_get_contents ( $ path ) ; if ( ! $ src ) { throw new \ Exception ( "could not read $path" ) ; } preg_match ( self :: $ frontmatter_regex , $ src , $ matches ) ; if ( ! empty ( $ matches ) ) { if ( ! ( $ frontmatter = json_decode ( trim ( $ matches [ 1 ] ) , true ) ) ) { $ frontmatter = array ( ) ; } } else { $ frontmatter = false ; } $ plain_src = preg_replace ( self :: $ frontmatter_regex , "" , $ src ) ; return array ( 'frontmatter' => $ frontmatter , 'content' => $ plain_src ) ; }
parse out the frontmatter and content from the file
43,798
public function add ( $ key , $ value ) { if ( ! isset ( $ this -> _params [ $ key ] ) ) { $ this -> _params [ $ key ] = array ( ) ; } $ this -> _params [ $ key ] [ ] = $ value ; }
add param .
43,799
public function getAsArray ( $ key , array $ default = array ( ) ) { $ value = parent :: get ( $ key , $ default ) ; if ( is_array ( $ value ) && ! $ value ) $ value = $ default ; return ( array ) $ value ; }
Get param as array .