idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
9,400
|
public function getAudioStream ( $ from = null , $ to = null ) { if ( isset ( $ this -> _type ) && $ this -> _type == 'playlist' ) { throw new Exception ( _ ( 'Conversion of playlists is not supported.' ) ) ; } if ( isset ( $ this -> protocol ) ) { if ( in_array ( $ this -> protocol , [ 'm3u8' , 'm3u8_native' ] ) ) { throw new Exception ( _ ( 'Conversion of M3U8 files is not supported.' ) ) ; } elseif ( $ this -> protocol == 'http_dash_segments' ) { throw new Exception ( _ ( 'Conversion of DASH segments is not supported.' ) ) ; } } $ avconvProc = $ this -> getAvconvProcess ( $ this -> config -> audioBitrate , 'mp3' , true , $ from , $ to ) ; $ stream = popen ( $ avconvProc -> getCommandLine ( ) , 'r' ) ; if ( ! is_resource ( $ stream ) ) { throw new Exception ( _ ( 'Could not open popen stream.' ) ) ; } return $ stream ; }
|
Get audio stream of converted video .
|
9,401
|
public function getM3uStream ( ) { if ( ! $ this -> checkCommand ( [ $ this -> config -> avconv , '-version' ] ) ) { throw new Exception ( _ ( 'Can\'t find avconv or ffmpeg at ' ) . $ this -> config -> avconv . '.' ) ; } $ urls = $ this -> getUrl ( ) ; $ process = new Process ( [ $ this -> config -> avconv , '-v' , $ this -> config -> avconvVerbosity , '-i' , $ urls [ 0 ] , '-f' , $ this -> ext , '-c' , 'copy' , '-bsf:a' , 'aac_adtstoasc' , '-movflags' , 'frag_keyframe+empty_moov' , 'pipe:1' , ] ) ; $ stream = popen ( $ process -> getCommandLine ( ) , 'r' ) ; if ( ! is_resource ( $ stream ) ) { throw new Exception ( _ ( 'Could not open popen stream.' ) ) ; } return $ stream ; }
|
Get video stream from an M3U playlist .
|
9,402
|
public function getRemuxStream ( ) { $ urls = $ this -> getUrl ( ) ; if ( ! isset ( $ urls [ 0 ] ) || ! isset ( $ urls [ 1 ] ) ) { throw new Exception ( _ ( 'This video does not have two URLs.' ) ) ; } $ process = new Process ( [ $ this -> config -> avconv , '-v' , $ this -> config -> avconvVerbosity , '-i' , $ urls [ 0 ] , '-i' , $ urls [ 1 ] , '-c' , 'copy' , '-map' , '0:v:0 ' , '-map' , '1:a:0' , '-f' , 'matroska' , 'pipe:1' , ] ) ; $ stream = popen ( $ process -> getCommandLine ( ) , 'r' ) ; if ( ! is_resource ( $ stream ) ) { throw new Exception ( _ ( 'Could not open popen stream.' ) ) ; } return $ stream ; }
|
Get an avconv stream to remux audio and video .
|
9,403
|
public function getRtmpStream ( ) { $ urls = $ this -> getUrl ( ) ; $ process = new Process ( array_merge ( [ $ this -> config -> avconv , '-v' , $ this -> config -> avconvVerbosity , ] , $ this -> getRtmpArguments ( ) , [ '-i' , $ urls [ 0 ] , '-f' , $ this -> ext , 'pipe:1' , ] ) ) ; $ stream = popen ( $ process -> getCommandLine ( ) , 'r' ) ; if ( ! is_resource ( $ stream ) ) { throw new Exception ( _ ( 'Could not open popen stream.' ) ) ; } return $ stream ; }
|
Get video stream from an RTMP video .
|
9,404
|
public function getConvertedStream ( $ audioBitrate , $ filetype ) { if ( in_array ( $ this -> protocol , [ 'm3u8' , 'm3u8_native' ] ) ) { throw new Exception ( _ ( 'Conversion of M3U8 files is not supported.' ) ) ; } $ avconvProc = $ this -> getAvconvProcess ( $ audioBitrate , $ filetype , false ) ; $ stream = popen ( $ avconvProc -> getCommandLine ( ) , 'r' ) ; if ( ! is_resource ( $ stream ) ) { throw new Exception ( _ ( 'Could not open popen stream.' ) ) ; } return $ stream ; }
|
Get the stream of a converted video .
|
9,405
|
public function getHttpResponse ( array $ headers = [ ] ) { $ client = new Client ( ) ; $ urls = $ this -> getUrl ( ) ; return $ client -> request ( 'GET' , $ urls [ 0 ] , [ 'stream' => true , 'headers' => $ headers ] ) ; }
|
Get a HTTP response containing the video .
|
9,406
|
protected function send ( $ data ) { $ pos = $ this -> tell ( ) ; $ this -> seek ( 0 , SEEK_END ) ; $ this -> write ( $ data ) ; if ( $ pos !== false ) { $ this -> seek ( $ pos ) ; } }
|
Add data to the archive .
|
9,407
|
public function getSupportedLocales ( ) { $ return = [ ] ; $ process = new Process ( [ 'locale' , '-a' ] ) ; $ process -> run ( ) ; $ installedLocales = explode ( PHP_EOL , trim ( $ process -> getOutput ( ) ) ) ; foreach ( $ this -> supportedLocales as $ supportedLocale ) { if ( in_array ( $ supportedLocale , $ installedLocales ) || in_array ( $ supportedLocale . '.utf8' , $ installedLocales ) ) { $ return [ ] = new Locale ( $ supportedLocale ) ; } } return $ return ; }
|
Get a list of supported locales .
|
9,408
|
public function setLocale ( Locale $ locale ) { putenv ( 'LANG=' . $ locale ) ; setlocale ( LC_ALL , [ $ locale . '.utf8' , $ locale ] ) ; $ this -> curLocale = $ locale ; $ this -> sessionSegment -> set ( 'locale' , $ locale ) ; }
|
Set the current locale .
|
9,409
|
protected function getFormat ( Request $ request ) { $ format = $ request -> getQueryParam ( 'format' ) ; if ( ! isset ( $ format ) ) { $ format = $ this -> defaultFormat ; } return $ format ; }
|
Get video format from request parameters or default format if none is specified .
|
9,410
|
protected function getPassword ( Request $ request ) { $ url = $ request -> getQueryParam ( 'url' ) ; $ password = $ request -> getParam ( 'password' ) ; if ( isset ( $ password ) ) { $ this -> sessionSegment -> setFlash ( $ url , $ password ) ; } else { $ password = $ this -> sessionSegment -> getFlash ( $ url ) ; } return $ password ; }
|
Get the password entered for the current video .
|
9,411
|
private function validateOptions ( ) { if ( ! is_file ( $ this -> youtubedl ) ) { throw new Exception ( "Can't find youtube-dl at " . $ this -> youtubedl ) ; } elseif ( ! Video :: checkCommand ( [ $ this -> python , '--version' ] ) ) { throw new Exception ( "Can't find Python at " . $ this -> python ) ; } }
|
Throw an exception if some of the options are invalid .
|
9,412
|
private function applyOptions ( array $ options ) { foreach ( $ options as $ option => $ value ) { if ( isset ( $ this -> $ option ) && isset ( $ value ) ) { $ this -> $ option = $ value ; } } }
|
Apply the provided options .
|
9,413
|
public static function setFile ( $ file ) { if ( is_file ( $ file ) ) { $ options = Yaml :: parse ( file_get_contents ( $ file ) ) ; self :: $ instance = new self ( $ options ) ; self :: $ instance -> validateOptions ( ) ; } else { throw new Exception ( "Can't find config file at " . $ file ) ; } }
|
Set options from a YAML file .
|
9,414
|
public static function setOptions ( array $ options , $ update = true ) { if ( $ update ) { $ config = self :: getInstance ( ) ; $ config -> applyOptions ( $ options ) ; $ config -> validateOptions ( ) ; } else { self :: $ instance = new self ( $ options ) ; } }
|
Manually set some options .
|
9,415
|
public function download ( Request $ request , Response $ response ) { $ url = $ request -> getQueryParam ( 'url' ) ; if ( isset ( $ url ) ) { $ this -> video = new Video ( $ url , $ this -> getFormat ( $ request ) , $ this -> getPassword ( $ request ) ) ; try { if ( $ this -> config -> convert && $ request -> getQueryParam ( 'audio' ) ) { return $ this -> getAudioResponse ( $ request , $ response ) ; } elseif ( $ this -> config -> convertAdvanced && ! is_null ( $ request -> getQueryParam ( 'customConvert' ) ) ) { return $ this -> getConvertedResponse ( $ request , $ response ) ; } return $ this -> getDownloadResponse ( $ request , $ response ) ; } catch ( PasswordException $ e ) { return $ response -> withRedirect ( $ this -> container -> get ( 'router' ) -> pathFor ( 'info' ) . '?' . http_build_query ( $ request -> getQueryParams ( ) ) ) ; } catch ( Exception $ e ) { $ response -> getBody ( ) -> write ( $ e -> getMessage ( ) ) ; return $ response -> withHeader ( 'Content-Type' , 'text/plain' ) -> withStatus ( 500 ) ; } } else { return $ response -> withRedirect ( $ this -> container -> get ( 'router' ) -> pathFor ( 'index' ) ) ; } }
|
Redirect to video file .
|
9,416
|
private function getConvertedAudioResponse ( Request $ request , Response $ response ) { $ from = $ request -> getQueryParam ( 'from' ) ; $ to = $ request -> getQueryParam ( 'to' ) ; $ response = $ response -> withHeader ( 'Content-Disposition' , 'attachment; filename="' . $ this -> video -> getFileNameWithExtension ( 'mp3' ) . '"' ) ; $ response = $ response -> withHeader ( 'Content-Type' , 'audio/mpeg' ) ; if ( $ request -> isGet ( ) || $ request -> isPost ( ) ) { try { $ process = $ this -> video -> getAudioStream ( $ from , $ to ) ; } catch ( Exception $ e ) { $ this -> video = $ this -> video -> withFormat ( $ this -> defaultFormat ) ; $ process = $ this -> video -> getAudioStream ( $ from , $ to ) ; } $ response = $ response -> withBody ( new Stream ( $ process ) ) ; } return $ response ; }
|
Return a converted MP3 file .
|
9,417
|
private function getAudioResponse ( Request $ request , Response $ response ) { try { if ( ! empty ( $ request -> getQueryParam ( 'from' ) ) || ! empty ( $ request -> getQueryParam ( 'to' ) ) ) { throw new Exception ( 'Force convert when we need to seek.' ) ; } if ( $ this -> config -> stream ) { $ this -> video = $ this -> video -> withFormat ( 'mp3' ) ; return $ this -> getStream ( $ request , $ response ) ; } else { $ this -> video = $ this -> video -> withFormat ( 'mp3[protocol=https]/mp3[protocol=http]' ) ; $ urls = $ this -> video -> getUrl ( ) ; return $ response -> withRedirect ( $ urls [ 0 ] ) ; } } catch ( PasswordException $ e ) { $ frontController = new FrontController ( $ this -> container ) ; return $ frontController -> password ( $ request , $ response ) ; } catch ( Exception $ e ) { $ this -> video = $ this -> video -> withFormat ( $ this -> defaultFormat ) ; return $ this -> getConvertedAudioResponse ( $ request , $ response ) ; } }
|
Return the MP3 file .
|
9,418
|
private function getRemuxStream ( Request $ request , Response $ response ) { if ( ! $ this -> config -> remux ) { throw new Exception ( _ ( 'You need to enable remux mode to merge two formats.' ) ) ; } $ stream = $ this -> video -> getRemuxStream ( ) ; $ response = $ response -> withHeader ( 'Content-Type' , 'video/x-matroska' ) ; if ( $ request -> isGet ( ) ) { $ response = $ response -> withBody ( new Stream ( $ stream ) ) ; } return $ response -> withHeader ( 'Content-Disposition' , 'attachment; filename="' . $ this -> video -> getFileNameWithExtension ( 'mkv' ) ) ; }
|
Get a remuxed stream piped through the server .
|
9,419
|
private function getDownloadResponse ( Request $ request , Response $ response ) { try { $ videoUrls = $ this -> video -> getUrl ( ) ; } catch ( EmptyUrlException $ e ) { $ videoUrls = [ ] ; } if ( count ( $ videoUrls ) > 1 ) { return $ this -> getRemuxStream ( $ request , $ response ) ; } elseif ( $ this -> config -> stream && ( isset ( $ this -> video -> entries ) || $ request -> getQueryParam ( 'stream' ) ) ) { return $ this -> getStream ( $ request , $ response ) ; } else { if ( empty ( $ videoUrls [ 0 ] ) ) { throw new Exception ( _ ( "Can't find URL of video." ) ) ; } return $ response -> withRedirect ( $ videoUrls [ 0 ] ) ; } }
|
Get approriate HTTP response to download query . Depends on whether we want to stream remux or simply redirect .
|
9,420
|
private function getConvertedResponse ( Request $ request , Response $ response ) { $ response = $ response -> withHeader ( 'Content-Disposition' , 'attachment; filename="' . $ this -> video -> getFileNameWithExtension ( $ request -> getQueryParam ( 'customFormat' ) ) . '"' ) ; $ response = $ response -> withHeader ( 'Content-Type' , 'video/' . $ request -> getQueryParam ( 'customFormat' ) ) ; if ( $ request -> isGet ( ) || $ request -> isPost ( ) ) { $ process = $ this -> video -> getConvertedStream ( $ request -> getQueryParam ( 'customBitrate' ) , $ request -> getQueryParam ( 'customFormat' ) ) ; $ response = $ response -> withBody ( new Stream ( $ process ) ) ; } return $ response ; }
|
Return a converted video file .
|
9,421
|
public function index ( Request $ request , Response $ response ) { $ uri = $ request -> getUri ( ) -> withUserInfo ( '' ) ; $ this -> view -> render ( $ response , 'index.tpl' , [ 'config' => $ this -> config , 'class' => 'index' , 'description' => _ ( 'Easily download videos from Youtube, Dailymotion, Vimeo and other websites.' ) , 'domain' => $ uri -> getScheme ( ) . '://' . $ uri -> getAuthority ( ) , 'canonical' => $ this -> getCanonicalUrl ( $ request ) , 'supportedLocales' => $ this -> localeManager -> getSupportedLocales ( ) , 'locale' => $ this -> localeManager -> getLocale ( ) , ] ) ; return $ response ; }
|
Display index page .
|
9,422
|
public function locale ( Request $ request , Response $ response , array $ data ) { $ this -> localeManager -> setLocale ( new Locale ( $ data [ 'locale' ] ) ) ; return $ response -> withRedirect ( $ this -> container -> get ( 'router' ) -> pathFor ( 'index' ) ) ; }
|
Switch locale .
|
9,423
|
public function extractors ( Request $ request , Response $ response ) { $ this -> view -> render ( $ response , 'extractors.tpl' , [ 'config' => $ this -> config , 'extractors' => Video :: getExtractors ( ) , 'class' => 'extractors' , 'title' => _ ( 'Supported websites' ) , 'description' => _ ( 'List of all supported websites from which Alltube Download ' . 'can extract video or audio files' ) , 'canonical' => $ this -> getCanonicalUrl ( $ request ) , 'locale' => $ this -> localeManager -> getLocale ( ) , ] ) ; return $ response ; }
|
Display a list of extractors .
|
9,424
|
public function password ( Request $ request , Response $ response ) { $ this -> view -> render ( $ response , 'password.tpl' , [ 'config' => $ this -> config , 'class' => 'password' , 'title' => _ ( 'Password prompt' ) , 'description' => _ ( 'You need a password in order to download this video with Alltube Download' ) , 'canonical' => $ this -> getCanonicalUrl ( $ request ) , 'locale' => $ this -> localeManager -> getLocale ( ) , ] ) ; return $ response ; }
|
Display a password prompt .
|
9,425
|
private function getInfoResponse ( Request $ request , Response $ response ) { try { $ this -> video -> getJson ( ) ; } catch ( PasswordException $ e ) { return $ this -> password ( $ request , $ response ) ; } if ( isset ( $ this -> video -> entries ) ) { $ template = 'playlist.tpl' ; } else { $ template = 'info.tpl' ; } $ title = _ ( 'Video download' ) ; $ description = _ ( 'Download video from ' ) . $ this -> video -> extractor_key ; if ( isset ( $ this -> video -> title ) ) { $ title = $ this -> video -> title ; $ description = _ ( 'Download' ) . ' "' . $ this -> video -> title . '" ' . _ ( 'from' ) . ' ' . $ this -> video -> extractor_key ; } $ this -> view -> render ( $ response , $ template , [ 'video' => $ this -> video , 'class' => 'info' , 'title' => $ title , 'description' => $ description , 'config' => $ this -> config , 'canonical' => $ this -> getCanonicalUrl ( $ request ) , 'locale' => $ this -> localeManager -> getLocale ( ) , 'defaultFormat' => $ this -> defaultFormat , ] ) ; return $ response ; }
|
Return the video description page .
|
9,426
|
public function info ( Request $ request , Response $ response ) { $ url = $ request -> getQueryParam ( 'url' ) ? : $ request -> getQueryParam ( 'v' ) ; if ( isset ( $ url ) && ! empty ( $ url ) ) { $ this -> video = new Video ( $ url , $ this -> getFormat ( $ request ) , $ this -> getPassword ( $ request ) ) ; if ( $ this -> config -> convert && $ request -> getQueryParam ( 'audio' ) ) { return $ response -> withRedirect ( $ this -> container -> get ( 'router' ) -> pathFor ( 'download' ) . '?' . http_build_query ( $ request -> getQueryParams ( ) ) ) ; } else { return $ this -> getInfoResponse ( $ request , $ response ) ; } } else { return $ response -> withRedirect ( $ this -> container -> get ( 'router' ) -> pathFor ( 'index' ) ) ; } }
|
Dislay information about the video .
|
9,427
|
public function error ( Request $ request , Response $ response , Exception $ exception ) { $ this -> view -> render ( $ response , 'error.tpl' , [ 'config' => $ this -> config , 'errors' => $ exception -> getMessage ( ) , 'class' => 'video' , 'title' => _ ( 'Error' ) , 'canonical' => $ this -> getCanonicalUrl ( $ request ) , 'locale' => $ this -> localeManager -> getLocale ( ) , ] ) ; return $ response -> withStatus ( 500 ) ; }
|
Display an error page .
|
9,428
|
private function getCanonicalUrl ( Request $ request ) { $ uri = $ request -> getUri ( ) ; $ return = 'https://alltubedownload.net/' ; $ path = $ uri -> getPath ( ) ; if ( $ path != '/' ) { $ return .= $ path ; } $ query = $ uri -> getQuery ( ) ; if ( ! empty ( $ query ) ) { $ return .= '?' . $ query ; } return $ return ; }
|
Generate the canonical URL of the current page .
|
9,429
|
public function json ( Request $ request , Response $ response ) { $ url = $ request -> getQueryParam ( 'url' ) ; if ( isset ( $ url ) ) { try { $ this -> video = new Video ( $ url , $ this -> getFormat ( $ request ) , $ this -> getPassword ( $ request ) ) ; return $ response -> withJson ( $ this -> video -> getJson ( ) ) ; } catch ( Exception $ e ) { return $ response -> withJson ( [ 'error' => $ e -> getMessage ( ) ] ) -> withStatus ( 500 ) ; } } else { return $ response -> withJson ( [ 'error' => 'You need to provide the url parameter' ] ) -> withStatus ( 400 ) ; } }
|
Return the JSON object generated by youtube - dl .
|
9,430
|
public static function getSession ( ) { if ( ! isset ( self :: $ session ) ) { $ session_factory = new SessionFactory ( ) ; self :: $ session = $ session_factory -> newInstance ( $ _COOKIE ) ; } return self :: $ session ; }
|
Get the current session .
|
9,431
|
public static function apiPath ( $ pathFormat , $ args = null , $ _ = null ) { $ arguments = array_slice ( func_get_args ( ) , 1 ) ; foreach ( $ arguments as & $ arg ) { $ arg = urlencode ( urldecode ( $ arg ) ) ; } array_unshift ( $ arguments , $ pathFormat ) ; return call_user_func_array ( 'sprintf' , $ arguments ) ; }
|
Use this function to generate API path . It will ensure that all parameters are properly urlencoded . The function will not double encode if the params are already urlencoded Signature is the same sprintf .
|
9,432
|
public static function buildQuery ( array $ args ) { if ( ! $ args ) { return '' ; } $ args = array_map ( function ( $ value ) { if ( is_array ( $ value ) ) { return json_encode ( $ value ) ; } elseif ( is_bool ( $ value ) ) { return $ value ? 'true' : 'false' ; } else { return $ value ; } } , $ args ) ; return http_build_query ( $ args ) ; }
|
When building a query string array values must be json_encoded . This function can be used to turn any array into a Algolia - valid query string .
|
9,433
|
public static function isSameDocumentReference ( UriInterface $ uri , UriInterface $ base = null ) { if ( null !== $ base ) { $ uri = UriResolver :: resolve ( $ base , $ uri ) ; return ( $ uri -> getScheme ( ) === $ base -> getScheme ( ) ) && ( $ uri -> getAuthority ( ) === $ base -> getAuthority ( ) ) && ( $ uri -> getPath ( ) === $ base -> getPath ( ) ) && ( $ uri -> getQuery ( ) === $ base -> getQuery ( ) ) ; } return '' === $ uri -> getScheme ( ) && '' === $ uri -> getAuthority ( ) && '' === $ uri -> getPath ( ) && '' === $ uri -> getQuery ( ) ; }
|
Whether the URI is a same - document reference .
|
9,434
|
public function addDefaultHeader ( $ name , $ value ) { if ( ! isset ( $ this -> headers [ $ name ] ) ) { $ this -> headers [ $ name ] = $ value ; } return $ this ; }
|
Add a new header to the list if there is no value already set .
|
9,435
|
public function addDefaultHeaders ( $ headers ) { foreach ( $ headers as $ name => $ value ) { $ this -> addDefaultHeader ( $ name , $ value ) ; } return $ this ; }
|
Add the headers passed if the value isn t already set .
|
9,436
|
public function addDefaultQueryParameter ( $ name , $ value ) { if ( ! isset ( $ this -> query [ $ name ] ) ) { $ this -> query [ $ name ] = $ value ; } return $ this ; }
|
Add a query parameter if it isn t already set .
|
9,437
|
public function addDefaultBodyParameter ( $ name , $ value ) { if ( ! isset ( $ this -> body [ $ name ] ) ) { $ this -> body [ $ name ] = $ value ; } return $ this ; }
|
Add a body parameter if it isn t already set .
|
9,438
|
public static function normalize ( UriInterface $ uri , $ flags = self :: PRESERVING_NORMALIZATIONS ) { if ( $ flags & self :: CAPITALIZE_PERCENT_ENCODING ) { $ uri = self :: capitalizePercentEncoding ( $ uri ) ; } if ( $ flags & self :: DECODE_UNRESERVED_CHARACTERS ) { $ uri = self :: decodeUnreservedCharacters ( $ uri ) ; } if ( $ flags & self :: CONVERT_EMPTY_PATH && $ uri -> getPath ( ) === '' && ( $ uri -> getScheme ( ) === 'http' || $ uri -> getScheme ( ) === 'https' ) ) { $ uri = $ uri -> withPath ( '/' ) ; } if ( $ flags & self :: REMOVE_DEFAULT_HOST && $ uri -> getScheme ( ) === 'file' && $ uri -> getHost ( ) === 'localhost' ) { $ uri = $ uri -> withHost ( '' ) ; } if ( $ flags & self :: REMOVE_DEFAULT_PORT && $ uri -> getPort ( ) !== null && Uri :: isDefaultPort ( $ uri ) ) { $ uri = $ uri -> withPort ( null ) ; } if ( $ flags & self :: REMOVE_DOT_SEGMENTS && ! Uri :: isRelativePathReference ( $ uri ) ) { $ uri = $ uri -> withPath ( UriResolver :: removeDotSegments ( $ uri -> getPath ( ) ) ) ; } if ( $ flags & self :: REMOVE_DUPLICATE_SLASHES ) { $ uri = $ uri -> withPath ( preg_replace ( '#//++#' , '/' , $ uri -> getPath ( ) ) ) ; } if ( $ flags & self :: SORT_QUERY_PARAMETERS && $ uri -> getQuery ( ) !== '' ) { $ queryKeyValues = explode ( '&' , $ uri -> getQuery ( ) ) ; sort ( $ queryKeyValues ) ; $ uri = $ uri -> withQuery ( implode ( '&' , $ queryKeyValues ) ) ; } return $ uri ; }
|
Returns a normalized URI .
|
9,439
|
public static function isEquivalent ( UriInterface $ uri1 , UriInterface $ uri2 , $ normalizations = self :: PRESERVING_NORMALIZATIONS ) { return ( string ) self :: normalize ( $ uri1 , $ normalizations ) === ( string ) self :: normalize ( $ uri2 , $ normalizations ) ; }
|
Whether two URIs can be considered equivalent .
|
9,440
|
public static function withQueryValues ( UriInterface $ uri , array $ keyValueArray ) { $ result = self :: getFilteredQueryString ( $ uri , array_keys ( $ keyValueArray ) ) ; foreach ( $ keyValueArray as $ key => $ value ) { $ result [ ] = self :: generateQueryString ( $ key , $ value ) ; } return $ uri -> withQuery ( implode ( '&' , $ result ) ) ; }
|
Creates a new URI with multiple specific query string values .
|
9,441
|
public static function relativize ( UriInterface $ base , UriInterface $ target ) { if ( $ target -> getScheme ( ) !== '' && ( $ base -> getScheme ( ) !== $ target -> getScheme ( ) || $ target -> getAuthority ( ) === '' && $ base -> getAuthority ( ) !== '' ) ) { return $ target ; } if ( Uri :: isRelativePathReference ( $ target ) ) { return $ target ; } if ( $ target -> getAuthority ( ) !== '' && $ base -> getAuthority ( ) !== $ target -> getAuthority ( ) ) { return $ target -> withScheme ( '' ) ; } $ emptyPathUri = $ target -> withScheme ( '' ) -> withPath ( '' ) -> withUserInfo ( '' ) -> withPort ( null ) -> withHost ( '' ) ; if ( $ base -> getPath ( ) !== $ target -> getPath ( ) ) { return $ emptyPathUri -> withPath ( self :: getRelativePath ( $ base , $ target ) ) ; } if ( $ base -> getQuery ( ) === $ target -> getQuery ( ) ) { return $ emptyPathUri -> withQuery ( '' ) ; } if ( $ target -> getQuery ( ) === '' ) { $ segments = explode ( '/' , $ target -> getPath ( ) ) ; $ lastSegment = end ( $ segments ) ; return $ emptyPathUri -> withPath ( $ lastSegment === '' ? './' : $ lastSegment ) ; } return $ emptyPathUri ; }
|
Returns the target URI as a relative reference from the base URI .
|
9,442
|
private function _renameSession ( $ ticket ) { phpCAS :: traceBegin ( ) ; if ( $ this -> getChangeSessionID ( ) ) { if ( ! empty ( $ this -> _user ) ) { $ old_session = $ _SESSION ; phpCAS :: trace ( "Killing session: " . session_id ( ) ) ; session_destroy ( ) ; $ session_id = $ this -> _sessionIdForTicket ( $ ticket ) ; phpCAS :: trace ( "Starting session: " . $ session_id ) ; session_id ( $ session_id ) ; session_start ( ) ; phpCAS :: trace ( "Restoring old session vars" ) ; $ _SESSION = $ old_session ; } else { phpCAS :: trace ( 'Session should only be renamed after successfull authentication' ) ; } } else { phpCAS :: trace ( "Skipping session rename since phpCAS is not handling the session." ) ; } phpCAS :: traceEnd ( ) ; }
|
Renaming the session
|
9,443
|
private function _authError ( $ failure , $ cas_url , $ no_response = false , $ bad_response = false , $ cas_response = '' , $ err_code = - 1 , $ err_msg = '' ) { phpCAS :: traceBegin ( ) ; $ lang = $ this -> getLangObj ( ) ; $ this -> printHTMLHeader ( $ lang -> getAuthenticationFailed ( ) ) ; printf ( $ lang -> getYouWereNotAuthenticated ( ) , htmlentities ( $ this -> getURL ( ) ) , isset ( $ _SERVER [ 'SERVER_ADMIN' ] ) ? $ _SERVER [ 'SERVER_ADMIN' ] : '' ) ; phpCAS :: trace ( 'CAS URL: ' . $ cas_url ) ; phpCAS :: trace ( 'Authentication failure: ' . $ failure ) ; if ( $ no_response ) { phpCAS :: trace ( 'Reason: no response from the CAS server' ) ; } else { if ( $ bad_response ) { phpCAS :: trace ( 'Reason: bad response from the CAS server' ) ; } else { switch ( $ this -> getServerVersion ( ) ) { case CAS_VERSION_1_0 : phpCAS :: trace ( 'Reason: CAS error' ) ; break ; case CAS_VERSION_2_0 : case CAS_VERSION_3_0 : if ( $ err_code === - 1 ) { phpCAS :: trace ( 'Reason: no CAS error' ) ; } else { phpCAS :: trace ( 'Reason: [' . $ err_code . '] CAS error: ' . $ err_msg ) ; } break ; } } phpCAS :: trace ( 'CAS response: ' . $ cas_response ) ; } $ this -> printHTMLFooter ( ) ; phpCAS :: traceExit ( ) ; throw new CAS_GracefullTerminationException ( ) ; }
|
This method is used to print the HTML output when the user was not authenticated .
|
9,444
|
public static function getSupportedProtocols ( ) { $ supportedProtocols = array ( ) ; $ supportedProtocols [ CAS_VERSION_1_0 ] = 'CAS 1.0' ; $ supportedProtocols [ CAS_VERSION_2_0 ] = 'CAS 2.0' ; $ supportedProtocols [ CAS_VERSION_3_0 ] = 'CAS 3.0' ; $ supportedProtocols [ SAML_VERSION_1_1 ] = 'SAML 1.1' ; return $ supportedProtocols ; }
|
This method returns supported protocols .
|
9,445
|
public function saveAsFile ( $ contents ) { $ this -> createFolderIfMissing ( ) ; $ filename = md5 ( uniqid ( ) ) . '.jpg' ; $ filePath = $ this -> webPath . '/' . $ this -> imageFolder . '/' . $ filename ; imagejpeg ( $ contents , $ filePath , 15 ) ; return '/' . $ this -> imageFolder . '/' . $ filename ; }
|
Saves the provided image content as a file
|
9,446
|
public function collectGarbage ( ) { if ( ! mt_rand ( 1 , $ this -> gcFreq ) == 1 ) { return false ; } $ this -> createFolderIfMissing ( ) ; $ finder = new Finder ( ) ; $ criteria = sprintf ( '<= now - %s minutes' , $ this -> expiration ) ; $ finder -> in ( $ this -> webPath . '/' . $ this -> imageFolder ) -> date ( $ criteria ) ; foreach ( $ finder -> files ( ) as $ file ) { unlink ( $ file -> getPathname ( ) ) ; } return true ; }
|
Randomly runs garbage collection on the image directory
|
9,447
|
protected function createFolderIfMissing ( ) { if ( ! file_exists ( $ this -> webPath . '/' . $ this -> imageFolder ) ) { mkdir ( $ this -> webPath . '/' . $ this -> imageFolder , 0755 ) ; } }
|
Creates the folder if it doesn t exist
|
9,448
|
public function build ( $ length = null , $ charset = null ) { if ( $ length !== null ) { $ this -> length = $ length ; } if ( $ charset !== null ) { $ this -> charset = $ charset ; } $ phrase = '' ; $ chars = str_split ( $ this -> charset ) ; for ( $ i = 0 ; $ i < $ this -> length ; $ i ++ ) { $ phrase .= $ chars [ array_rand ( $ chars ) ] ; } return $ phrase ; }
|
Generates random phrase of given length with given charset
|
9,449
|
public function setTextColor ( $ r , $ g , $ b ) { $ this -> textColor = array ( $ r , $ g , $ b ) ; return $ this ; }
|
Sets the text color to use
|
9,450
|
public function setBackgroundColor ( $ r , $ g , $ b ) { $ this -> backgroundColor = array ( $ r , $ g , $ b ) ; return $ this ; }
|
Sets the background color to use
|
9,451
|
protected function postEffect ( $ image ) { if ( ! function_exists ( 'imagefilter' ) ) { return ; } if ( $ this -> backgroundColor != null || $ this -> textColor != null ) { return ; } if ( $ this -> rand ( 0 , 1 ) == 0 ) { imagefilter ( $ image , IMG_FILTER_NEGATE ) ; } if ( $ this -> rand ( 0 , 10 ) == 0 ) { imagefilter ( $ image , IMG_FILTER_EDGEDETECT ) ; } imagefilter ( $ image , IMG_FILTER_CONTRAST , $ this -> rand ( - 50 , 10 ) ) ; if ( $ this -> rand ( 0 , 5 ) == 0 ) { imagefilter ( $ image , IMG_FILTER_COLORIZE , $ this -> rand ( - 80 , 50 ) , $ this -> rand ( - 80 , 50 ) , $ this -> rand ( - 80 , 50 ) ) ; } }
|
Apply some post effects
|
9,452
|
protected function writePhrase ( $ image , $ phrase , $ font , $ width , $ height ) { $ length = mb_strlen ( $ phrase ) ; if ( $ length === 0 ) { return \ imagecolorallocate ( $ image , 0 , 0 , 0 ) ; } $ size = $ width / $ length - $ this -> rand ( 0 , 3 ) - 1 ; $ box = \ imagettfbbox ( $ size , 0 , $ font , $ phrase ) ; $ textWidth = $ box [ 2 ] - $ box [ 0 ] ; $ textHeight = $ box [ 1 ] - $ box [ 7 ] ; $ x = ( $ width - $ textWidth ) / 2 ; $ y = ( $ height - $ textHeight ) / 2 + $ size ; if ( ! $ this -> textColor ) { $ textColor = array ( $ this -> rand ( 0 , 150 ) , $ this -> rand ( 0 , 150 ) , $ this -> rand ( 0 , 150 ) ) ; } else { $ textColor = $ this -> textColor ; } $ col = \ imagecolorallocate ( $ image , $ textColor [ 0 ] , $ textColor [ 1 ] , $ textColor [ 2 ] ) ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ symbol = mb_substr ( $ phrase , $ i , 1 ) ; $ box = \ imagettfbbox ( $ size , 0 , $ font , $ symbol ) ; $ w = $ box [ 2 ] - $ box [ 0 ] ; $ angle = $ this -> rand ( - $ this -> maxAngle , $ this -> maxAngle ) ; $ offset = $ this -> rand ( - $ this -> maxOffset , $ this -> maxOffset ) ; \ imagettftext ( $ image , $ size , $ angle , $ x , $ y + $ offset , $ col , $ font , $ symbol ) ; $ x += $ w ; } return $ col ; }
|
Writes the phrase on the image
|
9,453
|
public function isOCRReadable ( ) { if ( ! is_dir ( $ this -> tempDir ) ) { @ mkdir ( $ this -> tempDir , 0755 , true ) ; } $ tempj = $ this -> tempDir . uniqid ( 'captcha' , true ) . '.jpg' ; $ tempp = $ this -> tempDir . uniqid ( 'captcha' , true ) . '.pgm' ; $ this -> save ( $ tempj ) ; shell_exec ( "convert $tempj $tempp" ) ; $ value = trim ( strtolower ( shell_exec ( "ocrad $tempp" ) ) ) ; @ unlink ( $ tempj ) ; @ unlink ( $ tempp ) ; return $ this -> testPhrase ( $ value ) ; }
|
Try to read the code against an OCR
|
9,454
|
public function buildAgainstOCR ( $ width = 150 , $ height = 40 , $ font = null , $ fingerprint = null ) { do { $ this -> build ( $ width , $ height , $ font , $ fingerprint ) ; } while ( $ this -> isOCRReadable ( ) ) ; }
|
Builds while the code is readable against an OCR
|
9,455
|
public function distort ( $ image , $ width , $ height , $ bg ) { $ contents = imagecreatetruecolor ( $ width , $ height ) ; $ X = $ this -> rand ( 0 , $ width ) ; $ Y = $ this -> rand ( 0 , $ height ) ; $ phase = $ this -> rand ( 0 , 10 ) ; $ scale = 1.1 + $ this -> rand ( 0 , 10000 ) / 30000 ; for ( $ x = 0 ; $ x < $ width ; $ x ++ ) { for ( $ y = 0 ; $ y < $ height ; $ y ++ ) { $ Vx = $ x - $ X ; $ Vy = $ y - $ Y ; $ Vn = sqrt ( $ Vx * $ Vx + $ Vy * $ Vy ) ; if ( $ Vn != 0 ) { $ Vn2 = $ Vn + 4 * sin ( $ Vn / 30 ) ; $ nX = $ X + ( $ Vx * $ Vn2 / $ Vn ) ; $ nY = $ Y + ( $ Vy * $ Vn2 / $ Vn ) ; } else { $ nX = $ X ; $ nY = $ Y ; } $ nY = $ nY + $ scale * sin ( $ phase + $ nX * 0.2 ) ; if ( $ this -> interpolation ) { $ p = $ this -> interpolate ( $ nX - floor ( $ nX ) , $ nY - floor ( $ nY ) , $ this -> getCol ( $ image , floor ( $ nX ) , floor ( $ nY ) , $ bg ) , $ this -> getCol ( $ image , ceil ( $ nX ) , floor ( $ nY ) , $ bg ) , $ this -> getCol ( $ image , floor ( $ nX ) , ceil ( $ nY ) , $ bg ) , $ this -> getCol ( $ image , ceil ( $ nX ) , ceil ( $ nY ) , $ bg ) ) ; } else { $ p = $ this -> getCol ( $ image , round ( $ nX ) , round ( $ nY ) , $ bg ) ; } if ( $ p == 0 ) { $ p = $ bg ; } imagesetpixel ( $ contents , $ x , $ y , $ p ) ; } } return $ contents ; }
|
Distorts the image
|
9,456
|
protected function rand ( $ min , $ max ) { if ( ! is_array ( $ this -> fingerprint ) ) { $ this -> fingerprint = array ( ) ; } if ( $ this -> useFingerprint ) { $ value = current ( $ this -> fingerprint ) ; next ( $ this -> fingerprint ) ; } else { $ value = mt_rand ( $ min , $ max ) ; $ this -> fingerprint [ ] = $ value ; } return $ value ; }
|
Returns a random number or the next number in the fingerprint
|
9,457
|
protected function validateBackgroundImage ( $ backgroundImage ) { if ( ! file_exists ( $ backgroundImage ) ) { $ backgroundImageExploded = explode ( '/' , $ backgroundImage ) ; $ imageFileName = count ( $ backgroundImageExploded ) > 1 ? $ backgroundImageExploded [ count ( $ backgroundImageExploded ) - 1 ] : $ backgroundImage ; throw new Exception ( 'Invalid background image: ' . $ imageFileName ) ; } $ finfo = finfo_open ( FILEINFO_MIME_TYPE ) ; $ imageType = finfo_file ( $ finfo , $ backgroundImage ) ; finfo_close ( $ finfo ) ; if ( ! in_array ( $ imageType , $ this -> allowedBackgroundImageTypes ) ) { throw new Exception ( 'Invalid background image type! Allowed types are: ' . join ( ', ' , $ this -> allowedBackgroundImageTypes ) ) ; } return $ imageType ; }
|
Validate the background image path . Return the image type if valid
|
9,458
|
protected function createBackgroundImageFromType ( $ backgroundImage , $ imageType ) { switch ( $ imageType ) { case 'image/jpeg' : $ image = imagecreatefromjpeg ( $ backgroundImage ) ; break ; case 'image/png' : $ image = imagecreatefrompng ( $ backgroundImage ) ; break ; case 'image/gif' : $ image = imagecreatefromgif ( $ backgroundImage ) ; break ; default : throw new Exception ( 'Not supported file type for background image!' ) ; break ; } return $ image ; }
|
Create background image from type
|
9,459
|
protected function getBuilder ( $ bundleName , $ className ) { $ name = sprintf ( '%s:%s' , $ bundleName , $ className ) ; if ( ! isset ( $ this -> builders [ $ name ] ) ) { $ class = null ; $ logs = [ ] ; $ bundles = [ ] ; $ allBundles = $ this -> kernel -> getBundle ( $ bundleName , false ) ; if ( ! is_array ( $ allBundles ) ) { $ allBundles = [ $ allBundles ] ; } foreach ( $ allBundles as $ bundle ) { $ try = $ bundle -> getNamespace ( ) . '\\Menu\\' . $ className ; if ( class_exists ( $ try ) ) { $ class = $ try ; break ; } $ logs [ ] = sprintf ( 'Class "%s" does not exist for menu builder "%s".' , $ try , $ name ) ; $ bundles [ ] = $ bundle -> getName ( ) ; } if ( null === $ class ) { if ( 1 === count ( $ logs ) ) { throw new \ InvalidArgumentException ( $ logs [ 0 ] ) ; } throw new \ InvalidArgumentException ( sprintf ( 'Unable to find menu builder "%s" in bundles %s.' , $ name , implode ( ', ' , $ bundles ) ) ) ; } $ builder = new $ class ( ) ; if ( $ builder instanceof ContainerAwareInterface ) { $ builder -> setContainer ( $ this -> container ) ; } $ this -> builders [ $ name ] = $ builder ; } return $ this -> builders [ $ name ] ; }
|
Creates and returns the builder that lives in the given bundle
|
9,460
|
public function get ( $ menu , array $ path = [ ] , array $ options = [ ] ) { return $ this -> helper -> get ( $ menu , $ path , $ options ) ; }
|
Retrieves an item following a path in the tree .
|
9,461
|
public function isAncestor ( ItemInterface $ item , $ depth = null ) { return $ this -> matcher -> isAncestor ( $ item , $ depth ) ; }
|
Checks whether an item is the ancestor of a current item .
|
9,462
|
public function load ( array $ configs , ContainerBuilder $ container ) { $ loader = new XmlFileLoader ( $ container , new FileLocator ( __DIR__ . '/../Resources/config' ) ) ; $ loader -> load ( 'menu.xml' ) ; $ configuration = new Configuration ( ) ; $ config = $ this -> processConfiguration ( $ configuration , $ configs ) ; foreach ( $ config [ 'providers' ] as $ builder => $ enabled ) { if ( $ enabled ) { $ container -> getDefinition ( sprintf ( 'knp_menu.menu_provider.%s' , $ builder ) ) -> addTag ( 'knp_menu.provider' ) ; } } if ( isset ( $ config [ 'twig' ] ) ) { $ loader -> load ( 'twig.xml' ) ; $ container -> setParameter ( 'knp_menu.renderer.twig.template' , $ config [ 'twig' ] [ 'template' ] ) ; } if ( $ config [ 'templating' ] ) { $ loader -> load ( 'templating.xml' ) ; } $ container -> setParameter ( 'knp_menu.default_renderer' , $ config [ 'default_renderer' ] ) ; if ( method_exists ( $ container , 'registerForAutoconfiguration' ) ) { $ container -> registerForAutoconfiguration ( VoterInterface :: class ) -> addTag ( 'knp_menu.voter' ) ; } }
|
Handles the knp_menu configuration .
|
9,463
|
public function owner ( ) { $ userModel = Config :: get ( 'teamwork.user_model' ) ; $ userKeyName = ( new $ userModel ( ) ) -> getKeyName ( ) ; return $ this -> hasOne ( Config :: get ( 'teamwork.user_model' ) , $ userKeyName , "owner_id" ) ; }
|
Has - One relation with the user model . This indicates the owner of the team
|
9,464
|
public function hasUser ( Model $ user ) { return $ this -> users ( ) -> where ( $ user -> getKeyName ( ) , "=" , $ user -> getKey ( ) ) -> first ( ) ? true : false ; }
|
Helper function to determine if a user is part of this team
|
9,465
|
public function inviteToTeam ( $ user , $ team = null , callable $ success = null ) { if ( is_null ( $ team ) ) { $ team = $ this -> user ( ) -> current_team_id ; } elseif ( is_object ( $ team ) ) { $ team = $ team -> getKey ( ) ; } elseif ( is_array ( $ team ) ) { $ team = $ team [ "id" ] ; } if ( is_object ( $ user ) && isset ( $ user -> email ) ) { $ email = $ user -> email ; } elseif ( is_string ( $ user ) ) { $ email = $ user ; } else { throw new \ Exception ( 'The provided object has no "email" attribute and is not a string.' ) ; } $ invite = $ this -> app -> make ( Config :: get ( 'teamwork.invite_model' ) ) ; $ invite -> user_id = $ this -> user ( ) -> getKey ( ) ; $ invite -> team_id = $ team ; $ invite -> type = 'invite' ; $ invite -> email = $ email ; $ invite -> accept_token = md5 ( uniqid ( microtime ( ) ) ) ; $ invite -> deny_token = md5 ( uniqid ( microtime ( ) ) ) ; $ invite -> save ( ) ; if ( ! is_null ( $ success ) ) { event ( new UserInvitedToTeam ( $ invite ) ) ; return $ success ( $ invite ) ; } }
|
Invite an email adress to a team . Either provide a email address or an object with an email property .
|
9,466
|
public function hasPendingInvite ( $ email , $ team ) { if ( is_object ( $ team ) ) { $ team = $ team -> getKey ( ) ; } if ( is_array ( $ team ) ) { $ team = $ team [ "id" ] ; } return $ this -> app -> make ( Config :: get ( 'teamwork.invite_model' ) ) -> where ( 'email' , "=" , $ email ) -> where ( 'team_id' , "=" , $ team ) -> first ( ) ? true : false ; }
|
Checks if the given email address has a pending invite for the provided Team
|
9,467
|
public function isOwnerOfTeam ( $ team ) { $ team_id = $ this -> retrieveTeamId ( $ team ) ; return ( $ this -> teams ( ) -> where ( 'owner_id' , $ this -> getKey ( ) ) -> where ( 'team_id' , $ team_id ) -> first ( ) ) ? true : false ; }
|
Returns if the user owns the given team
|
9,468
|
public function switchTeam ( $ team ) { if ( $ team !== 0 && $ team !== null ) { $ team = $ this -> retrieveTeamId ( $ team ) ; $ teamModel = Config :: get ( 'teamwork.team_model' ) ; $ teamObject = ( new $ teamModel ( ) ) -> find ( $ team ) ; if ( ! $ teamObject ) { $ exception = new ModelNotFoundException ( ) ; $ exception -> setModel ( $ teamModel ) ; throw $ exception ; } if ( ! $ teamObject -> users -> contains ( $ this -> getKey ( ) ) ) { $ exception = new UserNotInTeamException ( ) ; $ exception -> setTeam ( $ teamObject -> name ) ; throw $ exception ; } } $ this -> current_team_id = $ team ; $ this -> save ( ) ; if ( $ this -> relationLoaded ( 'currentTeam' ) ) { $ this -> load ( 'currentTeam' ) ; } return $ this ; }
|
Switch the current team of the user
|
9,469
|
protected static function bootUsedByTeams ( ) { static :: addGlobalScope ( 'team' , function ( Builder $ builder ) { static :: teamGuard ( ) ; $ builder -> where ( $ builder -> getQuery ( ) -> from . '.team_id' , auth ( ) -> user ( ) -> currentTeam -> getKey ( ) ) ; } ) ; static :: saving ( function ( Model $ model ) { static :: teamGuard ( ) ; if ( ! isset ( $ model -> team_id ) ) { $ model -> team_id = auth ( ) -> user ( ) -> currentTeam -> getKey ( ) ; } } ) ; }
|
Boot the global scope
|
9,470
|
public function getFilters ( ) { return array ( 'markdown' => new Twig_SimpleFilter ( 'markdown' , array ( $ this , 'markdownFilter' ) ) , 'map' => new Twig_SimpleFilter ( 'map' , array ( $ this , 'mapFilter' ) ) , 'sort_by' => new Twig_SimpleFilter ( 'sort_by' , array ( $ this , 'sortByFilter' ) ) , 'link' => new Twig_SimpleFilter ( 'link' , array ( $ this -> pico , 'getPageUrl' ) ) ) ; }
|
Returns a list of Pico - specific Twig filters
|
9,471
|
public function markdownFilter ( $ markdown , array $ meta = array ( ) ) { $ markdown = $ this -> getPico ( ) -> substituteFileContent ( $ markdown , $ meta ) ; return $ this -> getPico ( ) -> parseFileContent ( $ markdown ) ; }
|
Parses a markdown string to HTML
|
9,472
|
public function mapFilter ( $ var , $ mapKeyPath ) { if ( ! is_array ( $ var ) && ( ! is_object ( $ var ) || ! ( $ var instanceof Traversable ) ) ) { throw new Twig_Error_Runtime ( sprintf ( 'The map filter only works with arrays or "Traversable", got "%s"' , is_object ( $ var ) ? get_class ( $ var ) : gettype ( $ var ) ) ) ; } $ result = array ( ) ; foreach ( $ var as $ key => $ value ) { $ mapValue = $ this -> getKeyOfVar ( $ value , $ mapKeyPath ) ; $ result [ $ key ] = ( $ mapValue !== null ) ? $ mapValue : $ value ; } return $ result ; }
|
Returns a array with the values of the given key or key path
|
9,473
|
public function sortByFilter ( $ var , $ sortKeyPath , $ fallback = 'bottom' ) { if ( is_object ( $ var ) && ( $ var instanceof Traversable ) ) { $ var = iterator_to_array ( $ var , true ) ; } elseif ( ! is_array ( $ var ) ) { throw new Twig_Error_Runtime ( sprintf ( 'The sort_by filter only works with arrays or "Traversable", got "%s"' , is_object ( $ var ) ? get_class ( $ var ) : gettype ( $ var ) ) ) ; } if ( ( $ fallback !== 'top' ) && ( $ fallback !== 'bottom' ) && ( $ fallback !== 'keep' ) && ( $ fallback !== "remove" ) ) { throw new Twig_Error_Runtime ( 'The sort_by filter only supports the "top", "bottom", "keep" and "remove" fallbacks' ) ; } $ twigExtension = $ this ; $ varKeys = array_keys ( $ var ) ; $ removeItems = array ( ) ; uksort ( $ var , function ( $ a , $ b ) use ( $ twigExtension , $ var , $ varKeys , $ sortKeyPath , $ fallback , & $ removeItems ) { $ aSortValue = $ twigExtension -> getKeyOfVar ( $ var [ $ a ] , $ sortKeyPath ) ; $ aSortValueNull = ( $ aSortValue === null ) ; $ bSortValue = $ twigExtension -> getKeyOfVar ( $ var [ $ b ] , $ sortKeyPath ) ; $ bSortValueNull = ( $ bSortValue === null ) ; if ( ( $ fallback === 'remove' ) && ( $ aSortValueNull || $ bSortValueNull ) ) { if ( $ aSortValueNull ) { $ removeItems [ $ a ] = $ var [ $ a ] ; } if ( $ bSortValueNull ) { $ removeItems [ $ b ] = $ var [ $ b ] ; } return ( $ aSortValueNull - $ bSortValueNull ) ; } elseif ( $ aSortValueNull xor $ bSortValueNull ) { if ( $ fallback === 'top' ) { return ( $ aSortValueNull - $ bSortValueNull ) * - 1 ; } elseif ( $ fallback === 'bottom' ) { return ( $ aSortValueNull - $ bSortValueNull ) ; } } elseif ( ! $ aSortValueNull && ! $ bSortValueNull ) { if ( $ aSortValue != $ bSortValue ) { return ( $ aSortValue > $ bSortValue ) ? 1 : - 1 ; } } $ aIndex = array_search ( $ a , $ varKeys ) ; $ bIndex = array_search ( $ b , $ varKeys ) ; return ( $ aIndex > $ bIndex ) ? 1 : - 1 ; } ) ; if ( $ removeItems ) { $ var = array_diff_key ( $ var , $ removeItems ) ; } return $ var ; }
|
Sorts an array by one of its keys or a arbitrary deep sub - key
|
9,474
|
public static function getKeyOfVar ( $ var , $ keyPath ) { if ( ! $ keyPath ) { return null ; } elseif ( ! is_array ( $ keyPath ) ) { $ keyPath = array ( $ keyPath ) ; } foreach ( $ keyPath as $ key ) { if ( is_object ( $ var ) ) { if ( $ var instanceof ArrayAccess ) { } elseif ( $ var instanceof Traversable ) { $ var = iterator_to_array ( $ var ) ; } elseif ( isset ( $ var -> { $ key } ) ) { $ var = $ var -> { $ key } ; continue ; } elseif ( is_callable ( array ( $ var , 'get' . ucfirst ( $ key ) ) ) ) { try { $ var = call_user_func ( array ( $ var , 'get' . ucfirst ( $ key ) ) ) ; continue ; } catch ( BadMethodCallException $ e ) { return null ; } } else { return null ; } } elseif ( ! is_array ( $ var ) ) { return null ; } if ( isset ( $ var [ $ key ] ) ) { $ var = $ var [ $ key ] ; continue ; } return null ; } return $ var ; }
|
Returns the value of a variable item specified by a scalar key or a arbitrary deep sub - key using a key path
|
9,475
|
public function getPluginConfig ( $ configName = null , $ default = null ) { $ pluginConfig = $ this -> getConfig ( get_called_class ( ) , array ( ) ) ; if ( $ configName === null ) { return $ pluginConfig ; } return isset ( $ pluginConfig [ $ configName ] ) ? $ pluginConfig [ $ configName ] : $ default ; }
|
Returns either the value of the specified plugin config variable or the config array
|
9,476
|
protected function checkDependencies ( $ recursive ) { foreach ( $ this -> getDependencies ( ) as $ pluginName ) { try { $ plugin = $ this -> getPlugin ( $ pluginName ) ; } catch ( RuntimeException $ e ) { throw new RuntimeException ( "Unable to enable plugin '" . get_called_class ( ) . "': " . "Required plugin '" . $ pluginName . "' not found" ) ; } if ( ( $ plugin instanceof PicoPluginInterface ) && ! $ plugin -> isEnabled ( ) ) { if ( $ recursive ) { if ( ! $ plugin -> isStatusChanged ( ) ) { $ plugin -> setEnabled ( true , true , true ) ; } else { throw new RuntimeException ( "Unable to enable plugin '" . get_called_class ( ) . "': " . "Required plugin '" . $ pluginName . "' was disabled manually" ) ; } } else { throw new RuntimeException ( "Unable to enable plugin '" . get_called_class ( ) . "': " . "Required plugin '" . $ pluginName . "' is disabled" ) ; } } } }
|
Enables all plugins which this plugin depends on
|
9,477
|
protected function checkDependants ( $ recursive ) { $ dependants = $ this -> getDependants ( ) ; if ( $ dependants ) { if ( $ recursive ) { foreach ( $ this -> getDependants ( ) as $ pluginName => $ plugin ) { if ( $ plugin -> isEnabled ( ) ) { if ( ! $ plugin -> isStatusChanged ( ) ) { $ plugin -> setEnabled ( false , true , true ) ; } else { throw new RuntimeException ( "Unable to disable plugin '" . get_called_class ( ) . "': " . "Required by manually enabled plugin '" . $ pluginName . "'" ) ; } } } } else { $ dependantsList = 'plugin' . ( ( count ( $ dependants ) > 1 ) ? 's' : '' ) . ' ' . "'" . implode ( "', '" , array_keys ( $ dependants ) ) . "'" ; throw new RuntimeException ( "Unable to disable plugin '" . get_called_class ( ) . "': " . "Required by " . $ dependantsList ) ; } } }
|
Disables all plugins which depend on this plugin
|
9,478
|
protected function checkCompatibility ( ) { if ( $ this -> nativePlugin === null ) { $ picoClassName = get_class ( $ this -> pico ) ; $ picoApiVersion = defined ( $ picoClassName . '::API_VERSION' ) ? $ picoClassName :: API_VERSION : 1 ; $ pluginApiVersion = defined ( 'static::API_VERSION' ) ? static :: API_VERSION : 1 ; $ this -> nativePlugin = ( $ pluginApiVersion === $ picoApiVersion ) ; if ( ! $ this -> nativePlugin && ( $ pluginApiVersion > $ picoApiVersion ) ) { throw new RuntimeException ( "Unable to enable plugin '" . get_called_class ( ) . "': The plugin's API (version " . $ pluginApiVersion . ") isn't compatible with Pico's API (version " . $ picoApiVersion . ")" ) ; } } }
|
Checks compatibility with Pico s API version
|
9,479
|
public function loadPlugin ( $ plugin ) { if ( ! is_object ( $ plugin ) ) { $ className = ( string ) $ plugin ; if ( class_exists ( $ className ) ) { $ plugin = new $ className ( $ this ) ; } else { throw new RuntimeException ( "Unable to load plugin '" . $ className . "': Class not found" ) ; } } $ className = get_class ( $ plugin ) ; if ( ! ( $ plugin instanceof PicoPluginInterface ) ) { throw new RuntimeException ( "Unable to load plugin '" . $ className . "': " . "Manually loaded plugins must implement 'PicoPluginInterface'" ) ; } $ this -> plugins [ $ className ] = $ plugin ; if ( defined ( $ className . '::API_VERSION' ) && ( $ className :: API_VERSION >= static :: API_VERSION ) ) { $ this -> nativePlugins [ $ className ] = $ plugin ; } $ this -> triggerEvent ( 'onPluginManuallyLoaded' , array ( $ plugin ) ) ; return $ plugin ; }
|
Manually loads a plugin
|
9,480
|
protected function sortPlugins ( ) { $ plugins = $ this -> plugins ; $ nativePlugins = $ this -> nativePlugins ; $ sortedPlugins = array ( ) ; $ sortedNativePlugins = array ( ) ; $ visitedPlugins = array ( ) ; $ visitPlugin = function ( $ plugin ) use ( $ plugins , $ nativePlugins , & $ sortedPlugins , & $ sortedNativePlugins , & $ visitedPlugins , & $ visitPlugin ) { $ pluginName = get_class ( $ plugin ) ; if ( ! isset ( $ visitedPlugins [ $ pluginName ] ) ) { $ visitedPlugins [ $ pluginName ] = true ; $ dependencies = array ( ) ; if ( $ plugin instanceof PicoPluginInterface ) { $ dependencies = $ plugin -> getDependencies ( ) ; } if ( ! isset ( $ nativePlugins [ $ pluginName ] ) ) { $ dependencies [ ] = 'PicoDeprecated' ; } foreach ( $ dependencies as $ dependency ) { if ( isset ( $ plugins [ $ dependency ] ) ) { $ visitPlugin ( $ plugins [ $ dependency ] ) ; } } $ sortedPlugins [ $ pluginName ] = $ plugin ; if ( isset ( $ nativePlugins [ $ pluginName ] ) ) { $ sortedNativePlugins [ $ pluginName ] = $ plugin ; } } } ; if ( isset ( $ this -> plugins [ 'PicoDeprecated' ] ) ) { $ visitPlugin ( $ this -> plugins [ 'PicoDeprecated' ] ) ; } foreach ( $ this -> plugins as $ plugin ) { $ visitPlugin ( $ plugin ) ; } $ this -> plugins = $ sortedPlugins ; $ this -> nativePlugins = $ sortedNativePlugins ; }
|
Sorts all loaded plugins using a plugin dependency topology
|
9,481
|
public function getPlugin ( $ pluginName ) { if ( isset ( $ this -> plugins [ $ pluginName ] ) ) { return $ this -> plugins [ $ pluginName ] ; } throw new RuntimeException ( "Missing plugin '" . $ pluginName . "'" ) ; }
|
Returns the instance of a named plugin
|
9,482
|
public function getConfig ( $ configName = null , $ default = null ) { if ( $ configName !== null ) { return isset ( $ this -> config [ $ configName ] ) ? $ this -> config [ $ configName ] : $ default ; } else { return $ this -> config ; } }
|
Returns either the value of the specified config variable or the config array
|
9,483
|
protected function evaluateRequestUrl ( ) { $ pathComponent = isset ( $ _SERVER [ 'QUERY_STRING' ] ) ? $ _SERVER [ 'QUERY_STRING' ] : '' ; if ( $ pathComponent ) { $ pathComponent = strstr ( $ pathComponent , '&' , true ) ? : $ pathComponent ; if ( strpos ( $ pathComponent , '=' ) === false ) { $ this -> requestUrl = trim ( rawurldecode ( $ pathComponent ) , '/' ) ; } } if ( ( $ this -> requestUrl === null ) && $ this -> isUrlRewritingEnabled ( ) ) { $ scriptName = isset ( $ _SERVER [ 'SCRIPT_NAME' ] ) ? $ _SERVER [ 'SCRIPT_NAME' ] : '/index.php' ; $ basePath = dirname ( $ scriptName ) ; $ basePath = ! in_array ( $ basePath , array ( '.' , '/' , '\\' ) , true ) ? $ basePath . '/' : '/' ; $ basePathLength = strlen ( $ basePath ) ; $ requestUri = isset ( $ _SERVER [ 'REQUEST_URI' ] ) ? $ _SERVER [ 'REQUEST_URI' ] : '' ; if ( $ requestUri && ( substr ( $ requestUri , 0 , $ basePathLength ) === $ basePath ) ) { $ requestUri = substr ( $ requestUri , $ basePathLength ) ; if ( $ requestUri && ( ( $ queryStringPos = strpos ( $ requestUri , '?' ) ) !== false ) ) { $ requestUri = substr ( $ requestUri , 0 , $ queryStringPos ) ; } if ( $ requestUri && ( $ requestUri !== basename ( $ scriptName ) ) ) { $ this -> requestUrl = rtrim ( rawurldecode ( $ requestUri ) , '/' ) ; } } } if ( $ this -> requestUrl === null ) { $ this -> requestUrl = '' ; } }
|
Evaluates the requested URL
|
9,484
|
public function resolveFilePath ( $ requestUrl ) { $ contentDir = $ this -> getConfig ( 'content_dir' ) ; $ contentExt = $ this -> getConfig ( 'content_ext' ) ; if ( ! $ requestUrl ) { return $ contentDir . 'index' . $ contentExt ; } else { $ requestUrl = str_replace ( '\\' , '/' , $ requestUrl ) ; $ requestUrlParts = explode ( '/' , $ requestUrl ) ; $ requestFileParts = array ( ) ; foreach ( $ requestUrlParts as $ requestUrlPart ) { if ( ( $ requestUrlPart === '' ) || ( $ requestUrlPart === '.' ) ) { continue ; } elseif ( $ requestUrlPart === '..' ) { array_pop ( $ requestFileParts ) ; continue ; } $ requestFileParts [ ] = $ requestUrlPart ; } if ( ! $ requestFileParts ) { return $ contentDir . 'index' . $ contentExt ; } $ requestFile = $ contentDir . implode ( '/' , $ requestFileParts ) ; if ( is_dir ( $ requestFile ) ) { $ indexFile = $ requestFile . '/index' . $ contentExt ; if ( file_exists ( $ indexFile ) || ! file_exists ( $ requestFile . $ contentExt ) ) { return $ indexFile ; } } return $ requestFile . $ contentExt ; } }
|
Resolves a given file path to its corresponding content file
|
9,485
|
public function load404Content ( $ file ) { $ contentDir = $ this -> getConfig ( 'content_dir' ) ; $ contentDirLength = strlen ( $ contentDir ) ; $ contentExt = $ this -> getConfig ( 'content_ext' ) ; if ( substr ( $ file , 0 , $ contentDirLength ) === $ contentDir ) { $ errorFileDir = substr ( $ file , $ contentDirLength ) ; while ( $ errorFileDir !== '.' ) { $ errorFileDir = dirname ( $ errorFileDir ) ; $ errorFile = $ errorFileDir . '/404' . $ contentExt ; if ( file_exists ( $ contentDir . $ errorFile ) ) { return $ this -> loadFileContent ( $ contentDir . $ errorFile ) ; } } } elseif ( file_exists ( $ contentDir . '404' . $ contentExt ) ) { return $ this -> loadFileContent ( $ contentDir . '404' . $ contentExt ) ; } $ rawErrorContent = "---\n" . "Title: Error 404\n" . "Robots: noindex,nofollow\n" . "---\n\n" . "# Error 404\n\n" . "Woops. Looks like this page doesn't exist.\n" ; return $ rawErrorContent ; }
|
Returns the raw contents of the first found 404 file when traversing up from the directory the requested file is in
|
9,486
|
public function getMetaHeaders ( ) { if ( $ this -> metaHeaders === null ) { $ this -> metaHeaders = array ( 'Title' => 'title' , 'Description' => 'description' , 'Author' => 'author' , 'Date' => 'date' , 'Formatted Date' => 'date_formatted' , 'Time' => 'time' , 'Robots' => 'robots' , 'Template' => 'template' , 'Hidden' => 'hidden' ) ; $ this -> triggerEvent ( 'onMetaHeaders' , array ( & $ this -> metaHeaders ) ) ; } return $ this -> metaHeaders ; }
|
Returns known meta headers
|
9,487
|
public function getYamlParser ( ) { if ( $ this -> yamlParser === null ) { $ this -> yamlParser = new \ Symfony \ Component \ Yaml \ Parser ( ) ; $ this -> triggerEvent ( 'onYamlParserRegistered' , array ( & $ this -> yamlParser ) ) ; } return $ this -> yamlParser ; }
|
Returns the Symfony YAML parser
|
9,488
|
public function parseFileMeta ( $ rawContent , array $ headers ) { $ meta = array ( ) ; $ pattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n" . "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s" ; if ( preg_match ( $ pattern , $ rawContent , $ rawMetaMatches ) && isset ( $ rawMetaMatches [ 3 ] ) ) { $ meta = $ this -> getYamlParser ( ) -> parse ( $ rawMetaMatches [ 3 ] ) ? : array ( ) ; $ meta = is_array ( $ meta ) ? $ meta : array ( 'title' => $ meta ) ; foreach ( $ headers as $ name => $ key ) { if ( isset ( $ meta [ $ name ] ) ) { if ( $ key != $ name ) { $ meta [ $ key ] = $ meta [ $ name ] ; unset ( $ meta [ $ name ] ) ; } } elseif ( ! isset ( $ meta [ $ key ] ) ) { $ meta [ $ key ] = '' ; } } if ( ! empty ( $ meta [ 'date' ] ) || ! empty ( $ meta [ 'time' ] ) ) { if ( is_int ( $ meta [ 'date' ] ) ) { $ meta [ 'time' ] = $ meta [ 'date' ] ; $ meta [ 'date' ] = '' ; } if ( empty ( $ meta [ 'time' ] ) ) { $ meta [ 'time' ] = strtotime ( $ meta [ 'date' ] ) ? : '' ; } elseif ( empty ( $ meta [ 'date' ] ) ) { $ rawDateFormat = ( date ( 'H:i:s' , $ meta [ 'time' ] ) === '00:00:00' ) ? 'Y-m-d' : 'Y-m-d H:i:s' ; $ meta [ 'date' ] = date ( $ rawDateFormat , $ meta [ 'time' ] ) ; } } else { $ meta [ 'date' ] = $ meta [ 'time' ] = '' ; } if ( empty ( $ meta [ 'date_formatted' ] ) ) { $ dateFormat = $ this -> getConfig ( 'date_format' ) ; $ meta [ 'date_formatted' ] = $ meta [ 'time' ] ? utf8_encode ( strftime ( $ dateFormat , $ meta [ 'time' ] ) ) : '' ; } } else { $ meta = array_fill_keys ( $ headers , '' ) ; } return $ meta ; }
|
Parses the file meta from raw file contents
|
9,489
|
public function getParsedown ( ) { if ( $ this -> parsedown === null ) { $ className = $ this -> config [ 'content_config' ] [ 'extra' ] ? 'ParsedownExtra' : 'Parsedown' ; $ this -> parsedown = new $ className ( ) ; $ this -> parsedown -> setBreaksEnabled ( ( bool ) $ this -> config [ 'content_config' ] [ 'breaks' ] ) ; $ this -> parsedown -> setMarkupEscaped ( ( bool ) $ this -> config [ 'content_config' ] [ 'escape' ] ) ; $ this -> parsedown -> setUrlsLinked ( ( bool ) $ this -> config [ 'content_config' ] [ 'auto_urls' ] ) ; $ this -> triggerEvent ( 'onParsedownRegistered' , array ( & $ this -> parsedown ) ) ; } return $ this -> parsedown ; }
|
Returns the Parsedown markdown parser
|
9,490
|
public function prepareFileContent ( $ rawContent , array $ meta = array ( ) ) { $ metaHeaderPattern = "/^(\/(\*)|---)[[:blank:]]*(?:\r)?\n" . "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s" ; $ markdown = preg_replace ( $ metaHeaderPattern , '' , $ rawContent , 1 ) ; $ markdown = $ this -> substituteFileContent ( $ markdown , $ meta ) ; return $ markdown ; }
|
Applies some static preparations to the raw contents of a page
|
9,491
|
public function substituteFileContent ( $ markdown , array $ meta = array ( ) ) { $ variables = array ( ) ; $ variables [ '%version%' ] = static :: VERSION ; $ variables [ '%site_title%' ] = $ this -> getConfig ( 'site_title' ) ; if ( $ this -> isUrlRewritingEnabled ( ) ) { $ variables [ '%base_url%?' ] = $ this -> getBaseUrl ( ) ; } else { $ variables [ '%base_url%?' ] = $ this -> getBaseUrl ( ) . '?' ; } $ variables [ '%base_url%' ] = rtrim ( $ this -> getBaseUrl ( ) , '/' ) ; $ variables [ '%theme_url%' ] = $ this -> getBaseThemeUrl ( ) . $ this -> getConfig ( 'theme' ) ; if ( $ meta ) { foreach ( $ meta as $ metaKey => $ metaValue ) { if ( is_scalar ( $ metaValue ) || ( $ metaValue === null ) ) { $ variables [ '%meta.' . $ metaKey . '%' ] = ( string ) $ metaValue ; } } } return str_replace ( array_keys ( $ variables ) , $ variables , $ markdown ) ; }
|
Replaces all % ... % placeholders in a page s contents
|
9,492
|
protected function readPages ( ) { $ contentDir = $ this -> getConfig ( 'content_dir' ) ; $ contentExt = $ this -> getConfig ( 'content_ext' ) ; $ this -> pages = array ( ) ; $ files = $ this -> getFiles ( $ contentDir , $ contentExt , self :: SORT_NONE ) ; foreach ( $ files as $ i => $ file ) { if ( basename ( $ file ) === '404' . $ contentExt ) { unset ( $ files [ $ i ] ) ; continue ; } $ id = substr ( $ file , strlen ( $ contentDir ) , - strlen ( $ contentExt ) ) ; $ conflictFile = $ contentDir . $ id . '/index' . $ contentExt ; $ skipFile = in_array ( $ conflictFile , $ files , true ) ? : null ; $ this -> triggerEvent ( 'onSinglePageLoading' , array ( $ id , & $ skipFile ) ) ; if ( $ skipFile ) { continue ; } $ url = $ this -> getPageUrl ( $ id ) ; if ( $ file !== $ this -> requestFile ) { $ rawContent = $ this -> loadFileContent ( $ file ) ; $ this -> triggerEvent ( 'onSinglePageContent' , array ( $ id , & $ rawContent ) ) ; $ headers = $ this -> getMetaHeaders ( ) ; try { $ meta = $ this -> parseFileMeta ( $ rawContent , $ headers ) ; } catch ( \ Symfony \ Component \ Yaml \ Exception \ ParseException $ e ) { $ meta = $ this -> parseFileMeta ( '' , $ headers ) ; $ meta [ 'YAML_ParseError' ] = $ e -> getMessage ( ) ; } } else { $ rawContent = & $ this -> rawContent ; $ meta = & $ this -> meta ; } $ page = array ( 'id' => $ id , 'url' => $ url , 'title' => & $ meta [ 'title' ] , 'description' => & $ meta [ 'description' ] , 'author' => & $ meta [ 'author' ] , 'time' => & $ meta [ 'time' ] , 'date' => & $ meta [ 'date' ] , 'date_formatted' => & $ meta [ 'date_formatted' ] , 'hidden' => ( preg_match ( '/(?:^|\/)_/' , $ id ) || $ meta [ 'hidden' ] ) , 'raw_content' => & $ rawContent , 'meta' => & $ meta ) ; if ( $ file === $ this -> requestFile ) { $ page [ 'content' ] = & $ this -> content ; } unset ( $ rawContent , $ meta ) ; $ this -> triggerEvent ( 'onSinglePageLoaded' , array ( & $ page ) ) ; if ( $ page !== null ) { $ this -> pages [ $ id ] = $ page ; } } }
|
Reads the data of all pages known to Pico
|
9,493
|
protected function discoverPageSiblings ( ) { if ( ( $ this -> getConfig ( 'order_by' ) === 'date' ) && ( $ this -> getConfig ( 'order' ) === 'desc' ) ) { $ precedingPageKey = 'next_page' ; $ succeedingPageKey = 'previous_page' ; } else { $ precedingPageKey = 'previous_page' ; $ succeedingPageKey = 'next_page' ; } $ precedingPageId = null ; foreach ( $ this -> pages as $ id => & $ pageData ) { $ pageData [ $ precedingPageKey ] = null ; $ pageData [ $ succeedingPageKey ] = null ; if ( ! empty ( $ pageData [ 'hidden' ] ) ) { continue ; } if ( $ precedingPageId !== null ) { $ precedingPageData = & $ this -> pages [ $ precedingPageId ] ; $ pageData [ $ precedingPageKey ] = & $ precedingPageData ; $ precedingPageData [ $ succeedingPageKey ] = & $ pageData ; } $ precedingPageId = $ id ; } }
|
Walks through the list of all known pages and discovers the previous and next page respectively
|
9,494
|
protected function discoverCurrentPage ( ) { $ currentPageId = $ this -> getPageId ( $ this -> requestFile ) ; if ( $ currentPageId && isset ( $ this -> pages [ $ currentPageId ] ) ) { $ this -> currentPage = & $ this -> pages [ $ currentPageId ] ; $ this -> previousPage = & $ this -> pages [ $ currentPageId ] [ 'previous_page' ] ; $ this -> nextPage = & $ this -> pages [ $ currentPageId ] [ 'next_page' ] ; } }
|
Discovers the page data of the requested page as well as the previous and next page relative to it
|
9,495
|
protected function buildPageTree ( ) { $ this -> pageTree = array ( ) ; foreach ( $ this -> pages as $ id => & $ pageData ) { if ( $ id === 'index' ) { $ this -> pageTree [ '' ] [ '/' ] [ 'id' ] = '/' ; $ this -> pageTree [ '' ] [ '/' ] [ 'page' ] = & $ pageData ; $ pageData [ 'tree_node' ] = & $ this -> pageTree [ '' ] [ '/' ] ; continue ; } $ basename = basename ( $ id ) ; $ branch = dirname ( $ id ) ; $ isIndexPage = ( $ basename === 'index' ) ; if ( $ isIndexPage ) { $ basename = basename ( $ branch ) ; $ branch = dirname ( $ branch ) ; } $ branch = ( $ branch !== '.' ) ? $ branch : '/' ; $ node = ( $ branch !== '/' ) ? $ branch . '/' . $ basename : $ basename ; if ( isset ( $ this -> pageTree [ $ branch ] [ $ node ] [ 'page' ] ) && ! $ isIndexPage ) { continue ; } $ isNewBranch = ! isset ( $ this -> pageTree [ $ branch ] ) ; $ this -> pageTree [ $ branch ] [ $ node ] [ 'id' ] = $ node ; $ this -> pageTree [ $ branch ] [ $ node ] [ 'page' ] = & $ pageData ; $ pageData [ 'tree_node' ] = & $ this -> pageTree [ $ branch ] [ $ node ] ; while ( $ isNewBranch && $ branch ) { $ parentNode = $ branch ; $ parentBranch = ( $ branch !== '/' ) ? dirname ( $ parentNode ) : '' ; $ parentBranch = ( $ parentBranch !== '.' ) ? $ parentBranch : '/' ; $ isNewBranch = ! isset ( $ this -> pageTree [ $ parentBranch ] ) ; $ this -> pageTree [ $ parentBranch ] [ $ parentNode ] [ 'id' ] = $ parentNode ; $ this -> pageTree [ $ parentBranch ] [ $ parentNode ] [ 'children' ] = & $ this -> pageTree [ $ branch ] ; $ branch = $ parentBranch ; } } }
|
Builds a tree structure containing all known pages
|
9,496
|
public function getTwig ( ) { if ( $ this -> twig === null ) { $ twigConfig = $ this -> getConfig ( 'twig_config' ) ; $ twigLoader = new Twig_Loader_Filesystem ( $ this -> getThemesDir ( ) . $ this -> getConfig ( 'theme' ) ) ; $ this -> twig = new Twig_Environment ( $ twigLoader , $ twigConfig ) ; $ this -> twig -> addExtension ( new PicoTwigExtension ( $ this ) ) ; if ( ! empty ( $ twigConfig [ 'debug' ] ) ) { $ this -> twig -> addExtension ( new Twig_Extension_Debug ( ) ) ; } $ pico = $ this ; $ pages = & $ this -> pages ; $ this -> twig -> addFilter ( new Twig_SimpleFilter ( 'content' , function ( $ page ) use ( $ pico , & $ pages ) { if ( isset ( $ pages [ $ page ] ) ) { $ pageData = & $ pages [ $ page ] ; if ( ! isset ( $ pageData [ 'content' ] ) ) { $ pageData [ 'content' ] = $ pico -> prepareFileContent ( $ pageData [ 'raw_content' ] , $ pageData [ 'meta' ] ) ; $ pageData [ 'content' ] = $ pico -> parseFileContent ( $ pageData [ 'content' ] ) ; } return $ pageData [ 'content' ] ; } return null ; } ) ) ; $ this -> triggerEvent ( 'onTwigRegistered' , array ( & $ this -> twig ) ) ; } return $ this -> twig ; }
|
Returns the Twig template engine
|
9,497
|
protected function getTwigVariables ( ) { return array ( 'config' => $ this -> getConfig ( ) , 'base_dir' => rtrim ( $ this -> getRootDir ( ) , '/' ) , 'base_url' => rtrim ( $ this -> getBaseUrl ( ) , '/' ) , 'theme_dir' => $ this -> getThemesDir ( ) . $ this -> getConfig ( 'theme' ) , 'theme_url' => $ this -> getBaseThemeUrl ( ) . $ this -> getConfig ( 'theme' ) , 'site_title' => $ this -> getConfig ( 'site_title' ) , 'meta' => $ this -> meta , 'content' => $ this -> content , 'pages' => $ this -> pages , 'prev_page' => $ this -> previousPage , 'current_page' => $ this -> currentPage , 'next_page' => $ this -> nextPage , 'version' => static :: VERSION ) ; }
|
Returns the variables passed to the template
|
9,498
|
public function getBaseUrl ( ) { $ baseUrl = $ this -> getConfig ( 'base_url' ) ; if ( $ baseUrl ) { return $ baseUrl ; } $ host = 'localhost' ; if ( ! empty ( $ _SERVER [ 'HTTP_X_FORWARDED_HOST' ] ) ) { $ host = $ _SERVER [ 'HTTP_X_FORWARDED_HOST' ] ; } elseif ( ! empty ( $ _SERVER [ 'HTTP_HOST' ] ) ) { $ host = $ _SERVER [ 'HTTP_HOST' ] ; } elseif ( ! empty ( $ _SERVER [ 'SERVER_NAME' ] ) ) { $ host = $ _SERVER [ 'SERVER_NAME' ] ; } $ port = 80 ; if ( ! empty ( $ _SERVER [ 'HTTP_X_FORWARDED_PORT' ] ) ) { $ port = ( int ) $ _SERVER [ 'HTTP_X_FORWARDED_PORT' ] ; } elseif ( ! empty ( $ _SERVER [ 'SERVER_PORT' ] ) ) { $ port = ( int ) $ _SERVER [ 'SERVER_PORT' ] ; } $ hostPortPosition = ( $ host [ 0 ] === '[' ) ? strpos ( $ host , ':' , strrpos ( $ host , ']' ) ? : 0 ) : strrpos ( $ host , ':' ) ; if ( $ hostPortPosition !== false ) { $ port = ( int ) substr ( $ host , $ hostPortPosition + 1 ) ; $ host = substr ( $ host , 0 , $ hostPortPosition ) ; } $ protocol = 'http' ; if ( ! empty ( $ _SERVER [ 'HTTP_X_FORWARDED_PROTO' ] ) ) { $ secureProxyHeader = strtolower ( current ( explode ( ',' , $ _SERVER [ 'HTTP_X_FORWARDED_PROTO' ] ) ) ) ; $ protocol = in_array ( $ secureProxyHeader , array ( 'https' , 'on' , 'ssl' , '1' ) , true ) ? 'https' : 'http' ; } elseif ( ! empty ( $ _SERVER [ 'HTTPS' ] ) && ( $ _SERVER [ 'HTTPS' ] !== 'off' ) ) { $ protocol = 'https' ; } elseif ( $ port === 443 ) { $ protocol = 'https' ; } $ basePath = isset ( $ _SERVER [ 'SCRIPT_NAME' ] ) ? dirname ( $ _SERVER [ 'SCRIPT_NAME' ] ) : '/' ; $ basePath = ! in_array ( $ basePath , array ( '.' , '/' , '\\' ) , true ) ? $ basePath . '/' : '/' ; if ( ( ( $ protocol === 'http' ) && ( $ port !== 80 ) ) || ( ( $ protocol === 'https' ) && ( $ port !== 443 ) ) ) { $ host = $ host . ':' . $ port ; } $ this -> config [ 'base_url' ] = $ protocol . "://" . $ host . $ basePath ; return $ this -> config [ 'base_url' ] ; }
|
Returns the base URL of this Pico instance
|
9,499
|
public function isUrlRewritingEnabled ( ) { $ urlRewritingEnabled = $ this -> getConfig ( 'rewrite_url' ) ; if ( $ urlRewritingEnabled !== null ) { return $ urlRewritingEnabled ; } if ( isset ( $ _SERVER [ 'PICO_URL_REWRITING' ] ) ) { $ this -> config [ 'rewrite_url' ] = ( bool ) $ _SERVER [ 'PICO_URL_REWRITING' ] ; } elseif ( isset ( $ _SERVER [ 'REDIRECT_PICO_URL_REWRITING' ] ) ) { $ this -> config [ 'rewrite_url' ] = ( bool ) $ _SERVER [ 'REDIRECT_PICO_URL_REWRITING' ] ; } else { $ this -> config [ 'rewrite_url' ] = false ; } return $ this -> config [ 'rewrite_url' ] ; }
|
Returns TRUE if URL rewriting is enabled
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.