idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
18,700
public static function staticPages ( ) { if ( ! getConfig ( 'sitemap.static_pages' ) ) { return [ ] ; } return array_map ( function ( Entity $ page ) { return self :: parse ( [ '_name' => 'page' , $ page -> slug ] , [ 'lastmod' => $ page -> modified ] ) ; } , StaticPage :: all ( ) ) ; }
Returns static pages urls
18,701
protected function recurseString ( array $ string ) { $ isOptional = $ this -> isOptional ; foreach ( $ string as $ k => $ element ) { if ( is_array ( $ element ) ) { $ string [ $ k ] = $ this -> runner -> run ( $ element ) ; } } $ this -> isOptional = $ isOptional ; return $ string ; }
Recurse into given string and run all passes on each element
18,702
public function run ( RequestInterface $ request , ResponseInterface $ response ) { unset ( $ request ) ; $ this -> startLock ( ) ; $ climate = $ this -> climate ( ) ; $ processedCallback = function ( $ success , $ failures , $ skipped ) use ( $ climate ) { if ( ! empty ( $ success ) ) { $ climate -> green ( ) -> out ( sprintf ( '%s emails were successfully sent.' , count ( $ success ) ) ) ; } if ( ! empty ( $ failures ) ) { $ climate -> red ( ) -> out ( sprintf ( '%s emails were not successfully sent' , count ( $ failures ) ) ) ; } if ( ! empty ( $ skipped ) ) { $ climate -> dim ( ) -> out ( sprintf ( '%s emails were skipped.' , count ( $ skipped ) ) ) ; } } ; $ queueManager = new EmailQueueManager ( [ 'logger' => $ this -> logger , 'queue_item_factory' => $ this -> queueItemFactory ] ) ; $ queueManager -> setProcessedCallback ( $ processedCallback ) ; $ queueManager -> processQueue ( ) ; $ this -> stopLock ( ) ; return $ response ; }
Process all messages currently in queue .
18,703
protected function ensureSslEndpoint ( $ url ) { if ( substr ( $ url , 0 , 5 ) != 'https' ) { $ endpoint = parse_url ( $ url ) ; $ url = 'https://' . $ endpoint [ 'host' ] . $ endpoint [ 'path' ] ; } return $ url ; }
Ensure the endpoint is SSL
18,704
protected function Cache ( $ action , $ filename , $ data = '' , $ max_age = '' ) { if ( ! is_dir ( $ this -> cache_dir ) ) { return '' ; } $ cache_file = $ this -> cache_dir . $ filename ; $ cache = '' ; if ( $ action == 'get' ) { clearstatcache ( ) ; if ( is_file ( $ cache_file ) && $ max_age != '' ) { if ( is_string ( $ max_age ) && substr ( $ max_age , 0 , 1 ) != '-' ) { $ max_age = '-' . $ max_age ; } if ( ! is_int ( $ max_age ) ) { $ max_age = strtotime ( $ max_age ) ; } if ( filemtime ( $ cache_file ) >= date ( $ max_age ) ) { $ cache = file_get_contents ( $ cache_file ) ; } } } else { if ( is_writable ( $ this -> cache_dir ) ) { $ store = serialize ( $ data ) ; $ fp = fopen ( $ cache_file , "w" ) ; fwrite ( $ fp , $ store ) ; fclose ( $ fp ) ; chmod ( $ cache_file , 0770 ) ; $ cache = strlen ( $ store ) ; } } return $ cache ; }
Get or Set Cache
18,705
protected function getEndpoint ( ) { if ( $ this -> force_production ) { $ this -> force_production = false ; return $ this -> endpoints [ 'production' ] ; } return $ this -> endpoints [ $ this -> active_endpoint ] ; }
Get the current active endpoint
18,706
protected function addEndpoint ( $ name , $ url ) { $ this -> endpoints [ $ name ] = $ this -> ensureSslEndpoint ( $ url ) ; $ this -> active_endpoint = $ name ; return array_key_exists ( $ name , $ this -> endpoints ) ; }
Add a user defined endpoint
18,707
public function get_resource_url ( ) { $ info = $ this -> data [ $ this -> url ] ; if ( ! isset ( $ info [ 'http://purl.org/vocab/resourcelist/schema#resource' ] ) ) { return null ; } return $ info [ 'http://purl.org/vocab/resourcelist/schema#resource' ] [ 0 ] [ 'value' ] ; }
Returns the resource list URL .
18,708
private function get_values ( $ scheme ) { $ resourceurl = $ this -> get_resource_url ( ) ; if ( ! $ resourceurl ) { return array ( ) ; } $ info = $ this -> data [ $ resourceurl ] ; if ( ! isset ( $ info [ $ scheme ] ) ) { return array ( ) ; } $ values = array ( ) ; foreach ( $ info [ $ scheme ] as $ k => $ v ) { $ values [ $ k ] = $ v [ 'value' ] ; } return $ values ; }
Returns a value from the resource metadata .
18,709
public function get_authors ( ) { $ authors = array ( ) ; $ url = $ this -> get_value ( 'http://purl.org/ontology/bibo/authorList' ) ; $ info = $ this -> data [ $ url ] ; foreach ( $ info as $ k => $ v ) { if ( strpos ( $ k , '#type' ) !== false ) { continue ; } $ authors [ ] = $ this -> get_author ( $ v [ 0 ] [ 'value' ] ) ; } return $ authors ; }
Returns the authors of the item .
18,710
public function get_publisher ( ) { $ url = $ this -> get_value ( 'http://purl.org/dc/terms/publisher' ) ; if ( ! $ url ) { return ; } $ info = $ this -> data [ $ url ] ; return $ info [ 'http://xmlns.com/foaf/0.1/name' ] [ 0 ] [ 'value' ] ; }
Returns the name of a publisher .
18,711
public function setFileHead ( ) : void { $ this -> fileHead = $ this -> prepareFilePath ( 'head' , false ) ; if ( ! file_exists ( $ this -> fileHead ) ) { $ this -> fileHead = $ this -> prepareDefaultFilePath ( 'head' ) ; } }
Set file head .
18,712
public function setFileFoot ( ) : void { $ this -> fileFoot = $ this -> prepareFilePath ( 'foot' , false ) ; if ( ! file_exists ( $ this -> fileFoot ) ) { $ this -> fileFoot = $ this -> prepareDefaultFilePath ( 'foot' ) ; } }
Set file foot .
18,713
private function prepareFilePath ( string $ file , bool $ fileCheck = true ) : string { $ file = str_replace ( [ "\0" , "\r" , "\n" ] , '' , trim ( $ file ) ) ; if ( $ file == '' ) { throw new ViewException ( 'No valid file given' ) ; } if ( $ file [ 0 ] == '.' ) { $ fileCheck = false ; if ( ! file_exists ( $ file ) ) { throw new ViewException ( "Custom view file '{$file}' not found" ) ; } } elseif ( $ file [ 0 ] == '@' ) { $ file = sprintf ( '%s/app/service/_default/view/%s.php' , APP_DIR , substr ( $ file , 1 ) ) ; $ fileCheck = false ; if ( ! file_exists ( $ file ) ) { throw new ViewException ( "Default view file '{$file}' not found" ) ; } } else { $ file = sprintf ( '%s/app/service/%s/view/%s.php' , APP_DIR , $ this -> service -> getName ( ) , $ file ) ; } if ( $ fileCheck && ! file_exists ( $ file ) ) { if ( $ this -> service -> isDefaultService ( ) ) { $ file = sprintf ( '%s/app/service/_default/%s/view/%s' , APP_DIR , $ this -> service -> getName ( ) , basename ( $ file ) ) ; } if ( ! file_exists ( $ file ) ) { throw new ViewException ( "View file '{$file}' not found" ) ; } } return $ file ; }
Prepare file path .
18,714
private function prepareDefaultFilePath ( string $ file , bool $ fileCheck = true ) : string { $ file = sprintf ( '%s/app/service/_default/view/%s.php' , APP_DIR , $ file ) ; if ( $ fileCheck && ! file_exists ( $ file ) ) { throw new ViewException ( "View file '{$file}' not found" ) ; } return $ file ; }
Prepare default file path .
18,715
public function clear ( ) { $ this -> date = $ this -> base -> toInternalDateTime ( ) ; $ this -> calendar = $ this -> createCalendar ( $ this -> locale ) ; if ( null === $ this -> locale ) { $ this -> calendar -> setFirstDayOfWeek ( \ IntlCalendar :: DOW_MONDAY ) ; } }
Clears the current calculation and returns to the base date .
18,716
protected function validate ( $ value ) { if ( $ value < $ this -> minValue || $ value > $ this -> maxValue ) { throw new InvalidArgumentException ( 'Value ' . $ value . ' is out of bounds (' . $ this -> minValue . '..' . $ this -> maxValue . ')' ) ; } }
Validate given value
18,717
protected function setBlocks ( ) { if ( getConfig ( 'default.toolbar_color' ) ) { $ this -> Html -> meta ( 'theme-color' , getConfig ( 'default.toolbar_color' ) ) ; } if ( getConfig ( 'default.rss_meta' ) ) { $ this -> Html -> meta ( __d ( 'me_cms' , 'Latest posts' ) , '/posts/rss' , [ 'type' => 'rss' ] ) ; } if ( getConfig ( 'default.analytics' ) ) { echo $ this -> Library -> analytics ( getConfig ( 'default.analytics' ) ) ; } if ( getConfig ( 'shareaholic.site_id' ) ) { echo $ this -> Library -> shareaholic ( getConfig ( 'shareaholic.site_id' ) ) ; } $ this -> Html -> meta ( [ 'content' => $ this -> getTitleForLayout ( ) , 'property' => 'og:title' ] ) ; $ this -> Html -> meta ( [ 'content' => Router :: url ( null , true ) , 'property' => 'og:url' ] ) ; if ( getConfig ( 'default.facebook_app_id' ) ) { $ this -> Html -> meta ( [ 'content' => getConfig ( 'default.facebook_app_id' ) , 'property' => 'fb:app_id' , ] ) ; } }
Internal method to set some blocks
18,718
public function userbar ( $ content = null ) { if ( ! $ content ) { return $ this -> userbar ; } $ this -> userbar = array_merge ( $ this -> userbar , ( array ) $ content ) ; }
Sets one or more userbar contents .
18,719
public function updateModule ( ) { $ this -> moduleHandle -> cacheModuleConfig ( ) ; $ this -> moduleHandle -> setModules ( ) ; $ this -> moduleHandle -> updateModuleAddon ( ) ; }
Cache module update and install to file
18,720
public function add ( ) { $ category = $ this -> PagesCategories -> newEntity ( ) ; if ( $ this -> request -> is ( 'post' ) ) { $ category = $ this -> PagesCategories -> patchEntity ( $ category , $ this -> request -> getData ( ) ) ; if ( $ this -> PagesCategories -> save ( $ category ) ) { $ this -> Flash -> success ( I18N_OPERATION_OK ) ; return $ this -> redirect ( [ 'action' => 'index' ] ) ; } $ this -> Flash -> error ( I18N_OPERATION_NOT_OK ) ; } $ this -> set ( compact ( 'category' ) ) ; }
Adds pages category
18,721
public function edit ( $ id = null ) { $ category = $ this -> PagesCategories -> get ( $ id ) ; if ( $ this -> request -> is ( [ 'patch' , 'post' , 'put' ] ) ) { $ category = $ this -> PagesCategories -> patchEntity ( $ category , $ this -> request -> getData ( ) ) ; if ( $ this -> PagesCategories -> save ( $ category ) ) { $ this -> Flash -> success ( I18N_OPERATION_OK ) ; return $ this -> redirect ( [ 'action' => 'index' ] ) ; } $ this -> Flash -> error ( I18N_OPERATION_NOT_OK ) ; } $ this -> set ( compact ( 'category' ) ) ; }
Edits pages category
18,722
public function delete ( $ id = null ) { $ this -> request -> allowMethod ( [ 'post' , 'delete' ] ) ; $ category = $ this -> PagesCategories -> get ( $ id ) ; if ( ! $ category -> page_count ) { $ this -> PagesCategories -> deleteOrFail ( $ category ) ; $ this -> Flash -> success ( I18N_OPERATION_OK ) ; } else { $ this -> Flash -> alert ( I18N_BEFORE_DELETE ) ; } return $ this -> redirect ( [ 'action' => 'index' ] ) ; }
Deletes pages category
18,723
public function validTags ( $ value ) { $ validator = new TagValidator ; $ messages = [ ] ; foreach ( $ value as $ tag ) { $ errors = $ validator -> errors ( $ tag ) ; if ( ! empty ( $ errors [ 'tag' ] ) ) { foreach ( $ errors [ 'tag' ] as $ error ) { $ messages [ ] = __d ( 'me_cms' , 'Tag "{0}": {1}' , $ tag [ 'tag' ] , lcfirst ( $ error ) ) ; } } } return empty ( $ messages ) ? : implode ( PHP_EOL , $ messages ) ; }
Tags validation method .
18,724
public function run ( array $ strings ) { foreach ( $ this -> passes as $ pass ) { $ strings = $ pass -> run ( $ strings ) ; } return $ strings ; }
Run all passes on the list of strings
18,725
public function findElementsByPageId ( $ pageId ) { $ this -> makeSelect ( ) ; $ this -> sql .= ' and page_element.page_id = ? order by block_key, element_sort' ; $ this -> bindValues [ ] = $ pageId ; return $ this -> find ( ) ; }
Find Elements by Page ID
18,726
public function getUserProviderMapper ( ) { if ( $ this -> userProviderMapper == null ) { $ this -> userProviderMapper = $ this -> getServiceManager ( ) -> get ( 'playgrounduser_userprovider_mapper' ) ; } return $ this -> userProviderMapper ; }
Retourne le modele de userProviderMapper
18,727
public function getHybridAuth ( ) { if ( $ this -> hybridAuth == null ) { $ this -> hybridAuth = $ this -> getServiceManager ( ) -> get ( 'HybridAuth' ) ; } return $ this -> hybridAuth ; }
Retourne l objet HybridAuth
18,728
public function getSocialConfig ( ) { if ( $ this -> SocialConfig == null ) { $ this -> SocialConfig = $ this -> getServiceManager ( ) -> get ( 'SocialConfig' ) ; } return $ this -> SocialConfig ; }
Retourne la configuration des providers
18,729
public function getInfoMe ( $ socialnetworktype , $ options = array ( ) ) { $ infoMe = null ; $ provider = ucfirst ( strtolower ( $ socialnetworktype ) ) ; if ( is_string ( $ socialnetworktype ) ) { try { $ adapter = $ this -> getHybridAuth ( ) -> authenticate ( $ provider ) ; if ( $ adapter -> isConnected ( ) ) { $ infoMe = $ adapter -> getUserProfile ( ) ; } } catch ( \ Exception $ ex ) { if ( ( $ ex -> getCode ( ) == 6 ) || ( $ ex -> getCode ( ) == 7 ) ) { $ this -> getHybridAuth ( ) -> getAdapter ( $ provider ) -> logout ( ) ; $ adapter = $ this -> getHybridAuth ( ) -> authenticate ( $ provider ) ; if ( $ adapter -> isConnected ( ) ) { $ infoMe = $ adapter -> getUserProfile ( ) ; } } else { return null ; } } } return $ infoMe ; }
Retourne mes infos
18,730
public function addUsers ( ArrayCollection $ users ) { foreach ( $ users as $ user ) { $ user -> addTeam ( $ this ) ; $ this -> users -> add ( $ user ) ; } }
Add users to the team .
18,731
public function removeUsers ( ArrayCollection $ users ) { foreach ( $ users as $ user ) { $ user -> removeTeam ( $ this ) ; $ this -> users -> removeElement ( $ user ) ; } }
Remove users from the team .
18,732
public function index ( ) { $ this -> validateToken ( ) ; $ oAuthModel = Factory :: model ( 'Auth' , 'nails/module-auth' ) ; $ oMfaDevice = $ oAuthModel -> mfaDeviceSecretGet ( $ this -> mfaUser -> id ) ; if ( $ oMfaDevice ) { $ this -> requestCode ( ) ; } else { $ this -> setupDevice ( ) ; } }
Remaps requests to the correct method
18,733
protected function setupDevice ( ) { $ oSession = Factory :: service ( 'Session' , 'nails/module-auth' ) ; $ oAuthModel = Factory :: model ( 'Auth' , 'nails/module-auth' ) ; $ oInput = Factory :: service ( 'Input' ) ; if ( $ oInput -> post ( ) ) { $ oFormValidation = Factory :: service ( 'FormValidation' ) ; $ oFormValidation -> set_rules ( 'mfa_secret' , '' , 'required' ) ; $ oFormValidation -> set_rules ( 'mfa_code' , '' , 'required' ) ; $ oFormValidation -> set_message ( 'required' , lang ( 'fv_required' ) ) ; if ( $ oFormValidation -> run ( ) ) { $ sSecret = $ oInput -> post ( 'mfa_secret' ) ; $ sMfaCode = $ oInput -> post ( 'mfa_code' ) ; if ( $ oAuthModel -> mfaDeviceSecretValidate ( $ this -> mfaUser -> id , $ sSecret , $ sMfaCode ) ) { $ sStatus = 'success' ; $ sMessage = '<strong>Multi Factor Authentication Enabled!</strong><br />You successfully ' ; $ sMessage .= 'associated an MFA device with your account. You will be required to use it ' ; $ sMessage .= 'the next time you log in.' ; $ oSession -> setFlashData ( $ sStatus , $ sMessage ) ; $ this -> loginUser ( ) ; } else { $ this -> data [ 'error' ] = 'Sorry, that code failed to validate. Please try again.' ; } } else { $ this -> data [ 'error' ] = lang ( 'fv_there_were_errors' ) ; } } $ this -> data [ 'secret' ] = $ oAuthModel -> mfaDeviceSecretGenerate ( $ this -> mfaUser -> id , $ oInput -> post ( 'mfa_secret' , true ) ) ; if ( ! $ this -> data [ 'secret' ] ) { $ sStatus = 'error' ; $ sMessage = '<Strong>Sorry,</strong> it has not been possible to get an MFA device set up for this user. ' ; $ sMessage .= $ oAuthModel -> lastError ( ) ; $ oSession -> setFlashData ( $ sStatus , $ sMessage ) ; if ( $ this -> returnTo ) { redirect ( 'auth/login?return_to=' . $ this -> returnTo ) ; } else { redirect ( 'auth/login' ) ; } } $ this -> data [ 'page' ] -> title = 'Set up a new MFA device' ; $ this -> loadStyles ( NAILS_APP_PATH . 'application/modules/auth/views/mfa/device/setup.php' ) ; Factory :: service ( 'View' ) -> load ( [ 'structure/header/blank' , 'auth/mfa/device/setup' , 'structure/footer/blank' , ] ) ; }
Sets up a new MFA device
18,734
protected function requestCode ( ) { $ oInput = Factory :: service ( 'Input' ) ; if ( $ oInput -> post ( ) ) { $ oFormValidation = Factory :: service ( 'FormValidation' ) ; $ oFormValidation -> set_rules ( 'mfa_code' , '' , 'required' ) ; $ oFormValidation -> set_message ( 'required' , lang ( 'fv_required' ) ) ; if ( $ oFormValidation -> run ( ) ) { $ oAuthModel = Factory :: model ( 'Auth' , 'nails/module-auth' ) ; $ sMfaCode = $ oInput -> post ( 'mfa_code' ) ; if ( $ oAuthModel -> mfaDeviceCodeValidate ( $ this -> mfaUser -> id , $ sMfaCode ) ) { $ this -> loginUser ( ) ; } else { $ this -> data [ 'error' ] = 'Sorry, that code failed to validate. Please try again. ' ; $ this -> data [ 'error' ] .= $ oAuthModel -> lastError ( ) ; } } else { $ this -> data [ 'error' ] = lang ( 'fv_there_were_errors' ) ; } } $ this -> data [ 'page' ] -> title = 'Enter your Code' ; $ this -> loadStyles ( NAILS_APP_PATH . 'application/modules/auth/views/mfa/device/ask.php' ) ; Factory :: service ( 'View' ) -> load ( [ 'structure/header/blank' , 'auth/mfa/device/ask' , 'structure/footer/blank' , ] ) ; }
Requests a code from the user
18,735
private function addToOptionCache ( string $ identifier , $ option ) : void { if ( ! isset ( $ option [ $ identifier ] ) ) { return ; } $ cacheKey = "${option['command']}${option[$identifier]}" ; if ( ! isset ( $ this -> optionsCache [ $ cacheKey ] ) ) { $ this -> optionsCache [ $ cacheKey ] = $ option ; } else { throw new OptionExistsException ( "An argument option with $identifier {$option['command']} {$option[$identifier]} already exists." ) ; } }
Add an option to the option cache for easy access through associative arrays . The option cache associates arguments with their options .
18,736
public function addOption ( array $ option ) : void { $ this -> validator -> validateOption ( $ option , $ this -> commands ) ; $ option [ 'command' ] = $ option [ 'command' ] ?? '' ; $ option [ 'repeats' ] = $ option [ 'repeats' ] ?? false ; $ this -> options [ ] = $ option ; $ this -> addToOptionCache ( 'name' , $ option ) ; $ this -> addToOptionCache ( 'short_name' , $ option ) ; }
Add an option to be parsed . Arguments are presented as a structured array with the following possible keys .
18,737
private function parseShortArgument ( $ command , $ arguments , & $ argPointer , & $ output ) { $ argument = $ arguments [ $ argPointer ] ; $ option = $ this -> retrieveOptionFromCache ( $ command , substr ( $ argument , 1 , 1 ) ) ; $ value = true ; if ( isset ( $ option [ 'type' ] ) ) { if ( substr ( $ argument , 2 ) != "" ) { $ value = substr ( $ argument , 2 ) ; } else { $ value = $ this -> getNextValueOrFail ( $ arguments , $ argPointer , $ option [ 'name' ] ) ; } } $ this -> assignValue ( $ option , $ output , $ option [ 'name' ] , $ value ) ; }
Parse a short argument that is prefixed with a single dash -
18,738
public function parse ( $ arguments = null ) { try { global $ argv ; $ arguments = $ arguments ?? $ argv ; $ argPointer = 1 ; $ parsed = [ ] ; $ this -> name = $ this -> name ?? $ arguments [ 0 ] ; $ this -> parseCommand ( $ arguments , $ argPointer , $ parsed ) ; $ this -> parseArgumentArray ( $ arguments , $ argPointer , $ parsed ) ; $ this -> maybeShowHelp ( $ parsed ) ; $ this -> validator -> validateArguments ( $ this -> options , $ parsed ) ; $ this -> fillInDefaults ( $ parsed ) ; $ parsed [ '__executed' ] = $ this -> name ; return $ parsed ; } catch ( HelpMessageRequestedException $ exception ) { $ this -> programControl -> quit ( ) ; } catch ( InvalidArgumentException $ exception ) { print $ exception -> getMessage ( ) . PHP_EOL ; $ this -> programControl -> quit ( ) ; } }
Parses command line arguments and return a structured array of options and their associated values .
18,739
public function enableHelp ( string $ description = null , string $ footer = null , string $ name = null ) : void { $ this -> name = $ name ; $ this -> description = $ description ; $ this -> footer = $ footer ; $ this -> helpEnabled = true ; $ this -> addOption ( [ 'name' => 'help' , 'short_name' => 'h' , 'help' => "display this help message" ] ) ; foreach ( $ this -> commands as $ command ) { $ this -> addOption ( [ 'name' => 'help' , 'help' => 'display this help message' , 'command' => $ command [ 'name' ] ] ) ; } }
Enables help messages so they show automatically . This method also allows you to optionally pass the name of the application a description header for the help message and a footer .
18,740
public function view ( $ slug = null ) { $ static = StaticPage :: get ( $ slug ) ; if ( $ static ) { $ page = new Entity ( array_merge ( [ 'category' => new Entity ( [ 'slug' => null , 'title' => null ] ) , 'title' => StaticPage :: title ( $ slug ) , 'subtitle' => null , ] , compact ( 'slug' ) ) ) ; $ this -> set ( compact ( 'page' ) ) ; return $ this -> render ( $ static ) ; } $ slug = rtrim ( $ slug , '/' ) ; $ page = $ this -> Pages -> findActiveBySlug ( $ slug ) -> contain ( [ $ this -> Pages -> Categories -> getAlias ( ) => [ 'fields' => [ 'title' , 'slug' ] ] ] ) -> cache ( sprintf ( 'view_%s' , md5 ( $ slug ) ) , $ this -> Pages -> getCacheName ( ) ) -> firstOrFail ( ) ; $ this -> set ( compact ( 'page' ) ) ; }
Views page .
18,741
public function preview ( $ slug = null ) { $ page = $ this -> Pages -> findPendingBySlug ( $ slug ) -> contain ( [ $ this -> Pages -> Categories -> getAlias ( ) => [ 'fields' => [ 'title' , 'slug' ] ] ] ) -> firstOrFail ( ) ; $ this -> set ( compact ( 'page' ) ) ; $ this -> render ( 'view' ) ; }
Preview for pages . It uses the view template .
18,742
protected static function getMethods ( $ plugin ) { $ class = App :: classname ( $ plugin . '.Sitemap' , 'Utility' ) ; $ methods = get_child_methods ( $ class ) ; if ( empty ( $ methods ) ) { return [ ] ; } return collection ( $ methods ) -> map ( function ( $ method ) use ( $ class ) { return array_merge ( compact ( 'class' ) , [ 'name' => $ method ] ) ; } ) -> toList ( ) ; }
Internal method to get methods from Sitemap classes
18,743
public function pathFor ( $ name , $ data = [ ] , $ queryParams = [ ] ) { if ( $ name === 'showPage' && isset ( $ data [ 'url' ] ) && $ data [ 'url' ] === 'home' ) { $ name = 'home' ; unset ( $ data [ 'url' ] ) ; } return $ this -> container -> router -> pathFor ( $ name , $ data , $ queryParams ) ; }
Get Path for Named Route
18,744
public function getMediaPath ( $ fileName ) { if ( stripos ( $ fileName , 'http' ) === 0 || empty ( $ fileName ) ) { return $ fileName ; } return ( $ this -> container -> filePath ) ( $ fileName ) . $ fileName ; }
Get Media Path
18,745
public function browser ( ) { $ type = $ this -> request -> getQuery ( 'type' ) ; $ types = $ this -> KcFinder -> getTypes ( ) ; if ( ! $ type && count ( $ types ) < 2 ) { $ type = array_key_first ( $ types ) ; $ this -> request = $ this -> request -> withQueryParams ( compact ( 'type' ) ) ; } if ( $ type && array_key_exists ( $ type , $ types ) ) { $ locale = substr ( I18n :: getLocale ( ) , 0 , 2 ) ; $ locale = empty ( $ locale ) ? 'en' : $ locale ; $ this -> set ( 'kcfinder' , sprintf ( '%s/kcfinder/browse.php?lang=%s&type=%s' , Router :: url ( '/vendor' , true ) , $ locale , $ type ) ) ; } $ this -> set ( 'types' , array_combine ( array_keys ( $ types ) , array_keys ( $ types ) ) ) ; }
Media browser with KCFinder .
18,746
public function healFreshOrdinaryWounds ( HealingPower $ healingPower , WoundBoundary $ woundBoundary ) : int { $ this -> checkIfNeedsToRollAgainstMalusFirst ( ) ; $ healedAmount = 0 ; $ remainingHealUpToWounds = $ healingPower -> getHealUpToWounds ( ) ; foreach ( $ this -> getUnhealedFreshOrdinaryWounds ( ) as $ newOrdinaryWound ) { $ currentlyRegenerated = $ newOrdinaryWound -> heal ( $ remainingHealUpToWounds ) ; $ remainingHealUpToWounds -= $ currentlyRegenerated ; $ healedAmount += $ currentlyRegenerated ; } $ this -> treatmentBoundary = TreatmentBoundary :: getIt ( $ this -> getUnhealedWoundsSum ( ) ) ; $ this -> resolveMalusAfterHeal ( $ healedAmount , $ woundBoundary ) ; return $ healedAmount ; }
Also sets treatment boundary to unhealed wounds after . Even if the heal itself heals nothing!
18,747
public function regenerate ( HealingPower $ healingPower , WoundBoundary $ woundBoundary ) : int { $ this -> checkIfNeedsToRollAgainstMalusFirst ( ) ; $ regeneratedAmount = 0 ; $ remainingHealUpToWounds = $ healingPower -> getHealUpToWounds ( ) ; foreach ( $ this -> getUnhealedWounds ( ) as $ unhealedWound ) { $ currentlyRegenerated = $ unhealedWound -> heal ( $ remainingHealUpToWounds ) ; $ remainingHealUpToWounds -= $ currentlyRegenerated ; $ regeneratedAmount += $ currentlyRegenerated ; } $ this -> treatmentBoundary = TreatmentBoundary :: getIt ( $ this -> getUnhealedWoundsSum ( ) ) ; $ this -> resolveMalusAfterHeal ( $ regeneratedAmount , $ woundBoundary ) ; return $ regeneratedAmount ; }
Regenerate any wound both ordinary and serious both new and old by natural or unnatural way .
18,748
public function getUnhealedFreshOrdinaryWoundsSum ( ) : int { return \ array_sum ( \ array_map ( function ( OrdinaryWound $ ordinaryWound ) { return $ ordinaryWound -> getValue ( ) ; } , $ this -> getUnhealedFreshOrdinaryWounds ( ) ) ) ; }
Usable for info about amount of wounds which can be healed by basic healing
18,749
public function getUnhealedFreshSeriousWoundsSum ( ) : int { return \ array_sum ( \ array_map ( function ( SeriousWound $ seriousWound ) { return $ seriousWound -> getValue ( ) ; } , $ this -> getUnhealedFreshSeriousWounds ( ) ) ) ; }
Usable for info about amount of wounds which can be healed by treatment
18,750
public static function identifier ( array $ match ) { $ name = $ match [ 1 ] ; if ( $ name === '*' ) { return '(?P<pathInfo>.*)' ; } $ type = '[-_0-9a-zA-Z]' ; if ( strpos ( $ name , ':' ) !== false ) { list ( $ name , $ type ) = explode ( ':' , $ name , 2 ) ; if ( isset ( self :: $ types [ $ type ] ) ) { $ type = self :: $ types [ $ type ] ; } } return "(?P<{$name}>{$type}+)" ; }
a callback method for converting identifier in route pattern to regex s one .
18,751
public function remove ( ) { if ( $ this -> removed ) { return ; } if ( ! \ unlink ( $ this -> file ) ) { throw new RuntimeException ( sprintf ( 'Impossible to remove file "%s"' , $ this -> file ) ) ; } $ this -> removed = true ; }
Removes the temporary file . Please consider unset the object instead .
18,752
public function isCorrect ( $ iUserId , $ sPassword ) { if ( empty ( $ iUserId ) || empty ( $ sPassword ) ) { return false ; } $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> select ( 'u.password, u.password_engine, u.salt' ) ; $ oDb -> where ( 'u.id' , $ iUserId ) ; $ oDb -> limit ( 1 ) ; $ oResult = $ oDb -> get ( NAILS_DB_PREFIX . 'user u' ) ; if ( $ oResult -> num_rows ( ) !== 1 ) { return false ; } $ sHash = sha1 ( sha1 ( $ sPassword ) . $ oResult -> row ( ) -> salt ) ; return $ oResult -> row ( ) -> password === $ sHash ; }
Determines whether a password is correct for a particular user .
18,753
public function isExpired ( $ iUserId ) { if ( empty ( $ iUserId ) ) { return false ; } $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> select ( 'u.password_changed,ug.password_rules' ) ; $ oDb -> where ( 'u.id' , $ iUserId ) ; $ oDb -> join ( NAILS_DB_PREFIX . 'user_group ug' , 'ug.id = u.group_id' ) ; $ oDb -> limit ( 1 ) ; $ oResult = $ oDb -> get ( NAILS_DB_PREFIX . 'user u' ) ; if ( $ oResult -> num_rows ( ) !== 1 ) { return false ; } $ oGroupPwRules = json_decode ( $ oResult -> row ( ) -> password_rules ) ; if ( empty ( $ oGroupPwRules -> expiresAfter ) ) { return false ; } $ sChanged = $ oResult -> row ( ) -> password_changed ; if ( is_null ( $ sChanged ) ) { return true ; } else { $ oThen = new \ DateTime ( $ sChanged ) ; $ oNow = new \ DateTime ( ) ; $ oInterval = $ oNow -> diff ( $ oThen ) ; return $ oInterval -> days >= $ oGroupPwRules -> expiresAfter ; } }
Determines whether a user s password has expired
18,754
public function expiresAfter ( $ iGroupId ) { if ( empty ( $ iGroupId ) ) { return null ; } $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> select ( 'password_rules' ) ; $ oDb -> where ( 'id' , $ iGroupId ) ; $ oDb -> limit ( 1 ) ; $ oResult = $ oDb -> get ( NAILS_DB_PREFIX . 'user_group' ) ; if ( $ oResult -> num_rows ( ) !== 1 ) { return null ; } $ oGroupPwRules = json_decode ( $ oResult -> row ( ) -> password_rules ) ; return empty ( $ oGroupPwRules -> expiresAfter ) ? null : $ oGroupPwRules -> expiresAfter ; }
Returns how many days a password is valid for
18,755
public function generateHash ( $ iGroupId , $ sPassword ) { if ( empty ( $ sPassword ) ) { $ this -> setError ( 'No password to hash' ) ; return false ; } $ aPwRules = $ this -> getRules ( $ iGroupId ) ; if ( ! empty ( $ aPwRules [ 'min' ] ) && strlen ( $ sPassword ) < $ aPwRules [ 'min' ] ) { $ this -> setError ( 'Password is too short.' ) ; return false ; } if ( ! empty ( $ aPwRules [ 'max' ] ) && strlen ( $ sPassword ) > $ aPwRules [ 'max' ] ) { $ this -> setError ( 'Password is too long.' ) ; return false ; } $ aFailedRequirements = [ ] ; if ( ! empty ( $ aPwRules [ 'requirements' ] ) ) { foreach ( $ aPwRules [ 'requirements' ] as $ sRequirement => $ bValue ) { switch ( $ sRequirement ) { case 'symbol' : if ( ! $ this -> strContainsFromCharset ( $ sPassword , 'symbol' ) ) { $ aFailedRequirements [ ] = 'a symbol' ; } break ; case 'number' : if ( ! $ this -> strContainsFromCharset ( $ sPassword , 'number' ) ) { $ aFailedRequirements [ ] = 'a number' ; } break ; case 'lower_alpha' : if ( ! $ this -> strContainsFromCharset ( $ sPassword , 'lower_alpha' ) ) { $ aFailedRequirements [ ] = 'a lowercase letter' ; } break ; case 'upper_alpha' : if ( ! $ this -> strContainsFromCharset ( $ sPassword , 'upper_alpha' ) ) { $ aFailedRequirements [ ] = 'an uppercase letter' ; } break ; } } } if ( ! empty ( $ aFailedRequirements ) ) { $ sError = 'Password must contain ' . implode ( ', ' , $ aFailedRequirements ) . '.' ; $ sError = str_lreplace ( ', ' , ' and ' , $ sError ) ; $ this -> setError ( $ sError ) ; return false ; } if ( ! empty ( $ aPwRules [ 'banned' ] ) ) { foreach ( $ aPwRules [ 'banned' ] as $ sStr ) { if ( trim ( strtolower ( $ sPassword ) ) == strtolower ( $ sStr ) ) { $ this -> setError ( 'Password cannot be "' . $ sStr . '"' ) ; return false ; } } } return $ this -> generateHashObject ( $ sPassword ) ; }
Create a password hash checks to ensure a password is strong enough according to the password rules defined by the app .
18,756
private function strContainsFromCharset ( $ sStr , $ sCharset ) { if ( empty ( $ this -> aCharset [ $ sCharset ] ) ) { return true ; } return preg_match ( '/[' . preg_quote ( $ this -> aCharset [ $ sCharset ] , '/' ) . ']/' , $ sStr ) ; }
Determines whether a string contains any of the characters from a defined charset .
18,757
public function generateHashObject ( $ sPassword ) { $ sSalt = $ this -> salt ( ) ; $ oOut = new \ stdClass ( ) ; $ oOut -> password = sha1 ( sha1 ( $ sPassword ) . $ sSalt ) ; $ oOut -> password_md5 = md5 ( $ oOut -> password ) ; $ oOut -> salt = $ sSalt ; $ oOut -> engine = 'NAILS_1' ; return $ oOut ; }
Generates a password hash no strength checks
18,758
public function generate ( $ iGroupId ) { $ aPwRules = $ this -> getRules ( $ iGroupId ) ; $ aPwOut = [ ] ; $ aCharsets = [ ] ; $ aCharsets [ ] = $ this -> aCharset [ 'lower_alpha' ] ; if ( ! empty ( $ aPwRules [ 'requirements' ] ) ) { foreach ( $ aPwRules [ 'requirements' ] as $ sRequirement => $ bValue ) { switch ( $ sRequirement ) { case 'symbol' : $ aCharsets [ ] = $ this -> aCharset [ 'symbol' ] ; break ; case 'number' : $ aCharsets [ ] = $ this -> aCharset [ 'number' ] ; break ; case 'upper_alpha' : $ aCharsets [ ] = $ this -> aCharset [ 'upper_alpha' ] ; break ; } } } $ iMin = getFromArray ( 'min' , $ aPwRules ) ; if ( empty ( $ iMin ) ) { $ iMin = 8 ; } $ iMax = getFromArray ( 'max' , $ aPwRules ) ; if ( empty ( $ iMax ) || $ iMin > $ iMax ) { $ iMax = $ iMin + count ( $ aCharsets ) * 2 ; } $ bPwValid = true ; do { do { foreach ( $ aCharsets as $ sCharset ) { $ sCharacter = rand ( 0 , strlen ( $ sCharset ) - 1 ) ; $ aPwOut [ ] = $ sCharset [ $ sCharacter ] ; } } while ( count ( $ aPwOut ) < $ iMax ) ; if ( ! empty ( $ aPwRules [ 'banned' ] ) ) { foreach ( $ aPwRules [ 'banned' ] as $ sString ) { if ( strtolower ( implode ( '' , $ aPwOut ) ) == strtolower ( $ sString ) ) { $ bPwValid = false ; break ; } } } } while ( ! $ bPwValid ) ; shuffle ( $ aPwOut ) ; return implode ( '' , $ aPwOut ) ; }
Generates a password which is sufficiently secure according to the app s password rules
18,759
protected function getRules ( $ iGroupId ) { $ sCacheKey = 'password-rules-' . $ iGroupId ; $ aCacheResult = $ this -> getCache ( $ sCacheKey ) ; if ( ! empty ( $ aCacheResult ) ) { return $ aCacheResult ; } $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> select ( 'password_rules' ) ; $ oDb -> where ( 'id' , $ iGroupId ) ; $ oResult = $ oDb -> get ( NAILS_DB_PREFIX . 'user_group' ) ; if ( $ oResult -> num_rows ( ) === 0 ) { return [ ] ; } $ oPwRules = json_decode ( $ oResult -> row ( ) -> password_rules ) ; $ aOut = [ ] ; $ aOut [ 'min' ] = ! empty ( $ oPwRules -> min ) ? $ oPwRules -> min : null ; $ aOut [ 'max' ] = ! empty ( $ oPwRules -> max ) ? $ oPwRules -> max : null ; $ aOut [ 'expiresAfter' ] = ! empty ( $ oPwRules -> expiresAfter ) ? $ oPwRules -> expiresAfter : null ; $ aOut [ 'requirements' ] = ! empty ( $ oPwRules -> requirements ) ? $ oPwRules -> requirements : [ ] ; $ aOut [ 'banned' ] = ! empty ( $ oPwRules -> banned ) ? $ oPwRules -> banned : [ ] ; $ this -> setCache ( $ sCacheKey , $ aOut ) ; return $ aOut ; }
Returns the app s raw password rules as an array
18,760
public function getRulesAsString ( $ iGroupId ) { $ aRules = $ this -> getRulesAsArray ( $ iGroupId ) ; if ( empty ( $ aRules ) ) { return '' ; } $ sStr = 'Passwords must ' . strtolower ( implode ( ', ' , $ aRules ) ) . '.' ; return str_lreplace ( ', ' , ' and ' , $ sStr ) ; }
Returns the app s password rules as a formatted string
18,761
public function getRulesAsArray ( $ iGroupId ) { $ aRules = $ this -> getRules ( $ iGroupId ) ; $ aOut = [ ] ; if ( ! empty ( $ aRules [ 'min' ] ) ) { $ aOut [ ] = 'Have at least ' . $ aRules [ 'min' ] . ' characters' ; } if ( ! empty ( $ aRules [ 'max' ] ) ) { $ aOut [ ] = 'Have at most ' . $ aRules [ 'max' ] . ' characters' ; } if ( ! empty ( $ aRules [ 'requirements' ] ) ) { foreach ( $ aRules [ 'requirements' ] as $ sKey => $ bValue ) { switch ( $ sKey ) { case 'symbol' : $ aOut [ ] = 'Contain a symbol' ; break ; case 'lower_alpha' : $ aOut [ ] = 'Contain a lowercase letter' ; break ; case 'upper_alpha' : $ aOut [ ] = 'Contain an upper case letter' ; break ; case 'number' : $ aOut [ ] = 'Contain a number' ; break ; } } } return $ aOut ; }
Returns the app s password rules as an array of human friendly strings
18,762
public function setToken ( $ sIdentifier ) { if ( empty ( $ sIdentifier ) ) { return false ; } $ sKey = sha1 ( sha1 ( $ this -> salt ( ) ) . $ this -> salt ( ) . APP_PRIVATE_KEY ) ; $ iTtl = time ( ) + 86400 ; $ oUserModel = Factory :: model ( 'User' , 'nails/module-auth' ) ; $ oUser = $ oUserModel -> getByIdentifier ( $ sIdentifier ) ; if ( $ oUser ) { $ aData = [ 'forgotten_password_code' => $ iTtl . ':' . $ sKey , ] ; return $ oUserModel -> update ( $ oUser -> id , $ aData ) ; } else { return false ; } }
Sets a forgotten password token for a user
18,763
public function validateToken ( $ sCode , $ bGenerateNewPw ) { if ( empty ( $ sCode ) ) { return false ; } $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> select ( 'id, group_id, forgotten_password_code' ) ; $ oDb -> like ( 'forgotten_password_code' , ':' . $ sCode , 'before' ) ; $ oResult = $ oDb -> get ( NAILS_DB_PREFIX . 'user' ) ; if ( $ oResult -> num_rows ( ) != 1 ) { return false ; } $ oUser = $ oResult -> row ( ) ; $ aCode = explode ( ':' , $ oUser -> forgotten_password_code ) ; if ( time ( ) > $ aCode [ 0 ] ) { return 'EXPIRED' ; } else { $ aOut = [ ] ; $ aOut [ 'user_id' ] = $ oUser -> id ; if ( $ bGenerateNewPw ) { $ aOut [ 'password' ] = $ this -> generate ( $ oUser -> group_id ) ; if ( empty ( $ aOut [ 'password' ] ) ) { return false ; } $ oHash = $ this -> generateHash ( $ oUser -> group_id , $ aOut [ 'password' ] ) ; if ( ! $ oHash ) { return false ; } $ aData [ 'password' ] = $ oHash -> password ; $ aData [ 'password_md5' ] = $ oHash -> password_md5 ; $ aData [ 'password_engine' ] = $ oHash -> engine ; $ aData [ 'salt' ] = $ oHash -> salt ; $ aData [ 'temp_pw' ] = true ; $ aData [ 'forgotten_password_code' ] = null ; $ oDb -> where ( 'forgotten_password_code' , $ oUser -> forgotten_password_code ) ; $ oDb -> set ( $ aData ) ; $ oDb -> update ( NAILS_DB_PREFIX . 'user' ) ; } } return $ aOut ; }
Validate a forgotten password code .
18,764
public function findPageSettings ( $ pageId ) { $ this -> makeSelect ( ) ; $ this -> sql .= ' and page_id = ?' ; $ this -> bindValues [ ] = $ pageId ; return $ this -> find ( ) ; }
Find Page Settings
18,765
protected function getAll ( ) { $ widgets = getConfig ( 'Widgets.general' , [ ] ) ; if ( $ this -> getView ( ) -> getRequest ( ) -> isUrl ( [ '_name' => 'homepage' ] ) && getConfig ( 'Widgets.homepage' ) ) { $ widgets = getConfig ( 'Widgets.homepage' ) ; } return $ widgets ? collection ( $ widgets ) -> map ( function ( $ args , $ name ) { if ( is_string ( $ name ) && is_array ( $ args ) ) { return [ $ name => $ args ] ; } elseif ( is_string ( $ args ) ) { return [ $ args => [ ] ] ; } list ( $ name , $ args ) = [ array_key_first ( $ args ) , array_value_first ( $ args ) ] ; return is_int ( $ name ) && is_string ( $ args ) ? [ $ args => [ ] ] : [ $ name => $ args ] ; } ) -> toList ( ) : [ ] ; }
Internal method to get all widgets
18,766
public function all ( ) { foreach ( $ this -> getAll ( ) as $ widget ) { foreach ( $ widget as $ name => $ args ) { $ widgets [ ] = $ this -> widget ( $ name , $ args ) ; } } return empty ( $ widgets ) ? null : trim ( implode ( PHP_EOL , $ widgets ) ) ; }
Renders all widgets
18,767
public function widget ( $ name , array $ data = [ ] , array $ options = [ ] ) { $ parts = explode ( '::' , $ name ) ; $ name = $ parts [ 0 ] . 'Widgets' ; $ name = empty ( $ parts [ 1 ] ) ? $ name : sprintf ( '%s::%s' , $ name , $ parts [ 1 ] ) ; return $ this -> getView ( ) -> cell ( $ name , $ data , $ options ) ; }
Returns a widget
18,768
public function index ( ) { $ backups = collection ( $ this -> BackupManager -> index ( ) ) -> map ( function ( Entity $ backup ) { return $ backup -> set ( 'slug' , urlencode ( $ backup -> filename ) ) ; } ) ; $ this -> set ( compact ( 'backups' ) ) ; }
Lists backup files
18,769
public function add ( ) { $ backup = new BackupForm ; if ( $ this -> request -> is ( 'post' ) ) { if ( $ backup -> execute ( $ this -> request -> getData ( ) ) ) { $ this -> Flash -> success ( I18N_OPERATION_OK ) ; return $ this -> redirect ( [ 'action' => 'index' ] ) ; } $ this -> Flash -> error ( I18N_OPERATION_NOT_OK ) ; } $ this -> set ( compact ( 'backup' ) ) ; }
Adds a backup file
18,770
public function delete ( $ filename ) { $ this -> request -> allowMethod ( [ 'post' , 'delete' ] ) ; $ this -> BackupManager -> delete ( $ this -> getFilename ( $ filename ) ) ; $ this -> Flash -> success ( I18N_OPERATION_OK ) ; return $ this -> redirect ( [ 'action' => 'index' ] ) ; }
Deletes a backup file
18,771
public function deleteAll ( ) { $ this -> request -> allowMethod ( [ 'post' , 'delete' ] ) ; $ this -> BackupManager -> deleteAll ( ) ; $ this -> Flash -> success ( I18N_OPERATION_OK ) ; return $ this -> redirect ( [ 'action' => 'index' ] ) ; }
Deletes all backup files
18,772
public function restore ( $ filename ) { ( new BackupImport ) -> filename ( $ this -> getFilename ( $ filename ) ) -> import ( ) ; Cache :: clearAll ( ) ; $ this -> Flash -> success ( I18N_OPERATION_OK ) ; return $ this -> redirect ( [ 'action' => 'index' ] ) ; }
Restores a backup file
18,773
public function send ( $ filename ) { $ this -> BackupManager -> send ( $ this -> getFilename ( $ filename ) , getConfigOrFail ( 'email.webmaster' ) ) ; $ this -> Flash -> success ( I18N_OPERATION_OK ) ; return $ this -> redirect ( [ 'action' => 'index' ] ) ; }
Sends a backup file via mail
18,774
public function setURL ( $ url ) { if ( ! $ this -> validateURL ( $ url ) ) { throw new \ InvalidArgumentException ( sprintf ( 'The URL "%s" is invalid.' , $ url ) ) ; } $ this -> url = $ url ; $ this -> endpoint = null ; }
Set a URL to fetch from
18,775
public function removeProvider ( Provider $ provider ) { $ index = array_search ( $ provider , $ this -> providers ) ; if ( $ index !== false ) { unset ( $ this -> providers [ $ index ] ) ; } return $ this ; }
Removes the given provider from the registered providers array .
18,776
public function getObject ( array $ parameters = array ( ) ) { if ( $ this -> url === null ) { throw new \ InvalidArgumentException ( 'Missing URL.' ) ; } if ( $ this -> endpoint === null ) { $ this -> endpoint = $ this -> discover ( $ this -> url ) ; } $ sign = '?' ; if ( $ query = parse_url ( $ this -> endpoint , PHP_URL_QUERY ) ) { $ sign = '&' ; parse_str ( $ query , $ parameters ) ; } if ( ! isset ( $ parameters [ 'url' ] ) ) { $ parameters [ 'url' ] = $ this -> url ; } if ( ! isset ( $ parameters [ 'format' ] ) ) { $ parameters [ 'format' ] = 'json' ; } $ client = new Client ( sprintf ( '%s%s%s' , $ this -> endpoint , $ sign , http_build_query ( $ parameters ) ) ) ; $ data = $ client -> send ( ) ; switch ( $ parameters [ 'format' ] ) { case 'json' : $ data = json_decode ( $ data ) ; if ( ! is_object ( $ data ) ) { throw new \ InvalidArgumentException ( 'Could not parse JSON response.' ) ; } break ; case 'xml' : libxml_use_internal_errors ( true ) ; $ data = simplexml_load_string ( $ data ) ; if ( ! $ data instanceof \ SimpleXMLElement ) { $ errors = libxml_get_errors ( ) ; $ error = array_shift ( $ errors ) ; libxml_clear_errors ( ) ; libxml_use_internal_errors ( false ) ; throw new \ InvalidArgumentException ( $ error -> message , $ error -> code ) ; } break ; } return Object :: factory ( $ data ) ; }
Get the oEmbed response
18,777
protected function discover ( $ url ) { $ endpoint = $ this -> findEndpointFromProviders ( $ url ) ; if ( $ this -> discovery && ! $ endpoint ) { $ discover = new Discoverer ( ) ; $ endpoint = $ discover -> getEndpointForUrl ( $ url ) ; } if ( ! $ endpoint ) { throw new \ InvalidArgumentException ( 'No oEmbed links found.' ) ; } return $ endpoint ; }
Discover an oEmbed API endpoint
18,778
protected function findEndpointFromProviders ( $ url ) { foreach ( $ this -> providers as $ provider ) { if ( $ provider -> match ( $ url ) ) { return $ provider -> getEndpoint ( ) ; } } return null ; }
Finds an endpoint by looping trough the providers array and matching the url against the allowed schemes for each provider .
18,779
public function indexByDate ( $ date ) { if ( $ this -> request -> getQuery ( 'q' ) ) { return $ this -> redirect ( [ $ this -> request -> getQuery ( 'q' ) ] ) ; } list ( $ start , $ end ) = $ this -> getStartAndEndDate ( $ date ) ; $ page = $ this -> request -> getQuery ( 'page' , 1 ) ; $ cache = sprintf ( 'index_date_%s_limit_%s_page_%s' , md5 ( serialize ( [ $ start , $ end ] ) ) , $ this -> paginate [ 'limit' ] , $ page ) ; list ( $ posts , $ paging ) = array_values ( Cache :: readMany ( [ $ cache , sprintf ( '%s_paging' , $ cache ) ] , $ this -> Posts -> getCacheName ( ) ) ) ; if ( empty ( $ posts ) || empty ( $ paging ) ) { $ query = $ this -> Posts -> find ( 'active' ) -> find ( 'forIndex' ) -> where ( [ sprintf ( '%s.created >=' , $ this -> Posts -> getAlias ( ) ) => $ start , sprintf ( '%s.created <' , $ this -> Posts -> getAlias ( ) ) => $ end , ] ) ; $ posts = $ this -> paginate ( $ query ) ; Cache :: writeMany ( [ $ cache => $ posts , sprintf ( '%s_paging' , $ cache ) => $ this -> request -> getParam ( 'paging' ) , ] , $ this -> Posts -> getCacheName ( ) ) ; } else { $ this -> request = $ this -> request -> withParam ( 'paging' , $ paging ) ; } $ this -> set ( compact ( 'date' , 'posts' , 'start' ) ) ; }
Lists posts for a specific date .
18,780
public function rss ( ) { is_true_or_fail ( $ this -> RequestHandler -> prefers ( 'rss' ) , ForbiddenException :: class ) ; $ posts = $ this -> Posts -> find ( 'active' ) -> select ( [ 'title' , 'preview' , 'slug' , 'text' , 'created' ] ) -> limit ( getConfigOrFail ( 'default.records_for_rss' ) ) -> order ( [ sprintf ( '%s.created' , $ this -> Posts -> getAlias ( ) ) => 'DESC' ] ) -> cache ( 'rss' , $ this -> Posts -> getCacheName ( ) ) ; $ this -> set ( compact ( 'posts' ) ) ; }
Lists posts as RSS
18,781
public function preview ( $ slug = null ) { $ post = $ this -> Posts -> findPendingBySlug ( $ slug ) -> find ( 'forIndex' ) -> firstOrFail ( ) ; $ this -> set ( compact ( 'post' ) ) ; if ( getConfig ( 'post.related' ) ) { $ related = $ this -> Posts -> getRelated ( $ post , getConfigOrFail ( 'post.related.limit' ) , getConfig ( 'post.related.images' ) ) ; $ this -> set ( compact ( 'related' ) ) ; } $ this -> render ( 'view' ) ; }
Preview for posts . It uses the view template .
18,782
protected function extractImages ( $ html ) { if ( empty ( $ html ) ) { return [ ] ; } $ libxmlPreviousState = libxml_use_internal_errors ( true ) ; $ dom = new DOMDocument ; $ dom -> loadHTML ( $ html ) ; libxml_clear_errors ( ) ; libxml_use_internal_errors ( $ libxmlPreviousState ) ; $ images = [ ] ; foreach ( $ dom -> getElementsByTagName ( 'img' ) as $ item ) { $ src = $ item -> getAttribute ( 'src' ) ; if ( in_array ( strtolower ( pathinfo ( $ src , PATHINFO_EXTENSION ) ) , [ 'gif' , 'jpg' , 'jpeg' , 'png' ] ) ) { $ images [ ] = $ src ; } } if ( preg_match_all ( '/\[youtube](.+?)\[\/youtube]/' , $ html , $ items ) ) { foreach ( $ items [ 1 ] as $ item ) { $ images [ ] = Youtube :: getPreview ( $ item ) ; } } return $ images ; }
Internal method to extract all images from an html string including the previews of Youtube videos
18,783
public function getPreviews ( $ html ) { $ images = array_map ( function ( $ url ) { if ( $ url && ! is_url ( $ url ) ) { $ url = Folder :: isAbsolute ( $ url ) ? $ url : WWW_ROOT . 'img' . DS . $ url ; if ( ! file_exists ( $ url ) ) { return false ; } $ thumber = new ThumbCreator ( $ url ) ; $ thumber -> resize ( 1200 , 1200 ) -> save ( [ 'format' => 'jpg' ] ) ; $ url = $ thumber -> getUrl ( ) ; } list ( $ width , $ height ) = $ this -> getPreviewSize ( $ url ) ; return new Entity ( compact ( 'url' , 'width' , 'height' ) ) ; } , $ this -> extractImages ( $ html ) ) ; return array_filter ( $ images ) ; }
Gets all the available images from an html string including the previews of Youtube videos and returns an array of Entity
18,784
public function get ( $ resource , $ body = null , $ params = [ ] ) { return $ this -> send ( $ this -> prepare ( 'GET' , $ resource , $ body , $ params ) ) ; }
Perform a GET request for the specified resource .
18,785
public function post ( $ resource , $ body = null , $ params = [ ] ) { return $ this -> send ( $ this -> prepare ( 'POST' , $ resource , $ body , $ params ) ) ; }
Perform a POST request on the specified resource .
18,786
protected function send ( Request $ request ) { try { $ response = $ this -> client -> send ( $ request ) ; } catch ( ClientException $ e ) { $ response = $ e -> getResponse ( ) ; } catch ( ServerException $ e ) { $ response = $ e -> getResponse ( ) ; } return $ response ; }
Perform the given request and return the response .
18,787
protected function prepare ( $ method , $ resource , $ body , $ params ) { $ resource = trim ( $ resource , '/' ) . '/' . $ this -> username ; foreach ( $ params as $ param ) { $ resource .= '/' . $ param ; } return new Request ( $ method , $ resource , [ ] , $ body ) ; }
Prepare a request for sending .
18,788
protected function escapeControlCode ( $ cp ) { $ table = [ 9 => '\\t' , 10 => '\\n' , 13 => '\\r' ] ; return ( isset ( $ table [ $ cp ] ) ) ? $ table [ $ cp ] : $ this -> escapeAscii ( $ cp ) ; }
Escape given control code
18,789
public function bleed ( Bleeding $ bleeding , WoundsTable $ woundsTable , WoundBoundary $ woundBoundary ) : Wound { $ effectSize = $ bleeding -> getAfflictionSize ( ) -> getValue ( ) - 6 ; $ woundsFromTable = $ woundsTable -> toWounds ( new WoundsBonus ( $ effectSize , $ woundsTable ) ) ; $ woundSize = new WoundSize ( $ woundsFromTable -> getValue ( ) ) ; $ woundCausedBleeding = $ bleeding -> getSeriousWound ( ) ; return $ woundCausedBleeding -> getHealth ( ) -> addWound ( $ woundSize , $ woundCausedBleeding -> getWoundOriginCode ( ) , $ woundBoundary ) ; }
Creates new wound right in the health of origin wound
18,790
public function create ( $ params ) { $ client = new Client ; $ client -> fill ( $ params ) ; $ client -> save ( ) ; $ this -> generateDataciteSymbol ( $ client ) ; return $ client ; }
Create a client
18,791
public function generateDataciteSymbol ( Client $ client ) { $ prefix = "ANDS." ; $ id = $ client -> client_id ; if ( $ id < 100 ) { $ prefix .= "CENTRE" ; } if ( $ id < 10 ) { $ prefix .= "-" ; } elseif ( $ id >= 100 ) { $ prefix .= "C" ; } $ client -> datacite_symbol = $ prefix . $ id ; $ client -> save ( ) ; return $ client ; }
Generate a datacite symbol for the given client ANDS . CENTRE - 1 ANDS . CENTRE - 9 ANDS . CENTRE10 ANDS . CENTRE99 ANDS . C100 ANDS . C102
18,792
public function postParam ( string $ name , $ valueDefault = null ) { return $ this -> params -> post ( $ name , $ valueDefault ) ; }
Post param .
18,793
public function cookieParam ( string $ name , $ valueDefault = null ) { return $ this -> params -> cookie ( $ name , $ valueDefault ) ; }
Cookie param .
18,794
private function loadHttpHeaders ( ) : array { if ( function_exists ( 'getallheaders' ) ) { $ headers = getallheaders ( ) ; } else { $ headers = [ ] ; foreach ( $ _SERVER as $ key => $ value ) { if ( stripos ( strval ( $ key ) , 'HTTP_' ) === 0 ) { $ headers [ implode ( '-' , array_map ( 'ucwords' , explode ( '_' , strtolower ( substr ( $ key , 5 ) ) ) ) ) ] = $ value ; } } } if ( isset ( $ _SERVER [ 'CONTENT_TYPE' ] ) ) { $ headers [ 'Content-Type' ] = $ _SERVER [ 'CONTENT_TYPE' ] ; } if ( isset ( $ _SERVER [ 'CONTENT_LENGTH' ] ) ) { $ headers [ 'Content-Length' ] = $ _SERVER [ 'CONTENT_LENGTH' ] ; } if ( isset ( $ _SERVER [ 'CONTENT_MD5' ] ) ) { $ headers [ 'Content-MD5' ] = $ _SERVER [ 'CONTENT_MD5' ] ; } if ( ! isset ( $ headers [ 'Authorization' ] ) ) { if ( isset ( $ _SERVER [ 'REDIRECT_HTTP_AUTHORIZATION' ] ) ) { $ headers [ 'Authorization' ] = $ _SERVER [ 'REDIRECT_HTTP_AUTHORIZATION' ] ; } elseif ( isset ( $ _SERVER [ 'PHP_AUTH_DIGEST' ] ) ) { $ headers [ 'Authorization' ] = $ _SERVER [ 'PHP_AUTH_DIGEST' ] ; } elseif ( isset ( $ _SERVER [ 'PHP_AUTH_USER' ] ) ) { $ headers [ 'Authorization' ] = 'Basic ' . base64_encode ( $ _SERVER [ 'PHP_AUTH_USER' ] . ':' . ( $ _SERVER [ 'PHP_AUTH_PW' ] ?? '' ) ) ; } } return $ headers ; }
Load http headers .
18,795
public static function validate ( $ ip , $ ip_range ) { $ ip_ranges = explode ( ',' , $ ip_range ) ; foreach ( $ ip_ranges as $ ip_range ) { $ ip_range = explode ( '-' , $ ip_range ) ; if ( sizeof ( $ ip_range ) > 1 ) { $ target_ip = ip2long ( $ ip ) ; if ( count ( $ ip_range ) == 2 && $ target_ip ) { $ lower_bound = ip2long ( $ ip_range [ 0 ] ) ; $ upper_bound = ip2long ( $ ip_range [ 1 ] ) ; if ( $ target_ip >= $ lower_bound && $ target_ip <= $ upper_bound ) { return true ; } } } else { if ( self :: ip_match ( $ ip , $ ip_range [ 0 ] ) ) { return true ; } } } return false ; }
Test a string free form IP against a range
18,796
public static function ip_match ( $ ip , $ match ) { if ( ip2long ( $ match ) ) { if ( $ ip == $ match ) { return true ; } } else { if ( strpos ( $ match , '/' ) ) { if ( self :: cidr_match ( $ ip , $ match ) ) { return true ; } } else { $ match = gethostbyname ( $ match ) ; if ( $ ip == $ match ) { return true ; } else { return false ; } } } return false ; }
a helper function for test_ip
18,797
public function getMalusFromLoad ( Strength $ strength , Weight $ cargoWeight ) : int { $ requiredStrength = $ cargoWeight -> getBonus ( ) -> getValue ( ) ; $ missingStrength = $ requiredStrength - $ strength -> getValue ( ) ; $ malus = - SumAndRound :: half ( $ missingStrength ) ; if ( $ malus > 0 ) { return 0 ; } return $ malus ; }
Affects activities using strength agility or knack see PPH page 113 right column bottom .
18,798
public static function getThemes ( $ array = true ) { $ criteria = new CDbCriteria ; $ model = self :: model ( ) -> findAll ( $ criteria ) ; if ( $ array == true ) { $ items = array ( ) ; if ( $ model != null ) { foreach ( $ model as $ key => $ val ) { $ items [ $ val -> theme_id ] = $ val -> name ; } return $ items ; } else return false ; } else return $ model ; }
getThemes 0 = unpublish 1 = publish
18,799
public function login_as ( ) { $ oUserModel = Factory :: model ( 'User' , 'nails/module-auth' ) ; $ oUri = Factory :: service ( 'Uri' ) ; $ sHashId = $ oUri -> segment ( 4 ) ; $ sHashPw = $ oUri -> segment ( 5 ) ; $ oUser = $ oUserModel -> getByHashes ( $ sHashId , $ sHashPw ) ; if ( ! $ oUser ) { show404 ( ) ; } $ oSession = Factory :: service ( 'Session' , 'nails/module-auth' ) ; if ( ! wasAdmin ( ) ) { $ bHasPermission = userHasPermission ( 'admin:auth:accounts:loginAs' ) ; $ bIsCloning = activeUser ( 'id' ) == $ oUser -> id ; $ bIsSuperuser = ! isSuperuser ( ) && isSuperuser ( $ oUser ) ? true : false ; if ( ! $ bHasPermission || $ bIsCloning || $ bIsSuperuser ) { if ( ! $ bHasPermission ) { $ oSession -> setFlashData ( 'error' , lang ( 'auth_override_fail_nopermission' ) ) ; redirect ( 'admin/dashboard' ) ; } elseif ( $ bIsCloning ) { show404 ( ) ; } elseif ( $ bIsSuperuser ) { show404 ( ) ; } } } $ oInput = Factory :: service ( 'Input' ) ; if ( ! $ oInput -> get ( 'returningAdmin' ) && isAdmin ( ) ) { $ oUserModel -> setAdminRecoveryData ( $ oUser -> id , $ oInput -> get ( 'return_to' ) ) ; $ sRedirectUrl = $ oUser -> group_homepage ; $ sStatus = 'success' ; $ sMessage = lang ( 'auth_override_ok' , $ oUser -> first_name . ' ' . $ oUser -> last_name ) ; } elseif ( wasAdmin ( ) ) { $ oRecoveryData = getAdminRecoveryData ( ) ; $ sRedirectUrl = ! empty ( $ oRecoveryData -> returnTo ) ? $ oRecoveryData -> returnTo : $ oUser -> group_homepage ; unsetAdminRecoveryData ( ) ; $ sStatus = 'success' ; $ sMessage = lang ( 'auth_override_return' , $ oUser -> first_name . ' ' . $ oUser -> last_name ) ; } else { $ sRedirectUrl = $ oUser -> group_homepage ; $ sStatus = 'success' ; $ sMessage = lang ( 'auth_override_ok' , $ oUser -> first_name . ' ' . $ oUser -> last_name ) ; } $ oUserModel -> setLoginData ( $ oUser -> id ) ; if ( ! empty ( $ sMessage ) ) { $ oSession -> setFlashData ( $ sStatus , $ sMessage ) ; } redirect ( $ sRedirectUrl ) ; }
Log in as another user