idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
18,500
public function logout ( ) { $ oUserModel = Factory :: model ( 'User' , 'nails/module-auth' ) ; $ oUserModel -> clearRememberCookie ( ) ; $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> set ( 'remember_code' , null ) ; $ oDb -> where ( 'id' , activeUser ( 'id' ) ) ; $ oDb -> update ( NAILS_DB_PREFIX . 'user' ) ; $ oUserModel -> clearLoginData ( ) ; $ oSession = Factory :: service ( 'Session' , 'nails/module-auth' ) ; $ oSession -> destroy ( ) ; if ( session_id ( ) ) { session_destroy ( ) ; } return true ; }
Log a user out
18,501
public function mfaTokenGenerate ( $ iUserId ) { $ oPasswordModel = Factory :: model ( 'UserPassword' , 'nails/module-auth' ) ; $ oNow = Factory :: factory ( 'DateTime' ) ; $ oInput = Factory :: service ( 'Input' ) ; $ oDb = Factory :: service ( 'Database' ) ; $ sSalt = $ oPasswordModel -> salt ( ) ; $ sIp = $ oInput -> ipAddress ( ) ; $ sCreated = $ oNow -> format ( 'Y-m-d H:i:s' ) ; $ sExpires = $ oNow -> add ( new \ DateInterval ( 'PT10M' ) ) -> format ( 'Y-m-d H:i:s' ) ; $ aToken = [ 'token' => sha1 ( sha1 ( APP_PRIVATE_KEY . $ iUserId . $ sCreated . $ sExpires . $ sIp ) . $ sSalt ) , 'salt' => md5 ( $ sSalt ) , ] ; $ oDb -> set ( 'user_id' , $ iUserId ) ; $ oDb -> set ( 'token' , $ aToken [ 'token' ] ) ; $ oDb -> set ( 'salt' , $ aToken [ 'salt' ] ) ; $ oDb -> set ( 'created' , $ sCreated ) ; $ oDb -> set ( 'expires' , $ sExpires ) ; $ oDb -> set ( 'ip' , $ sIp ) ; if ( $ oDb -> insert ( NAILS_DB_PREFIX . 'user_auth_two_factor_token' ) ) { $ aToken [ 'id' ] = $ oDb -> insert_id ( ) ; return $ aToken ; } else { $ error = lang ( 'auth_twofactor_token_could_not_generate' ) ; $ this -> setError ( $ error ) ; return false ; } }
Generate an MFA token
18,502
public function mfaTokenValidate ( $ iUserId , $ sSalt , $ sToken , $ sIp ) { $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> where ( 'user_id' , $ iUserId ) ; $ oDb -> where ( 'salt' , $ sSalt ) ; $ oDb -> where ( 'token' , $ sToken ) ; $ oToken = $ oDb -> get ( NAILS_DB_PREFIX . 'user_auth_two_factor_token' ) -> row ( ) ; $ bReturn = true ; if ( ! $ oToken ) { $ this -> setError ( lang ( 'auth_twofactor_token_invalid' ) ) ; return false ; } elseif ( strtotime ( $ oToken -> expires ) <= time ( ) ) { $ this -> setError ( lang ( 'auth_twofactor_token_expired' ) ) ; $ bReturn = false ; } elseif ( $ oToken -> ip != $ sIp ) { $ this -> setError ( lang ( 'auth_twofactor_token_bad_ip' ) ) ; $ bReturn = false ; } $ this -> mfaTokenDelete ( $ oToken -> id ) ; return $ bReturn ; }
Validate a MFA token
18,503
public function mfaTokenDelete ( $ iTokenId ) { $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> where ( 'id' , $ iTokenId ) ; $ oDb -> delete ( NAILS_DB_PREFIX . 'user_auth_two_factor_token' ) ; return ( bool ) $ oDb -> affected_rows ( ) ; }
Delete an MFA token
18,504
public function mfaQuestionGet ( $ iUserId ) { $ oDb = Factory :: service ( 'Database' ) ; $ oInput = Factory :: service ( 'Input' ) ; $ oDb -> where ( 'user_id' , $ iUserId ) ; $ oDb -> order_by ( 'last_requested' , 'DESC' ) ; $ aQuestions = $ oDb -> get ( NAILS_DB_PREFIX . 'user_auth_two_factor_question' ) -> result ( ) ; if ( ! $ aQuestions ) { $ this -> setError ( 'No security questions available for this user.' ) ; return false ; } if ( count ( $ aQuestions ) == 1 ) { $ oOut = reset ( $ aQuestions ) ; } elseif ( count ( $ aQuestions ) > 1 ) { $ oOut = reset ( $ aQuestions ) ; if ( strtotime ( $ oOut -> last_requested ) < strtotime ( '-10 MINS' ) ) { $ oOut = $ aQuestions [ array_rand ( $ aQuestions ) ] ; } } else { $ this -> setError ( 'Could not determine security question.' ) ; return false ; } $ oEncrypt = Factory :: service ( 'Encrypt' ) ; $ oOut -> question = $ oEncrypt -> decode ( $ oOut -> question , APP_PRIVATE_KEY . $ oOut -> salt ) ; $ oDb -> set ( 'last_requested' , 'NOW()' , false ) ; $ oDb -> set ( 'last_requested_ip' , $ oInput -> ipAddress ( ) ) ; $ oDb -> where ( 'id' , $ oOut -> id ) ; $ oDb -> update ( NAILS_DB_PREFIX . 'user_auth_two_factor_question' ) ; return $ oOut ; }
Fetches a random MFA question for a user
18,505
public function mfaQuestionValidate ( $ iQuestionId , $ iUserId , $ answer ) { $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> select ( 'answer, salt' ) ; $ oDb -> where ( 'id' , $ iQuestionId ) ; $ oDb -> where ( 'user_id' , $ iUserId ) ; $ oQuestion = $ oDb -> get ( NAILS_DB_PREFIX . 'user_auth_two_factor_question' ) -> row ( ) ; if ( ! $ oQuestion ) { return false ; } $ hash = sha1 ( sha1 ( strtolower ( $ answer ) ) . APP_PRIVATE_KEY . $ oQuestion -> salt ) ; return $ hash === $ oQuestion -> answer ; }
Validates the answer to an MFA Question
18,506
public function mfaQuestionSet ( $ iUserId , $ aData , $ bClearOld = true ) { foreach ( $ aData as $ oDatum ) { if ( empty ( $ oDatum -> question ) || empty ( $ oDatum -> answer ) ) { $ this -> setError ( 'Malformed question/answer data.' ) ; return false ; } } $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> trans_begin ( ) ; if ( $ bClearOld ) { $ oDb -> where ( 'user_id' , $ iUserId ) ; $ oDb -> delete ( NAILS_DB_PREFIX . 'user_auth_two_factor_question' ) ; } $ oPasswordModel = Factory :: model ( 'UserPassword' , 'nails/module-auth' ) ; $ oEncrypt = Factory :: service ( 'Encrypt' ) ; $ aQuestionData = [ ] ; $ iCounter = 0 ; $ oNow = Factory :: factory ( 'DateTime' ) ; $ sDateTime = $ oNow -> format ( 'Y-m-d H:i:s' ) ; foreach ( $ aData as $ oDatum ) { $ sSalt = $ oPasswordModel -> salt ( ) ; $ aQuestionData [ $ iCounter ] = [ 'user_id' => $ iUserId , 'salt' => $ sSalt , 'question' => $ oEncrypt -> encode ( $ oDatum -> question , APP_PRIVATE_KEY . $ sSalt ) , 'answer' => sha1 ( sha1 ( strtolower ( $ oDatum -> answer ) ) . APP_PRIVATE_KEY . $ sSalt ) , 'created' => $ sDateTime , 'last_requested' => null , ] ; $ iCounter ++ ; } if ( $ aQuestionData ) { $ oDb -> insert_batch ( NAILS_DB_PREFIX . 'user_auth_two_factor_question' , $ aQuestionData ) ; if ( $ oDb -> trans_status ( ) !== false ) { $ oDb -> trans_commit ( ) ; return true ; } else { $ oDb -> trans_rollback ( ) ; return false ; } } else { $ oDb -> trans_rollback ( ) ; $ this -> setError ( 'No data to save.' ) ; return false ; } }
Sets MFA questions for a user
18,507
public function mfaDeviceSecretGet ( $ iUserId ) { $ oDb = Factory :: service ( 'Database' ) ; $ oEncrypt = Factory :: service ( 'Encrypt' ) ; $ oDb -> where ( 'user_id' , $ iUserId ) ; $ oDb -> limit ( 1 ) ; $ aResult = $ oDb -> get ( NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret' ) -> result ( ) ; if ( empty ( $ aResult ) ) { return false ; } $ oReturn = reset ( $ aResult ) ; $ oReturn -> secret = $ oEncrypt -> decode ( $ oReturn -> secret , APP_PRIVATE_KEY ) ; return $ oReturn ; }
Gets the user s MFA device if there is one
18,508
public function mfaDeviceSecretGenerate ( $ iUserId , $ sExistingSecret = null ) { $ oUserModel = Factory :: model ( 'User' , 'nails/module-auth' ) ; $ oUser = $ oUserModel -> getById ( $ iUserId ) ; if ( ! $ oUser ) { $ this -> setError ( 'User does not exist.' ) ; return false ; } $ oGoogleAuth = new GoogleAuthenticator ( ) ; if ( empty ( $ sExistingSecret ) ) { $ sSecret = $ oGoogleAuth -> generateSecret ( ) ; } else { $ sSecret = $ sExistingSecret ; } $ sHostname = Functions :: getDomainFromUrl ( BASE_URL ) ; $ sUsername = $ oUser -> username ; $ sUsername = empty ( $ sUsername ) ? preg_replace ( '/[^a-z]/' , '' , strtolower ( $ oUser -> first_name . $ oUser -> last_name ) ) : $ sUsername ; $ sUsername = empty ( $ sUsername ) ? preg_replace ( '/[^a-z]/' , '' , strtolower ( $ oUser -> email ) ) : $ sUsername ; return [ 'secret' => $ sSecret , 'url' => $ oGoogleAuth -> getUrl ( $ sUsername , $ sHostname , $ sSecret ) , ] ; }
Generates a MFA Device Secret
18,509
public function mfaDeviceSecretValidate ( $ iUserId , $ sSecret , $ iCode ) { $ sCode = preg_replace ( '/[^\d]/' , '' , $ iCode ) ; $ oGoogleAuth = new GoogleAuthenticator ( ) ; if ( $ oGoogleAuth -> checkCode ( $ sSecret , $ sCode ) ) { $ oDb = Factory :: service ( 'Database' ) ; $ oEncrypt = Factory :: service ( 'Encrypt' ) ; $ oDb -> set ( 'user_id' , $ iUserId ) ; $ oDb -> set ( 'secret' , $ oEncrypt -> encode ( $ sSecret , APP_PRIVATE_KEY ) ) ; $ oDb -> set ( 'created' , 'NOW()' , false ) ; if ( $ oDb -> insert ( NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret' ) ) { $ iSecretId = $ oDb -> insert_id ( ) ; $ oNow = Factory :: factory ( 'DateTime' ) ; $ oDb -> set ( 'secret_id' , $ iSecretId ) ; $ oDb -> set ( 'code' , $ sCode ) ; $ oDb -> set ( 'used' , $ oNow -> format ( 'Y-m-d H:i:s' ) ) ; $ oDb -> insert ( NAILS_DB_PREFIX . 'user_auth_two_factor_device_code' ) ; return true ; } else { $ this -> setError ( 'Could not save secret.' ) ; return false ; } } else { $ this -> setError ( 'Codes did not validate.' ) ; return false ; } }
Validates a secret against two given codes if valid adds as a device for the user
18,510
public function mfaDeviceCodeValidate ( $ iUserId , $ sCode ) { $ oSecret = $ this -> mfaDeviceSecretGet ( $ iUserId ) ; if ( ! $ oSecret ) { $ this -> setError ( 'Invalid User' ) ; return false ; } $ oDb = Factory :: service ( 'Database' ) ; $ oDb -> where ( 'secret_id' , $ oSecret -> id ) ; $ oDb -> where ( 'code' , $ sCode ) ; if ( $ oDb -> count_all_results ( NAILS_DB_PREFIX . 'user_auth_two_factor_device_code' ) ) { $ this -> setError ( 'Code has already been used.' ) ; return false ; } $ sCode = preg_replace ( '/[^\d]/' , '' , $ sCode ) ; $ oGoogleAuth = new GoogleAuthenticator ( ) ; $ checkCode = $ oGoogleAuth -> checkCode ( $ oSecret -> secret , $ sCode ) ; if ( $ checkCode ) { $ oDb -> set ( 'secret_id' , $ oSecret -> id ) ; $ oDb -> set ( 'code' , $ sCode ) ; $ oDb -> set ( 'used' , 'NOW()' , false ) ; $ oDb -> insert ( NAILS_DB_PREFIX . 'user_auth_two_factor_device_code' ) ; return true ; } else { return false ; } }
Validates an MFA Device code
18,511
private function saveReferrer ( ServerRequestInterface $ request ) { Respond :: session ( ) -> set ( self :: REFERRER , $ request -> getUri ( ) -> __toString ( ) ) ; }
saves the referrer uri to session .
18,512
public function setMessage ( $ type , $ message ) { if ( ! is_null ( $ message ) ) { $ this -> messages [ ] = [ 'message' => $ message , 'type' => $ type , ] ; } return $ this ; }
a generic message method for Message helper . use success alert and error methods .
18,513
public function modules ( ) { $ modules = [ ] ; foreach ( $ this -> modulesToCheck as $ module ) { $ modules [ $ module ] = in_array ( 'mod_' . $ module , apache_get_modules ( ) ) ; } return $ modules ; }
Checks if some modules are loaded
18,514
public function brokenLinksColumnSorting ( ) { add_filter ( 'posts_fields' , function ( $ fields , $ query ) { if ( $ query -> get ( 'orderby' ) !== 'broken-links' ) { return $ fields ; } global $ wpdb ; $ fields .= ", ( SELECT COUNT(*) FROM " . self :: $ dbTable . " WHERE post_id = {$wpdb->posts}.ID ) AS broken_links_count" ; return $ fields ; } , 10 , 2 ) ; add_filter ( 'posts_orderby' , function ( $ orderby , $ query ) { if ( $ query -> get ( 'orderby' ) !== 'broken-links' ) { return $ orderby ; } $ orderby = "broken_links_count {$query->get('order')}, " . $ orderby ; return $ orderby ; } , 10 , 2 ) ; }
Sort post if sorting on broken - links column
18,515
public function addListTablePage ( ) { add_submenu_page ( 'options-general.php' , 'Broken links' , 'Broken links' , 'edit_posts' , 'broken-links-detector' , function ( ) { \ BrokenLinkDetector \ App :: checkInstall ( ) ; $ listTable = new \ BrokenLinkDetector \ ListTable ( ) ; $ offset = get_option ( 'gmt_offset' ) ; if ( $ offset > - 1 ) { $ offset = '+' . $ offset ; } else { $ offset = '-' . ( 1 * abs ( $ offset ) ) ; } $ nextRun = date ( 'Y-m-d H:i' , strtotime ( $ offset . ' hours' , wp_next_scheduled ( 'broken-links-detector-external' ) ) ) ; include BROKENLINKDETECTOR_TEMPLATE_PATH . 'list-table.php' ; } ) ; }
Adds the list table page of broken links
18,516
public function checkSavedPost ( $ data , $ postarr ) { remove_action ( 'wp_insert_post_data' , array ( $ this , 'checkSavedPost' ) , 10 , 2 ) ; $ detector = new \ BrokenLinkDetector \ InternalDetector ( $ data , $ postarr ) ; return $ data ; }
Checks if a saved posts permalink is changed and updates permalinks throughout the site
18,517
public function deleteBrokenLinks ( $ postId ) { global $ wpdb ; $ tableName = self :: $ dbTable ; $ wpdb -> delete ( $ tableName , array ( 'post_id' => $ postId ) , array ( '%d' ) ) ; }
Remove broken links when deleting a page
18,518
public function findAuth ( Query $ query , array $ options ) { return $ query -> contain ( 'Groups' , function ( Query $ q ) { return $ q -> select ( [ 'name' ] ) ; } ) ; }
auth find method
18,519
public function findBanned ( Query $ query , array $ options ) { return $ query -> where ( [ sprintf ( '%s.banned' , $ this -> getAlias ( ) ) => true ] ) ; }
banned find method
18,520
public function findPending ( Query $ query , array $ options ) { return $ query -> where ( [ sprintf ( '%s.active' , $ this -> getAlias ( ) ) => false , sprintf ( '%s.banned' , $ this -> getAlias ( ) ) => false , ] ) ; }
pending find method
18,521
public function getActiveList ( ) { return $ this -> find ( ) -> select ( [ 'id' , 'first_name' , 'last_name' ] ) -> where ( [ sprintf ( '%s.active' , $ this -> getAlias ( ) ) => true ] ) -> order ( [ 'username' => 'ASC' ] ) -> formatResults ( function ( ResultSet $ results ) { return $ results -> indexBy ( 'id' ) -> map ( function ( User $ user ) { return $ user -> first_name . ' ' . $ user -> last_name ; } ) ; } ) -> cache ( sprintf ( 'active_%s_list' , $ this -> getTable ( ) ) , $ this -> getCacheName ( ) ) ; }
Gets active users as list
18,522
public function validationDoNotRequirePresence ( UserValidator $ validator ) { foreach ( $ validator -> getIterator ( ) as $ field => $ rules ) { $ validator -> requirePresence ( $ field , false ) ; } return $ validator ; }
Validation do not require presence .
18,523
protected function getFontSizes ( array $ style = [ ] ) { $ maxFont = empty ( $ style [ 'maxFont' ] ) ? 40 : $ style [ 'maxFont' ] ; $ minFont = empty ( $ style [ 'minFont' ] ) ? 12 : $ style [ 'minFont' ] ; is_true_or_fail ( $ maxFont > $ minFont , __d ( 'me_cms' , 'Invalid values' ) , InvalidArgumentException :: class ) ; return [ $ maxFont , $ minFont ] ; }
Internal method to get the font sizes
18,524
public function popular ( $ limit = 10 , $ prefix = '#' , $ render = 'cloud' , $ shuffle = true , $ style = [ 'maxFont' => 40 , 'minFont' => 12 ] ) { $ this -> viewBuilder ( ) -> setTemplate ( sprintf ( 'popular_as_%s' , $ render ) ) ; if ( $ this -> request -> isUrl ( [ '_name' => 'postsTags' ] ) ) { return ; } $ maxFont = $ minFont = 0 ; $ cache = sprintf ( 'widget_tags_popular_%s' , $ limit ) ; if ( $ style && is_array ( $ style ) ) { list ( $ maxFont , $ minFont ) = $ this -> getFontSizes ( $ style ) ; $ cache = sprintf ( '%s_max_%s_min_%s' , $ cache , $ maxFont , $ minFont ) ; } $ tags = $ this -> Tags -> find ( ) -> select ( [ 'tag' , 'post_count' ] ) -> limit ( $ limit ) -> order ( [ sprintf ( '%s.post_count' , $ this -> Tags -> getAlias ( ) ) => 'DESC' , sprintf ( '%s.tag' , $ this -> Tags -> getAlias ( ) ) => 'ASC' , ] ) -> formatResults ( function ( ResultSet $ results ) use ( $ style , $ maxFont , $ minFont ) { $ results = $ results -> indexBy ( 'slug' ) ; if ( ! $ results -> count ( ) || ! $ style || ! $ maxFont || ! $ minFont ) { return $ results ; } $ minCount = $ results -> last ( ) -> post_count ; $ diffCount = $ results -> first ( ) -> post_count - $ minCount ; $ diffFont = $ maxFont - $ minFont ; return $ results -> map ( function ( Tag $ tag ) use ( $ minCount , $ diffCount , $ maxFont , $ minFont , $ diffFont ) { $ tag -> size = $ diffCount ? round ( ( ( $ tag -> post_count - $ minCount ) / $ diffCount * $ diffFont ) + $ minFont ) : $ maxFont ; return $ tag ; } ) ; } ) -> cache ( $ cache , $ this -> Tags -> getCacheName ( ) ) -> all ( ) ; if ( $ shuffle ) { $ tags = $ tags -> shuffle ( ) ; } $ this -> set ( compact ( 'prefix' , 'tags' ) ) ; }
Popular tags widgets
18,525
public static function registerPackage ( Event $ event ) { $ installedPackage = $ event -> getOperation ( ) -> getPackage ( ) ; if ( ! self :: isBundle ( $ installedPackage ) ) { return ; } self :: enablePackage ( $ installedPackage ) ; }
On Composer s post - package - install event register the package .
18,526
public function toPath ( $ path ) { $ uri = $ this -> request -> getUri ( ) -> withPath ( $ path ) ; return $ this -> toAbsoluteUri ( $ uri ) ; }
redirects to a path in string . uses current hosts and scheme .
18,527
public function months ( $ render = 'form' ) { $ this -> viewBuilder ( ) -> setTemplate ( sprintf ( 'months_as_%s' , $ render ) ) ; if ( $ this -> request -> isUrl ( [ '_name' => 'posts' ] ) ) { return ; } $ query = $ this -> Posts -> find ( 'active' ) ; $ time = $ query -> func ( ) -> date_format ( [ 'created' => 'identifier' , "'%Y/%m'" => 'literal' ] ) ; $ months = $ query -> select ( [ 'month' => $ time , 'post_count' => $ query -> func ( ) -> count ( $ time ) , ] ) -> distinct ( [ 'month' ] ) -> formatResults ( function ( ResultSet $ results ) { return $ results -> indexBy ( 'month' ) -> map ( function ( Post $ post ) { list ( $ year , $ month ) = explode ( '/' , $ post -> month ) ; $ post -> month = ( new FrozenDate ( ) ) -> day ( 1 ) -> month ( $ month ) -> year ( $ year ) ; return $ post ; } ) ; } ) -> order ( [ 'month' => 'DESC' ] ) -> cache ( 'widget_months' , $ this -> Posts -> getCacheName ( ) ) -> all ( ) ; $ this -> set ( compact ( 'months' ) ) ; }
Posts by month widget
18,528
protected function filterArrayStrings ( $ array , $ search , $ replace ) { $ return = array ( ) ; foreach ( ( array ) $ array as $ key => $ value ) { $ key = str_replace ( $ search , $ replace , $ key ) ; $ value = is_array ( $ value ) ? $ this -> filterArrayStrings ( $ value , $ search , $ replace ) : str_replace ( $ search , $ replace , $ value ) ; $ return [ $ key ] = $ value ; } return $ return ; }
Replaces strings in array keys and values recursively .
18,529
public function escapeCharacterClass ( $ char ) { return ( isset ( $ this -> inCharacterClass [ $ char ] ) ) ? $ this -> inCharacterClass [ $ char ] : $ char ; }
Escape given character to be used in a character class
18,530
public function escapeLiteral ( $ char ) { return ( isset ( $ this -> inLiteral [ $ char ] ) ) ? $ this -> inLiteral [ $ char ] : $ char ; }
Escape given character to be used outside of a character class
18,531
public function add ( $ id , $ data = 1 ) { try { return $ this -> resource -> hSet ( static :: CACHE_KEY , $ id , $ data ) ; } catch ( ConnectionException $ e ) { return false ; } }
Cache an id
18,532
public function exists ( $ id ) { try { return ! ! $ this -> resource -> hExists ( static :: CACHE_KEY , $ id ) ; } catch ( ConnectionException $ e ) { return false ; } }
Returns true if a key exists
18,533
public function remove ( $ id ) { try { return $ this -> resource -> hDel ( static :: CACHE_KEY , $ id ) ; } catch ( ConnectionException $ e ) { return false ; } }
Remove a cache key
18,534
protected function hasMatchingSuffix ( array $ strings ) { $ suffix = end ( $ strings [ 1 ] ) ; foreach ( $ strings as $ string ) { if ( end ( $ string ) !== $ suffix ) { return false ; } } return ( $ suffix !== false ) ; }
Test whether all given strings have the same last element
18,535
protected function pop ( array $ strings ) { $ cnt = count ( $ strings ) ; $ i = $ cnt ; while ( -- $ i >= 0 ) { array_pop ( $ strings [ $ i ] ) ; } $ strings = array_filter ( $ strings ) ; if ( count ( $ strings ) < $ cnt ) { array_unshift ( $ strings , [ ] ) ; } return $ strings ; }
Remove the last element of every string
18,536
public function getSearch ( $ aData = [ ] ) { if ( ! userHasPermission ( 'admin:auth:accounts:browse' ) ) { $ oHttpCodes = Factory :: service ( 'HttpCodes' ) ; throw new ApiException ( 'You are not authorised to search users' , $ oHttpCodes :: STATUS_UNAUTHORIZED ) ; } return parent :: getSearch ( $ aData ) ; }
Search for an item
18,537
public function getEmail ( ) { $ oHttpCodes = Factory :: service ( 'HttpCodes' ) ; if ( ! userHasPermission ( 'admin:auth:accounts:browse' ) ) { throw new ApiException ( 'You are not authorised to browse users' , $ oHttpCodes :: STATUS_UNAUTHORIZED ) ; } $ oInput = Factory :: service ( 'Input' ) ; $ sEmail = $ oInput -> get ( 'email' ) ; if ( ! valid_email ( $ sEmail ) ) { throw new ApiException ( '"' . $ sEmail . '" is not a valid email' , $ oHttpCodes :: STATUS_BAD_REQUEST ) ; } $ oUserModel = Factory :: model ( static :: CONFIG_MODEL_NAME , static :: CONFIG_MODEL_PROVIDER ) ; $ oUser = $ oUserModel -> getByEmail ( $ sEmail ) ; if ( empty ( $ oUser ) ) { throw new ApiException ( 'No user found for email "' . $ sEmail . '"' , $ oHttpCodes :: STATUS_NOT_FOUND ) ; } return Factory :: factory ( 'ApiResponse' , 'nails/module-api' ) -> setData ( $ this -> formatObject ( $ oUser ) ) ; }
Returns a user by their email
18,538
public function postRemap ( ) { $ oUri = Factory :: service ( 'Uri' ) ; $ iItemId = ( int ) $ oUri -> segment ( 4 ) ; if ( $ iItemId && $ iItemId != activeUSer ( 'id' ) && ! userHasPermission ( 'admin:auth:accounts:editothers' ) ) { return [ 'status' => 401 , 'error' => 'You do not have permission to update this resource' , ] ; } elseif ( ! $ iItemId && ! userHasPermission ( 'admin:auth:accounts:create' ) ) { return [ 'status' => 401 , 'error' => 'You do not have permission to create this type of resource' , ] ; } return parent :: postRemap ( ) ; }
Creates or updates a user
18,539
public function formatObject ( $ oObj ) { return [ 'id' => $ oObj -> id , 'first_name' => $ oObj -> first_name , 'last_name' => $ oObj -> last_name , 'email' => $ oObj -> email , ] ; }
Format the output
18,540
public function upload ( string $ fileKey ) { if ( ! isset ( $ this -> uploadedFiles [ $ fileKey ] ) ) { throw new Exception ( 'PitonCMS: File upload key does not exist' ) ; } $ file = $ this -> uploadedFiles [ $ fileKey ] ; if ( $ file -> getError ( ) === UPLOAD_ERR_OK ) { $ uploadFileName = $ file -> getClientFilename ( ) ; $ ext = strtolower ( pathinfo ( $ uploadFileName , PATHINFO_EXTENSION ) ) ; do { $ name = $ this -> generateName ( ) ; $ path = $ this -> getFilePath ( $ name ) ; $ exists = $ this -> makeFileDirectory ( $ path ) ; } while ( ! $ exists ) ; $ this -> fileName = "$name.$ext" ; $ file -> moveTo ( "{$this->publicRoot}{$path}{$this->fileName}" ) ; unset ( $ file ) ; return true ; } $ this -> error = $ file -> getError ( ) ; return false ; }
Upload File Action
18,541
public function getErrorMessage ( ) { switch ( $ this -> error ) { case UPLOAD_ERR_INI_SIZE : $ message = "The uploaded file exceeds the upload_max_filesize directive in php.ini" ; break ; case UPLOAD_ERR_FORM_SIZE : $ message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ; break ; case UPLOAD_ERR_PARTIAL : $ message = "The uploaded file was only partially uploaded" ; break ; case UPLOAD_ERR_NO_FILE : $ message = "No file was uploaded" ; break ; case UPLOAD_ERR_NO_TMP_DIR : $ message = "Missing a temporary folder" ; break ; case UPLOAD_ERR_CANT_WRITE : $ message = "Failed to write file to disk" ; break ; case UPLOAD_ERR_EXTENSION : $ message = "File upload stopped by extension" ; break ; default : $ message = "Unknown upload error" ; } return $ message ; }
Get Upload Error Message
18,542
protected function makeFileDirectory ( $ directoryPath ) { $ filePath = $ this -> publicRoot . $ directoryPath ; if ( ! is_dir ( $ filePath ) ) { try { mkdir ( $ filePath , 0775 , true ) ; return true ; } catch ( Exception $ e ) { throw new Exception ( 'PitonCMS: Failed to create file upload directory' ) ; } } return false ; }
Make Directory Path
18,543
protected function charsToCodepointsWithSurrogates ( array $ chars ) { $ codepoints = [ ] ; foreach ( $ chars as $ char ) { $ cp = $ this -> cp ( $ char ) ; if ( $ cp < 0x10000 ) { $ codepoints [ ] = $ cp ; } else { $ codepoints [ ] = 0xD7C0 + ( $ cp >> 10 ) ; $ codepoints [ ] = 0xDC00 + ( $ cp & 0x3FF ) ; } } return $ codepoints ; }
Convert a list of UTF - 8 characters into a list of Unicode codepoint with surrogates
18,544
protected function cp ( $ char ) { $ cp = ord ( $ char [ 0 ] ) ; if ( $ cp >= 0xF0 ) { $ cp = ( $ cp << 18 ) + ( ord ( $ char [ 1 ] ) << 12 ) + ( ord ( $ char [ 2 ] ) << 6 ) + ord ( $ char [ 3 ] ) - 0x3C82080 ; } elseif ( $ cp >= 0xE0 ) { $ cp = ( $ cp << 12 ) + ( ord ( $ char [ 1 ] ) << 6 ) + ord ( $ char [ 2 ] ) - 0xE2080 ; } elseif ( $ cp >= 0xC0 ) { $ cp = ( $ cp << 6 ) + ord ( $ char [ 1 ] ) - 0x3080 ; } return $ cp ; }
Compute and return the Unicode codepoint for given UTF - 8 char
18,545
public function getPublishedStatus ( ) { $ today = date ( 'Y-m-d' ) ; if ( empty ( $ this -> published_date ) ) { return 'draft' ; } elseif ( $ this -> published_date > $ today ) { return 'pending' ; } elseif ( $ this -> published_date <= $ today ) { return 'published' ; } return null ; }
Get Published Status
18,546
public function addAttachment ( $ attachment , $ group = 'contents' ) { if ( ! $ attachment instanceof AttachableInterface && ! $ attachment instanceof ModelInterface ) { return false ; } $ join = $ this -> modelFactory ( ) -> create ( Join :: class ) ; $ objId = $ this -> id ( ) ; $ objType = $ this -> objType ( ) ; $ attId = $ attachment -> id ( ) ; $ join -> setAttachmentId ( $ attId ) ; $ join -> setObjectId ( $ objId ) ; $ join -> setGroup ( $ group ) ; $ join -> setObjectType ( $ objType ) ; $ join -> save ( ) ; return $ this ; }
Attach an node to the current object .
18,547
public function removeAttachmentJoins ( ) { $ joinProto = $ this -> modelFactory ( ) -> get ( Join :: class ) ; $ loader = $ this -> collectionLoader ( ) ; $ loader -> setModel ( $ joinProto ) -> addFilter ( 'object_type' , $ this -> objType ( ) ) -> addFilter ( 'object_id' , $ this -> id ( ) ) ; $ collection = $ loader -> load ( ) ; foreach ( $ collection as $ obj ) { $ obj -> delete ( ) ; } return true ; }
Remove all joins linked to a specific attachment .
18,548
public function generateLinksCenter ( string $ page = null , string $ ignoredKeys = null , $ linksClassName = null ) : string { $ totalPages = $ this -> totalPages ; if ( $ totalPages == 1 ) { return $ this -> template ( [ '<a class="current" href="#">1</a>' ] , $ linksClassName , true ) ; } $ links = ( array ) $ this -> linksCenter ; if ( $ links != null ) { return $ this -> template ( $ links , $ linksClassName , true ) ; } $ linksTemplate = $ this -> linksTemplate ; $ s = $ this -> startKey ; $ query = $ this -> prepareQuery ( $ ignoredKeys ) ; $ start = max ( 1 , ( $ this -> start / $ this -> stop ) + 1 ) ; $ prev = $ start - 1 ; if ( $ prev >= 1 ) { $ links [ ] = sprintf ( '<a class="first" rel="first" href="%s%s=1">%s</a>' , $ query , $ s , $ linksTemplate [ 'first' ] ) ; $ links [ ] = sprintf ( '<a class="prev" rel="prev" href="%s%s=%s">%s</a>' , $ query , $ s , $ prev , $ linksTemplate [ 'prev' ] ) ; } $ links [ ] = sprintf ( '<a class="current" href="#">%s %s</a>' , $ page ?? $ linksTemplate [ 'page' ] , $ start ) ; $ next = $ start + 1 ; if ( $ start < $ totalPages ) { $ links [ ] = sprintf ( '<a class="next" rel="next" href="%s%s=%s">%s</a>' , $ query , $ s , $ next , $ linksTemplate [ 'next' ] ) ; $ links [ ] = sprintf ( '<a class="last" rel="last" href="%s%s=%s">%s</a>' , $ query , $ s , $ totalPages , $ linksTemplate [ 'last' ] ) ; } $ this -> linksCenter = $ links ; return $ this -> template ( $ links , $ linksClassName , true ) ; }
Generate links center .
18,549
protected function getStartAndEndDate ( $ date ) { $ year = $ month = $ day = null ; if ( in_array ( $ date , [ 'today' , 'yesterday' ] ) ) { $ start = Time :: parse ( $ date ) ; } else { list ( $ year , $ month , $ day ) = array_replace ( [ null , null , null ] , explode ( '/' , $ date ) ) ; $ start = Time :: now ( ) -> setDate ( $ year , $ month ? : 1 , $ day ? : 1 ) ; } $ start = $ start -> setTime ( 0 , 0 , 0 ) ; $ end = Time :: parse ( $ start ) ; if ( ( $ year && $ month && $ day ) || in_array ( $ date , [ 'today' , 'yesterday' ] ) ) { $ end = $ end -> addDay ( 1 ) ; } else { $ end = $ year && $ month ? $ end -> addMonth ( 1 ) : $ end -> addYear ( 1 ) ; } return [ $ start , $ end ] ; }
Gets start and end date as Time instances starting from a string . These can be used for a where condition to search for records based on a date .
18,550
public function addTeams ( ArrayCollection $ teams ) { foreach ( $ teams as $ team ) { $ team -> addUser ( $ this ) ; $ this -> teams -> add ( $ team ) ; } }
Add teams to the user
18,551
public function removeTeams ( ArrayCollection $ teams ) { foreach ( $ teams as $ team ) { $ team -> removeUser ( $ this ) ; $ this -> teams -> removeElement ( $ team ) ; } }
Remove teams from the app .
18,552
public static function transform ( $ xslFileName , DOMDocument $ xml ) { $ xsl = new DOMDocument ; $ xsl -> load ( __DIR__ . '/../../xslt/' . $ xslFileName . '.xsl' ) ; $ proc = new XSLTProcessor ; $ proc -> importStyleSheet ( $ xsl ) ; libxml_use_internal_errors ( true ) ; $ result = $ proc -> transformToXML ( $ xml ) ; foreach ( libxml_get_errors ( ) as $ error ) { } return $ result ; }
Common transform functionality
18,553
public function delete ( $ id = null ) { $ this -> request -> allowMethod ( [ 'post' , 'delete' ] ) ; $ category = $ this -> PostsCategories -> get ( $ id ) ; if ( ! $ category -> post_count ) { $ this -> PostsCategories -> deleteOrFail ( $ category ) ; $ this -> Flash -> success ( I18N_OPERATION_OK ) ; } else { $ this -> Flash -> alert ( I18N_BEFORE_DELETE ) ; } return $ this -> redirect ( [ 'action' => 'index' ] ) ; }
Deletes posts category
18,554
protected function setOption ( $ name , $ value , $ reset = false ) { $ changed = ! isset ( $ this -> options [ $ name ] ) || $ this -> options [ $ name ] !== $ value ; if ( $ changed && $ reset ) { $ this -> data = null ; } $ this -> options [ $ name ] = $ value ; return $ this ; }
Set a query option .
18,555
public static function forge ( $ name , $ cookie = null ) { $ factory = new SessionFactory ( ) ; $ cookie = $ cookie ? : $ _COOKIE ; $ session = $ factory -> newInstance ( $ cookie ) ; $ self = new self ( $ session ) ; $ self -> start ( ) ; return $ self -> withStorage ( $ name ) ; }
construct a SessionStorage using Aura . Session as a default implementation .
18,556
public function withStorage ( $ name ) { $ self = clone ( $ this ) ; $ self -> segment = $ this -> session -> getSegment ( $ name ) ; return $ self ; }
create a new segment
18,557
public function index ( ) { if ( isLoggedIn ( ) ) { redirect ( $ this -> data [ 'return_to' ] ) ; } $ oInput = Factory :: service ( 'Input' ) ; if ( $ oInput -> post ( ) ) { $ oFormValidation = Factory :: service ( 'FormValidation' ) ; switch ( APP_NATIVE_LOGIN_USING ) { case 'EMAIL' : $ oFormValidation -> set_rules ( 'identifier' , 'Email' , 'required|trim|valid_email' ) ; break ; case 'USERNAME' : $ oFormValidation -> set_rules ( 'identifier' , 'Username' , 'required|trim' ) ; break ; default : $ oFormValidation -> set_rules ( 'identifier' , 'Username or Email' , 'trim' ) ; break ; } $ oFormValidation -> set_rules ( 'password' , 'Password' , 'required' ) ; $ oFormValidation -> set_message ( 'required' , lang ( 'fv_required' ) ) ; $ oFormValidation -> set_message ( 'valid_email' , lang ( 'fv_valid_email' ) ) ; if ( $ oFormValidation -> run ( ) ) { $ sIdentifier = $ oInput -> post ( 'identifier' ) ; $ sPassword = $ oInput -> post ( 'password' ) ; $ bRememberMe = ( bool ) $ oInput -> post ( 'remember' ) ; $ oAuthModel = Factory :: model ( 'Auth' , 'nails/module-auth' ) ; $ oUser = $ oAuthModel -> login ( $ sIdentifier , $ sPassword , $ bRememberMe ) ; if ( $ oUser ) { $ this -> _login ( $ oUser , $ bRememberMe ) ; } else { $ this -> data [ 'error' ] = $ oAuthModel -> lastError ( ) ; } } else { $ this -> data [ 'error' ] = lang ( 'fv_there_were_errors' ) ; } } $ oSocial = Factory :: service ( 'SocialSignOn' , 'nails/module-auth' ) ; $ this -> data [ 'social_signon_enabled' ] = $ oSocial -> isEnabled ( ) ; $ this -> data [ 'social_signon_providers' ] = $ oSocial -> getProviders ( 'ENABLED' ) ; $ this -> loadStyles ( NAILS_APP_PATH . 'application/modules/auth/views/login/form.php' ) ; Factory :: service ( 'View' ) -> load ( [ 'structure/header/blank' , 'auth/login/form' , 'structure/footer/blank' , ] ) ; }
Validate data and log the user in .
18,558
public function with_hashes ( ) { $ oUri = Factory :: service ( 'Uri' ) ; $ oConfig = Factory :: service ( 'Config' ) ; if ( ! $ oConfig -> item ( 'authEnableHashedLogin' ) ) { show404 ( ) ; } $ hash [ 'id' ] = $ oUri -> segment ( 4 ) ; $ hash [ 'pw' ] = $ oUri -> segment ( 5 ) ; if ( empty ( $ hash [ 'id' ] ) || empty ( $ hash [ 'pw' ] ) ) { throw new NailsException ( lang ( 'auth_with_hashes_incomplete_creds' ) , 1 ) ; } if ( isLoggedIn ( ) ) { if ( md5 ( activeUser ( 'id' ) ) == $ hash [ 'id' ] ) { if ( $ this -> data [ 'return_to' ] ) { redirect ( $ this -> data [ 'return_to' ] ) ; } else { redirect ( activeUser ( 'group_homepage' ) ) ; } } else { $ oAuthModel = Factory :: model ( 'Auth' , 'nails/module-auth' ) ; $ oAuthModel -> logout ( ) ; redirect ( preg_replace ( '/^\//' , '' , $ _SERVER [ 'REQUEST_URI' ] ) ) ; } } $ oSession = Factory :: service ( 'Session' , 'nails/module-auth' ) ; $ oUserModel = Factory :: model ( 'User' , 'nails/module-auth' ) ; $ oUser = $ oUserModel -> getByHashes ( $ hash [ 'id' ] , $ hash [ 'pw' ] ) ; if ( $ oUser ) { $ oUserModel -> setLoginData ( $ oUser -> id ) ; if ( $ oUser -> last_login ) { $ lastLogin = $ oConfig -> item ( 'authShowNicetimeOnLogin' ) ? niceTime ( strtotime ( $ oUser -> last_login ) ) : toUserDatetime ( $ oUser -> last_login ) ; if ( $ oConfig -> item ( 'authShowLastIpOnLogin' ) ) { $ sStatus = 'positive' ; $ sMessage = lang ( 'auth_login_ok_welcome_with_ip' , [ $ oUser -> first_name , $ lastLogin , $ oUser -> last_ip , ] ) ; } else { $ sStatus = 'positive' ; $ sMessage = lang ( 'auth_login_ok_welcome' , [ $ oUser -> first_name , $ oUser -> last_login ] ) ; } } else { $ sStatus = 'positive' ; $ sMessage = lang ( 'auth_login_ok_welcome_notime' , [ $ oUser -> first_name ] ) ; } $ oSession -> setFlashData ( $ sStatus , $ sMessage ) ; $ oUserModel -> updateLastLogin ( $ oUser -> id ) ; if ( $ this -> data [ 'return_to' ] != site_url ( ) ) { redirect ( $ this -> data [ 'return_to' ] ) ; } else { redirect ( $ oUser -> group_homepage ) ; } } else { $ oSession -> setFlashData ( 'error' , lang ( 'auth_with_hashes_autologin_fail' ) ) ; redirect ( $ this -> data [ 'return_to' ] ) ; } }
Log a user in using hashes of their user ID and password ; easy way of automatically logging a user in from the likes of an email .
18,559
protected function requestData ( & $ aRequiredData , $ provider ) { $ oInput = Factory :: service ( 'Input' ) ; if ( $ oInput -> post ( ) ) { $ oFormValidation = Factory :: service ( 'FormValidation' ) ; if ( isset ( $ aRequiredData [ 'email' ] ) ) { $ oFormValidation -> set_rules ( 'email' , 'email' , 'trim|required|valid_email|is_unique[' . NAILS_DB_PREFIX . 'user_email.email]' ) ; } if ( isset ( $ aRequiredData [ 'username' ] ) ) { $ oFormValidation -> set_rules ( 'username' , 'username' , 'trim|required|is_unique[' . NAILS_DB_PREFIX . 'user.username]' ) ; } if ( empty ( $ aRequiredData [ 'first_name' ] ) ) { $ oFormValidation -> set_rules ( 'first_name' , '' , 'trim|required' ) ; } if ( empty ( $ aRequiredData [ 'last_name' ] ) ) { $ oFormValidation -> set_rules ( 'last_name' , '' , 'trim|required' ) ; } $ oFormValidation -> set_message ( 'required' , lang ( 'fv_required' ) ) ; $ oFormValidation -> set_message ( 'valid_email' , lang ( 'fv_valid_email' ) ) ; if ( APP_NATIVE_LOGIN_USING == 'EMAIL' ) { $ oFormValidation -> set_message ( 'is_unique' , lang ( 'fv_email_already_registered' , site_url ( 'auth/password/forgotten' ) ) ) ; } elseif ( APP_NATIVE_LOGIN_USING == 'USERNAME' ) { $ oFormValidation -> set_message ( 'is_unique' , lang ( 'fv_username_already_registered' , site_url ( 'auth/password/forgotten' ) ) ) ; } else { $ oFormValidation -> set_message ( 'is_unique' , lang ( 'fv_identity_already_registered' , site_url ( 'auth/password/forgotten' ) ) ) ; } if ( $ oFormValidation -> run ( ) ) { if ( isset ( $ aRequiredData [ 'email' ] ) ) { $ aRequiredData [ 'email' ] = $ oInput -> post ( 'email' ) ; } if ( isset ( $ aRequiredData [ 'username' ] ) ) { $ aRequiredData [ 'username' ] = $ oInput -> post ( 'username' ) ; } if ( empty ( $ aRequiredData [ 'first_name' ] ) ) { $ aRequiredData [ 'first_name' ] = $ oInput -> post ( 'first_name' ) ; } if ( empty ( $ aRequiredData [ 'last_name' ] ) ) { $ aRequiredData [ 'last_name' ] = $ oInput -> post ( 'last_name' ) ; } } else { $ this -> data [ 'error' ] = lang ( 'fv_there_were_errors' ) ; $ this -> requestDataForm ( $ aRequiredData , $ provider ) ; } } else { $ this -> requestDataForm ( $ aRequiredData , $ provider ) ; } }
Handles requesting of additional data from the user
18,560
protected function requestDataForm ( & $ aRequiredData , $ provider ) { $ oUri = Factory :: service ( 'Uri' ) ; $ this -> data [ 'required_data' ] = $ aRequiredData ; $ this -> data [ 'form_url' ] = 'auth/login/' . $ provider ; if ( $ oUri -> segment ( 4 ) == 'register' ) { $ this -> data [ 'form_url' ] .= '/register' ; } if ( $ this -> data [ 'return_to' ] ) { $ this -> data [ 'form_url' ] .= '?return_to=' . urlencode ( $ this -> data [ 'return_to' ] ) ; } Factory :: service ( 'View' ) -> load ( [ 'structure/header/blank' , 'auth/register/social_request_data' , 'structure/footer/blank' , ] ) ; $ oOutput = Factory :: service ( 'Output' ) ; echo $ oOutput -> get_output ( ) ; exit ( ) ; }
Renders the request data form
18,561
public function _remap ( ) { $ oUri = Factory :: service ( 'Uri' ) ; $ method = $ oUri -> segment ( 3 ) ? $ oUri -> segment ( 3 ) : 'index' ; if ( method_exists ( $ this , $ method ) && substr ( $ method , 0 , 1 ) != '_' ) { $ this -> { $ method } ( ) ; } else { $ oSocial = Factory :: service ( 'SocialSignOn' , 'nails/module-auth' ) ; if ( $ oSocial -> isValidProvider ( $ method ) ) { $ this -> socialSignon ( $ method ) ; } else { show404 ( ) ; } } }
Route requests appropriately
18,562
public function getBlockElementsHtml ( $ block ) { if ( empty ( $ block ) ) { return '' ; } $ blockHtml = '' ; foreach ( $ block as $ element ) { $ blockHtml .= $ this -> getElementHtml ( $ element ) . PHP_EOL ; } return $ blockHtml ; }
Get All Block Elements HTML
18,563
public function getElementHtml ( $ element ) { if ( ! isset ( $ element -> template ) && empty ( $ element -> template ) ) { throw new Exception ( "Missing page element template" ) ; } return $ this -> container -> view -> fetch ( "elements/{$element->template}" , [ 'element' => $ element ] ) ; }
Get HTML Element
18,564
public function getCollectionPages ( $ collectionId ) { $ pageMapper = ( $ this -> container -> dataMapper ) ( 'PageMapper' ) ; $ data = $ pageMapper -> findCollectionPagesById ( $ collectionId ) ; return $ data ; }
Get Collection Page List
18,565
public function getGallery ( int $ galleryId = null ) { $ mediaCategory = ( $ this -> container -> dataMapper ) ( 'MediaCategoryMapper' ) ; return $ mediaCategory -> findMediaByCategoryId ( $ galleryId ) ; }
Get Gallery by ID
18,566
public function generateSegments ( string $ root = null ) : void { $ path = rawurldecode ( $ this -> sourceData [ 'path' ] ?? '' ) ; if ( $ path && $ path != '/' ) { if ( $ root && $ root != '/' ) { $ root = '/' . trim ( $ root , '/' ) . '/' ; if ( strpos ( $ path , $ root ) === false ) { throw new HttpException ( "Uri path '{$path}' has no root such '{$root}'" ) ; } $ path = substr ( $ path , strlen ( $ root ) ) ; $ this -> segmentsRoot = $ root ; } $ segments = array_map ( 'trim' , preg_split ( '~/+~' , $ path , - 1 , PREG_SPLIT_NO_EMPTY ) ) ; if ( $ segments != null ) { foreach ( $ segments as $ i => $ segment ) { $ this -> segments [ $ i + 1 ] = $ segment ; } } } }
Generate segments .
18,567
public function showMessages ( ) { $ messageMapper = ( $ this -> container -> dataMapper ) ( 'MessageMapper' ) ; $ messages = $ messageMapper -> findAllInDateOrder ( ) ; return $ this -> render ( 'messages.html' , [ 'messages' => $ messages ] ) ; }
Show All Messages
18,568
public function findMediaByCategoryId ( int $ catId = null ) { if ( null === $ catId ) { return ; } $ this -> sql = <<<SQLselect mc.category, m.id, m.file, m.captionfrom media_category mcjoin media_category_map mcp on mc.id = mcp.category_idjoin media m on mcp.media_id = m.idwhere mc.id = ?SQL ; $ this -> bindValues [ ] = $ catId ; return $ this -> find ( ) ; }
Find Media By Category ID
18,569
public function saveMediaCategoryAssignments ( int $ mediaId , array $ categoryIds = null ) { $ this -> deleteMediaCategoryAssignments ( $ mediaId ) ; if ( null !== $ categoryIds ) { $ this -> sql = 'insert into media_category_map (media_id, category_id) values ' ; foreach ( $ categoryIds as $ id ) { $ this -> sql .= '(?, ?),' ; $ this -> bindValues [ ] = $ mediaId ; $ this -> bindValues [ ] = $ id ; } $ this -> sql = rtrim ( $ this -> sql , ',' ) . ';' ; $ this -> execute ( ) ; } }
Save Media Category Assignments
18,570
public function deleteMediaCategoryAssignments ( int $ mediaId ) { $ this -> sql = 'delete from media_category_map where media_id = ?' ; $ this -> bindValues [ ] = $ mediaId ; $ this -> execute ( ) ; }
Delete Media Category Assignments
18,571
public function anyIndex ( ) { return Factory :: factory ( 'ApiResponse' , 'nails/module-api' ) -> setData ( [ 'id' => ( int ) activeUser ( 'id' ) , 'first_name' => activeUser ( 'first_name' ) ? : null , 'last_name' => activeUser ( 'last_name' ) ? : null , 'email' => activeUser ( 'email' ) ? : null , 'username' => activeUser ( 'username' ) ? : null , 'avatar' => cdnAvatar ( ) ? : null , 'gender' => activeUser ( 'gender' ) ? : null , ] ) ; }
Returns basic details about the currently logged in user
18,572
private function wrapHelp ( $ argumentPart , & $ help , $ minSize = 29 ) { if ( strlen ( $ argumentPart ) <= $ minSize ) { return $ argumentPart . array_shift ( $ help ) ; } else { return $ argumentPart ; } }
Wraps the help message arround the argument by producing two different columns . The argument is placed in the first column and the help message is placed in the second column .
18,573
protected function getDefaultConfig ( ) { $ defaultConfig = [ 'denyExtensionRename' => true , 'denyUpdateCheck' => true , 'dirnameChangeChars' => [ ' ' => '_' , ':' => '_' ] , 'disabled' => false , 'filenameChangeChars' => [ ' ' => '_' , ':' => '_' ] , 'jpegQuality' => 100 , 'uploadDir' => UPLOADED , 'uploadURL' => Router :: url ( '/files' , true ) , 'types' => $ this -> getTypes ( ) , ] ; if ( ! $ this -> Auth -> isGroup ( [ 'admin' ] ) ) { $ defaultConfig [ 'access' ] [ 'dirs' ] = [ 'create' => true , 'delete' => false , 'rename' => false , ] ; $ defaultConfig [ 'access' ] [ 'files' ] = [ 'upload' => true , 'delete' => false , 'copy' => true , 'move' => false , 'rename' => false , ] ; } return $ defaultConfig ; }
Internal method to get the default config
18,574
public function getTypes ( ) { list ( $ folders ) = ( new Folder ( UPLOADED ) ) -> read ( true , true ) ; foreach ( $ folders as $ type ) { $ types [ $ type ] = '' ; } $ types [ 'images' ] = '*img' ; return $ types ; }
Gets the file types supported by KCFinder
18,575
protected function uploadedDirIsWriteable ( ) { $ result = $ this -> Checkup -> Webroot -> isWriteable ( ) ; return $ result && array_key_exists ( UPLOADED , $ result ) ? $ result [ UPLOADED ] : false ; }
Internal method to check if the uploaded directory is writeable
18,576
public function call ( $ service , ... $ params ) { if ( ! $ this -> hasHandler ( $ service ) ) { throw ServiceHandlerMethodException :: notFound ( $ service ) ; } return $ this -> container -> make ( $ service ) -> { $ this :: $ handlerMethod } ( ... $ params ) ; }
Call a service through its appropriate handler .
18,577
protected function getPostObject ( ) : array { $ oInput = Factory :: service ( 'Input' ) ; $ oUserGroupModel = Factory :: model ( 'UserGroup' , 'nails/module-auth' ) ; $ oUserPasswordModel = Factory :: model ( 'UserPassword' , 'nails/module-auth' ) ; return [ 'slug' => $ oInput -> post ( 'slug' ) , 'label' => $ oInput -> post ( 'label' ) , 'description' => $ oInput -> post ( 'description' ) , 'default_homepage' => $ oInput -> post ( 'default_homepage' ) , 'registration_redirect' => $ oInput -> post ( 'registration_redirect' ) , 'acl' => $ oUserGroupModel -> processPermissions ( $ oInput -> post ( 'acl' ) ) , 'password_rules' => $ oUserPasswordModel -> processRules ( $ oInput -> post ( 'pw' ) ) , ] ; }
Extract data from post variable
18,578
public function set_default ( ) : void { if ( ! userHasPermission ( 'admin:auth:groups:setDefault' ) ) { show404 ( ) ; } $ oUri = Factory :: service ( 'Uri' ) ; $ oUserGroupModel = Factory :: model ( 'UserGroup' , 'nails/module-auth' ) ; $ oSession = Factory :: service ( 'Session' , 'nails/module-auth' ) ; if ( $ oUserGroupModel -> setAsDefault ( $ oUri -> segment ( 5 ) ) ) { $ oSession -> setFlashData ( 'success' , 'Group set as default successfully.' ) ; } else { $ oSession -> setFlashData ( 'error' , 'Failed to set default user group. ' . $ oUserGroupModel -> lastError ( ) ) ; } redirect ( 'admin/auth/groups' ) ; }
Set the default user group
18,579
public function build ( ) { if ( $ this -> isBuild ) { return ; } $ settings = $ this -> getObject ( ) ; $ form = $ this -> formManager -> get ( $ settings -> getForm ( ) ) ; $ this -> setLabel ( $ form -> getOption ( 'settings_label' ) ? : sprintf ( 'Customize enabled elements for %s' , get_class ( $ form ) ) ) ; $ this -> add ( array ( 'type' => 'Checkbox' , 'name' => 'isActive' , 'options' => array ( 'label' => 'Activate' , 'long_label' => 'Enables the form element customization.' , ) , 'attributes' => array ( 'class' => 'decfs-active-toggle' , ) , ) ) ; $ element = new DisableElementsCapableFormSettings ( 'disableElements' ) ; $ element -> setForm ( $ form ) ; $ this -> add ( $ element ) ; $ this -> isBuild = true ; }
Builds this fieldset .
18,580
public function toPHP ( $ value , Driver $ driver ) { $ value = parent :: toPHP ( $ value , $ driver ) ; return is_array ( $ value ) ? array_map ( function ( $ value ) { return is_array ( $ value ) ? new Entity ( $ value ) : $ value ; } , $ value ) : $ value ; }
Convert string values to PHP arrays .
18,581
public function setFetchMode ( $ mode , ... $ args ) { if ( is_string ( $ mode ) ) { array_unshift ( $ args , PDO :: $ mode ) ; $ mode = PDO :: FETCH_CLASS ; } $ this -> fetchArgs = array_merge ( [ $ mode ] , $ args ) ; return $ this ; }
Set the default fetch mode .
18,582
protected function sendResponse ( $ output , $ status = 200 , $ header = array ( ) , $ json = true ) { $ output = date ( 'Y.m.d H:i:s' ) . " - $output" ; $ data = json_encode ( [ 'output' => $ output ] ) ; return new JsonResponse ( $ data , $ status , $ header , $ json ) ; }
Erstellt das Response .
18,583
function onBeforeInit ( ) { foreach ( Requirements :: $ disable_cache_busted_file_extensions_for as $ class ) { if ( is_a ( $ this -> owner , $ class ) ) { Requirements :: $ use_cache_busted_file_extensions = false ; } } }
Disable cache busted file extensions for some classes ( usually
18,584
public function execute ( Arguments $ args , ConsoleIo $ io ) { foreach ( $ this -> config as $ file ) { list ( $ plugin , $ file ) = pluginSplit ( $ file ) ; $ this -> copyFile ( $ io , Plugin :: path ( $ plugin , 'config' . DS . $ file . '.php' ) , Folder :: slashTerm ( CONFIG ) . $ file . '.php' ) ; } return null ; }
Copies the configuration files
18,585
public function saveAll ( ) { $ this -> init ( ) ; $ parameters = [ ] ; foreach ( $ this -> configurations as $ configuration ) { $ parameters = array_merge ( $ parameters , $ this -> getConfigurationParameters ( $ configuration ) ) ; } $ this -> parameterRepository -> save ( $ parameters ) ; }
Saves configurations .
18,586
public function init ( ) { if ( $ this -> initialized ) { return ; } $ parameters = [ ] ; foreach ( $ this -> parameterRepository -> getAllParameters ( ) as $ parameter ) { $ configurationName = $ parameter -> getConfigurationName ( ) ; if ( ! isset ( $ parameters [ $ configurationName ] ) ) { $ parameters [ $ configurationName ] = [ ] ; } $ parameters [ $ configurationName ] [ $ parameter -> getName ( ) ] = $ parameter ; } $ this -> persistedParameters = $ parameters ; foreach ( $ this -> configurations as $ configuration ) { $ configurationName = $ configuration -> getName ( ) ; $ this -> initConfiguration ( $ configuration , isset ( $ parameters [ $ configurationName ] ) ? $ parameters [ $ configurationName ] : [ ] ) ; } $ this -> initialized = true ; }
Initializes configurations .
18,587
protected function setup ( $ bForceSetup = false ) { if ( ! empty ( $ this -> oSession ) ) { return ; } $ oInput = Factory :: service ( 'Input' ) ; if ( ! $ oInput :: isCli ( ) && class_exists ( 'CI_Controller' ) ) { $ oConfig = Factory :: service ( 'Config' ) ; $ sCookieName = $ oConfig -> item ( 'sess_cookie_name' ) ; if ( $ bForceSetup || $ oInput :: cookie ( $ sCookieName ) ) { $ oCi = get_instance ( ) ; $ oCi -> load -> library ( 'session' ) ; if ( empty ( $ oCi -> session ) ) { throw new NailsException ( 'Failed to load CodeIgniter session library.' ) ; } $ this -> oSession = $ oCi -> session ; } } }
Attempts to restore or set up a session
18,588
public function setFlashData ( $ mKey , $ mValue = null ) { $ this -> setup ( true ) ; if ( empty ( $ this -> oSession ) ) { return $ this ; } $ this -> oSession -> set_flashdata ( $ mKey , $ mValue ) ; return $ this ; }
Sets session flashdata
18,589
public function getFlashData ( $ sKey = null ) { $ this -> setup ( ) ; if ( empty ( $ this -> oSession ) ) { return null ; } return $ this -> oSession -> flashdata ( $ sKey ) ; }
Retrieves flash data from the session
18,590
public function setUserData ( $ mKey , $ mValue = null ) { $ this -> setup ( true ) ; if ( empty ( $ this -> oSession ) ) { return $ this ; } $ this -> oSession -> set_userdata ( $ mKey , $ mValue ) ; return $ this ; }
Writes data to the user s session
18,591
public function getUserData ( $ sKey = null ) { $ this -> setup ( ) ; if ( empty ( $ this -> oSession ) ) { return null ; } return $ this -> oSession -> userdata ( $ sKey ) ; }
Retrieves data from the session
18,592
public function unsetUserData ( $ mKey ) { if ( empty ( $ this -> oSession ) ) { return $ this ; } $ this -> oSession -> unset_userdata ( $ mKey ) ; return $ this ; }
Removes data from the session
18,593
public function destroy ( ) { if ( empty ( $ this -> oSession ) ) { return $ this ; } $ oConfig = Factory :: service ( 'Config' ) ; $ sCookieName = $ oConfig -> item ( 'sess_cookie_name' ) ; $ this -> oSession -> sess_destroy ( ) ; if ( isset ( $ _COOKIE ) && array_key_exists ( $ sCookieName , $ _COOKIE ) ) { delete_cookie ( $ sCookieName ) ; unset ( $ _COOKIE [ $ sCookieName ] ) ; } return $ this ; }
Destroy the user s session
18,594
public function regenerate ( $ bDestroy = false ) { if ( empty ( $ this -> oSession ) ) { return $ this ; } $ this -> oSession -> sess_regenerate ( $ bDestroy ) ; return $ this ; }
Regenerate the user s session
18,595
public static function getDataProviderPager ( $ dataProvider , $ attr = true ) { if ( $ attr == true ) $ data = $ dataProvider -> getPagination ( ) ; else $ data = $ dataProvider ; $ pageCount = $ data -> itemCount >= $ data -> pageSize ? ( $ data -> itemCount % $ data -> pageSize === 0 ? ( int ) ( $ data -> itemCount / $ data -> pageSize ) : ( int ) ( $ data -> itemCount / $ data -> pageSize ) + 1 ) : 1 ; $ currentPage = $ data -> itemCount != 0 ? $ data -> currentPage + 1 : 1 ; $ nextPage = ( ( $ pageCount != $ currentPage ) && ( $ pageCount > $ currentPage ) ) ? $ currentPage + 1 : 0 ; $ return = array ( 'pageVar' => $ data -> pageVar , 'itemCount' => $ data -> itemCount , 'pageSize' => $ data -> pageSize , 'pageCount' => $ pageCount , 'currentPage' => $ currentPage , 'nextPage' => $ nextPage , ) ; return $ return ; }
get data provider pager
18,596
public static function validHostURL ( $ targetUrl ) { $ req = Yii :: app ( ) -> request ; $ url = ( $ req -> port == 80 ? 'http://' : 'https://' ) . $ req -> serverName ; if ( substr ( $ targetUrl , 0 , 1 ) != '/' ) $ targetUrl = '/' . $ targetUrl ; return $ url = $ url . $ targetUrl ; }
Valid target api url if application ecc3 datacenter is accessed from other place Defined host url + target url
18,597
public function remove ( $ entity ) { $ entity -> setState ( 0 ) ; $ this -> em -> persist ( $ entity ) ; $ this -> em -> flush ( ) ; }
We don t delete the user but just disable it
18,598
private function settingEnv ( array $ data ) : void { $ loadedVars = \ array_flip ( \ explode ( ',' , \ getenv ( self :: FULL_KEY ) ) ) ; unset ( $ loadedVars [ '' ] ) ; foreach ( $ data as $ name => $ value ) { if ( \ is_int ( $ name ) || ! \ is_string ( $ value ) ) { continue ; } $ name = \ strtoupper ( $ name ) ; $ notHttpName = 0 !== \ strpos ( $ name , 'HTTP_' ) ; if ( ( isset ( $ _ENV [ $ name ] ) || ( isset ( $ _SERVER [ $ name ] ) && $ notHttpName ) ) && ! isset ( $ loadedVars [ $ name ] ) ) { continue ; } if ( $ value && \ defined ( $ value ) ) { $ value = \ constant ( $ value ) ; } \ putenv ( "$name=$value" ) ; $ _ENV [ $ name ] = $ value ; if ( $ notHttpName ) { $ _SERVER [ $ name ] = $ value ; } $ loadedVars [ $ name ] = true ; } if ( $ loadedVars ) { $ loadedVars = \ implode ( ',' , \ array_keys ( $ loadedVars ) ) ; \ putenv ( self :: FULL_KEY . "=$loadedVars" ) ; $ _ENV [ self :: FULL_KEY ] = $ loadedVars ; $ _SERVER [ self :: FULL_KEY ] = $ loadedVars ; } }
setting env data
18,599
public function setColumn ( $ name , $ type , $ nullDefault = false ) { $ this -> columns [ $ name ] = $ this -> createColumnDef ( $ type , $ nullDefault ) ; return $ this ; }
Define a column .