idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
41,000
public function _decode ( $ val ) { if ( ! is_string ( $ val ) ) { return $ val ; } $ decoded = json_decode ( $ val , $ this -> _config [ 'decodeParams' ] [ 'assoc' ] , $ this -> _config [ 'decodeParams' ] [ 'depth' ] , $ this -> _config [ 'decodeParams' ] [ 'options' ] ) ; if ( $ decoded === false ) { return false ; } if ( $ this -> _config [ 'decodeParams' ] [ 'assoc' ] ) { $ decoded = ( array ) $ decoded ; } if ( $ this -> _config [ 'output' ] === 'param' ) { $ decoded = $ this -> _toParam ( $ decoded ) ; } elseif ( $ this -> _config [ 'output' ] === 'list' ) { $ decoded = $ this -> _toList ( $ decoded ) ; } return $ decoded ; }
Fields are absolutely necessary to function properly!
41,001
public function metaRobots ( $ type = null ) { if ( $ type === null && ( $ meta = Configure :: read ( 'Config.robots' ) ) !== null ) { $ type = $ meta ; } $ content = [ ] ; if ( $ type === 'public' ) { $ content [ 'robots' ] = [ 'index' , 'follow' , 'noarchive' ] ; } else { $ content [ 'robots' ] = [ 'noindex' , 'nofollow' , 'noarchive' ] ; } $ return = '<meta name="robots" content="' . implode ( ',' , $ content [ 'robots' ] ) . '" />' ; return $ return ; }
Convenience method for clean ROBOTS allowance
41,002
public function metaName ( $ name = null , $ content = null ) { if ( empty ( $ name ) || empty ( $ content ) ) { return '' ; } $ content = ( array ) $ content ; $ return = '<meta name="' . $ name . '" content="' . implode ( ', ' , $ content ) . '" />' ; return $ return ; }
Convenience method for clean meta name tags
41,003
public function metaDescription ( $ content , $ language = null , $ options = [ ] ) { if ( ! empty ( $ language ) ) { $ options [ 'lang' ] = mb_strtolower ( $ language ) ; } elseif ( $ language !== false ) { $ options [ 'lang' ] = Configure :: read ( 'Config.locale' ) ; } return $ this -> Html -> meta ( 'description' , $ content , $ options ) ; }
Convenience method for meta description
41,004
public function metaKeywords ( $ keywords = null , $ language = null , $ escape = true ) { if ( $ keywords === null ) { $ keywords = Configure :: read ( 'Config.keywords' ) ; } if ( is_array ( $ keywords ) ) { $ keywords = implode ( ', ' , $ keywords ) ; } if ( $ escape ) { $ keywords = h ( $ keywords ) ; } $ options = [ ] ; if ( ! empty ( $ language ) ) { $ options [ 'lang' ] = mb_strtolower ( $ language ) ; } elseif ( $ language !== false ) { $ options [ 'lang' ] = Configure :: read ( 'Config.locale' ) ; } return $ this -> Html -> meta ( 'keywords' , $ keywords , $ options ) ; }
Convenience method to output meta keywords
41,005
public function metaCanonical ( $ url = null , $ full = false ) { $ canonical = $ this -> Url -> build ( $ url , $ full ) ; $ options = [ 'rel' => 'canonical' , 'link' => $ canonical ] ; return $ this -> Html -> meta ( $ options ) ; }
Convenience function for canonical SEO links
41,006
public function metaAlternate ( $ url , $ lang , $ full = false ) { $ url = $ this -> Url -> build ( $ url , $ full ) ; $ lang = ( array ) $ lang ; $ res = [ ] ; foreach ( $ lang as $ language => $ countries ) { if ( is_numeric ( $ language ) ) { $ language = '' ; } else { $ language .= '-' ; } $ countries = ( array ) $ countries ; foreach ( $ countries as $ country ) { $ l = $ language . $ country ; $ options = [ 'rel' => 'alternate' , 'hreflang' => $ l , 'link' => $ url ] ; $ res [ ] = $ this -> Html -> meta ( $ options ) . PHP_EOL ; } } return implode ( '' , $ res ) ; }
Convenience method for alternate SEO links
41,007
public function beforeSave ( Event $ event , EntityInterface $ entity , ArrayObject $ options ) { $ formField = $ this -> _config [ 'formField' ] ; $ field = $ this -> _config [ 'field' ] ; $ PasswordHasher = $ this -> _getPasswordHasher ( $ this -> _config [ 'passwordHasher' ] ) ; if ( $ entity -> get ( $ formField ) !== null ) { $ entity -> set ( $ field , $ PasswordHasher -> hash ( $ entity -> get ( $ formField ) ) ) ; if ( ! $ entity -> get ( $ field ) ) { throw new RuntimeException ( 'Empty field' ) ; } $ entity -> unsetProperty ( $ formField ) ; if ( $ this -> _config [ 'confirm' ] ) { $ formFieldRepeat = $ this -> _config [ 'formFieldRepeat' ] ; $ entity -> unsetProperty ( $ formFieldRepeat ) ; } if ( $ this -> _config [ 'current' ] ) { $ formFieldCurrent = $ this -> _config [ 'formFieldCurrent' ] ; $ entity -> unsetProperty ( $ formFieldCurrent ) ; } } else { $ PasswordHasher -> hash ( '' ) ; } }
Hashing the password and whitelisting
41,008
public function nl2brExceptPre ( $ str ) { $ ex = explode ( 'pre>' , $ str ) ; $ ct = count ( $ ex ) ; $ newstr = '' ; for ( $ i = 0 ; $ i < $ ct ; $ i ++ ) { if ( ( $ i % 2 ) == 0 ) { $ newstr .= nl2br ( $ ex [ $ i ] ) ; } else { $ newstr .= $ ex [ $ i ] ; } if ( $ ct - 1 != $ i ) { $ newstr .= 'pre>' ; } } return $ newstr ; }
Convert newlines to HTML line breaks except within PRE tags
41,009
public function image ( $ text , array $ options = [ ] ) { return $ this -> Html -> image ( $ this -> uri ( $ text ) , $ options ) ; }
Main barcode display function
41,010
public function formatText ( $ text , $ type = null ) { switch ( $ type ) { case 'text' : break ; case 'url' : $ text = $ this -> Url -> build ( $ text , true ) ; break ; case 'sms' : $ text = 'smsto:' . implode ( ':' , ( array ) $ text ) ; break ; case 'tel' : $ text = 'tel:' . $ text ; break ; case 'email' : $ text = 'mailto:' . $ text ; break ; case 'geo' : $ text = 'geo:' . implode ( ',' , ( array ) $ text ) ; break ; case 'market' : $ text = 'market://search?q=pname:' . $ text ; } return $ text ; }
Format a text in a specific format - url sms tel email market geo
41,011
protected function _init ( ) { $ mobileOverwrite = $ this -> Controller -> getRequest ( ) -> getQuery ( 'mobile' ) ; if ( $ mobileOverwrite !== null ) { if ( $ mobileOverwrite === '-1' ) { $ this -> Controller -> getRequest ( ) -> getSession ( ) -> delete ( 'User.mobile' ) ; } else { $ wantsMobile = ( bool ) $ mobileOverwrite ; $ this -> Controller -> getRequest ( ) -> getSession ( ) -> write ( 'User.mobile' , ( int ) $ wantsMobile ) ; } } $ this -> isMobile ( ) ; if ( ! $ this -> _config [ 'auto' ] ) { return ; } $ this -> setMobile ( ) ; }
Main auto - detection logic including session based storage to avoid multiple lookups .
41,012
public function setMobile ( ) { if ( $ this -> isMobile === null ) { $ this -> isMobile ( ) ; } $ forceMobile = $ this -> Controller -> getRequest ( ) -> getSession ( ) -> read ( 'User.mobile' ) ; if ( $ forceMobile !== null && ! $ forceMobile ) { $ this -> setMobile = false ; } elseif ( $ forceMobile !== null && $ forceMobile || $ this -> isMobile ( ) ) { $ this -> setMobile = true ; } else { $ this -> setMobile = false ; } $ urlParams = [ ] ; if ( ! isset ( $ urlParams [ 'pass' ] ) ) { $ urlParams [ 'pass' ] = [ ] ; } $ urlParams = array_merge ( $ urlParams , $ urlParams [ 'pass' ] ) ; unset ( $ urlParams [ 'pass' ] ) ; if ( isset ( $ urlParams [ 'prefix' ] ) ) { unset ( $ urlParams [ 'prefix' ] ) ; } if ( $ this -> setMobile ) { $ urlParams [ '?' ] [ 'mobile' ] = 0 ; $ url = Router :: url ( $ urlParams ) ; $ this -> Controller -> set ( 'desktopUrl' , $ url ) ; } else { $ urlParams [ '?' ] [ 'mobile' ] = 1 ; $ url = Router :: url ( $ urlParams ) ; $ this -> Controller -> set ( 'mobileUrl' , $ url ) ; } Configure :: write ( 'User.setMobile' , ( int ) $ this -> setMobile ) ; if ( ! $ this -> setMobile ) { return ; } $ this -> Controller -> viewBuilder ( ) -> setClassName ( 'Theme' ) ; $ this -> Controller -> viewBuilder ( ) -> setTheme ( 'Mobile' ) ; }
Sets mobile views as Mobile theme .
41,013
public function isMobile ( ) { if ( $ this -> isMobile !== null ) { return $ this -> isMobile ; } $ this -> isMobile = Configure :: read ( 'User.isMobile' ) ; if ( $ this -> isMobile !== null ) { return $ this -> isMobile ; } $ this -> isMobile = ( bool ) $ this -> detect ( ) ; Configure :: write ( 'User.isMobile' , ( int ) $ this -> isMobile ) ; return $ this -> isMobile ; }
Determines if we need to so serve mobile views based on session preference and browser headers .
41,014
public function detect ( ) { if ( ! $ this -> _config [ 'engine' ] ) { if ( isset ( $ this -> Controller -> RequestHandler ) ) { return $ this -> Controller -> getRequest ( ) -> is ( 'mobile' ) || $ this -> Controller -> RequestHandler -> accepts ( 'wap' ) ; } return $ this -> Controller -> getRequest ( ) -> is ( 'mobile' ) ; } if ( is_callable ( $ this -> _config [ 'engine' ] ) ) { return call_user_func ( $ this -> _config [ 'engine' ] ) ; } throw new RuntimeException ( sprintf ( 'Engine %s not available' , $ this -> _config [ 'engine' ] ) ) ; }
Detects if the current request is from a mobile device .
41,015
public function neighbors ( array $ neighbors , $ field , array $ options = [ ] ) { $ name = 'Record' ; if ( ! empty ( $ options [ 'name' ] ) ) { $ name = ucfirst ( $ options [ 'name' ] ) ; } $ prevSlug = $ nextSlug = null ; if ( ! empty ( $ options [ 'slug' ] ) ) { if ( ! empty ( $ neighbors [ 'prev' ] ) ) { $ prevSlug = $ this -> slug ( $ neighbors [ 'prev' ] [ $ field ] ) ; } if ( ! empty ( $ neighbors [ 'next' ] ) ) { $ nextSlug = $ this -> slug ( $ neighbors [ 'next' ] [ $ field ] ) ; } } $ titleField = $ field ; if ( ! empty ( $ options [ 'titleField' ] ) ) { $ titleField = $ options [ 'titleField' ] ; } if ( ! isset ( $ options [ 'escape' ] ) || $ options [ 'escape' ] === false ) { $ titleField = h ( $ titleField ) ; } $ ret = '<div class="next-prev-navi nextPrevNavi">' ; if ( ! empty ( $ neighbors [ 'prev' ] ) ) { $ url = [ $ neighbors [ 'prev' ] [ 'id' ] , $ prevSlug ] ; if ( ! empty ( $ options [ 'url' ] ) ) { $ url += $ options [ 'url' ] ; } $ ret .= $ this -> Html -> link ( $ this -> icon ( 'prev' ) . '&nbsp;' . __d ( 'tools' , 'prev' . $ name ) , $ url , [ 'escape' => false , 'title' => $ neighbors [ 'prev' ] [ $ titleField ] ] ) ; } else { $ ret .= $ this -> icon ( 'prev' ) ; } $ ret .= '&nbsp;&nbsp;' ; if ( ! empty ( $ neighbors [ 'next' ] ) ) { $ url = [ $ neighbors [ 'next' ] [ 'id' ] , $ nextSlug ] ; if ( ! empty ( $ options [ 'url' ] ) ) { $ url += $ options [ 'url' ] ; } $ ret .= $ this -> Html -> link ( $ this -> icon ( 'next' ) . '&nbsp;' . __d ( 'tools' , 'next' . $ name ) , $ url , [ 'escape' => false , 'title' => $ neighbors [ 'next' ] [ $ titleField ] ] ) ; } else { $ ret .= $ this -> icon ( 'next' ) . '&nbsp;' . __d ( 'tools' , 'next' . $ name ) ; } $ ret .= '</div>' ; return $ ret ; }
Display neighbor quicklinks
41,016
public function genderIcon ( $ value ) { $ value = ( int ) $ value ; if ( $ value == static :: GENDER_FEMALE ) { $ icon = $ this -> icon ( 'female' ) ; } elseif ( $ value == static :: GENDER_MALE ) { $ icon = $ this -> icon ( 'male' ) ; } else { $ icon = $ this -> icon ( 'genderless' , [ ] , [ 'title' => __d ( 'tools' , 'Unknown' ) ] ) ; } return $ icon ; }
Displays gender icon
41,017
public function icon ( $ icon , array $ options = [ ] , array $ attributes = [ ] ) { if ( ! $ icon ) { return '' ; } $ defaults = [ 'translate' => true , ] ; $ options += $ defaults ; $ type = $ icon ; if ( $ this -> getConfig ( 'autoPrefix' ) && empty ( $ options [ 'iconNamespace' ] ) ) { $ namespace = $ this -> detectNamespace ( $ icon ) ; if ( $ namespace ) { $ options [ 'iconNamespace' ] = $ namespace ; $ options [ 'autoPrefix' ] = false ; $ icon = substr ( $ icon , strlen ( $ namespace ) + 1 ) ; } } if ( ! isset ( $ attributes [ 'title' ] ) ) { if ( isset ( $ options [ 'title' ] ) ) { $ attributes [ 'title' ] = $ options [ 'title' ] ; } else { $ attributes [ 'title' ] = Inflector :: humanize ( $ icon ) ; } } return $ this -> _fontIcon ( $ type , $ options , $ attributes ) ; }
Icons using the default namespace or an already prefixed one .
41,018
protected function _customIcon ( $ icon , array $ options = [ ] , array $ attributes = [ ] ) { $ translate = isset ( $ options [ 'translate' ] ) ? $ options [ 'translate' ] : true ; $ type = pathinfo ( $ icon , PATHINFO_FILENAME ) ; $ title = ucfirst ( $ type ) ; $ alt = $ this -> slug ( $ title ) ; if ( $ translate !== false ) { $ title = __ ( $ title ) ; $ alt = __ ( $ alt ) ; } $ alt = '[' . $ alt . ']' ; $ defaults = [ 'title' => $ title , 'alt' => $ alt , 'class' => 'icon' ] ; $ options = $ attributes + $ options ; $ options += $ defaults ; if ( substr ( $ icon , 0 , 1 ) !== '/' ) { $ icon = 'icons/' . $ icon ; } return $ this -> Html -> image ( $ icon , $ options ) ; }
Deprecated img icons font icons should be used instead but sometimes we still need a custom img icon .
41,019
protected function _fontIcon ( $ type , $ options , $ attributes ) { $ iconClass = $ type ; $ options += $ this -> _config ; if ( $ options [ 'autoPrefix' ] && $ options [ 'iconNamespace' ] ) { $ iconClass = $ options [ 'iconNamespace' ] . '-' . $ iconClass ; } if ( $ options [ 'iconNamespace' ] ) { $ iconClass = $ options [ 'iconNamespace' ] . ' ' . $ iconClass ; } if ( isset ( $ this -> _config [ 'fontIcons' ] [ $ type ] ) ) { $ iconClass = $ this -> _config [ 'fontIcons' ] [ $ type ] ; } $ defaults = [ 'class' => 'icon icon-' . $ type . ' ' . $ iconClass , 'escape' => true , ] ; $ options += $ defaults ; if ( ! isset ( $ attributes [ 'title' ] ) ) { $ attributes [ 'title' ] = ucfirst ( $ type ) ; if ( ! isset ( $ options [ 'translate' ] ) || $ options [ 'translate' ] !== false ) { $ attributes [ 'title' ] = __ ( $ attributes [ 'title' ] ) ; } } $ attributes += [ 'data-placement' => 'bottom' , 'data-toggle' => 'tooltip' ] ; $ formatOptions = $ attributes + [ 'escape' => $ options [ 'escape' ] , ] ; $ options [ 'attributes' ] = $ this -> template -> formatAttributes ( $ formatOptions ) ; return $ this -> template -> format ( 'icon' , $ options ) ; }
Renders a font icon .
41,020
public function disabledLink ( $ text , array $ options = [ ] ) { $ defaults = [ 'class' => 'disabledLink' , 'title' => __d ( 'tools' , 'notAvailable' ) ] ; $ options += $ defaults ; return $ this -> Html -> tag ( 'span' , $ text , $ options ) ; }
Display a disabled link tag
41,021
public function warning ( $ value , $ ok = false ) { if ( ! $ ok ) { return $ this -> ok ( $ value , false ) ; } return $ value ; }
Returns red colored if not ok
41,022
public function ok ( $ content , $ ok = false , array $ attributes = [ ] ) { if ( $ ok ) { $ type = 'yes' ; $ color = 'green' ; } else { $ type = 'no' ; $ color = 'red' ; } $ options = [ 'type' => $ type , 'color' => $ color ] ; $ options [ 'content' ] = $ content ; $ options [ 'attributes' ] = $ this -> template -> formatAttributes ( $ attributes ) ; return $ this -> template -> format ( 'ok' , $ options ) ; }
Returns green on ok red otherwise
41,023
public function array2table ( array $ array , array $ options = [ ] , array $ attributes = [ ] ) { $ defaults = [ 'null' => '&nbsp;' , 'recursive' => false , 'heading' => true , 'escape' => true ] ; $ options += $ defaults ; if ( empty ( $ array ) ) { return '' ; } if ( ! isset ( $ array [ 0 ] ) || ! is_array ( $ array [ 0 ] ) ) { $ array = [ $ array ] ; } $ attributes += [ 'class' => 'table' ] ; $ attributes = $ this -> template -> formatAttributes ( $ attributes ) ; $ table = "<table$attributes>\n" ; if ( $ options [ 'heading' ] ) { $ table .= "\t<tr>" ; foreach ( array_keys ( $ array [ 0 ] ) as $ heading ) { $ table .= '<th>' . ( $ options [ 'escape' ] ? h ( $ heading ) : $ heading ) . '</th>' ; } $ table .= "</tr>\n" ; } foreach ( $ array as $ row ) { $ table .= "\t<tr>" ; foreach ( $ row as $ cell ) { $ table .= '<td>' ; if ( is_object ( $ cell ) ) { $ cell = ( array ) $ cell ; } if ( $ options [ 'recursive' ] && is_array ( $ cell ) && ! empty ( $ cell ) ) { $ table .= "\n" . static :: array2table ( $ cell , $ options ) . "\n" ; } else { $ table .= ( ! is_array ( $ cell ) && strlen ( $ cell ) > 0 ) ? ( $ options [ 'escape' ] ? h ( $ cell ) : $ cell ) : $ options [ 'null' ] ; } $ table .= '</td>' ; } $ table .= "</tr>\n" ; } $ table .= '</table>' ; return $ table ; }
Translate a result array into a HTML table
41,024
protected function fixateLocale ( ) { $ this -> locale = I18n :: getLocale ( ) ; $ primaryLocale = $ this -> getPrimaryLocale ( ) ; if ( $ primaryLocale && $ primaryLocale !== $ this -> locale ) { I18n :: setLocale ( $ primaryLocale ) ; } }
Switch to primary locale if applicable .
41,025
protected function restoreLocale ( ) { $ primaryLocale = $ this -> getPrimaryLocale ( ) ; if ( $ primaryLocale && $ primaryLocale !== $ this -> locale ) { I18n :: setLocale ( $ this -> locale ) ; } }
Restore to current locale if applicable .
41,026
protected function getPrimaryLocale ( ) { $ primaryLanguage = Configure :: read ( 'Config.defaultLanguage' ) ; if ( Configure :: read ( 'Config.defaultLocale' ) ) { return Configure :: read ( 'Config.defaultLocale' ) ; } $ primaryLocale = Configure :: read ( 'Config.allowedLanguages.' . $ primaryLanguage . '.locale' ) ; return $ primaryLocale ; }
Returns the configured default locale .
41,027
public function create ( $ model = null , array $ options = [ ] ) { $ defaults = [ 'novalidate' => $ this -> _defaultConfig [ 'novalidate' ] ] ; $ options += $ defaults ; return parent :: create ( $ model , $ options ) ; }
Overwrite to allow FormConfig Configure settings to be applied .
41,028
public function needsSlugUpdate ( EntityInterface $ entity , $ deep = false ) { foreach ( ( array ) $ this -> _config [ 'label' ] as $ label ) { if ( $ entity -> isDirty ( $ label ) ) { return true ; } } if ( $ deep ) { $ copy = clone $ entity ; $ this -> slug ( $ copy , [ 'overwrite' => true ] ) ; return $ copy -> get ( $ this -> _config [ 'field' ] ) !== $ entity -> get ( $ this -> _config [ 'field' ] ) ; } return false ; }
Method to find out if the current slug needs updating .
41,029
public function resetSlugs ( $ params = [ ] ) { if ( ! $ this -> _table -> hasField ( $ this -> _config [ 'field' ] ) ) { throw new RuntimeException ( 'Table does not have field ' . $ this -> _config [ 'field' ] ) ; } $ defaults = [ 'page' => 1 , 'limit' => 100 , 'fields' => array_merge ( [ $ this -> _table -> getPrimaryKey ( ) ] , $ this -> _config [ 'label' ] ) , 'order' => $ this -> _table -> getDisplayField ( ) . ' ASC' , 'conditions' => $ this -> _config [ 'scope' ] , 'overwrite' => true , ] ; $ params = array_merge ( $ defaults , $ params ) ; $ conditions = $ params [ 'conditions' ] ; $ count = $ this -> _table -> find ( 'all' , compact ( 'conditions' ) ) -> count ( ) ; $ max = ini_get ( 'max_execution_time' ) ; if ( $ max ) { set_time_limit ( max ( $ max , $ count / 100 ) ) ; } $ this -> setConfig ( $ params , null , false ) ; while ( ( $ records = $ this -> _table -> find ( 'all' , $ params ) -> toArray ( ) ) ) { foreach ( $ records as $ record ) { $ record -> isNew ( true ) ; $ fields = array_merge ( [ $ this -> _table -> getPrimaryKey ( ) , $ this -> _config [ 'field' ] ] , $ this -> _config [ 'label' ] ) ; $ options = [ 'validate' => true , 'fields' => $ fields , ] ; if ( ! $ this -> _table -> save ( $ record , $ options ) ) { throw new RuntimeException ( print_r ( $ record -> getErrors ( ) , true ) ) ; } } $ params [ 'page' ] ++ ; } return true ; }
ResetSlugs method .
41,030
protected function _multiSlug ( EntityInterface $ entity ) { $ label = $ this -> getConfig ( 'label' ) ; $ field = current ( $ label ) ; $ fields = ( array ) $ entity -> get ( $ field ) ; $ locale = [ ] ; foreach ( $ fields as $ locale => $ _ ) { $ res = null ; foreach ( $ label as $ field ) { $ res = $ entity -> get ( $ field ) ; if ( is_array ( $ entity -> get ( $ field ) ) ) { $ res = $ this -> generateSlug ( $ field [ $ locale ] , $ entity ) ; } } $ locale [ $ locale ] = $ res ; } $ entity -> set ( $ this -> getConfig ( 'slugField' ) , $ locale ) ; }
Multi slug method
41,031
public function getNextAutoIncrement ( ) { $ query = "SHOW TABLE STATUS WHERE name = '" . $ this -> getTable ( ) . "'" ; $ statement = $ this -> _connection -> execute ( $ query ) ; $ result = $ statement -> fetch ( ) ; if ( ! isset ( $ result [ 10 ] ) ) { return false ; } return ( int ) $ result [ 10 ] ; }
Return the next auto increment id from the current table UUIDs will return false
41,032
public function getRelatedInUse ( $ tableName , $ groupField = null , $ type = 'all' , $ options = [ ] ) { if ( $ groupField === null ) { $ groupField = $ this -> belongsTo [ $ tableName ] [ 'foreignKey' ] ; } $ defaults = [ 'contain' => [ $ tableName ] , 'group' => $ groupField , 'order' => isset ( $ this -> $ tableName -> order ) ? $ this -> $ tableName -> order : [ $ tableName . '.' . $ this -> $ tableName -> getDisplayField ( ) => 'ASC' ] , ] ; if ( $ type === 'list' ) { $ defaults [ 'fields' ] = [ $ tableName . '.' . $ this -> $ tableName -> getPrimaryKey ( ) , $ tableName . '.' . $ this -> $ tableName -> getDisplayField ( ) ] ; $ defaults [ 'keyField' ] = $ tableName . '.' . $ this -> $ tableName -> getPrimaryKey ( ) ; $ defaults [ 'valueField' ] = $ tableName . '.' . $ this -> $ tableName -> getDisplayField ( ) ; } $ options += $ defaults ; return $ this -> find ( $ type , $ options ) ; }
Get all related entries that have been used so far
41,033
public function getFieldInUse ( $ groupField , $ type = 'all' , array $ options = [ ] ) { $ defaults = [ 'group' => $ groupField , 'order' => [ $ this -> getDisplayField ( ) => 'ASC' ] , ] ; if ( $ type === 'list' ) { $ defaults [ 'fields' ] = [ '' . $ this -> getPrimaryKey ( ) , '' . $ this -> getDisplayField ( ) ] ; } $ options += $ defaults ; return $ this -> find ( $ type , $ options ) ; }
Get all fields that have been used so far
41,034
protected function _autoCompleteUrl ( $ url ) { if ( mb_strpos ( $ url , '/' ) === 0 ) { $ url = Router :: url ( $ url , true ) ; } elseif ( mb_strpos ( $ url , '://' ) === false && mb_strpos ( $ url , 'www.' ) === 0 ) { $ url = 'http://' . $ url ; } return $ url ; }
Prepend protocol if missing
41,035
protected function _validUrl ( $ url ) { $ headers = Utility :: getHeaderFromUrl ( $ url ) ; if ( $ headers === false ) { return false ; } $ headers = implode ( "\n" , $ headers ) ; $ protocol = mb_strpos ( $ url , 'https://' ) === 0 ? 'HTTP' : 'HTTP' ; if ( ! preg_match ( '#^' . $ protocol . '/.*?\s+[(200|301|302)]+\s#i' , $ headers ) ) { return false ; } if ( preg_match ( '#^' . $ protocol . '/.*?\s+[(404|999)]+\s#i' , $ headers ) ) { return false ; } return true ; }
Checks if a url is valid
41,036
public function validateTime ( $ value , $ options = [ ] , array $ context = [ ] ) { if ( ! $ value ) { return false ; } $ dateTime = explode ( ' ' , $ value , 2 ) ; $ value = array_pop ( $ dateTime ) ; if ( Validation :: time ( $ value ) ) { if ( ! empty ( $ options [ 'after' ] ) && isset ( $ context [ 'data' ] [ $ options [ 'after' ] ] ) ) { if ( $ context [ 'data' ] [ $ options [ 'after' ] ] >= $ value ) { return false ; } } if ( ! empty ( $ options [ 'before' ] ) && isset ( $ context [ 'data' ] [ $ options [ 'before' ] ] ) ) { if ( $ context [ 'data' ] [ $ options [ 'before' ] ] <= $ value ) { return false ; } } return true ; } return false ; }
Validation of Time fields
41,037
public static function date ( $ min = null , $ max = null , $ formatReturn = null ) { if ( $ min === null && $ max === null ) { $ res = time ( ) ; } elseif ( $ min > 0 && $ max === null ) { $ res = $ min ; } elseif ( $ min > 0 && $ max > 0 ) { $ res = static :: int ( $ min , $ max ) ; } else { $ res = time ( ) ; } $ res = 0 ; $ formatReturnAs = FORMAT_DB_DATETIME ; if ( $ formatReturn !== null ) { if ( $ formatReturn === false ) { return $ res ; } $ formatReturnAs = $ formatReturn ; } return date ( $ formatReturnAs ) ; }
1950 - 01 - 01 - 2050 - 12 - 31
41,038
public static function dob ( $ min = 18 , $ max = 100 ) { $ dobYear = ( int ) date ( 'Y' ) - ( static :: int ( $ min , $ max ) ) ; $ dobMonth = static :: int ( 1 , 12 ) ; if ( $ dobMonth == 2 ) { if ( $ dobYear % 4 || $ dobYear % 400 ) { $ maxDays = 29 ; } else { $ maxDays = 28 ; } } elseif ( in_array ( $ dobMonth , [ 4 , 6 , 9 , 11 ] ) ) { $ maxDays = 30 ; } else { $ maxDays = 31 ; } $ dobDay = static :: int ( 1 , $ maxDays ) ; $ dob = sprintf ( '%4d-%02d-%02d' , $ dobYear , $ dobMonth , $ dobDay ) ; return $ dob ; }
Returns a date of birth within the specified age range
41,039
public static function pronounceablePwd ( $ length = 10 ) { srand ( ( double ) microtime ( ) * 1000000 ) ; $ password = '' ; $ vowels = [ 'a' , 'e' , 'i' , 'o' , 'u' ] ; $ cons = [ 'b' , 'c' , 'd' , 'g' , 'h' , 'j' , 'k' , 'l' , 'm' , 'n' , 'p' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'tr' , 'cr' , 'br' , 'fr' , 'th' , 'dr' , 'ch' , 'ph' , 'wr' , 'st' , 'sp' , 'sw' , 'pr' , 'sl' , 'cl' ] ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ password .= $ cons [ mt_rand ( 0 , 31 ) ] . $ vowels [ mt_rand ( 0 , 4 ) ] ; } return substr ( $ password , 0 , $ length ) ; }
Generates a password
41,040
public static function pwd ( $ length , $ chars = null ) { if ( $ chars === null ) { $ chars = '234567890abcdefghijkmnopqrstuvwxyz' ; } $ i = 0 ; $ password = '' ; $ max = strlen ( $ chars ) - 1 ; while ( $ i < $ length ) { $ password .= $ chars [ mt_rand ( 0 , $ max ) ] ; $ i ++ ; } return $ password ; }
Generates random passwords .
41,041
public function mimeTypes ( $ coreHasPrecedence = false ) { if ( $ coreHasPrecedence ) { return $ this -> _mimeTypes += $ this -> _mimeTypesExt ; } return $ this -> _mimeTypesExt += $ this -> _mimeTypes ; }
Get all mime types that are supported right now
41,042
public static function getEncoding ( $ file = null , $ default = 'utf-8' ) { if ( ! function_exists ( 'finfo_open' ) ) { return $ default ; } $ finfo = finfo_open ( FILEINFO_MIME_ENCODING ) ; $ encoding = finfo_file ( $ finfo , $ file ) ; finfo_close ( $ finfo ) ; if ( $ encoding !== false ) { return $ encoding ; } return $ default ; }
Get encoding .
41,043
protected static function _getExtension ( $ file ) { $ pieces = explode ( '.' , $ file ) ; $ ext = strtolower ( array_pop ( $ pieces ) ) ; return $ ext ; }
Gets the file extention from a string
41,044
public function getSafeRedirectUrl ( $ default , $ data = null , $ key = 'redirect' ) { $ redirectUrl = $ data ? : ( $ this -> Controller -> getRequest ( ) -> getData ( $ key ) ? : $ this -> Controller -> getRequest ( ) -> getQuery ( $ key ) ) ; if ( $ redirectUrl && ( mb_substr ( $ redirectUrl , 0 , 1 ) !== '/' || mb_substr ( $ redirectUrl , 0 , 2 ) === '//' ) ) { $ redirectUrl = null ; } return $ redirectUrl ? : $ default ; }
Returns internal redirect only otherwise falls back to default .
41,045
public function listActions ( ) { $ parentClassMethods = get_class_methods ( get_parent_class ( $ this -> Controller ) ) ; $ subClassMethods = get_class_methods ( $ this -> Controller ) ; $ classMethods = array_diff ( $ subClassMethods , $ parentClassMethods ) ; foreach ( $ classMethods as $ key => $ classMethod ) { if ( mb_substr ( $ classMethod , 0 , 1 ) === '_' ) { unset ( $ classMethods [ $ key ] ) ; } } return $ classMethods ; }
List all direct actions of a controller
41,046
public function getPassedParam ( $ var , $ default = null ) { $ passed = $ this -> Controller -> getRequest ( ) -> getParam ( 'pass' ) ; return isset ( $ passed [ $ var ] ) ? $ passed [ $ var ] : $ default ; }
Used to get the value of a passed param .
41,047
public static function defaultUrlParams ( ) { $ defaults = [ 'plugin' => false ] ; $ prefixes = ( array ) Configure :: read ( 'Routing.prefixes' ) ; foreach ( $ prefixes as $ prefix ) { $ defaults [ $ prefix ] = false ; } return $ defaults ; }
Returns defaultUrlParams including configured prefixes .
41,048
public function autoRedirect ( $ whereTo , $ allowSelf = false , $ status = 302 ) { if ( $ allowSelf || $ this -> Controller -> referer ( null , true ) !== $ this -> Controller -> getRequest ( ) -> getRequestTarget ( ) ) { return $ this -> Controller -> redirect ( $ this -> Controller -> referer ( $ whereTo , true ) , $ status ) ; } return $ this -> Controller -> redirect ( $ whereTo , $ status ) ; }
Smart Referer Redirect - will try to use an existing referer first otherwise it will use the default url
41,049
protected function _getMethod ( ) { $ validCharacters = [ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' , 'q' ] ; $ validCommands = array_merge ( $ validCharacters , $ this -> validCommands ) ; $ command = null ; while ( empty ( $ command ) ) { $ this -> out ( 'Please type the number or name of the inflection method you would like to use' ) ; $ this -> hr ( ) ; $ this -> out ( '[1] Pluralize' ) ; $ this -> out ( '[2] Singularize' ) ; $ this -> out ( '[3] Camelize' ) ; $ this -> out ( '[4] Underscore' ) ; $ this -> out ( '[5] Humanize' ) ; $ this -> out ( '[6] Tableize' ) ; $ this -> out ( '[7] Classify' ) ; $ this -> out ( '[8] Variable' ) ; $ this -> out ( '[9] Dasherize' ) ; $ this -> out ( '[10] Slug' ) ; $ this -> out ( '[q] Quit' ) ; $ temp = $ this -> in ( 'What command would you like to perform?' , null , 'q' ) ; if ( in_array ( strtolower ( $ temp ) , $ validCommands ) ) { $ command = strtolower ( $ temp ) ; } else { $ this -> out ( 'Try again.' ) ; } } switch ( $ command ) { case '1' : case 'pluralize' : return 'pluralize' ; case '2' : case 'singularize' : return 'singularize' ; case '3' : case 'camelize' : return 'camelize' ; case '4' : case 'underscore' : return 'underscore' ; case '5' : case 'humanize' : return 'humanize' ; case '6' : case 'tableize' : return 'tableize' ; case '7' : case 'classify' : return 'classify' ; case '8' : case 'variable' : return 'variable' ; case '9' : case 'dasherize' : return 'dasherize' ; case '10' : case 'slug' : return 'slug' ; case 'q' : case 'quit' : default : $ this -> out ( 'Exit' ) ; $ this -> _stop ( ) ; return null ; } }
Requests a valid inflection method
41,050
protected function _getWords ( ) { $ words = null ; while ( empty ( $ words ) ) { $ temp = $ this -> in ( 'What word(s) would you like to inflect?' ) ; if ( ! empty ( $ temp ) ) { $ words = $ temp ; } else { $ this -> out ( 'Try again.' ) ; } } return $ words ; }
Requests words to inflect
41,051
protected function _inflect ( $ function , $ words ) { $ this -> out ( $ words ) ; if ( $ function === 'all' ) { foreach ( $ this -> validMethods as $ method ) { $ functionName = $ this -> _getMessage ( $ method ) ; $ this -> out ( "{$functionName}: " . Inflector :: $ method ( $ words ) ) ; } } else { $ functionName = $ this -> _getMessage ( $ function ) ; $ this -> out ( "{$functionName}: " . Inflector :: $ function ( $ words ) ) ; } }
Inflects a set of words based upon the inflection set in the arguments
41,052
public function help ( ) { $ this -> out ( 'Inflector Shell' ) ; $ this -> out ( '' ) ; $ this -> out ( 'This shell uses the Inflector class to inflect any word(s) you wish' ) ; $ this -> hr ( ) ; $ this -> out ( 'Usage: cake inflect' ) ; $ this -> out ( ' cake inflect methodName' ) ; $ this -> out ( ' cake inflect methodName word' ) ; $ this -> out ( ' cake inflect methodName words to inflect' ) ; $ this -> out ( '' ) ; }
Displays help contents
41,053
public function readWithPattern ( $ text , $ pattern ) { $ pieces = explode ( "\n" , $ text ) ; $ result = [ ] ; foreach ( $ pieces as $ piece ) { $ result [ ] = sscanf ( trim ( $ piece , "\r\n" ) , $ pattern ) ; } return $ result ; }
Read with a specific pattern .
41,054
public static function numberOfWords ( $ text ) { $ count = 0 ; $ words = explode ( ' ' , $ text ) ; foreach ( $ words as $ word ) { $ word = trim ( $ word ) ; if ( ! empty ( $ word ) ) { $ count ++ ; } } return $ count ; }
Count words in a text .
41,055
public static function numberOfChars ( $ text , array $ options = [ ] ) { $ text = str_replace ( [ "\r" , "\n" , "\t" , ' ' ] , '' , $ text ) ; $ count = mb_strlen ( $ text ) ; return $ count ; }
Count chars in a text .
41,056
public function explodeTags ( $ tags ) { $ regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x' ; preg_match_all ( $ regexp , $ tags , $ matches ) ; $ typedTags = array_unique ( $ matches [ 1 ] ) ; $ tags = [ ] ; foreach ( $ typedTags as $ tag ) { $ tag = trim ( str_replace ( '""' , '"' , preg_replace ( '/^"(.*)"$/' , '\1' , $ tag ) ) ) ; if ( $ tag ) { $ tags [ ] = $ tag ; } } return $ tags ; }
Explode a string of given tags into an array .
41,057
public function implodeTags ( array $ tags ) { $ encodedTags = [ ] ; foreach ( $ tags as $ tag ) { if ( strpos ( $ tag , ',' ) !== false || strpos ( $ tag , '"' ) !== false ) { $ tag = '"' . str_replace ( '"' , '""' , $ tag ) . '"' ; } $ encodedTags [ ] = $ tag ; } return implode ( ', ' , $ encodedTags ) ; }
Implode an array of tags into a string .
41,058
public function asciiToEntities ( $ str ) { $ count = 1 ; $ out = '' ; $ temp = [ ] ; for ( $ i = 0 , $ s = strlen ( $ str ) ; $ i < $ s ; $ i ++ ) { $ ordinal = ord ( $ str [ $ i ] ) ; if ( $ ordinal < 128 ) { if ( count ( $ temp ) == 1 ) { $ out .= '&#' . array_shift ( $ temp ) . ';' ; $ count = 1 ; } $ out .= $ str [ $ i ] ; } else { if ( count ( $ temp ) == 0 ) { $ count = ( $ ordinal < 224 ) ? 2 : 3 ; } $ temp [ ] = $ ordinal ; if ( count ( $ temp ) == $ count ) { $ number = ( $ count == 3 ) ? ( ( $ temp [ '0' ] % 16 ) * 4096 ) + ( ( $ temp [ '1' ] % 64 ) * 64 ) + ( $ temp [ '2' ] % 64 ) : ( ( $ temp [ '0' ] % 32 ) * 64 ) + ( $ temp [ '1' ] % 64 ) ; $ out .= '&#' . $ number . ';' ; $ count = 1 ; $ temp = [ ] ; } } } return $ out ; }
High ASCII to Entities
41,059
public function entitiesToAscii ( $ str , $ all = true ) { if ( preg_match_all ( '/\&#(\d+)\;/' , $ str , $ matches ) ) { for ( $ i = 0 , $ s = count ( $ matches [ '0' ] ) ; $ i < $ s ; $ i ++ ) { $ digits = $ matches [ '1' ] [ $ i ] ; $ out = '' ; if ( $ digits < 128 ) { $ out .= chr ( $ digits ) ; } elseif ( $ digits < 2048 ) { $ out .= chr ( 192 + ( ( $ digits - ( $ digits % 64 ) ) / 64 ) ) ; $ out .= chr ( 128 + ( $ digits % 64 ) ) ; } else { $ out .= chr ( 224 + ( ( $ digits - ( $ digits % 4096 ) ) / 4096 ) ) ; $ out .= chr ( 128 + ( ( ( $ digits % 4096 ) - ( $ digits % 64 ) ) / 64 ) ) ; $ out .= chr ( 128 + ( $ digits % 64 ) ) ; } $ str = str_replace ( $ matches [ '0' ] [ $ i ] , $ out , $ str ) ; } } if ( $ all ) { $ str = str_replace ( [ '&amp;' , '&lt;' , '&gt;' , '&quot;' , '&apos;' , '&#45;' ] , [ '&' , '<' , '>' , '"' , "'" , '-' ] , $ str ) ; } return $ str ; }
Entities to ASCII
41,060
public function hasDaylightSavingTime ( $ timezone = null ) { $ timezone = $ this -> safeCreateDateTimeZone ( $ timezone ) ; $ offset = $ timezone -> getOffset ( new CakeTime ( '@' . mktime ( 0 , 0 , 0 , 2 , 1 , date ( 'Y' ) ) ) ) ; $ offset = $ offset / HOUR ; $ offset2 = $ timezone -> getOffset ( new CakeTime ( '@' . mktime ( 0 , 0 , 0 , 8 , 1 , date ( 'Y' ) ) ) ) ; $ offset2 = $ offset2 / HOUR ; return abs ( $ offset2 - $ offset ) > 0 ; }
Detect if a timezone has a DST
41,061
public static function difference ( $ startTime , $ endTime = null , array $ options = [ ] ) { if ( ! is_int ( $ startTime ) ) { $ startTime = strtotime ( $ startTime ) ; } if ( ! is_int ( $ endTime ) ) { $ endTime = strtotime ( $ endTime ) ; } return abs ( $ endTime - $ startTime ) ; }
Calculate the difference between two dates
41,062
public static function age ( $ start , $ end = null ) { if ( empty ( $ start ) && empty ( $ end ) || $ start == $ end ) { return 0 ; } if ( is_int ( $ start ) ) { $ start = date ( FORMAT_DB_DATE , $ start ) ; } if ( is_int ( $ end ) ) { $ end = date ( FORMAT_DB_DATE , $ end ) ; } $ startDate = $ start ; if ( ! is_object ( $ start ) ) { $ startDate = new CakeTime ( $ start ) ; } $ endDate = $ end ; if ( ! is_object ( $ end ) ) { $ endDate = new CakeTime ( $ end ) ; } if ( $ startDate > $ endDate ) { return - 1 ; } $ oDateInterval = $ endDate -> diff ( $ startDate ) ; return $ oDateInterval -> y ; }
Calculates the age using start and optional end date . Both dates default to current date . Note that start needs to be before end for a valid result .
41,063
public static function cWeekBeginning ( $ year , $ cWeek = 0 ) { if ( $ cWeek <= 1 || $ cWeek > static :: cWeeks ( $ year ) ) { $ first = mktime ( 0 , 0 , 0 , 1 , 1 , $ year ) ; $ wtag = ( int ) date ( 'w' , $ first ) ; if ( $ wtag <= 4 ) { $ firstmonday = mktime ( 0 , 0 , 0 , 1 , 1 - ( $ wtag - 1 ) , $ year ) ; } elseif ( $ wtag != 1 ) { $ firstmonday = mktime ( 0 , 0 , 0 , 1 , 1 + ( 7 - $ wtag + 1 ) , $ year ) ; } else { $ firstmonday = $ first ; } return $ firstmonday ; } $ monday = strtotime ( $ year . 'W' . static :: pad ( $ cWeek ) . '1' ) ; return $ monday ; }
Calculate the beginning of a calender week if no calendar week is given get the beginning of the first week of the year
41,064
public static function cWeekEnding ( $ year , $ cWeek = 0 ) { if ( $ cWeek < 1 || $ cWeek >= static :: cWeeks ( $ year ) ) { return static :: cWeekBeginning ( $ year + 1 ) - 1 ; } return static :: cWeekBeginning ( $ year , $ cWeek + 1 ) - 1 ; }
Calculate the ending of a calenderweek if no cweek is given get the ending of the last week of the year
41,065
public static function cWeeks ( $ year = null ) { if ( $ year === null ) { $ year = date ( 'Y' ) ; } return ( int ) date ( 'W' , mktime ( 23 , 59 , 59 , 12 , 28 , $ year ) ) ; }
Calculate the amount of calender weeks in a year
41,066
protected static function _strftime ( $ format , $ date ) { $ format = strftime ( $ format , $ date ) ; $ encoding = Configure :: read ( 'App.encoding' ) ; if ( ! empty ( $ encoding ) && $ encoding === 'UTF-8' ) { $ valid = mb_check_encoding ( $ format , $ encoding ) ; if ( ! $ valid ) { $ format = utf8_encode ( $ format ) ; } } return $ format ; }
Multibyte wrapper for strftime .
41,067
public static function convertDate ( $ oldDateString , $ newDateFormatString , $ timezone = null ) { $ Date = new CakeTime ( $ oldDateString , $ timezone ) ; return $ Date -> format ( $ newDateFormatString ) ; }
Convenience method to convert a given date
41,068
public static function isNotTodayAndInTheFuture ( $ dateString , $ timezone = null ) { $ date = new CakeTime ( $ dateString , $ timezone ) ; $ date = $ date -> format ( 'U' ) ; return date ( FORMAT_DB_DATE , $ date ) > date ( FORMAT_DB_DATE , time ( ) ) ; }
Returns true if given datetime string is not today AND is in the future .
41,069
public static function isInTheFuture ( $ dateString , $ timezone = null ) { $ date = new CakeTime ( $ dateString , $ timezone ) ; $ date = $ date -> format ( 'U' ) ; return date ( FORMAT_DB_DATETIME , $ date ) > date ( FORMAT_DB_DATETIME , time ( ) ) ; }
Returns true if given datetime string is not now AND is in the future .
41,070
public static function daysAsSql ( $ begin , $ end , $ fieldName , $ timezone = null ) { $ begin = new CakeTime ( $ begin , $ timezone ) ; $ begin = $ begin -> format ( 'U' ) ; $ end = new CakeTime ( $ end , $ timezone ) ; $ end = $ end -> format ( 'U' ) ; $ begin = date ( 'Y-m-d' , $ begin ) . ' 00:00:00' ; $ end = date ( 'Y-m-d' , $ end ) . ' 23:59:59' ; return "($fieldName >= '$begin') AND ($fieldName <= '$end')" ; }
Returns a partial SQL string to search for all records between two dates .
41,071
public static function dayAsSql ( $ dateString , $ fieldName , $ timezone = null ) { return static :: daysAsSql ( $ dateString , $ dateString , $ fieldName , $ timezone ) ; }
Returns a partial SQL string to search for all records between two times occurring on the same day .
41,072
public static function parseLocalDate ( $ date , array $ allowed = [ '.' , '-' ] ) { $ datePieces = explode ( ' ' , $ date , 2 ) ; $ date = array_shift ( $ datePieces ) ; if ( strpos ( $ date , '.' ) !== false ) { $ pieces = explode ( '.' , $ date ) ; $ year = $ pieces [ 2 ] ; if ( strlen ( $ year ) === 2 ) { if ( $ year < 50 ) { $ year = '20' . $ year ; } else { $ year = '19' . $ year ; } } $ date = mktime ( 0 , 0 , 0 , $ pieces [ 1 ] , $ pieces [ 0 ] , $ year ) ; } elseif ( strpos ( $ date , '-' ) !== false ) { $ date = strtotime ( $ date ) ; } else { return 0 ; } return $ date ; }
Parse 2022 - 11 - 12 or 12 . 11 . 2022 or even 12 . 11 . 22
41,073
public function wordCensor ( $ str , array $ censored , $ replacement = null ) { if ( empty ( $ censored ) ) { return $ str ; } $ str = ' ' . $ str . ' ' ; $ delim = '[-_\'\"`() {}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]' ; foreach ( $ censored as $ badword ) { if ( $ replacement !== null ) { $ str = preg_replace ( "/({$delim})(" . str_replace ( '\*' , '\w*?' , preg_quote ( $ badword , '/' ) ) . ")({$delim})/i" , "\\1{$replacement}\\3" , $ str ) ; } else { $ str = preg_replace_callback ( "/({$delim})(" . str_replace ( '\*' , '\w*?' , preg_quote ( $ badword , '/' ) ) . ")({$delim})/i" , function ( $ matches ) { return $ matches [ 1 ] . str_repeat ( '#' , strlen ( $ matches [ 2 ] ) ) . $ matches [ 3 ] ; } , $ str ) ; } } return trim ( $ str ) ; }
Word Censoring Function
41,074
public function language ( $ language = null ) { $ this -> getRequest ( ) -> allowMethod ( [ 'post' ] ) ; $ allowedLanguages = ( array ) Configure :: read ( 'Config.allowedLanguages' ) ; if ( ! $ language ) { $ language = Configure :: read ( 'Config.defaultLanguage' ) ; } if ( ! $ language ) { $ keys = array_keys ( $ allowedLanguages ) ; $ language = $ allowedLanguages [ array_shift ( $ keys ) ] ; } if ( ! array_key_exists ( $ language , $ allowedLanguages ) ) { throw new RuntimeException ( 'Invalid Language' ) ; } $ language = $ allowedLanguages [ $ language ] ; $ this -> getRequest ( ) -> getSession ( ) -> write ( 'Config.language' , $ language [ 'locale' ] ) ; I18n :: setLocale ( $ language [ 'locale' ] ) ; $ this -> Flash -> success ( __d ( 'tools' , 'Language switched to {0}' , $ language [ 'name' ] ) ) ; return $ this -> redirect ( $ this -> referer ( '/' , true ) ) ; }
Switch language as post link .
41,075
public static function parseLanguageList ( $ languageList = null , $ options = [ ] ) { $ defaultOptions = [ 'forceLowerCase' => true , ] ; if ( ! is_array ( $ options ) ) { $ options = [ 'forceLowerCase' => $ options ] ; } $ options += $ defaultOptions ; if ( $ languageList === null ) { if ( ! env ( 'HTTP_ACCEPT_LANGUAGE' ) ) { return [ ] ; } $ languageList = env ( 'HTTP_ACCEPT_LANGUAGE' ) ; } $ languages = [ ] ; $ languagesRanks = [ ] ; $ languageRanges = explode ( ',' , trim ( $ languageList ) ) ; foreach ( $ languageRanges as $ languageRange ) { $ pattern = '/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/' ; if ( preg_match ( $ pattern , trim ( $ languageRange ) , $ match ) ) { if ( ! isset ( $ match [ 2 ] ) ) { $ rank = '1.0' ; } else { $ rank = ( string ) ( float ) ( $ match [ 2 ] ) ; } if ( ! isset ( $ languages [ $ rank ] ) ) { if ( $ rank === '1' ) { $ rank = '1.0' ; } $ languages [ $ rank ] = [ ] ; } $ language = $ match [ 1 ] ; if ( $ options [ 'forceLowerCase' ] ) { $ language = strtolower ( $ language ) ; } else { $ language = substr_replace ( $ language , strtolower ( substr ( $ language , 0 , 2 ) ) , 0 , 2 ) ; if ( strlen ( $ language ) === 5 ) { $ language = substr_replace ( $ language , strtoupper ( substr ( $ language , 3 , 2 ) ) , 3 , 2 ) ; } } if ( array_key_exists ( $ language , $ languagesRanks ) === false ) { $ languages [ $ rank ] [ ] = $ language ; $ languagesRanks [ $ language ] = $ rank ; } elseif ( $ rank > $ languagesRanks [ $ language ] ) { foreach ( $ languages as $ existRank => $ existLangs ) { $ key = array_search ( $ existLangs , $ languages ) ; if ( $ key !== false ) { unset ( $ languages [ $ existRank ] [ $ key ] ) ; if ( empty ( $ languages [ $ existRank ] ) ) { unset ( $ languages [ $ existRank ] ) ; } } } $ languages [ $ rank ] [ ] = $ language ; $ languagesRanks [ $ language ] = $ rank ; } } } krsort ( $ languages ) ; return $ languages ; }
Parse languages from a browser language list .
41,076
protected static function _matchLanguage ( $ a , $ b ) { $ a = explode ( '-' , strtolower ( $ a ) ) ; $ b = explode ( '-' , strtolower ( $ b ) ) ; for ( $ i = 0 , $ n = min ( count ( $ a ) , count ( $ b ) ) ; $ i < $ n ; $ i ++ ) { if ( $ a [ $ i ] !== $ b [ $ i ] ) { break ; } } return $ i === 0 ? 0 : ( float ) $ i / count ( $ a ) ; }
Compare two language tags and distinguish the degree of matching
41,077
public static function inArray ( $ needle , $ haystack ) { $ strict = ! is_numeric ( $ needle ) ; return in_array ( ( string ) $ needle , $ haystack , $ strict ) ; }
Clean implementation of inArray to avoid false positives .
41,078
public static function getClientIp ( $ safe = true ) { if ( ! $ safe && env ( 'HTTP_X_FORWARDED_FOR' ) ) { $ ipaddr = preg_replace ( '/(?:,.*)/' , '' , env ( 'HTTP_X_FORWARDED_FOR' ) ) ; } elseif ( ! $ safe && env ( 'HTTP_CLIENT_IP' ) ) { $ ipaddr = env ( 'HTTP_CLIENT_IP' ) ; } else { $ ipaddr = env ( 'REMOTE_ADDR' ) ; } return trim ( $ ipaddr ) ; }
Get the current IP address .
41,079
public static function getReferer ( $ full = false ) { $ ref = env ( 'HTTP_REFERER' ) ; $ forwarded = env ( 'HTTP_X_FORWARDED_HOST' ) ; if ( $ forwarded ) { $ ref = $ forwarded ; } if ( empty ( $ ref ) ) { return $ ref ; } if ( $ full ) { $ ref = Router :: url ( $ ref , $ full ) ; } return $ ref ; }
Get the current referrer if available .
41,080
public static function getHeaderFromUrl ( $ url ) { $ url = @ parse_url ( $ url ) ; if ( empty ( $ url ) ) { return false ; } $ url = array_map ( 'trim' , $ url ) ; $ url [ 'port' ] = ( ! isset ( $ url [ 'port' ] ) ) ? '' : ( ':' . ( int ) $ url [ 'port' ] ) ; $ path = ( isset ( $ url [ 'path' ] ) ) ? $ url [ 'path' ] : '' ; if ( empty ( $ path ) ) { $ path = '/' ; } $ path .= ( isset ( $ url [ 'query' ] ) ) ? "?$url[query]" : '' ; $ defaults = [ 'http' => [ 'header' => "Accept: text/html\r\n" . "Connection: Close\r\n" . "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n" , ] ] ; stream_context_get_default ( $ defaults ) ; if ( isset ( $ url [ 'host' ] ) && $ url [ 'host' ] !== gethostbyname ( $ url [ 'host' ] ) ) { $ url = "$url[scheme]://$url[host]$url[port]$path" ; $ headers = get_headers ( $ url ) ; if ( is_array ( $ headers ) ) { return $ headers ; } } return false ; }
Parse headers from a specific URL content .
41,081
public static function typeCast ( $ value , $ type ) { switch ( $ type ) { case 'int' : $ value = ( int ) $ value ; break ; case 'float' : $ value = ( float ) $ value ; break ; case 'double' : $ value = ( double ) $ value ; break ; case 'array' : $ value = ( array ) $ value ; break ; case 'bool' : $ value = ( bool ) $ value ; break ; case 'string' : $ value = ( string ) $ value ; break ; default : return null ; } return $ value ; }
Convenience function for automatic casting in form methods etc .
41,082
public static function arrayFlatten ( $ array , $ preserveKeys = false ) { if ( $ preserveKeys ) { return static :: _arrayFlatten ( $ array ) ; } if ( ! $ array ) { return [ ] ; } $ result = [ ] ; foreach ( $ array as $ key => $ value ) { if ( is_array ( $ value ) ) { $ result = array_merge ( $ result , static :: arrayFlatten ( $ value ) ) ; } else { $ result [ $ key ] = $ value ; } } return $ result ; }
Force - flattens an array .
41,083
protected static function _arrayFlatten ( $ a , $ f = [ ] ) { if ( ! $ a ) { return [ ] ; } foreach ( $ a as $ k => $ v ) { if ( is_array ( $ v ) ) { $ f = static :: _arrayFlatten ( $ v , $ f ) ; } else { $ f [ $ k ] = $ v ; } } return $ f ; }
Force - flattens an array and preserves the keys .
41,084
public static function prettyJson ( $ json , $ indString = "\t" ) { $ tokens = preg_split ( '|([\{\}\]\[,])|' , str_replace ( '\"' , '~~PRETTY_JSON_QUOTEMARK~~' , $ json ) , - 1 , PREG_SPLIT_DELIM_CAPTURE ) ; $ indent = 0 ; $ result = '' ; $ quotemarksCounter = 0 ; $ nextTokenUsePrefix = true ; foreach ( $ tokens as $ token ) { $ quotemarksCounter = $ quotemarksCounter + ( count ( explode ( '"' , $ token ) ) - 1 ) ; if ( $ token === '' ) { continue ; } if ( $ nextTokenUsePrefix ) { $ prefix = str_repeat ( $ indString , $ indent ) ; } else { $ prefix = null ; } if ( $ quotemarksCounter & 1 ) { $ nextTokenUsePrefix = false ; $ newLine = null ; } else { $ nextTokenUsePrefix = true ; $ newLine = "\n" ; } if ( $ token === '{' || $ token === '[' ) { $ indent ++ ; $ result .= $ token . $ newLine ; } elseif ( $ token === '}' || $ token === ']' ) { $ indent -- ; if ( $ indent >= 0 ) { $ prefix = str_repeat ( $ indString , $ indent ) ; } if ( $ nextTokenUsePrefix ) { $ result .= $ newLine . $ prefix . $ token ; } else { $ result .= $ newLine . $ token ; } } elseif ( $ token === ',' ) { $ result .= $ token . $ newLine ; } else { $ result .= $ prefix . $ token ; } } return str_replace ( '~~PRETTY_JSON_QUOTEMARK~~' , '\"' , $ result ) ; }
Returns pretty JSON
41,085
public function newKey ( $ type , $ key = null , $ uid = null , $ content = null ) { if ( ! $ type ) { return false ; } if ( ! $ key ) { $ key = $ this -> generateKey ( $ this -> defaultLength ) ; $ keyLength = $ this -> defaultLength ; } else { $ keyLength = mb_strlen ( $ key ) ; } if ( is_array ( $ content ) ) { $ content = json_encode ( $ content ) ; } $ data = [ 'type' => $ type , 'user_id' => $ uid , 'content' => ( string ) $ content , 'key' => $ key , ] ; $ entity = $ this -> newEntity ( $ data ) ; $ max = 99 ; while ( ! $ this -> save ( $ entity ) ) { $ entity [ 'key' ] = $ this -> generateKey ( $ keyLength ) ; $ max -- ; if ( $ max === 0 ) { return false ; } } return $ entity [ 'key' ] ; }
Stores new key in DB
41,086
public function stats ( ) { $ keys = [ ] ; $ keys [ 'unused_valid' ] = $ this -> find ( 'count' , [ 'conditions' => [ $ this -> getAlias ( ) . '.used' => 0 , $ this -> getAlias ( ) . '.created >=' => date ( FORMAT_DB_DATETIME , time ( ) - $ this -> validity ) ] ] ) ; $ keys [ 'used_valid' ] = $ this -> find ( 'count' , [ 'conditions' => [ $ this -> getAlias ( ) . '.used' => 1 , $ this -> getAlias ( ) . '.created >=' => date ( FORMAT_DB_DATETIME , time ( ) - $ this -> validity ) ] ] ) ; $ keys [ 'unused_invalid' ] = $ this -> find ( 'count' , [ 'conditions' => [ $ this -> getAlias ( ) . '.used' => 0 , $ this -> getAlias ( ) . '.created <' => date ( FORMAT_DB_DATETIME , time ( ) - $ this -> validity ) ] ] ) ; $ keys [ 'used_invalid' ] = $ this -> find ( 'count' , [ 'conditions' => [ $ this -> getAlias ( ) . '.used' => 1 , $ this -> getAlias ( ) . '.created <' => date ( FORMAT_DB_DATETIME , time ( ) - $ this -> validity ) ] ] ) ; $ types = $ this -> find ( 'all' , [ 'conditions' => [ ] , 'fields' => [ 'DISTINCT type' ] ] ) -> toArray ( ) ; $ keys [ 'types' ] = ! empty ( $ types ) ? Hash :: extract ( $ types , '{n}.type' ) : [ ] ; return $ keys ; }
Get admin stats
41,087
public function generateKey ( $ length = null ) { if ( ! $ length ) { $ length = $ this -> defaultLength ; } if ( version_compare ( PHP_VERSION , '7.0.0' ) >= 0 ) { $ function = 'random_bytes' ; } elseif ( extension_loaded ( 'openssl' ) ) { $ function = 'openssl_random_pseudo_bytes' ; } else { trigger_error ( 'Not secure' , E_USER_DEPRECATED ) ; return Random :: pwd ( $ length ) ; } $ value = bin2hex ( $ function ( $ length / 2 ) ) ; if ( strlen ( $ value ) !== $ length ) { $ value = str_pad ( $ value , $ length , '0' ) ; } return $ value ; }
Generator of secure random tokens .
41,088
public function minimizeUrl ( $ url , $ max = null , array $ options = [ ] ) { if ( empty ( $ url ) || mb_strlen ( $ url ) <= ( int ) $ max ) { return $ url ; } $ url = Utility :: stripProtocol ( $ url ) ; if ( mb_strpos ( $ url , '/' ) !== false ) { $ url = strtok ( $ url , '/' ) ; } if ( mb_strlen ( $ url ) <= ( int ) $ max ) { return $ url ; } $ placeholder = CHAR_HELLIP ; if ( ! empty ( $ options [ 'placeholder' ] ) ) { $ placeholder = $ options [ 'placeholder' ] ; } $ end = mb_substr ( $ url , - 5 , 5 ) ; $ front = mb_substr ( $ url , 0 , ( int ) $ max - 8 ) ; return $ front . $ placeholder . $ end ; }
Minimizes the given URL to a maximum length
41,089
public function updateTypography ( $ dryRun = false ) { $ options = [ 'limit' => 100 , 'offset' => 0 ] ; $ count = 0 ; while ( $ records = $ this -> getTable ( ) -> find ( 'all' , $ options ) -> toArray ( ) ) { foreach ( $ records as $ record ) { $ changed = false ; foreach ( $ this -> _config [ 'fields' ] as $ field ) { if ( empty ( $ record [ $ field ] ) ) { continue ; } $ tmp = $ this -> _prepareInput ( $ record [ $ field ] ) ; if ( $ tmp == $ record [ $ field ] ) { continue ; } $ record [ $ field ] = $ tmp ; $ changed = true ; } if ( $ changed ) { if ( ! $ dryRun ) { $ this -> getTable ( ) -> save ( $ record , [ 'validate' => false ] ) ; } $ count ++ ; } } $ options [ 'offset' ] += 100 ; } return $ count ; }
Run the behavior over all records of this model This is useful if you attach it after some records have already been saved without it .
41,090
public function process ( ArrayAccess $ data ) { foreach ( $ this -> _config [ 'fields' ] as $ field ) { if ( ! empty ( $ data [ $ field ] ) ) { $ data [ $ field ] = $ this -> _prepareInput ( $ data [ $ field ] ) ; } } }
Run before a model is saved
41,091
public function _process ( $ val , $ map ) { foreach ( $ map as $ m => $ arg ) { if ( is_numeric ( $ m ) ) { $ m = $ arg ; $ arg = null ; } if ( $ arg !== null ) { $ ret = call_user_func ( $ m , $ val , $ arg ) ; } else { $ ret = call_user_func ( $ m , $ val ) ; } if ( $ ret !== false ) { $ val = $ ret ; } } return $ val ; }
Process val via map
41,092
public function imageFromBlob ( $ content , array $ options = [ ] ) { $ options += [ 'type' => 'png' ] ; $ mimeType = 'image/' . $ options [ 'type' ] ; $ text = 'data:' . $ mimeType . ';base64,' . base64_encode ( $ content ) ; return $ this -> formatTemplate ( 'image' , [ 'url' => $ text , 'attrs' => $ this -> templater ( ) -> formatAttributes ( $ options , [ 'block' , 'link' ] ) ] ) ; }
Display image tag from blob content . Enhancement for HtmlHelper . Defaults to png image
41,093
public function linkReset ( $ title , $ url = null , array $ options = [ ] ) { if ( is_array ( $ url ) ) { $ url += [ 'prefix' => false , 'plugin' => false ] ; } return parent :: link ( $ title , $ url , $ options ) ; }
Creates a reset HTML link . The prefix and plugin params are resetting to default false .
41,094
protected function _suffix ( $ reset = false ) { static $ _splitCount = 0 ; static $ _splitCounter = 0 ; if ( $ reset ) { $ _splitCount = 0 ; $ _splitCounter = 0 ; } extract ( $ this -> _config ) ; if ( $ splitDepth || $ splitCount ) { if ( ! $ splitDepth ) { $ _splitCount = $ totalNodes / $ splitCount ; $ rounded = ( int ) $ _splitCount ; if ( $ rounded < $ _splitCount ) { $ _splitCount = $ rounded + 1 ; } } elseif ( $ depth == $ splitDepth - 1 ) { $ total = $ numberOfDirectChildren ? $ numberOfDirectChildren : $ numberOfTotalChildren ; if ( $ total ) { $ _splitCounter = 0 ; $ _splitCount = $ total / $ splitCount ; $ rounded = ( int ) $ _splitCount ; if ( $ rounded < $ _splitCount ) { $ _splitCount = $ rounded + 1 ; } } } if ( ! $ splitDepth || $ depth == $ splitDepth ) { $ _splitCounter ++ ; if ( $ type && ( $ _splitCounter % $ _splitCount ) === 0 && ! $ lastChild ) { unset ( $ this -> _config [ 'callback' ] ) ; return '</' . $ type . '><' . $ type . '>' ; } } } }
Suffix method .
41,095
protected function _attributes ( $ rType , array $ elementData = [ ] , $ clear = true ) { extract ( $ this -> _config ) ; if ( $ rType === $ type ) { $ attributes = $ this -> _typeAttributes ; if ( $ clear ) { $ this -> _typeAttributes = $ this -> _typeAttributesNext ; $ this -> _typeAttributesNext = [ ] ; } } else { $ attributes = $ this -> _itemAttributes ; $ this -> _itemAttributes = [ ] ; if ( $ clear ) { $ this -> _itemAttributes = [ ] ; } } if ( $ rType === $ itemType && $ elementData [ 'activePathElement' ] ) { if ( $ elementData [ 'activePathElement' ] === true ) { $ attributes [ 'class' ] [ ] = $ autoPath [ 2 ] ; } else { $ attributes [ 'class' ] [ ] = $ elementData [ 'activePathElement' ] ; } } if ( ! $ attributes ) { return '' ; } foreach ( $ attributes as $ type => $ values ) { foreach ( $ values as $ key => $ val ) { if ( is_array ( $ val ) ) { $ attributes [ $ type ] [ $ key ] = '' ; foreach ( $ val as $ vKey => $ v ) { $ attributes [ $ type ] [ $ key ] [ $ vKey ] .= $ vKey . ':' . $ v ; } $ attributes [ $ type ] [ $ key ] = implode ( ';' , $ attributes [ $ type ] [ $ key ] ) ; } if ( is_string ( $ key ) ) { $ attributes [ $ type ] [ $ key ] = $ key . ':' . $ val . ';' ; } } $ attributes [ $ type ] = $ type . '="' . implode ( ' ' , $ attributes [ $ type ] ) . '"' ; } return ' ' . implode ( ' ' , $ attributes ) ; }
Attributes function .
41,096
public function finalize ( $ return = false , array $ scriptOptions = [ ] ) { $ settings = $ this -> getConfig ( ) ; $ timelineId = $ settings [ 'id' ] ; $ data = $ this -> _format ( $ this -> _items ) ; $ current = '' ; if ( $ settings [ 'current' ] ) { $ dateString = date ( 'Y-m-d H:i:s' , time ( ) ) ; $ current = 'timeline.setCurrentTime(' . $ this -> _date ( $ dateString ) . ');' ; } unset ( $ settings [ 'id' ] ) ; unset ( $ settings [ 'current' ] ) ; $ options = $ this -> _options ( $ settings ) ; $ script = <<<JSvar timeline;var data;var options;// Called when the Visualization API is loaded.function drawVisualization() { // Create a JSON data table data = $data options = $options // Instantiate our timeline object. timeline = new links.Timeline(document.getElementById('$timelineId')); // Draw our timeline with the created data and options timeline.draw(data, options); $current}drawVisualization();JS ; if ( $ return ) { return $ script ; } $ this -> _buffer ( $ script , $ scriptOptions ) ; }
Finalize the timeline and write the javascript to the buffer . Make sure that your view does also output the buffer at some place!
41,097
protected function _options ( $ options ) { $ e = [ ] ; foreach ( $ options as $ option => $ value ) { if ( $ value === null ) { continue ; } if ( is_string ( $ value ) ) { $ value = '\'' . $ value . '\'' ; } elseif ( is_object ( $ value ) ) { $ value = $ this -> _date ( $ value ) ; } elseif ( is_bool ( $ value ) ) { $ value = $ value ? 'true' : 'false' ; } else { $ value = str_replace ( '\'' , '\\\'' , $ value ) ; } $ e [ ] = '\'' . $ option . '\': ' . $ value ; } $ string = '{' . PHP_EOL . "\t" . implode ( ',' . PHP_EOL . "\t" , $ e ) . PHP_EOL . '}' ; return $ string ; }
Format options to JS code
41,098
protected function _format ( $ items ) { $ e = [ ] ; foreach ( $ items as $ item ) { $ tmp = [ ] ; foreach ( $ item as $ key => $ row ) { switch ( $ key ) { case 'editable' : $ tmp [ ] = $ row ? 'true' : 'false' ; break ; case 'start' : case 'end' : $ tmp [ ] = '\'' . $ key . '\': ' . $ this -> _date ( $ row ) ; break ; default : $ tmp [ ] = '\'' . $ key . '\': \'' . str_replace ( '\'' , '\\\'' , $ row ) . '\'' ; } } $ e [ ] = '{' . implode ( ',' . PHP_EOL , $ tmp ) . '}' ; } $ string = '[' . implode ( ',' . PHP_EOL , $ e ) . '];' ; return $ string ; }
Format items to JS code
41,099
protected function _date ( $ date = null ) { if ( $ date === null || ! $ date instanceof \ DateTimeInterface ) { return '' ; } $ datePieces = [ ] ; $ datePieces [ ] = $ date -> format ( 'Y' ) ; $ datePieces [ ] = ( int ) ( $ date -> format ( 'm' ) ) - 1 ; $ datePieces [ ] = ( int ) $ date -> format ( 'd' ) ; $ datePieces [ ] = ( int ) $ date -> format ( 'H' ) ; $ datePieces [ ] = ( int ) $ date -> format ( 'i' ) ; $ datePieces [ ] = ( int ) $ date -> format ( 's' ) ; return 'new Date(' . implode ( ', ' , $ datePieces ) . ')' ; }
Format date to JS code .