idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
18,800
public static function fromTimestampWithMicroseconds ( int $ timestamp ) : self { $ seconds = ( int ) ( $ timestamp / 10 ** 6 ) ; $ microseconds = $ timestamp - ( $ seconds * 10 ** 6 ) ; $ microseconds = str_pad ( $ microseconds , 6 , '0' , STR_PAD_LEFT ) ; return static :: fromFormat ( 'U.u' , $ seconds . '.' . $ microseconds ) ; }
Creates a new instance from a microsecond - precision unix timestamp .
18,801
public function withDateAt ( int $ year = null , int $ month = null , int $ day = null ) : self { if ( null === $ year && null === $ month && null === $ day ) { return $ this ; } $ year = $ year === null ? $ this -> year ( ) : $ year ; $ month = $ month ? : $ this -> month ( ) ; $ day = $ day ? : $ this -> day ( ) ; $ instance = clone $ this ; $ instance -> date -> setDate ( $ year , $ month , $ day ) ; return $ instance ; }
Returns a new instance with the date set accordingly .
18,802
public function withDateAtStartOfYear ( ) : self { $ instance = $ this -> withTimeAtMidnight ( ) ; $ instance -> date -> setDate ( $ instance -> format ( 'Y' ) , 1 , 1 ) ; return $ instance ; }
Returns a new instance with the date set to 1st of Jan in the current year and time set to midnight .
18,803
public function withDateAtEndOfMonth ( ) : self { $ instance = $ this -> withDateAtStartOfMonth ( ) ; $ instance -> date -> modify ( '+1 month' ) ; $ instance -> date -> modify ( '-1 day' ) ; return $ instance ; }
Returns a new instance with the date set to last day of the current month and time set to midnight .
18,804
public function withDateAtDayOfWeekInMonth ( int $ dayOfWeek , int $ occurrence ) : self { self :: assertValidDayOfWeek ( $ dayOfWeek ) ; if ( $ occurrence < - 5 || $ occurrence === 0 || $ occurrence > 5 ) { throw new \ InvalidArgumentException ( "Invalid occurrence: $occurrence." ) ; } $ calendar = $ this -> createCalendar ( ) ; if ( ++ $ dayOfWeek === 8 ) { $ dayOfWeek = 1 ; } $ calendar -> set ( \ IntlCalendar :: FIELD_DAY_OF_WEEK , $ dayOfWeek ) ; $ calendar -> set ( \ IntlCalendar :: FIELD_DAY_OF_WEEK_IN_MONTH , $ occurrence ) ; return static :: fromIntlCalendar ( $ calendar ) ; }
Returns a new instance with the date set to the specified instance of the week day in the current month .
18,805
public function withTimeAt ( int $ hour = null , int $ minute = null , int $ second = null , int $ microsecond = null ) : self { $ instance = clone $ this ; $ hour = $ hour === null ? $ this -> hour ( ) : $ hour ; $ minute = $ minute === null ? $ this -> minute ( ) : $ minute ; $ second = $ second === null ? $ this -> second ( ) : $ second ; $ microsecond = $ microsecond === null ? $ this -> microsecond ( ) : $ microsecond ; $ instance -> date -> setTime ( $ hour , $ minute , $ second ) ; $ format = 'Y-m-d H:i:s' ; $ value = $ instance -> format ( $ format ) . '.' . substr ( $ microsecond , 0 , 6 ) ; $ instance -> date = \ DateTime :: createFromFormat ( "$format.u" , $ value ) ; return $ instance ; }
Returns a new instance with the time set accordingly .
18,806
public function withTimeZone ( \ DateTimeZone $ timezone ) : self { if ( $ this -> timezone ( ) -> getName ( ) === $ timezone -> getName ( ) ) { return $ this ; } $ instance = clone $ this ; $ instance -> date -> setTimezone ( $ timezone ) ; return $ instance ; }
Returns a new instance with the specified timezone .
18,807
public function subtract ( $ interval ) : self { $ instance = clone $ this ; $ instance -> date -> sub ( self :: resolveDateInterval ( $ interval ) ) ; return $ instance ; }
Creates a new instance with the interval subtracted from it .
18,808
public function add ( $ interval ) : self { $ instance = clone $ this ; $ instance -> date -> add ( self :: resolveDateInterval ( $ interval ) ) ; return $ instance ; }
Creates a new instance with the interval added to it .
18,809
public function modify ( string $ specification ) : self { $ instance = clone $ this ; $ instance -> date -> modify ( $ specification ) ; return $ instance ; }
Creates a new instance modified according to the specification .
18,810
public function contains ( DateTime $ dateTime ) : bool { return $ this -> from -> isEarlierThanOrEqualTo ( $ dateTime ) && $ this -> until -> isLaterThan ( $ dateTime ) ; }
Determines if the range contains a specified date and time .
18,811
public function equals ( self $ other ) : bool { if ( $ other === $ this ) { return true ; } return $ other -> from -> equals ( $ this -> from ) && $ other -> until -> equals ( $ this -> until ) ; }
Determines if an instance is equal to this instance .
18,812
private function dateDiff ( ) : DateInterval { if ( null === $ this -> dateDiff ) { $ this -> dateDiff = $ this -> from -> withTimeAtMidnight ( ) -> diff ( $ this -> until -> withTimeAtMidnight ( ) ) ; } return $ this -> dateDiff ; }
A diff between the two dates with times set to midnight to guarantee resolution to whole days .
18,813
private function fullDiff ( ) : DateInterval { if ( null === $ this -> fullDiff ) { $ this -> fullDiff = $ this -> from -> diff ( $ this -> until ) ; } return $ this -> fullDiff ; }
A full diff between the two dates .
18,814
protected function applyObjectConditions ( ) { if ( $ this -> object !== null ) { $ this -> andWhere ( Db :: parseParam ( 'objectId' , $ this -> object ) ) ; } }
Apply query specific conditions
18,815
public function requestLoginToken ( ) { $ session = $ this -> container -> sessionHandler ; $ email = $ this -> container -> emailHandler ; $ security = $ this -> container -> accessHandler ; $ userMapper = ( $ this -> container -> dataMapper ) ( 'UserMapper' ) ; $ body = $ this -> request -> getParsedBody ( ) ; $ userList = $ userMapper -> find ( ) ; $ providedEmail = strtolower ( trim ( $ body [ 'email' ] ) ) ; $ foundValidUser = false ; foreach ( $ userList as $ user ) { if ( $ user -> email === $ providedEmail ) { $ foundValidUser = $ user ; break ; } } if ( ! $ foundValidUser ) { $ this -> container -> logger -> alert ( 'Failed login attempt: ' . $ body [ 'email' ] ) ; return $ this -> redirect ( 'home' ) ; } if ( $ foundValidUser -> email === $ providedEmail ) { $ token = $ security -> generateLoginToken ( ) ; $ session -> setData ( [ $ this -> loginTokenKey => $ token , $ this -> loginTokenExpiresKey => time ( ) + 120 , 'user_id' => $ foundValidUser -> id , 'email' => $ foundValidUser -> email ] ) ; $ scheme = $ this -> request -> getUri ( ) -> getScheme ( ) ; $ host = $ this -> request -> getUri ( ) -> getHost ( ) ; $ link = $ scheme . '://' . $ host ; $ link .= $ this -> container -> router -> pathFor ( 'adminProcessLoginToken' , [ 'token' => $ token ] ) ; $ email -> setTo ( $ providedEmail , '' ) -> setSubject ( 'PitonCMS Login' ) -> setMessage ( "Click to login\n\n {$link}" ) -> send ( ) ; } return $ this -> redirect ( 'home' ) ; }
Request Login Token
18,816
public function processLoginToken ( $ args ) { $ session = $ this -> container -> sessionHandler ; $ security = $ this -> container -> accessHandler ; $ savedToken = $ session -> getData ( $ this -> loginTokenKey ) ; $ tokenExpires = $ session -> getData ( $ this -> loginTokenExpiresKey ) ; if ( $ args [ 'token' ] === $ savedToken && time ( ) < $ tokenExpires ) { $ security -> startAuthenticatedSession ( ) ; $ session -> unsetData ( $ this -> loginTokenKey ) ; $ session -> unsetData ( $ this -> loginTokenExpiresKey ) ; return $ this -> redirect ( 'adminHome' ) ; } $ message = $ args [ 'token' ] . ' saved: ' . $ savedToken . ' time: ' . time ( ) . ' expires: ' . $ tokenExpires ; $ this -> container -> logger -> info ( 'Invalid login token, supplied: ' . $ message ) ; return $ this -> notFound ( ) ; }
Process Login Token
18,817
public function showSettings ( ) { $ settingMapper = ( $ this -> container -> dataMapper ) ( 'SettingMapper' ) ; $ json = $ this -> container -> json ; $ allSettings = $ settingMapper -> findSiteSettings ( ) ; $ jsonFilePath = ROOT_DIR . "structure/definitions/customSettings.json" ; if ( null === $ customSettings = $ json -> getJson ( $ jsonFilePath , 'setting' ) ) { $ this -> setAlert ( 'danger' , 'Custom Settings Error' , $ json -> getErrorMessages ( ) ) ; } else { $ allSettings = $ this -> mergeSettings ( $ allSettings , $ customSettings -> settings ) ; } return $ this -> render ( 'editSettings.html' , $ allSettings ) ; }
Manage Site Settings
18,818
public function lookForBrokenLinks ( $ postId = null , $ url = null ) { \ BrokenLinkDetector \ App :: checkInstall ( ) ; $ foundUrls = array ( ) ; if ( $ url ) { $ url = "REGEXP ('.*(href=\"{$url}\").*')" ; } else { $ url = "RLIKE ('href=*')" ; } global $ wpdb ; $ sql = " SELECT ID, post_content FROM $wpdb->posts WHERE post_content {$url} AND post_type NOT IN ('attachment', 'revision', 'acf', 'acf-field', 'acf-field-group') AND post_status IN ('publish', 'private', 'password') " ; if ( is_numeric ( $ postId ) ) { $ sql .= " AND ID = $postId" ; } $ posts = $ wpdb -> get_results ( $ sql ) ; if ( is_array ( $ posts ) && ! empty ( $ posts ) ) { foreach ( $ posts as $ post ) { preg_match_all ( '/<a[^>]+href=([\'"])(http|https)(.+?)\1[^>]*>/i' , $ post -> post_content , $ m ) ; if ( ! isset ( $ m [ 3 ] ) || count ( $ m [ 3 ] ) > 0 ) { foreach ( $ m [ 3 ] as $ key => $ url ) { $ url = $ m [ 2 ] [ $ key ] . $ url ; if ( preg_match ( '/\s/' , $ url ) ) { $ newUrl = preg_replace ( '/ /' , '%20' , $ url ) ; $ wpdb -> query ( $ wpdb -> prepare ( "UPDATE $wpdb->posts SET post_content = REPLACE(post_content, %s, %s) WHERE post_content LIKE %s AND ID = %d" , $ url , $ newUrl , '%' . $ wpdb -> esc_like ( $ url ) . '%' , $ post -> ID ) ) ; $ url = $ newUrl ; } if ( $ postId !== 'internal' && ! $ this -> isBroken ( $ url ) ) { continue ; } $ foundUrls [ ] = array ( 'post_id' => $ post -> ID , 'url' => $ url ) ; } } } } $ this -> saveBrokenLinks ( $ foundUrls , $ postId ) ; }
Look for broken links in post_content
18,819
public function isBroken ( $ url ) { if ( ! $ domain = parse_url ( $ url , PHP_URL_HOST ) ) { return true ; } if ( in_array ( $ domain , ( array ) apply_filters ( 'brokenLinks/External/ExceptedDomains' , array ( ) ) ) ) { return false ; } if ( count ( explode ( '.' , $ domain ) ) == count ( array_filter ( explode ( '.' , $ domain ) , function ( $ var ) { if ( strlen ( $ var ) < 1 ) { return false ; } return true ; } ) ) ) { try { $ punycode = new Punycode ( ) ; $ domainAscii = $ punycode -> encode ( $ domain ) ; $ url = str_ireplace ( $ domain , $ domainAscii , $ url ) ; } catch ( Exception $ e ) { return false ; } } if ( $ this -> isInternal ( $ url ) ) { return false ; } if ( ! $ this -> isValidDomainName ( isset ( $ domainAscii ) ? $ domainAscii : $ domain ) ) { return true ; } return ! $ this -> isDomainAvailable ( $ url ) ; }
Test if domain is valid with different methods
18,820
public function isDomainAvailable ( $ url , $ timeOut = 7 ) { $ ch = curl_init ( $ url ) ; curl_setopt ( $ ch , CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13' ) ; curl_setopt ( $ ch , CURLOPT_CONNECTTIMEOUT , $ timeOut ) ; curl_setopt ( $ ch , CURLOPT_HEADER , 1 ) ; curl_setopt ( $ ch , CURLOPT_HTTPGET , 1 ) ; curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER , 1 ) ; curl_setopt ( $ ch , CURLOPT_FOLLOWLOCATION , 1 ) ; curl_setopt ( $ ch , CURLOPT_MAXREDIRS , 5 ) ; curl_setopt ( $ ch , CURLOPT_SSL_VERIFYHOST , 0 ) ; curl_setopt ( $ ch , CURLOPT_SSL_VERIFYPEER , 0 ) ; $ response = curl_exec ( $ ch ) ; $ httpCode = curl_getinfo ( $ ch , CURLINFO_HTTP_CODE ) ; $ curlError = curl_error ( $ ch ) ; $ curlErrorNo = curl_errno ( $ ch ) ; curl_close ( $ ch ) ; if ( $ curlErrorNo ) { if ( in_array ( $ curlErrorNo , array ( CURLE_TOO_MANY_REDIRECTS ) ) ) { if ( defined ( "BROKEN_LINKS_LOG" ) && BROKEN_LINKS_LOG ) { error_log ( "Broken links: Could not probe url " . $ url . " due to a malfunction of curl [" . $ curlErrorNo . " - " . $ curlError . "]" ) ; } return true ; } else { if ( defined ( "BROKEN_LINKS_LOG" ) && BROKEN_LINKS_LOG ) { error_log ( "Broken links: Could not probe url " . $ url . ", link is considerd broken [" . $ curlErrorNo . " - " . $ curlError . "]" ) ; } return false ; } } if ( defined ( "BROKEN_LINKS_LOG" ) && BROKEN_LINKS_LOG ) { error_log ( "Broken links: Probe data " . $ url . " [Curl error no: " . $ curlErrorNo . "] [Curl error message:" . $ curlError . "] [Http code: " . $ httpCode . "]" ) ; } if ( $ response ) { if ( $ httpCode >= 200 && $ httpCode < 400 ) { return true ; } if ( in_array ( $ httpCode , array ( 401 , 406 , 413 ) ) ) { return true ; } } return false ; }
Test if domain is available with curl
18,821
public function isInternal ( $ url ) { $ postId = url_to_postid ( $ url ) ; if ( $ postId > 0 ) { return true ; } $ siteUrlComponents = parse_url ( get_site_url ( ) ) ; $ urlComponents = parse_url ( $ url ) ; if ( ! empty ( $ siteUrlComponents [ 'host' ] ) && ! empty ( $ urlComponents [ 'host' ] ) && strcasecmp ( $ urlComponents [ 'host' ] , $ siteUrlComponents [ 'host' ] ) === 0 ) { $ postTypes = get_post_types ( array ( 'public' => true ) ) ; if ( ! empty ( $ urlComponents [ 'path' ] ) && ! empty ( get_page_by_path ( basename ( untrailingslashit ( $ urlComponents [ 'path' ] ) ) , ARRAY_A , $ postTypes ) ) ) { return true ; } } return false ; }
Test if URL is internal and page exist
18,822
public function call ( $ presenter , array $ data = [ ] ) { $ response = $ this -> builder -> getView ( ) -> start ( $ this -> request , $ this -> response ) -> call ( $ presenter , $ data ) ; return $ this -> returnResponseBody ( $ response ) ; }
call a presenter object and renders the content .
18,823
public function render ( $ viewFile , $ data = [ ] ) { return $ this -> builder -> getView ( ) -> start ( $ this -> request , $ this -> response ) -> renderContents ( $ viewFile , $ data ) ; }
renders another template .
18,824
public function setIdent ( $ ident ) { if ( $ ident === null ) { $ this -> ident = null ; return $ this ; } if ( ! is_string ( $ ident ) ) { throw new InvalidArgumentException ( 'Ident needs to be a string' ) ; } $ this -> ident = $ ident ; return $ this ; }
Set the queue item s ID .
18,825
public function process ( callable $ callback = null , callable $ successCallback = null , callable $ failureCallback = null ) { if ( $ this -> processed ( ) === true ) { return null ; } $ email = $ this -> emailFactory ( ) -> create ( 'email' ) ; $ email -> setData ( $ this -> data ( ) ) ; try { $ res = $ email -> send ( ) ; if ( $ res === true ) { $ this -> setProcessed ( true ) ; $ this -> setProcessedDate ( 'now' ) ; $ this -> update ( [ 'processed' , 'processed_date' ] ) ; if ( $ successCallback !== null ) { $ successCallback ( $ this ) ; } } else { if ( $ failureCallback !== null ) { $ failureCallback ( $ this ) ; } } if ( $ callback !== null ) { $ callback ( $ this ) ; } return $ res ; } catch ( Exception $ e ) { if ( $ failureCallback !== null ) { $ failureCallback ( $ this ) ; } return false ; } }
Process the item .
18,826
public function home ( ) { $ json = $ this -> container -> json ; if ( null === $ definition = $ json -> getJson ( ROOT_DIR . '/composer.lock' ) ) { $ this -> setAlert ( 'danger' , 'Error Reading composer.lock' , $ json -> getErrorMessages ( ) ) ; } $ engineKey = array_search ( 'pitoncms/engine' , array_column ( $ definition -> packages , 'name' ) ) ; $ engineVersion = $ definition -> packages [ $ engineKey ] -> version ; return $ this -> render ( 'home.html' , [ 'pitonEngineVersion' => $ engineVersion ] ) ; }
Admin Home Page
18,827
public function release ( $ args ) { $ json = $ this -> container -> json ; $ markdown = $ this -> container -> markdownParser ; $ responseBody = '' ; if ( ! function_exists ( 'curl_init' ) ) { $ this -> setAlert ( 'warning' , 'Required PHP cURL not installed' ) ; } else { $ githubApi = 'https://api.github.com/repos/PitonCMS/Engine/releases' ; $ curl = curl_init ( ) ; curl_setopt_array ( $ curl , [ CURLOPT_RETURNTRANSFER => true , CURLOPT_URL => $ githubApi , CURLOPT_USERAGENT => $ this -> request -> getHeaderLine ( 'HTTP_USER_AGENT' ) ] ) ; $ responseBody = curl_exec ( $ curl ) ; $ responseStatus = curl_getinfo ( $ curl , CURLINFO_HTTP_CODE ) ; curl_close ( $ curl ) ; if ( $ responseStatus == '200' ) { $ releases = json_decode ( $ responseBody ) ; $ releases = array_slice ( $ releases , 0 , 5 , true ) ; foreach ( $ releases as $ key => $ release ) { $ releases [ $ key ] -> body = $ markdown -> text ( $ release -> body ) ; } if ( array_search ( $ args [ 'release' ] , array_column ( $ releases , 'tag_name' ) ) > 0 ) { $ message = "The current version is {$releases[0]->tag_name}, you have version {$args['release']}." ; $ message .= "\nTo upgrade, from your project root run <code>composer update pitoncms/engine</code>" ; $ this -> setAlert ( 'info' , 'There is a newer version of the PitonCMS Engine' , $ message ) ; } } else { $ releases = [ ] ; $ this -> setAlert ( 'warning' , "$responseStatus Response From GitHub" , $ responseBody ) ; } } return $ this -> render ( 'releaseNotes.html' , [ 'releases' => $ releases ] ) ; }
Show Piton Engine Release Notes
18,828
public function onBootstrap ( MvcEvent $ e ) { $ events = $ e -> getApplication ( ) -> getEventManager ( ) ; $ events -> attach ( MvcEvent :: EVENT_RENDER , new InjectSubNavigationListener ( ) , 10 ) ; }
Sets up services on the bootstrap event .
18,829
public function getEndpointForUrl ( $ url ) { if ( ! isset ( $ this -> cachedEndpoints [ $ url ] ) ) { $ this -> cachedEndpoints [ $ url ] = $ this -> fetchEndpointForUrl ( $ url ) ; } return $ this -> cachedEndpoints [ $ url ] ; }
Get the provider s endpoint URL for the supplied resource
18,830
protected function fetchEndpointForUrl ( $ url ) { $ client = new Client ( $ url ) ; $ body = $ client -> send ( ) ; $ regexp = str_replace ( '@formats@' , implode ( '|' , $ this -> supportedFormats ) , self :: LINK_REGEXP ) ; if ( ! preg_match_all ( $ regexp , $ body , $ matches , PREG_SET_ORDER ) ) { throw new \ InvalidArgumentException ( 'No valid oEmbed links found on page.' ) ; } foreach ( $ matches as $ match ) { if ( $ match [ 'Format' ] === $ this -> preferredFormat ) { return $ this -> extractEndpointFromAttributes ( $ match [ 'Attributes' ] ) ; } } return $ this -> extractEndpointFromAttributes ( $ match [ 'Attributes' ] ) ; }
Fetch the provider s endpoint URL for the supplied resource
18,831
public static function lowest ( ... $ datetimes ) { $ lowest = null ; foreach ( $ datetimes as $ datetime ) { if ( ! $ datetime instanceof \ DateTimeInterface ) { continue ; } if ( $ datetime < $ lowest || null === $ lowest ) { $ lowest = $ datetime ; } } return $ lowest ; }
Get the lowest DateTimeInterface from the parameters
18,832
public function authenticate ( $ appID , $ sharedSecret = null , $ ipAddress = null , $ manual = false ) { $ this -> setResponse ( 'app_id' , $ appID ) ; $ client = $ this -> clientRepo -> authenticate ( $ appID , $ sharedSecret , $ ipAddress , $ manual ) ; if ( $ client ) { $ this -> setAuthenticatedClient ( $ client ) ; return true ; } $ this -> setResponse ( 'responsecode' , 'MT009' ) ; $ this -> setResponse ( 'verbosemessage' , $ this -> clientRepo -> getMessage ( ) ) ; $ this -> clientRepo -> setMessage ( null ) ; return false ; }
Authenticate a client
18,833
public function isDoiAuthenticatedClients ( $ doiValue , $ client_id = null ) { if ( $ client_id === null ) { return false ; } $ client = $ this -> getAuthenticatedClient ( ) ; if ( $ client -> client_id != $ client_id ) { return false ; } if ( strpos ( $ doiValue , DOIServiceProvider :: $ globalTestPrefix ) === 0 ) { return true ; } foreach ( $ client -> prefixes as $ clientPrefix ) { if ( strpos ( $ doiValue , $ clientPrefix -> prefix -> prefix_value ) === 0 ) { return true ; } } return false ; }
Returns if a client is authenticated
18,834
public function mint ( $ url , $ xml , $ manual = false ) { if ( ! $ this -> isClientAuthenticated ( ) ) { $ this -> setResponse ( "responsecode" , "MT009" ) ; return false ; } $ this -> setResponse ( 'url' , $ url ) ; $ validDomain = URLValidator :: validDomains ( $ url , $ this -> getAuthenticatedClient ( ) -> domains ) ; if ( ! $ validDomain ) { $ this -> setResponse ( "responsecode" , "MT014" ) ; return false ; } if ( $ manual === true ) { $ doiValue = XMLValidator :: getDOIValue ( $ xml ) ; } else { $ doiValue = $ this -> getNewDOI ( ) ; $ xml = XMLValidator :: replaceDOIValue ( $ doiValue , $ xml ) ; } $ this -> setResponse ( 'doi' , $ doiValue ) ; if ( $ this -> validateXML ( $ xml ) === false ) { $ this -> setResponse ( 'responsecode' , 'MT006' ) ; return false ; } $ doi = $ this -> insertNewDOI ( $ doiValue , $ xml , $ url ) ; $ result = $ this -> dataciteClient -> mint ( $ doiValue , $ url , $ xml ) ; if ( $ result === true ) { $ this -> setResponse ( 'responsecode' , 'MT001' ) ; $ this -> doiRepo -> doiUpdate ( $ doi , array ( 'status' => 'ACTIVE' ) ) ; } else { $ this -> setResponse ( 'responsecode' , 'MT005' ) ; $ this -> setResponse ( 'verbosemessage' , array_first ( $ this -> dataciteClient -> getErrors ( ) ) ) ; } return $ result ; }
Mint a new DOI
18,835
public function validateXML ( $ xml ) { $ xmlValidator = new XMLValidator ( ) ; $ result = $ xmlValidator -> validateSchemaVersion ( $ xml ) ; if ( $ result === false ) { $ this -> setResponse ( "verbosemessage" , $ xmlValidator -> getValidationMessage ( ) ) ; return false ; } return true ; }
Returns true if xml is datacite valid else false and sets error
18,836
public function getNewDOI ( ) { $ prefix = "" ; $ testStr = "" ; $ client = $ this -> getAuthenticatedClient ( ) ; if ( sizeof ( $ client -> prefixes ) > 0 && $ client -> mode !== 'test' ) { foreach ( $ client -> prefixes as $ clientPrefix ) { if ( $ clientPrefix -> active && $ clientPrefix -> is_test == 0 ) { $ prefix = $ clientPrefix -> prefix -> prefix_value ; break ; } } } if ( sizeof ( $ client -> prefixes ) > 0 && $ client -> mode == 'test' ) { foreach ( $ client -> prefixes as $ clientPrefix ) { if ( $ clientPrefix -> active && $ clientPrefix -> is_test == 1 ) { $ prefix = $ clientPrefix -> prefix -> prefix_value ; $ testStr = "TEST_DOI_" ; break ; } } } $ prefix = ends_with ( $ prefix , '/' ) ? $ prefix : $ prefix . '/' ; $ doiValue = uniqid ( ) ; return $ prefix . $ testStr . $ doiValue ; }
Returns a new DOI for the currently existing authenticated client if client has no active prefix it probably means it s a test client
18,837
public function update ( $ doiValue , $ url = NULL , $ xml = NULL ) { if ( ! $ this -> isClientAuthenticated ( ) ) { $ this -> setResponse ( "responsecode" , "MT009" ) ; return false ; } $ doi = $ this -> doiRepo -> getByID ( $ doiValue ) ; $ this -> setResponse ( 'doi' , $ doiValue ) ; if ( $ doi === null ) { $ this -> setResponse ( 'responsecode' , 'MT011' ) ; return true ; } if ( ! $ this -> isDoiAuthenticatedClients ( $ doiValue , $ doi -> client_id ) ) { $ this -> setResponse ( 'responsecode' , 'MT008' ) ; $ this -> setResponse ( 'verbosemessage' , $ doiValue . " is not owned by " . $ this -> getAuthenticatedClient ( ) -> client_name ) ; return false ; } if ( isset ( $ url ) && $ url != "" ) { $ this -> setResponse ( 'url' , $ url ) ; $ validDomain = URLValidator :: validDomains ( $ url , $ this -> getAuthenticatedClient ( ) -> domains ) ; if ( ! $ validDomain ) { $ this -> setResponse ( "responsecode" , "MT014" ) ; return false ; } } if ( isset ( $ xml ) && $ xml != "" ) { $ xml = XMLValidator :: replaceDOIValue ( $ doiValue , $ xml ) ; if ( $ this -> validateXML ( $ xml ) === false ) { $ this -> setResponse ( 'responsecode' , 'MT007' ) ; return false ; } } if ( isset ( $ url ) && $ url != "" ) { $ result = $ this -> dataciteClient -> updateURL ( $ doiValue , $ url ) ; if ( $ result === true ) { $ this -> setResponse ( 'responsecode' , 'MT002' ) ; $ this -> doiRepo -> doiUpdate ( $ doi , array ( 'url' => $ url ) ) ; } else { $ this -> setResponse ( 'responsecode' , 'MT010' ) ; $ this -> setResponse ( 'verbosemessage' , array_first ( $ this -> dataciteClient -> getErrors ( ) ) ) ; return false ; } } if ( isset ( $ xml ) && $ xml != "" ) { $ result = $ this -> dataciteClient -> update ( $ xml ) ; if ( $ result === true ) { $ this -> setResponse ( 'responsecode' , 'MT002' ) ; $ this -> doiRepo -> doiUpdate ( $ doi , array ( 'datacite_xml' => $ xml , 'status' => 'ACTIVE' ) ) ; } else { $ this -> setResponse ( 'responsecode' , 'MT010' ) ; $ this -> setResponse ( 'verbosemessage' , array_first ( $ this -> dataciteClient -> getErrors ( ) ) ) ; return false ; } } return true ; }
Update a DOI
18,838
public function activate ( $ doiValue ) { if ( ! $ this -> isClientAuthenticated ( ) ) { $ this -> setResponse ( 'responsecode' , 'MT009' ) ; return false ; } $ doi = $ this -> doiRepo -> getByID ( $ doiValue ) ; $ this -> setResponse ( 'doi' , $ doiValue ) ; if ( $ doi === null ) { $ this -> setResponse ( 'responsecode' , 'MT011' ) ; return true ; } if ( ! $ this -> isDoiAuthenticatedClients ( $ doiValue , $ doi -> client_id ) ) { $ this -> setResponse ( 'responsecode' , 'MT008' ) ; $ this -> setResponse ( 'verbosemessage' , $ doiValue . " is not owned by " . $ this -> getAuthenticatedClient ( ) -> client_name ) ; return false ; } $ doi_xml = $ doi -> datacite_xml ; if ( $ doi -> status != 'INACTIVE' ) { $ this -> setResponse ( 'responsecode' , 'MT010' ) ; $ this -> setResponse ( 'verbosemessage' , 'DOI ' . $ doiValue . " not set to INACTIVE so cannot activate it" ) ; return false ; } $ result = $ this -> dataciteClient -> update ( $ doi_xml ) ; if ( $ result === true ) { $ this -> setResponse ( 'responsecode' , 'MT004' ) ; $ this -> doiRepo -> doiUpdate ( $ doi , array ( 'status' => 'ACTIVE' ) ) ; } else { $ this -> setResponse ( 'responsecode' , 'MT010' ) ; } return $ result ; }
Activate a DOI
18,839
public function getStatus ( $ doiValue ) { if ( ! $ this -> isClientAuthenticated ( ) ) { $ this -> setResponse ( 'responsecode' , 'MT009' ) ; return false ; } $ doi = $ this -> doiRepo -> getByID ( $ doiValue ) ; $ this -> setResponse ( 'doi' , $ doiValue ) ; if ( $ doi === null ) { $ this -> setResponse ( 'responsecode' , 'MT011' ) ; return true ; } if ( ! $ this -> isDoiAuthenticatedClients ( $ doiValue , $ doi -> client_id ) ) { $ this -> setResponse ( 'responsecode' , 'MT008' ) ; $ this -> setResponse ( 'verbosemessage' , $ doiValue . " is not owned by " . $ this -> getAuthenticatedClient ( ) -> client_name ) ; return false ; } $ this -> setResponse ( 'responsecode' , 'MT019' ) ; $ this -> setResponse ( 'verbosemessage' , $ doi -> status ) ; return true ; }
get status of the DOI
18,840
public function deactivate ( $ doiValue ) { if ( ! $ this -> isClientAuthenticated ( ) ) { $ this -> setResponse ( 'responsecode' , 'MT009' ) ; return false ; } $ doi = $ this -> doiRepo -> getByID ( $ doiValue ) ; $ this -> setResponse ( 'doi' , $ doiValue ) ; if ( $ doi === null ) { $ this -> setResponse ( 'responsecode' , 'MT011' ) ; return true ; } if ( ! $ this -> isDoiAuthenticatedClients ( $ doiValue , $ doi -> client_id ) ) { $ this -> setResponse ( 'responsecode' , 'MT008' ) ; $ this -> setResponse ( 'verbosemessage' , $ doiValue . " is not owned by " . $ this -> getAuthenticatedClient ( ) -> client_name ) ; return false ; } if ( $ doi -> status != 'ACTIVE' ) { $ this -> setResponse ( 'responsecode' , 'MT010' ) ; $ this -> setResponse ( 'verbosemessage' , 'DOI ' . $ doiValue . " not set to ACTIVE so cannot deactivate it" ) ; return false ; } $ result = $ this -> dataciteClient -> deActivate ( $ doiValue ) ; if ( $ result === true ) { $ this -> setResponse ( 'responsecode' , 'MT003' ) ; $ this -> doiRepo -> doiUpdate ( $ doi , array ( 'status' => 'INACTIVE' ) ) ; } else { $ this -> setResponse ( 'responsecode' , 'MT010' ) ; } return $ result ; }
Deactivate a DOI
18,841
private function guardLevelBoundaries ( $ levelValue ) { if ( $ levelValue < static :: MIN_LEVEL ) { throw new Exceptions \ MinLevelUnderflow ( 'Level has to be at least ' . self :: MIN_LEVEL . ', got ' . $ levelValue ) ; } if ( $ levelValue > static :: MAX_LEVEL ) { throw new Exceptions \ MaxLevelOverflow ( 'Level can not be greater than ' . self :: MAX_LEVEL . ', got ' . $ levelValue ) ; } }
Level is not limited by table values so has to be in code
18,842
public static function toJson ( $ e , bool $ getTrace = true , string $ catcher = null ) : string { if ( ! $ getTrace ) { return \ json_encode ( [ 'msg' => "Error: {$e->getMessage()}" ] ) ; } $ map = [ 'code' => $ e -> getCode ( ) ? : 500 , 'msg' => sprintf ( '%s(%d): %s, File: %s(Line %d)' , \ get_class ( $ e ) , $ e -> getCode ( ) , $ e -> getMessage ( ) , $ e -> getFile ( ) , $ e -> getLine ( ) ) , 'data' => $ e -> getTrace ( ) ] ; if ( $ catcher ) { $ map [ 'catcher' ] = $ catcher ; } if ( $ getTrace ) { $ map [ 'trace' ] = $ e -> getTrace ( ) ; } return \ json_encode ( $ map ) ; }
Converts an exception into a json string .
18,843
public static function normalizeFilesArray ( array $ files ) : array { $ return = [ ] ; foreach ( $ files as $ i => $ file ) { foreach ( $ file as $ key => $ value ) { $ return [ $ key ] [ $ i ] = $ value ; } } return $ return ; }
Normalize files array .
18,844
public function index ( ) { $ page = $ this -> request -> getQuery ( 'page' , 1 ) ; $ this -> paginate [ 'order' ] = [ 'tag' => 'ASC' ] ; $ this -> paginate [ 'limit' ] = $ this -> paginate [ 'maxLimit' ] = $ this -> paginate [ 'limit' ] * 4 ; $ cache = sprintf ( 'tags_limit_%s_page_%s' , $ this -> paginate [ 'limit' ] , $ page ) ; list ( $ tags , $ paging ) = array_values ( Cache :: readMany ( [ $ cache , sprintf ( '%s_paging' , $ cache ) ] , $ this -> PostsTags -> getCacheName ( ) ) ) ; if ( empty ( $ tags ) || empty ( $ paging ) ) { $ query = $ this -> PostsTags -> Tags -> find ( 'active' ) ; $ tags = $ this -> paginate ( $ query ) ; Cache :: writeMany ( [ $ cache => $ tags , sprintf ( '%s_paging' , $ cache ) => $ this -> request -> getParam ( 'paging' ) , ] , $ this -> PostsTags -> getCacheName ( ) ) ; } else { $ this -> request = $ this -> request -> withParam ( 'paging' , $ paging ) ; } $ this -> set ( compact ( 'tags' ) ) ; }
Lists posts tags
18,845
public function view ( $ slug = null ) { if ( $ this -> request -> getQuery ( 'q' ) ) { return $ this -> redirect ( [ $ this -> request -> getQuery ( 'q' ) ] ) ; } $ slug = Text :: slug ( $ slug , [ 'replacement' => ' ' ] ) ; $ tag = $ this -> PostsTags -> Tags -> findActiveByTag ( $ slug ) -> cache ( ( sprintf ( 'tag_%s' , md5 ( $ slug ) ) ) , $ this -> PostsTags -> getCacheName ( ) ) -> firstOrFail ( ) ; $ page = $ this -> request -> getQuery ( 'page' , 1 ) ; $ cache = sprintf ( 'tag_%s_limit_%s_page_%s' , md5 ( $ slug ) , $ this -> paginate [ 'limit' ] , $ page ) ; list ( $ posts , $ paging ) = array_values ( Cache :: readMany ( [ $ cache , sprintf ( '%s_paging' , $ cache ) ] , $ this -> PostsTags -> getCacheName ( ) ) ) ; if ( empty ( $ posts ) || empty ( $ paging ) ) { $ query = $ this -> PostsTags -> Posts -> find ( 'active' ) -> find ( 'forIndex' ) -> matching ( $ this -> PostsTags -> Tags -> getAlias ( ) , function ( Query $ q ) use ( $ slug ) { return $ q -> where ( [ 'tag' => $ slug ] ) ; } ) ; $ posts = $ this -> paginate ( $ query ) ; Cache :: writeMany ( [ $ cache => $ posts , sprintf ( '%s_paging' , $ cache ) => $ this -> request -> getParam ( 'paging' ) , ] , $ this -> PostsTags -> getCacheName ( ) ) ; } else { $ this -> request = $ this -> request -> withParam ( 'paging' , $ paging ) ; } $ this -> set ( compact ( 'posts' , 'tag' ) ) ; }
Lists posts for a tag
18,846
public function execute ( Arguments $ args , ConsoleIo $ io ) { $ this -> loadModel ( 'MeCms.UsersGroups' ) ; if ( ! $ this -> UsersGroups -> find ( ) -> isEmpty ( ) ) { $ io -> error ( __d ( 'me_cms' , 'Some user groups already exist' ) ) ; return null ; } ConnectionManager :: get ( 'default' ) -> execute ( sprintf ( 'TRUNCATE TABLE `%s`' , $ this -> UsersGroups -> getTable ( ) ) ) ; $ this -> UsersGroups -> saveMany ( $ this -> UsersGroups -> newEntities ( [ [ 'id' => 1 , 'name' => 'admin' , 'label' => 'Admin' ] , [ 'id' => 2 , 'name' => 'manager' , 'label' => 'Manager' ] , [ 'id' => 3 , 'name' => 'user' , 'label' => 'User' ] , ] ) ) ; $ io -> verbose ( __d ( 'me_cms' , 'The user groups have been created' ) ) ; return null ; }
Creates the user groups
18,847
public function getCurrentMalus ( ) : int { if ( $ this -> getGettingUsedToForRounds ( ) === 0 ) { return $ this -> malus ; } if ( $ this -> isShined ( ) ) { return $ this -> malus + $ this -> getGettingUsedToForRounds ( ) ; } return $ this -> malus + SumAndRound :: floor ( $ this -> getGettingUsedToForRounds ( ) / 10 ) ; }
Gives malus to activities requiring sight already lowered by a time getting used to the glare if any .
18,848
public function setGettingUsedToForTime ( Time $ gettingUsedToFor ) { $ inRounds = $ gettingUsedToFor -> findRounds ( ) ; if ( $ inRounds === null ) { if ( $ this -> isShined ( ) ) { $ this -> gettingUsedToForRounds = - $ this -> malus ; } else { $ this -> gettingUsedToForRounds = - $ this -> malus * 10 ; } return ; } if ( $ this -> isShined ( ) ) { if ( $ this -> malus + $ inRounds -> getValue ( ) > 0 ) { $ this -> gettingUsedToForRounds = - $ this -> malus ; } else { $ this -> gettingUsedToForRounds = $ inRounds -> getValue ( ) ; } } else { if ( $ this -> malus + $ inRounds -> getValue ( ) / 10 > 0 ) { $ this -> gettingUsedToForRounds = - $ this -> malus * 10 ; } else { $ this -> gettingUsedToForRounds = $ inRounds -> getValue ( ) ; } } }
Total rounds of getting used to current contrast which lowers glare and malus .
18,849
protected function loginUser ( ) { $ oUserModel = Factory :: model ( 'User' , 'nails/module-auth' ) ; $ oUserModel -> setLoginData ( $ this -> mfaUser -> id ) ; if ( $ this -> remember ) { $ oUserModel -> setRememberCookie ( $ this -> mfaUser -> id , $ this -> mfaUser -> password , $ this -> mfaUser -> email ) ; } $ oUserModel -> updateLastLogin ( $ this -> mfaUser -> id ) ; create_event ( 'did_log_in' , [ 'method' => $ this -> loginMethod ] , $ this -> mfaUser -> id ) ; if ( $ this -> mfaUser -> last_login ) { $ oConfig = Factory :: service ( 'Config' ) ; if ( $ oConfig -> item ( 'authShowNicetimeOnLogin' ) ) { $ sLastLogin = niceTime ( strtotime ( $ this -> mfaUser -> last_login ) ) ; } else { $ sLastLogin = toUserDatetime ( $ this -> mfaUser -> last_login ) ; } if ( $ oConfig -> item ( 'authShowLastIpOnLogin' ) ) { $ sStatus = 'positive' ; $ sMessage = lang ( 'auth_login_ok_welcome_with_ip' , [ $ this -> mfaUser -> first_name , $ sLastLogin , $ this -> mfaUser -> last_ip , ] ) ; } else { $ sStatus = 'positive' ; $ sMessage = lang ( 'auth_login_ok_welcome' , [ $ this -> mfaUser -> first_name , $ sLastLogin , ] ) ; } } else { $ sStatus = 'positive' ; $ sMessage = lang ( 'auth_login_ok_welcome_notime' , [ $ this -> mfaUser -> first_name , ] ) ; } $ oSession = Factory :: service ( 'Session' , 'nails/module-auth' ) ; $ oSession -> setFlashData ( $ sStatus , $ sMessage ) ; $ oAuthModel = Factory :: model ( 'Auth' , 'nails/module-auth' ) ; $ oAuthModel -> mfaTokenDelete ( $ this -> data [ 'token' ] [ 'id' ] ) ; $ sRedirectUrl = $ this -> returnTo != site_url ( ) ? $ this -> returnTo : $ this -> mfaUser -> group_homepage ; redirect ( $ sRedirectUrl ) ; }
Logs a user In
18,850
public function loadSettings ( ) { $ SettingMapper = ( $ this -> dataMapper ) ( 'SettingMapper' ) ; $ siteSettings = $ SettingMapper -> find ( ) ; $ this -> settings = array_column ( $ siteSettings , 'setting_value' , 'setting_key' ) ; $ this -> settings [ 'production' ] = $ this -> appSettings [ 'site' ] [ 'production' ] ; $ this -> settings [ 'pitonDev' ] = isset ( $ this -> appSettings [ 'site' ] [ 'pitonDev' ] ) ? $ this -> appSettings [ 'site' ] [ 'pitonDev' ] : false ; }
Load settings from DB
18,851
public function loadPages ( $ request ) { $ pageMapper = ( $ this -> dataMapper ) ( 'pageMapper' ) ; $ this -> pages = $ pageMapper -> findPages ( ) ; $ url = $ request -> getUri ( ) -> getPath ( ) ; $ url = ( $ url === '/' ) ? 'home' : ltrim ( $ url , '/' ) ; $ key = array_search ( $ url , array_column ( $ this -> pages , 'slug' ) ) ; if ( is_numeric ( $ key ) ) { $ this -> pages [ $ key ] -> currentPage = true ; } return ; }
Load pages from DB
18,852
public function getValue ( Db $ db , ... $ args ) { $ driver = $ this -> driverKey ( $ db ) ; if ( isset ( $ this -> driverValues [ $ driver ] ) ) { return sprintf ( $ this -> driverValues [ $ driver ] , ... $ args ) ; } elseif ( isset ( $ this -> driverValues [ 'default' ] ) ) { return sprintf ( $ this -> driverValues [ 'default' ] , ... $ args ) ; } else { throw new \ InvalidArgumentException ( "No literal for driver '$driver'." , 500 ) ; } }
Get the literal value .
18,853
public function setValue ( $ value , $ driver = 'default' ) { $ driver = $ this -> driverKey ( $ driver ) ; $ this -> driverValues [ $ driver ] = $ value ; return $ this ; }
Set the literal value .
18,854
protected function driverKey ( $ key ) { if ( is_object ( $ key ) ) { $ key = get_class ( $ key ) ; } $ key = strtolower ( basename ( $ key ) ) ; if ( preg_match ( '`([az]+)(Db)?$`' , $ key , $ m ) ) { $ key = $ m ; } return $ key ; }
Normalize the driver name for the drivers array .
18,855
public static function getOptions ( $ userSpecified , $ defaults ) { $ options = static :: getAnyOptions ( $ userSpecified , $ defaults ) ; foreach ( $ options as $ key => $ null ) { if ( array_key_exists ( $ key , $ defaults ) ) { continue ; } throw new \ InvalidArgumentException ( "Unknown parameter (" . $ key . ")" ) ; } return $ options ; }
Simulate named arguments using associative arrays . Basically just merge the two arrays giving user specified options the preference . Also ensures that each paramater in the user array is valid and throws an exception if an unknown element is found .
18,856
public static function toString ( $ data ) { if ( is_array ( $ data ) ) { $ newData = [ ] ; foreach ( $ data as $ key => $ val ) { $ key = ( string ) $ key ; $ newData [ $ key ] = static :: toString ( $ val ) ; } } else { $ newData = ( string ) $ data ; } return $ newData ; }
Ensure that the passed parameter is a string or an array of strings .
18,857
public static function toArray ( $ value ) { if ( is_array ( $ value ) ) { return $ value ; } if ( $ value instanceof SerialObject ) { return $ value -> asArray ( ) ; } if ( $ value instanceof \ ArrayObject ) { return $ value -> getArrayCopy ( ) ; } $ array = [ ] ; if ( $ value ) { $ array [ ] = $ value ; } return $ array ; }
Ensure that the passed parameter is an array . If it is a truthy value then make it the sole element of an array .
18,858
public static function dateDiff ( $ from , $ to = null ) { if ( ! $ to ) { $ to = $ from ; $ from = date ( "d/m/Y" ) ; } if ( ! $ dateFrom = static :: date ( "U" , $ from ) ) { return ; } if ( ! $ dateTo = static :: date ( "U" , $ to ) ) { return ; } $ diff = $ dateTo - $ dateFrom ; $ days = round ( $ diff / 86400 ) ; return $ days ; }
Compare two dates and return an integer representing their difference in days . Returns null if any of the parsing fails .
18,859
public static function getBestDivisor ( $ rows , $ options = null ) { $ options = static :: getOptions ( $ options , [ "min" => 5 , "max" => 10 , ] ) ; if ( $ rows <= $ options [ "max" ] ) { return $ rows ; } $ divisor = false ; $ divisorDiff = false ; for ( $ i = $ options [ "max" ] ; $ i >= $ options [ "min" ] ; $ i -- ) { $ remain = $ rows % $ i ; $ quality = $ i - $ remain ; if ( ! $ num ) { $ divisor = $ i ; $ divisorQuality = $ quality ; continue ; } if ( $ quality < $ divisorQuality ) { $ divisor = $ i ; $ divisorQuality = $ quality ; } } return $ divisor ; }
Calculate the most reasonable divisor for a total . Useful for repeating headers in a table with many rows .
18,860
public static function createPassword ( $ options = null ) { $ options = static :: getOptions ( $ options , [ "bad" => [ "1" , "l" , "I" , "5" , "S" , "0" , "O" , "o" ] , "exclude" => [ ] , "length" => 10 , "lowercase" => true , "uppercase" => true , "numbers" => true , "specialchars" => true , ] ) ; $ password = "" ; if ( ! $ options [ "lowercase" ] && ! $ options [ "specialchars" ] && ! $ options [ "numbers" ] && ! $ options [ "uppercase" ] ) { return $ password ; } $ exclude = array_merge ( $ options [ "bad" ] , $ options [ "exclude" ] ) ; while ( mb_strlen ( $ password ) < $ options [ "length" ] ) { if ( $ options [ "lowercase" ] ) { $ max = rand ( 1 , 3 ) ; for ( $ i = 0 ; $ i < $ max ; ++ $ i ) { $ password .= chr ( rand ( 97 , 122 ) ) ; } } if ( $ options [ "specialchars" ] ) { $ max = rand ( 1 , 3 ) ; for ( $ i = 0 ; $ i < $ max ; ++ $ i ) { switch ( rand ( 0 , 3 ) ) { case 0 : $ password .= chr ( rand ( 33 , 47 ) ) ; break ; case 1 : $ password .= chr ( rand ( 58 , 64 ) ) ; break ; case 2 : $ password .= chr ( rand ( 91 , 93 ) ) ; break ; case 3 : $ password .= chr ( rand ( 123 , 126 ) ) ; break ; } } } if ( $ options [ "numbers" ] ) { $ max = rand ( 1 , 3 ) ; for ( $ i = 0 ; $ i < $ max ; ++ $ i ) { $ password .= chr ( rand ( 48 , 57 ) ) ; } } if ( $ options [ "uppercase" ] ) { $ max = rand ( 1 , 3 ) ; for ( $ i = 0 ; $ i < $ max ; ++ $ i ) { $ password .= chr ( rand ( 65 , 90 ) ) ; } } $ password = str_replace ( $ exclude , "" , $ password ) ; } $ password = mb_substr ( $ password , 0 , $ options [ "length" ] ) ; return $ password ; }
Generate a password .
18,861
public static function checkPassword ( $ password , $ options = null ) { $ options = static :: getOptions ( $ options , [ "length" => 8 , "unique" => 4 , "lowercase" => true , "uppercase" => true , "alpha" => true , "numeric" => true , ] ) ; $ problems = [ ] ; $ len = mb_strlen ( $ password ) ; if ( $ len < $ options [ "length" ] ) { $ problems [ "length" ] = "Passwords must be at least " . $ options [ "length" ] . " characters long" ; } $ unique = [ ] ; for ( $ i = 0 ; $ i < $ len ; ++ $ i ) { $ char = mb_substr ( $ password , $ i , 1 ) ; if ( ! in_array ( $ char , $ unique ) ) { $ unique [ ] = $ char ; } } if ( count ( $ unique ) < $ options [ "unique" ] ) { $ problems [ "unique" ] = "Passwords must contain at least " . $ options [ "unique" ] . " unique characters" ; } if ( ! preg_match ( "/[a-z]/" , $ password ) ) { $ problems [ "lowercase" ] = "Passwords must contain at least 1 lowercase letter" ; } if ( ! preg_match ( "/[A-Z]/" , $ password ) ) { $ problems [ "uppercase" ] = "Passwords must contain at least 1 uppercase letter" ; } if ( ! preg_match ( "/[a-z]/i" , $ password ) ) { $ problems [ "alpha" ] = "Passwords must contain at least 1 letter" ; } if ( ! preg_match ( "/[0-9]/" , $ password ) ) { $ problems [ "numeric" ] = "Passwords must contain at least 1 number" ; } return $ problems ; }
Check if a password conforms to the specified complexitiy rules . If the password passes all tests then the function returns an empty array . Otherwise it returns an array of all the checks that failed .
18,862
public function setType ( $ type ) { if ( $ type === null ) { $ type = self :: TYPE_UNDEFINED ; } $ this -> type = $ type ; return $ this ; }
Sets message type .
18,863
public function initEventsManager ( ) { $ taskListener = new TaskListener ( ) ; $ eventsManager = $ this -> di -> getShared ( 'eventsManager' ) ; $ eventsManager -> attach ( 'console:beforeHandleTask' , $ taskListener -> beforeHandleTask ( $ this -> arguments ) ) ; $ eventsManager -> attach ( 'console:afterHandleTask' , $ taskListener -> afterHandleTask ( ) ) ; $ this -> application -> setEventsManager ( $ eventsManager ) ; }
Setups CLI events manager
18,864
public static function create ( $ body , DescriptionFactory $ descriptionFactory = null , Context $ context = null ) { Assert :: integerish ( $ body , self :: MSG ) ; Assert :: greaterThanEq ( $ body , 0 , self :: MSG ) ; Assert :: notNull ( $ descriptionFactory ) ; return new static ( $ descriptionFactory -> create ( $ body , $ context ) ) ; }
Create the tag
18,865
protected function detectResourcesBaseUri ( ) { $ uri = '' ; $ request = $ this -> getHttpRequest ( ) ; if ( $ request instanceof HttpRequest ) { $ uri = $ request -> getBaseUri ( ) ; } return ( string ) $ uri ; }
Detects and returns the website s base URI
18,866
public function getService ( $ name ) { try { if ( ! $ this -> isRegisteredService ( $ name ) ) { $ this -> registerService ( $ name ) ; } return $ this -> di -> get ( $ name ) ; } catch ( \ Phalcon \ DI \ Exception $ ex ) { throw new Exception ( $ ex -> getMessage ( ) . ', using: ' . $ name ) ; } }
Try to register and return service .
18,867
public function hasService ( $ name ) { try { $ service = $ this -> getService ( $ name ) ; return ! empty ( $ service ) ; } catch ( \ Vegas \ DI \ Service \ Exception $ ex ) { return false ; } }
Try to register service and return information about service existence .
18,868
protected function jsonResponse ( $ data = array ( ) ) { $ this -> view -> disable ( ) ; $ this -> response -> setContentType ( 'application/json' , 'UTF-8' ) ; return $ this -> response -> setJsonContent ( $ data ) ; }
Renders JSON response Disables view
18,869
protected function getForce ( PropertyMappingConfigurationInterface $ configuration = null ) { if ( $ configuration === null ) { throw new InvalidPropertyMappingConfigurationException ( 'Missing property configuration' , 1457516367 ) ; } return ( boolean ) $ configuration -> getConfigurationValue ( PackageConverter :: class , self :: FORCE ) ; }
Is force mode enabled
18,870
public static function getCurrencies ( $ symbols = null ) { $ currencies = Cache :: call ( "get-currencies" , function ( ) { $ currencies = Yaml :: decodeFromFile ( __DIR__ . "/../data/currencies.yaml" ) ; if ( $ currencies instanceof SerialObject ) { $ currencies = $ currencies -> asArray ( ) ; } return array_map ( function ( $ data ) { if ( ! isset ( $ data [ "prefix" ] ) ) { $ data [ "prefix" ] = "" ; } if ( ! isset ( $ data [ "suffix" ] ) ) { $ data [ "suffix" ] = "" ; } return $ data ; } , $ currencies ) ; } ) ; if ( $ symbols ) { return $ currencies ; } $ return = [ ] ; foreach ( $ currencies as $ key => $ val ) { $ return [ $ key ] = $ val [ "title" ] ; } return $ return ; }
Get the currencies supported by the Html class methods .
18,871
public static function formatKey ( $ key , $ options = null ) { $ options = Helper :: getOptions ( $ options , [ "underscores" => true , "ucwords" => true , ] ) ; if ( $ options [ "underscores" ] ) { $ val = str_replace ( "_" , "&nbsp;" , $ key ) ; } if ( $ options [ "ucwords" ] ) { $ val = ucwords ( $ val ) ; } return $ val ; }
Format a string in a human readable way . Typically used for converting safe strings like section_title to user displayable strings like Section Title
18,872
public static function string ( $ string , $ options = null ) { $ options = Helper :: getOptions ( $ options , [ "alt" => "n/a" , ] ) ; $ string = trim ( $ string ) ; if ( ! $ string ) { return $ options [ "alt" ] ; } return $ string ; }
Trim a string and return an alternative if it is falsey .
18,873
public static function stringLimit ( $ string , $ options = null ) { $ options = Helper :: getOptions ( $ options , [ "length" => 30 , "extra" => 0 , "alt" => "n/a" , "words" => true , "suffix" => "..." , ] ) ; if ( ! $ string = trim ( $ string ) ) { return $ options [ "alt" ] ; } if ( $ options [ "words" ] ) { while ( mb_strlen ( $ string ) > ( $ options [ "length" ] + $ options [ "extra" ] ) ) { $ string = mb_substr ( $ string , 0 , $ options [ "length" ] ) ; $ string = trim ( $ string ) ; $ words = explode ( " " , $ string ) ; array_pop ( $ words ) ; $ string = implode ( " " , $ words ) ; $ string .= $ options [ "suffix" ] ; } } else { $ length = $ options [ "length" ] + $ options [ "extra" ] + mb_strlen ( $ options [ "suffix" ] ) ; if ( mb_strlen ( $ string ) > $ length ) { $ string = mb_substr ( $ string , 0 , $ length ) ; $ string .= $ options [ "suffix" ] ; } } return $ string ; }
Limit a string to a maximum length .
18,874
public function parseArguments ( Console $ console , $ arguments ) { $ this -> consoleApp = $ console ; if ( count ( $ arguments ) == 1 ) { throw new TaskNotFoundException ( ) ; } $ taskName = $ this -> lookupTaskClass ( $ arguments ) ; $ parsedArguments = array ( 'task' => $ taskName , 'action' => isset ( $ arguments [ 2 ] ) ? $ arguments [ 2 ] : false ) ; $ parsedArguments [ ] = count ( $ arguments ) > 3 ? array_slice ( $ arguments , 3 ) : array ( ) ; return $ parsedArguments ; }
Parses indicated arguments from command line Returns prepared array with task action and additional arguments
18,875
private function toNamespace ( $ str ) { $ stringParts = preg_split ( '/_+/' , $ str ) ; foreach ( $ stringParts as $ key => $ stringPart ) { $ stringParts [ $ key ] = ucfirst ( strtolower ( $ stringPart ) ) ; } return implode ( '\\' , $ stringParts ) . '\\' ; }
Converts indicated string to namespace format .
18,876
private function loadAppTask ( array $ task ) { if ( count ( $ task ) > 2 ) { $ moduleName = ucfirst ( $ task [ 1 ] ) ; $ taskName = ucfirst ( $ task [ 2 ] ) ; $ taskName = $ this -> loadAppModuleTask ( $ moduleName , $ taskName ) ; } else { $ taskName = ucfirst ( $ task [ 1 ] ) ; } return $ taskName ; }
Loads task from application directory
18,877
private function loadAppModuleTask ( $ moduleName , $ taskName ) { $ modules = $ this -> consoleApp -> getModules ( ) ; if ( ! isset ( $ modules [ $ moduleName ] ) ) { throw new TaskNotFoundException ( ) ; } $ fullNamespace = strtr ( '\:moduleName\Tasks\:taskName' , array ( ':moduleName' => $ moduleName , ':taskName' => $ taskName ) ) ; $ this -> registerClass ( $ fullNamespace . 'Task' ) ; return $ fullNamespace ; }
Loads task from specified application module
18,878
private function loadCoreTask ( array $ task ) { if ( count ( $ task ) == 3 ) { $ namespace = $ this -> toNamespace ( $ task [ 1 ] ) ; $ taskName = ucfirst ( $ task [ 2 ] ) ; } else { $ namespace = '' ; $ taskName = ucfirst ( $ task [ 1 ] ) ; } $ fullNamespace = strtr ( '\Vegas\:namespaceTask\\:taskName' , array ( ':namespace' => $ namespace , ':taskName' => $ taskName ) ) ; $ this -> registerClass ( $ fullNamespace . 'Task' ) ; return $ fullNamespace ; }
Loads task from Vegas libraries mostly placed in vendor
18,879
public function createForumTopic ( $ forumID , $ authorID , $ title , $ post , $ extra = [ ] ) { $ data = [ "forum" => $ forumID , "author" => $ authorID , "title" => $ title , "post" => $ post ] ; $ data = array_merge ( $ data , $ extra ) ; $ validator = \ Validator :: make ( $ data , [ "forum" => "required|numeric" , "author" => "required|numeric" , "title" => "required|string" , "post" => "required|string" , "author_name" => "required_if:author,0|string" , "prefix" => "string" , "tags" => "string|is_csv_alphanumeric" , "date" => "date_format:YYYY-mm-dd H:i:s" , "ip_address" => "ip" , "locked" => "in:0,1" , "open_time" => "date_format:YYYY-mm-dd H:i:s" , "close_time" => "date_format:YYYY-mm-dd H:i:s" , "hidden" => "in:-1,0,1" , "pinned" => "in:0,1" , "featured" => "in:0,1" , ] , [ "is_csv_alphanumeric" => "The :attribute must be a comma separated string." , ] ) ; if ( $ validator -> fails ( ) ) { $ message = head ( array_flatten ( $ validator -> messages ( ) ) ) ; throw new Exceptions \ InvalidFormat ( $ message ) ; } return $ this -> postRequest ( "forums/topics" , $ data ) ; }
Create a forum topic with the given data .
18,880
public function updateForumTopic ( $ topicID , $ data = [ ] ) { $ validator = \ Validator :: make ( $ data , [ "forum" => "numeric" , "author" => "numeric" , "author_name" => "required_if:author,0|string" , "title" => "string" , "post" => "string" , "prefix" => "string" , "tags" => "string|is_csv_alphanumeric" , "date" => "date_format:YYYY-mm-dd H:i:s" , "ip_address" => "ip" , "locked" => "in:0,1" , "open_time" => "date_format:YYYY-mm-dd H:i:s" , "close_time" => "date_format:YYYY-mm-dd H:i:s" , "hidden" => "in:-1,0,1" , "pinned" => "in:0,1" , "featured" => "in:0,1" , ] , [ "is_csv_alphanumeric" => "The :attribute must be a comma separated string." , ] ) ; if ( $ validator -> fails ( ) ) { $ message = head ( array_flatten ( $ validator -> messages ( ) ) ) ; throw new Exceptions \ InvalidFormat ( $ message ) ; } return $ this -> postRequest ( "forums/topics/" . $ topicID , $ data ) ; }
Update a forum topic with the given ID .
18,881
public function beforeExecuteRoute ( ) { $ this -> actionName = $ this -> dispatcher -> getActionName ( ) ; $ this -> taskName = $ this -> dispatcher -> getTaskName ( ) ; $ this -> setupOptions ( ) ; $ this -> args = $ this -> dispatcher -> getParam ( 'args' ) ; if ( $ this -> containHelpOption ( $ this -> args ) ) { $ this -> renderActionHelp ( ) ; return false ; } try { $ this -> validate ( $ this -> args ) ; } catch ( InvalidArgumentException $ ex ) { $ this -> throwError ( strtr ( ':command: Invalid argument `:argument` for option `:option`' , [ ':command' => sprintf ( '%s %s' , $ this -> dispatcher -> getParam ( 'activeTask' ) , $ this -> dispatcher -> getParam ( 'activeAction' ) ) , ':option' => $ ex -> getOption ( ) , ':argument' => $ ex -> getArgument ( ) ] ) ) ; } catch ( InvalidOptionException $ ex ) { $ this -> throwError ( strtr ( ':command: Invalid option `:option`' , [ ':command' => sprintf ( '%s %s' , $ this -> dispatcher -> getParam ( 'activeTask' ) , $ this -> dispatcher -> getParam ( 'activeAction' ) ) , ':option' => $ ex -> getOption ( ) ] ) ) ; } return true ; }
Sets available actions with options Validates command line arguments and options for command Stops dispatching when detects help option
18,882
private function containHelpOption ( $ args ) { return array_key_exists ( self :: HELP_OPTION , $ args ) || array_key_exists ( self :: HELP_SHORTOPTION , $ args ) ; }
Determines if help option was typed in command line
18,883
protected function getOption ( $ name , $ default = null ) { $ matchedOption = null ; foreach ( $ this -> actions [ $ this -> actionName ] -> getOptions ( ) as $ option ) { if ( $ option -> matchParam ( $ name ) ) { $ matchedOption = $ option ; } } $ value = $ matchedOption -> getValue ( $ this -> args , $ default ) ; return $ value ; }
Get option value for action from command line
18,884
protected function renderActionHelp ( ) { $ action = $ this -> actions [ $ this -> actionName ] ; $ this -> appendLine ( $ this -> getColoredString ( $ action -> getDescription ( ) , 'green' ) ) ; $ this -> appendLine ( '' ) ; $ this -> appendLine ( 'Usage:' ) ; $ this -> appendLine ( $ this -> getColoredString ( sprintf ( ' %s %s [options]' , $ this -> dispatcher -> getParam ( 'activeTask' ) , $ this -> dispatcher -> getParam ( 'activeAction' ) ) , 'dark_gray' ) ) ; $ this -> appendLine ( '' ) ; $ this -> appendLine ( $ this -> getColoredString ( 'Options:' , 'gray' ) ) ; foreach ( $ action -> getOptions ( ) as $ option ) { $ this -> appendLine ( $ this -> getColoredString ( sprintf ( ' --%s -%s %s' , $ option -> getName ( ) , $ option -> getShortName ( ) , $ option -> getDescription ( ) ) , 'light_green' ) ) ; } }
Renders help for task action
18,885
protected function renderTaskHelp ( ) { $ this -> appendLine ( $ this -> getColoredString ( 'Available actions' , 'dark_gray' ) ) ; $ this -> appendLine ( PHP_EOL ) ; foreach ( $ this -> actions as $ action ) { $ this -> appendLine ( sprintf ( ' %s %s' , $ this -> getColoredString ( $ action -> getName ( ) , 'light_green' ) , $ this -> getColoredString ( $ action -> getDescription ( ) , 'green' ) ) ) ; } }
Renders help for task
18,886
protected function validate ( ) { $ args = $ this -> dispatcher -> getParam ( 'args' ) ; if ( isset ( $ this -> actions [ $ this -> actionName ] ) ) { $ action = $ this -> actions [ $ this -> actionName ] ; $ action -> validate ( $ args ) ; } }
Validates action options
18,887
protected function storeIntendedUrl ( ) { $ previousUrl = url ( ) -> previous ( ) ; $ loginUrl = url ( ) -> route ( $ this -> core -> prefixRoute ( NamedRoute :: AUTH_LOGIN ) ) ; if ( $ previousUrl == $ loginUrl ) return ; session ( ) -> put ( 'url.intended' , $ previousUrl ) ; }
Stores the intended URL to redirect to after succesful login .
18,888
private function toRegex ( string $ pattern ) : string { while ( \ preg_match ( self :: OPTIONAL_PLACEHOLDER_REGEX , $ pattern ) ) { $ pattern = \ preg_replace ( self :: OPTIONAL_PLACEHOLDER_REGEX , '($1)?' , $ pattern ) ; } $ pattern = \ preg_replace_callback ( self :: REQUIRED_PLACEHOLDER_REGEX , function ( array $ match = [ ] ) { $ match = \ array_pop ( $ match ) ; $ pos = \ mb_strpos ( $ match , self :: REGEX_PREFIX ) ; if ( false !== $ pos ) { $ parameterName = \ mb_substr ( $ match , 0 , $ pos ) ; $ parameterRegex = \ mb_substr ( $ match , $ pos + 2 ) ; return "(?<$parameterName>$parameterRegex)" ; } return "(?<$match>[^/]+)" ; } , $ pattern ) ; return $ pattern ; }
Transform a pattern into a regex .
18,889
public function add ( $ uri , $ method , $ controller , $ action ) { $ this -> currentRoute = [ 'uri' => $ uri , 'method' => $ method , 'controller' => $ controller , 'action' => $ action , 'module' => $ this -> module , ] ; if ( $ this -> currentGroupName ) { $ this -> virtualRoutes [ $ this -> currentGroupName ] [ ] = $ this -> currentRoute ; } else { $ this -> virtualRoutes [ '*' ] [ ] = $ this -> currentRoute ; } return $ this ; }
Adds new route entry to routes
18,890
public function group ( string $ groupName , \ Closure $ callback ) { $ this -> currentGroupName = $ groupName ; $ this -> isGroupe = TRUE ; $ this -> isGroupeMiddlewares = FALSE ; $ callback ( $ this ) ; $ this -> isGroupeMiddlewares = TRUE ; $ this -> currentGroupName = NULL ; return $ this ; }
Starts a named group of routes
18,891
public function middlewares ( array $ middlewares = [ ] ) { if ( ! $ this -> isGroupe ) { end ( $ this -> virtualRoutes [ '*' ] ) ; $ lastKey = key ( $ this -> virtualRoutes [ '*' ] ) ; $ this -> virtualRoutes [ '*' ] [ $ lastKey ] [ 'middlewares' ] = $ middlewares ; } else { end ( $ this -> virtualRoutes ) ; $ lastKeyOfFirstRound = key ( $ this -> virtualRoutes ) ; if ( ! $ this -> isGroupeMiddlewares ) { end ( $ this -> virtualRoutes [ $ lastKeyOfFirstRound ] ) ; $ lastKeyOfSecondRound = key ( $ this -> virtualRoutes [ $ lastKeyOfFirstRound ] ) ; $ this -> virtualRoutes [ $ lastKeyOfFirstRound ] [ $ lastKeyOfSecondRound ] [ 'middlewares' ] = $ middlewares ; } else { $ this -> isGroupe = FALSE ; foreach ( $ this -> virtualRoutes [ $ lastKeyOfFirstRound ] as & $ route ) { $ hasMiddleware = end ( $ route ) ; if ( ! is_array ( $ hasMiddleware ) ) { $ route [ 'middlewares' ] = $ middlewares ; } else { foreach ( $ middlewares as $ middleware ) { $ route [ 'middlewares' ] [ ] = $ middleware ; } } } } } }
Adds middlewares to routes and route groups
18,892
public function getRuntimeRoutes ( ) { $ runtimeRoutes = [ ] ; foreach ( $ this -> virtualRoutes as $ virtualRoute ) { foreach ( $ virtualRoute as $ route ) { $ runtimeRoutes [ ] = $ route ; } } return $ runtimeRoutes ; }
Gets the runtime routes
18,893
private function request ( $ method , $ function , $ extra = [ ] ) { $ response = null ; try { $ response = $ this -> httpRequest -> { $ method } ( $ function , $ extra ) -> getBody ( ) ; return json_decode ( $ response , false ) ; } catch ( ClientException $ e ) { $ this -> handleError ( $ e -> getResponse ( ) ) ; } }
Perform the specified request .
18,894
private function handleError ( $ response ) { $ error = json_decode ( $ response -> getBody ( ) , false ) ; $ errorCode = $ error -> errorCode ; try { if ( array_key_exists ( $ errorCode , $ this -> error_exceptions ) ) { throw new $ this -> error_exceptions [ $ errorCode ] ; } throw new $ this -> error_exceptions [ $ response -> getStatusCode ( ) ] ; } catch ( Exception $ e ) { throw new \ Exception ( "There was a malformed response from IPBoard." ) ; } }
Throw the error specific to the error code that has been returned .
18,895
public function validateMarkup ( array $ messageFilterConfiguration = array ( ) ) { $ markup = $ this -> markupProvider -> getMarkup ( ) ; $ messages = $ this -> markupValidator -> validate ( $ markup ) ; $ this -> messageFilter -> setConfiguration ( $ messageFilterConfiguration ) ; $ filteredMessages = $ this -> messageFilter -> filterMessages ( $ messages ) ; if ( empty ( $ filteredMessages ) === false ) { $ messagesString = $ this -> messagePrinter -> getMessagesString ( $ filteredMessages ) ; $ this -> fail ( $ messagesString ) ; } $ this -> assertTrue ( true ) ; }
Validates page markup via a markup validator . Allows to recongigure message filter component .
18,896
public static function run ( ) { try { $ router = new Router ( ) ; ( new ModuleLoader ( ) ) -> loadModules ( $ router ) ; $ router -> findRoute ( ) ; Environment :: load ( ) ; Config :: load ( ) ; Helpers :: load ( ) ; Libraries :: load ( ) ; $ mvcManager = new MvcManager ( ) ; $ mvcManager -> runMvc ( Router :: $ currentRoute ) ; } catch ( \ Exception $ e ) { echo $ e -> getMessage ( ) ; exit ; } }
Initializes the framework .
18,897
public function getLastMessage ( ) { $ filename = $ this -> getTempFilename ( ) ; if ( file_exists ( $ filename ) ) { $ result = unserialize ( file_get_contents ( $ filename ) ) ; } else { throw new Swift_IoException ( 'No last message found in "' . $ filename . '" - did you call send()?' ) ; } return $ result ; }
Returns the last message sent
18,898
private function validate ( ) { if ( empty ( $ this -> modelName ) && empty ( $ this -> model ) ) { throw new Exception \ ModelNotSetException ( ) ; } if ( empty ( $ this -> model ) ) { $ this -> model = new $ this -> modelName ( ) ; } if ( empty ( $ this -> modelName ) ) { $ this -> modelName = get_class ( $ this -> model ) ; } if ( empty ( $ this -> db ) ) { $ this -> db = $ this -> model -> getConnection ( ) ; } }
Validates model and database
18,899
public function getTotalPages ( ) { if ( empty ( $ this -> totalPages ) ) { $ this -> totalPages = ( int ) ceil ( $ this -> getCursor ( ) -> count ( ) / $ this -> limit ) ; } return $ this -> totalPages ; }
Returns number of pages