idx
int64 0
60.3k
| question
stringlengths 101
6.21k
| target
stringlengths 7
803
|
|---|---|---|
4,800
|
public static function member_from_tempid ( $ tempid ) { $ members = static :: get ( ) -> filter ( 'TempIDHash' , $ tempid ) ; if ( static :: config ( ) -> get ( 'temp_id_lifetime' ) ) { $ members = $ members -> filter ( 'TempIDExpired:GreaterThan' , DBDatetime :: now ( ) -> getValue ( ) ) ; } return $ members -> first ( ) ; }
|
Find a member record with the given TempIDHash value
|
4,801
|
public static function create_new_password ( ) { $ words = Security :: config ( ) -> uninherited ( 'word_list' ) ; if ( $ words && file_exists ( $ words ) ) { $ words = file ( $ words ) ; list ( $ usec , $ sec ) = explode ( ' ' , microtime ( ) ) ; mt_srand ( $ sec + ( ( float ) $ usec * 100000 ) ) ; $ word = trim ( $ words [ random_int ( 0 , count ( $ words ) - 1 ) ] ) ; $ number = random_int ( 10 , 999 ) ; return $ word . $ number ; } else { $ random = mt_rand ( ) ; $ string = md5 ( $ random ) ; $ output = substr ( $ string , 0 , 8 ) ; return $ output ; } }
|
Generate a random password with randomiser to kick in if there s no words file on the filesystem .
|
4,802
|
protected function deletePasswordLogs ( ) { foreach ( $ this -> LoggedPasswords ( ) as $ password ) { $ password -> delete ( ) ; $ password -> destroy ( ) ; } return $ this ; }
|
Delete the MemberPassword objects that are associated to this user
|
4,803
|
public function inGroups ( $ groups , $ strict = false ) { if ( $ groups ) { foreach ( $ groups as $ group ) { if ( $ this -> inGroup ( $ group , $ strict ) ) { return true ; } } } return false ; }
|
Check if the member is in one of the given groups .
|
4,804
|
public function inGroup ( $ group , $ strict = false ) { if ( is_numeric ( $ group ) ) { $ groupCheckObj = DataObject :: get_by_id ( Group :: class , $ group ) ; } elseif ( is_string ( $ group ) ) { $ groupCheckObj = DataObject :: get_one ( Group :: class , array ( '"Group"."Code"' => $ group ) ) ; } elseif ( $ group instanceof Group ) { $ groupCheckObj = $ group ; } else { throw new InvalidArgumentException ( 'Member::inGroup(): Wrong format for $group parameter' ) ; } if ( ! $ groupCheckObj ) { return false ; } $ groupCandidateObjs = ( $ strict ) ? $ this -> getManyManyComponents ( "Groups" ) : $ this -> Groups ( ) ; if ( $ groupCandidateObjs ) { foreach ( $ groupCandidateObjs as $ groupCandidateObj ) { if ( $ groupCandidateObj -> ID == $ groupCheckObj -> ID ) { return true ; } } } return false ; }
|
Check if the member is in the given group or any parent groups .
|
4,805
|
public function addToGroupByCode ( $ groupcode , $ title = "" ) { $ group = DataObject :: get_one ( Group :: class , array ( '"Group"."Code"' => $ groupcode ) ) ; if ( $ group ) { $ this -> Groups ( ) -> add ( $ group ) ; } else { if ( ! $ title ) { $ title = $ groupcode ; } $ group = new Group ( ) ; $ group -> Code = $ groupcode ; $ group -> Title = $ title ; $ group -> write ( ) ; $ this -> Groups ( ) -> add ( $ group ) ; } }
|
Adds the member to a group . This will create the group if the given group code does not return a valid group object .
|
4,806
|
public function removeFromGroupByCode ( $ groupcode ) { $ group = Group :: get ( ) -> filter ( array ( 'Code' => $ groupcode ) ) -> first ( ) ; if ( $ group ) { $ this -> Groups ( ) -> remove ( $ group ) ; } }
|
Removes a member from a group .
|
4,807
|
public function setName ( $ name ) { $ nameParts = explode ( ' ' , $ name ) ; $ this -> Surname = array_pop ( $ nameParts ) ; $ this -> FirstName = join ( ' ' , $ nameParts ) ; }
|
Set first - and surname
|
4,808
|
public static function map_in_groups ( $ groups = null ) { $ groupIDList = array ( ) ; if ( $ groups instanceof SS_List ) { foreach ( $ groups as $ group ) { $ groupIDList [ ] = $ group -> ID ; } } elseif ( is_array ( $ groups ) ) { $ groupIDList = $ groups ; } elseif ( $ groups ) { $ groupIDList [ ] = $ groups ; } if ( ! $ groupIDList ) { return static :: get ( ) -> sort ( array ( 'Surname' => 'ASC' , 'FirstName' => 'ASC' ) ) -> map ( ) ; } $ membersList = new ArrayList ( ) ; foreach ( Group :: get ( ) -> byIDs ( $ groupIDList ) as $ group ) { $ membersList -> merge ( $ group -> Members ( ) ) ; } $ membersList -> removeDuplicates ( 'ID' ) ; return $ membersList -> map ( ) ; }
|
Get a member SQLMap of members in specific groups
|
4,809
|
public static function mapInCMSGroups ( $ groups = null ) { if ( ! $ groups ) { $ groups = [ ] ; } if ( ! class_exists ( LeftAndMain :: class ) ) { return ArrayList :: create ( ) -> map ( ) ; } if ( count ( $ groups ) == 0 ) { $ perms = array ( 'ADMIN' , 'CMS_ACCESS_AssetAdmin' ) ; if ( class_exists ( CMSMain :: class ) ) { $ cmsPerms = CMSMain :: singleton ( ) -> providePermissions ( ) ; } else { $ cmsPerms = LeftAndMain :: singleton ( ) -> providePermissions ( ) ; } if ( ! empty ( $ cmsPerms ) ) { $ perms = array_unique ( array_merge ( $ perms , array_keys ( $ cmsPerms ) ) ) ; } $ permsClause = DB :: placeholders ( $ perms ) ; $ groups = Group :: get ( ) -> innerJoin ( "Permission" , '"Permission"."GroupID" = "Group"."ID"' ) -> where ( array ( "\"Permission\".\"Code\" IN ($permsClause)" => $ perms ) ) ; } $ groupIDList = array ( ) ; if ( $ groups instanceof SS_List ) { foreach ( $ groups as $ group ) { $ groupIDList [ ] = $ group -> ID ; } } elseif ( is_array ( $ groups ) ) { $ groupIDList = $ groups ; } $ members = static :: get ( ) -> innerJoin ( "Group_Members" , '"Group_Members"."MemberID" = "Member"."ID"' ) -> innerJoin ( "Group" , '"Group"."ID" = "Group_Members"."GroupID"' ) ; if ( $ groupIDList ) { $ groupClause = DB :: placeholders ( $ groupIDList ) ; $ members = $ members -> where ( array ( "\"Group\".\"ID\" IN ($groupClause)" => $ groupIDList ) ) ; } return $ members -> sort ( '"Member"."Surname", "Member"."FirstName"' ) -> map ( ) ; }
|
Get a map of all members in the groups given that have CMS permissions
|
4,810
|
public function memberNotInGroups ( $ groupList , $ memberGroups = null ) { if ( ! $ memberGroups ) { $ memberGroups = $ this -> Groups ( ) ; } foreach ( $ memberGroups as $ group ) { if ( in_array ( $ group -> Code , $ groupList ) ) { $ index = array_search ( $ group -> Code , $ groupList ) ; unset ( $ groupList [ $ index ] ) ; } } return $ groupList ; }
|
Get the groups in which the member is NOT in
|
4,811
|
public function canView ( $ member = null ) { if ( ! $ member ) { $ member = Security :: getCurrentUser ( ) ; } $ extended = $ this -> extendedCan ( __FUNCTION__ , $ member ) ; if ( $ extended !== null ) { return $ extended ; } if ( ! $ member ) { return false ; } if ( $ this -> ID == $ member -> ID ) { return true ; } return Permission :: checkMember ( $ member , 'CMS_ACCESS_SecurityAdmin' ) ; }
|
Users can view their own record . Otherwise they ll need ADMIN or CMS_ACCESS_SecurityAdmin permissions . This is likely to be customized for social sites etc . with a looser permission model .
|
4,812
|
public function validate ( ) { if ( ! DataObject :: config ( ) -> uninherited ( 'validation_enabled' ) ) { return ValidationResult :: create ( ) ; } $ valid = parent :: validate ( ) ; $ validator = static :: password_validator ( ) ; if ( ! $ this -> ID || $ this -> isChanged ( 'Password' ) ) { if ( $ this -> Password && $ validator ) { $ userValid = $ validator -> validate ( $ this -> Password , $ this ) ; $ valid -> combineAnd ( $ userValid ) ; } } return $ valid ; }
|
Validate this member object .
|
4,813
|
public function changePassword ( $ password , $ write = true ) { $ this -> Password = $ password ; $ valid = $ this -> validate ( ) ; $ this -> extend ( 'onBeforeChangePassword' , $ password , $ valid ) ; if ( $ valid -> isValid ( ) ) { $ this -> AutoLoginHash = null ; $ this -> encryptPassword ( ) ; if ( $ write ) { $ this -> passwordChangesToWrite = true ; $ this -> write ( ) ; } } $ this -> extend ( 'onAfterChangePassword' , $ password , $ valid ) ; return $ valid ; }
|
Change password . This will cause rehashing according to the PasswordEncryption property . This method will allow extensions to perform actions and augment the validation result if required before the password is written and can check it after the write also .
|
4,814
|
public function registerFailedLogin ( ) { $ lockOutAfterCount = self :: config ( ) -> get ( 'lock_out_after_incorrect_logins' ) ; if ( $ lockOutAfterCount ) { ++ $ this -> FailedLoginCount ; if ( $ this -> FailedLoginCount >= $ lockOutAfterCount ) { $ lockoutMins = self :: config ( ) -> get ( 'lock_out_delay_mins' ) ; $ this -> LockedOutUntil = date ( 'Y-m-d H:i:s' , DBDatetime :: now ( ) -> getTimestamp ( ) + $ lockoutMins * 60 ) ; $ this -> FailedLoginCount = 0 ; } } $ this -> extend ( 'registerFailedLogin' ) ; $ this -> write ( ) ; }
|
Tell this member that someone made a failed attempt at logging in as them . This can be used to lock the user out temporarily if too many failed attempts are made .
|
4,815
|
public function registerSuccessfulLogin ( ) { if ( self :: config ( ) -> get ( 'lock_out_after_incorrect_logins' ) ) { $ this -> FailedLoginCount = 0 ; $ this -> LockedOutUntil = null ; $ this -> write ( ) ; } }
|
Tell this member that a successful login has been made
|
4,816
|
public function getHtmlEditorConfigForCMS ( ) { $ currentName = '' ; $ currentPriority = 0 ; foreach ( $ this -> Groups ( ) as $ group ) { $ configName = $ group -> HtmlEditorConfig ; if ( $ configName ) { $ config = HTMLEditorConfig :: get ( $ group -> HtmlEditorConfig ) ; if ( $ config && $ config -> getOption ( 'priority' ) > $ currentPriority ) { $ currentName = $ configName ; $ currentPriority = $ config -> getOption ( 'priority' ) ; } } } return $ currentName ? $ currentName : 'cms' ; }
|
Get the HtmlEditorConfig for this user to be used in the CMS . This is set by the group . If multiple configurations are set the one with the highest priority wins .
|
4,817
|
protected function registerExtraMethodCallback ( $ name , $ callback ) { if ( ! isset ( $ this -> extra_method_registers [ $ name ] ) ) { $ this -> extra_method_registers [ $ name ] = $ callback ; } }
|
Register an callback to invoke that defines extra methods
|
4,818
|
protected function getExtraMethodConfig ( $ method ) { if ( ! isset ( self :: $ extra_methods [ static :: class ] ) ) { $ this -> defineMethods ( ) ; } if ( isset ( self :: $ extra_methods [ static :: class ] [ strtolower ( $ method ) ] ) ) { return self :: $ extra_methods [ static :: class ] [ strtolower ( $ method ) ] ; } return null ; }
|
Get meta - data details on a named method
|
4,819
|
public function allMethodNames ( $ custom = false ) { $ class = static :: class ; if ( ! isset ( self :: $ built_in_methods [ $ class ] ) ) { self :: $ built_in_methods [ $ class ] = array_map ( 'strtolower' , get_class_methods ( $ this ) ) ; } if ( $ custom && isset ( self :: $ extra_methods [ $ class ] ) ) { return array_merge ( self :: $ built_in_methods [ $ class ] , array_keys ( self :: $ extra_methods [ $ class ] ) ) ; } else { return self :: $ built_in_methods [ $ class ] ; } }
|
Return the names of all the methods available on this object
|
4,820
|
public function getSchemaDataDefaults ( ) { $ data = parent :: getSchemaDataDefaults ( ) ; $ data [ 'data' ] [ 'rows' ] = $ this -> getRows ( ) ; $ data [ 'data' ] [ 'columns' ] = $ this -> getColumns ( ) ; $ data [ 'data' ] [ 'maxlength' ] = $ this -> getMaxLength ( ) ; return $ data ; }
|
Set textarea specific schema data
|
4,821
|
public static function set ( $ name , $ value , $ expiry = 90 , $ path = null , $ domain = null , $ secure = false , $ httpOnly = true ) { return self :: get_inst ( ) -> set ( $ name , $ value , $ expiry , $ path , $ domain , $ secure , $ httpOnly ) ; }
|
Set a cookie variable .
|
4,822
|
public static function getTranslatables ( $ template , $ warnIfEmpty = true ) { $ parser = new Parser ( $ template , $ warnIfEmpty ) ; if ( substr ( $ template , 0 , 3 ) == pack ( "CCC" , 0xef , 0xbb , 0xbf ) ) { $ parser -> pos = 3 ; } $ parser -> match_TopTemplate ( ) ; return $ parser -> getEntities ( ) ; }
|
Parses a template and returns any translatable entities
|
4,823
|
public static function linkToFeed ( $ url , $ title = null ) { $ title = Convert :: raw2xml ( $ title ) ; Requirements :: insertHeadTags ( '<link rel="alternate" type="application/rss+xml" title="' . $ title . '" href="' . $ url . '" />' ) ; }
|
Include an link to the feed
|
4,824
|
public function Entries ( ) { $ output = new ArrayList ( ) ; if ( isset ( $ this -> entries ) ) { foreach ( $ this -> entries as $ entry ) { $ output -> push ( RSSFeed_Entry :: create ( $ entry , $ this -> titleField , $ this -> descriptionField , $ this -> authorField ) ) ; } } return $ output ; }
|
Get the RSS feed entries
|
4,825
|
public function Link ( $ action = null ) { return Controller :: join_links ( Director :: absoluteURL ( $ this -> link ) , $ action ) ; }
|
Get the URL of this feed
|
4,826
|
public function outputToBrowser ( ) { $ prevState = SSViewer :: config ( ) -> uninherited ( 'source_file_comments' ) ; SSViewer :: config ( ) -> update ( 'source_file_comments' , false ) ; $ response = Controller :: curr ( ) -> getResponse ( ) ; if ( is_int ( $ this -> lastModified ) ) { HTTPCacheControlMiddleware :: singleton ( ) -> registerModificationDate ( $ this -> lastModified ) ; $ response -> addHeader ( "Last-Modified" , gmdate ( "D, d M Y H:i:s" , $ this -> lastModified ) . ' GMT' ) ; } if ( ! empty ( $ this -> etag ) ) { $ response -> addHeader ( 'ETag' , "\"{$this->etag}\"" ) ; } $ response -> addHeader ( "Content-Type" , "application/rss+xml; charset=utf-8" ) ; SSViewer :: config ( ) -> update ( 'source_file_comments' , $ prevState ) ; return $ this -> renderWith ( $ this -> getTemplates ( ) ) ; }
|
Output the feed to the browser .
|
4,827
|
protected function backURLToken ( HTTPRequest $ request ) { $ backURL = $ request -> getVar ( 'BackURL' ) ; if ( ! strstr ( $ backURL , '?' ) ) { return null ; } list ( , $ query ) = explode ( '?' , $ backURL ) ; parse_str ( $ query , $ queryArgs ) ; $ name = $ this -> getName ( ) ; if ( isset ( $ queryArgs [ $ name ] ) ) { return $ queryArgs [ $ name ] ; } return null ; }
|
Check if this token exists in the BackURL
|
4,828
|
public function merge ( BulkLoader_Result $ other ) { $ this -> created = array_merge ( $ this -> created , $ other -> created ) ; $ this -> updated = array_merge ( $ this -> updated , $ other -> updated ) ; $ this -> deleted = array_merge ( $ this -> deleted , $ other -> deleted ) ; }
|
Merges another BulkLoader_Result into this one .
|
4,829
|
public function getEditorConfig ( ) { if ( $ this -> editorConfig instanceof HTMLEditorConfig ) { return $ this -> editorConfig ; } return HTMLEditorConfig :: get ( $ this -> editorConfig ) ; }
|
Gets the HTMLEditorConfig instance
|
4,830
|
public function getOrPrepareStatement ( $ sql ) { if ( isset ( $ this -> cachedStatements [ $ sql ] ) ) { return $ this -> cachedStatements [ $ sql ] ; } $ statement = $ this -> pdoConnection -> prepare ( $ sql , array ( PDO :: ATTR_CURSOR => PDO :: CURSOR_FWDONLY ) ) ; $ statementHandle = ( $ statement === false ) ? false : new PDOStatementHandle ( $ statement ) ; if ( preg_match ( '/^(\s*)select\b/i' , $ sql ) ) { $ this -> cachedStatements [ $ sql ] = $ statementHandle ; } return $ statementHandle ; }
|
Retrieve a prepared statement for a given SQL string or return an already prepared version if one exists for the given query
|
4,831
|
protected function beforeQuery ( $ sql ) { $ this -> rowCount = 0 ; $ this -> lastStatementError = null ; if ( $ this -> isQueryDDL ( $ sql ) ) { $ this -> flushStatements ( ) ; } }
|
Invoked before any query is executed
|
4,832
|
public function exec ( $ sql , $ errorLevel = E_USER_ERROR ) { $ this -> beforeQuery ( $ sql ) ; $ result = $ this -> pdoConnection -> exec ( $ sql ) ; if ( $ result !== false ) { return $ this -> rowCount = $ result ; } $ this -> databaseError ( $ this -> getLastError ( ) , $ errorLevel , $ sql ) ; return null ; }
|
Executes a query that doesn t return a resultset
|
4,833
|
public function bindParameters ( PDOStatement $ statement , $ parameters ) { $ parameterCount = count ( $ parameters ) ; for ( $ index = 0 ; $ index < $ parameterCount ; $ index ++ ) { $ value = $ parameters [ $ index ] ; $ phpType = gettype ( $ value ) ; if ( $ phpType === 'array' ) { $ phpType = $ value [ 'type' ] ; $ value = $ value [ 'value' ] ; } $ type = $ this -> getPDOParamType ( $ phpType ) ; if ( $ type === PDO :: PARAM_STR ) { $ value = ( string ) $ value ; } $ statement -> bindValue ( $ index + 1 , $ value , $ type ) ; } }
|
Bind all parameters to a PDOStatement
|
4,834
|
protected function prepareResults ( PDOStatementHandle $ statement , $ errorLevel , $ sql , $ parameters = array ( ) ) { if ( $ this -> hasError ( $ statement ) ) { $ this -> lastStatementError = $ statement -> errorInfo ( ) ; $ statement -> closeCursor ( ) ; $ this -> databaseError ( $ this -> getLastError ( ) , $ errorLevel , $ sql , $ this -> parameterValues ( $ parameters ) ) ; return null ; } $ this -> rowCount = $ statement -> rowCount ( ) ; return new PDOQuery ( $ statement ) ; }
|
Given a PDOStatement that has just been executed generate results and report any errors
|
4,835
|
protected function hasError ( $ resource ) { if ( empty ( $ resource ) ) { return false ; } $ code = $ resource -> errorCode ( ) ; if ( empty ( $ code ) ) { return false ; } return $ code !== '00000' && $ code !== '01000' ; }
|
Determine if a resource has an attached error
|
4,836
|
public function output ( ) { if ( Director :: is_ajax ( ) ) { Requirements :: include_in_response ( $ this ) ; } if ( $ this -> isRedirect ( ) && headers_sent ( ) ) { $ this -> htmlRedirect ( ) ; } else { $ this -> outputHeaders ( ) ; $ this -> outputBody ( ) ; } }
|
Send this HTTPResponse to the browser
|
4,837
|
protected function htmlRedirect ( ) { $ headersSent = headers_sent ( $ file , $ line ) ; $ location = $ this -> getHeader ( 'location' ) ; $ url = Director :: absoluteURL ( $ location ) ; $ urlATT = Convert :: raw2htmlatt ( $ url ) ; $ urlJS = Convert :: raw2js ( $ url ) ; $ title = ( Director :: isDev ( ) && $ headersSent ) ? "{$urlATT}... (output started on {$file}, line {$line})" : "{$urlATT}..." ; echo <<<EOT<p>Redirecting to <a href="{$urlATT}" title="Click this link if your browser does not redirect you">{$title}</a></p><meta http-equiv="refresh" content="1; url={$urlATT}" /><script type="application/javascript">setTimeout(function(){ window.location.href = "{$urlJS}";}, 50);</script>EOT ; }
|
Generate a browser redirect without setting headers
|
4,838
|
protected function outputHeaders ( ) { $ headersSent = headers_sent ( $ file , $ line ) ; if ( ! $ headersSent ) { $ method = sprintf ( "%s %d %s" , $ _SERVER [ 'SERVER_PROTOCOL' ] , $ this -> getStatusCode ( ) , $ this -> getStatusDescription ( ) ) ; header ( $ method ) ; foreach ( $ this -> getHeaders ( ) as $ header => $ value ) { header ( "{$header}: {$value}" , true , $ this -> getStatusCode ( ) ) ; } } elseif ( $ this -> getStatusCode ( ) >= 300 ) { user_error ( sprintf ( "Couldn't set response type to %d because of output on line %s of %s" , $ this -> getStatusCode ( ) , $ line , $ file ) , E_USER_WARNING ) ; } }
|
Output HTTP headers to the browser
|
4,839
|
public function isInsideVendor ( $ basename , $ pathname , $ depth ) { $ base = basename ( $ this -> upLevels ( $ pathname , $ depth - 1 ) ) ; return $ base === self :: VENDOR_DIR ; }
|
Check if the given dir is or is inside the vendor folder
|
4,840
|
public function isInsideThemes ( $ basename , $ pathname , $ depth ) { $ base = basename ( $ this -> upLevels ( $ pathname , $ depth - 1 ) ) ; return $ base === THEMES_DIR ; }
|
Check if the given dir is or is inside the themes folder
|
4,841
|
public function isInsideIgnored ( $ basename , $ pathname , $ depth ) { return $ this -> anyParents ( $ basename , $ pathname , $ depth , function ( $ basename , $ pathname , $ depth ) { return $ this -> isDirectoryIgnored ( $ basename , $ pathname , $ depth ) ; } ) ; }
|
Check if this folder or any parent is ignored
|
4,842
|
public function isInsideModule ( $ basename , $ pathname , $ depth ) { return $ this -> anyParents ( $ basename , $ pathname , $ depth , function ( $ basename , $ pathname , $ depth ) { return $ this -> isDirectoryModule ( $ basename , $ pathname , $ depth ) ; } ) ; }
|
Check if this folder is inside any module
|
4,843
|
protected function anyParents ( $ basename , $ pathname , $ depth , $ callback ) { while ( $ depth >= 0 ) { $ ignored = $ callback ( $ basename , $ pathname , $ depth ) ; if ( $ ignored ) { return true ; } $ pathname = dirname ( $ pathname ) ; $ basename = basename ( $ pathname ) ; $ depth -- ; } return false ; }
|
Check if any parents match the given callback
|
4,844
|
protected function upLevels ( $ pathname , $ depth ) { if ( $ depth < 0 ) { return null ; } while ( $ depth -- ) { $ pathname = dirname ( $ pathname ) ; } return $ pathname ; }
|
Get a parent path the given levels above
|
4,845
|
protected function getIgnoredDirs ( ) { $ ignored = [ self :: LANG_DIR , 'node_modules' ] ; if ( $ this -> getOption ( 'ignore_tests' ) ) { $ ignored [ ] = self :: TESTS_DIR ; } return $ ignored ; }
|
Get all ignored directories
|
4,846
|
public function isDirectoryIgnored ( $ basename , $ pathname , $ depth ) { if ( $ depth === 0 ) { return false ; } if ( file_exists ( $ pathname . '/' . self :: EXCLUDE_FILE ) ) { return true ; } $ ignored = $ this -> getIgnoredDirs ( ) ; if ( in_array ( $ basename , $ ignored ) ) { return true ; } if ( $ depth === 1 && in_array ( $ basename , [ ASSETS_DIR , RESOURCES_DIR ] ) ) { return true ; } return false ; }
|
Check if the given directory is ignored
|
4,847
|
public function Date ( ) { $ formatter = $ this -> getFormatter ( IntlDateFormatter :: MEDIUM , IntlDateFormatter :: NONE ) ; return $ formatter -> format ( $ this -> getTimestamp ( ) ) ; }
|
Returns the standard localised date
|
4,848
|
public function FormatFromSettings ( $ member = null ) { if ( ! $ member ) { $ member = Security :: getCurrentUser ( ) ; } if ( ! $ member ) { return $ this -> Nice ( ) ; } $ dateFormat = $ member -> getDateFormat ( ) ; $ timeFormat = $ member -> getTimeFormat ( ) ; return $ this -> Format ( $ dateFormat . ' ' . $ timeFormat , $ member -> getLocale ( ) ) ; }
|
Return a date and time formatted as per a CMS user s settings .
|
4,849
|
public function setFailover ( ViewableData $ failover ) { if ( $ this -> failover ) { $ this -> removeMethodsFrom ( 'failover' ) ; } $ this -> failover = $ failover ; $ this -> defineMethods ( ) ; }
|
Set a failover object to attempt to get data from if it is not present on this object .
|
4,850
|
public function escapeTypeForField ( $ field ) { $ class = $ this -> castingClass ( $ field ) ? : $ this -> config ( ) -> get ( 'default_cast' ) ; $ type = Injector :: inst ( ) -> get ( $ class , true ) ; return $ type -> config ( ) -> get ( 'escape_type' ) ; }
|
Return the string - format type for the given field .
|
4,851
|
protected function objCacheGet ( $ key ) { if ( isset ( $ this -> objCache [ $ key ] ) ) { return $ this -> objCache [ $ key ] ; } return null ; }
|
Get a cached value from the field cache
|
4,852
|
public function obj ( $ fieldName , $ arguments = [ ] , $ cache = false , $ cacheName = null ) { if ( ! $ cacheName && $ cache ) { $ cacheName = $ this -> objCacheName ( $ fieldName , $ arguments ) ; } $ value = $ cache ? $ this -> objCacheGet ( $ cacheName ) : null ; if ( $ value !== null ) { return $ value ; } if ( $ this -> hasMethod ( $ fieldName ) ) { $ value = call_user_func_array ( array ( $ this , $ fieldName ) , $ arguments ? : [ ] ) ; } else { $ value = $ this -> $ fieldName ; } if ( ! is_object ( $ value ) ) { $ castingHelper = $ this -> castingHelper ( $ fieldName ) ; $ valueObject = Injector :: inst ( ) -> create ( $ castingHelper , $ fieldName ) ; $ valueObject -> setValue ( $ value , $ this ) ; $ value = $ valueObject ; } if ( $ cache ) { $ this -> objCacheSet ( $ cacheName , $ value ) ; } return $ value ; }
|
Get the value of a field on this object automatically inserting the value into any available casting objects that have been specified .
|
4,853
|
public function XML_val ( $ field , $ arguments = [ ] , $ cache = false ) { $ result = $ this -> obj ( $ field , $ arguments , $ cache ) ; return $ result -> forTemplate ( ) ; }
|
Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template .
|
4,854
|
public function getXMLValues ( $ fields ) { $ result = [ ] ; foreach ( $ fields as $ field ) { $ result [ $ field ] = $ this -> XML_val ( $ field ) ; } return $ result ; }
|
Get an array of XML - escaped values by field name
|
4,855
|
public function CSSClasses ( $ stopAtClass = self :: class ) { $ classes = [ ] ; $ classAncestry = array_reverse ( ClassInfo :: ancestry ( static :: class ) ) ; $ stopClasses = ClassInfo :: ancestry ( $ stopAtClass ) ; foreach ( $ classAncestry as $ class ) { if ( in_array ( $ class , $ stopClasses ) ) { break ; } $ classes [ ] = $ class ; } if ( isset ( $ this -> template ) && ! in_array ( $ this -> template , $ classes ) ) { $ classes [ ] = $ this -> template ; } $ classes = preg_replace ( '#.*\\\\#' , '' , $ classes ) ; return Convert :: raw2att ( implode ( ' ' , $ classes ) ) ; }
|
Get part of the current classes ancestry to be used as a CSS class .
|
4,856
|
public static function modify ( ) { $ instance = static :: inst ( ) ; if ( $ instance instanceof MutableConfigCollectionInterface ) { return $ instance ; } $ instance = static :: nest ( ) ; if ( $ instance instanceof MutableConfigCollectionInterface ) { return $ instance ; } throw new InvalidArgumentException ( "Nested config could not be made mutable" ) ; }
|
Make this config available to be modified
|
4,857
|
public static function unnest ( ) { $ loader = ConfigLoader :: inst ( ) ; if ( $ loader -> countManifests ( ) <= 1 ) { user_error ( "Unable to unnest root Config, please make sure you don't have mis-matched nest/unnest" , E_USER_WARNING ) ; } else { $ loader -> popManifest ( ) ; } return static :: inst ( ) ; }
|
Change the active Config back to the Config instance the current active Config object was copied from .
|
4,858
|
public static function createFromEnvironment ( ) { $ variables = static :: cleanEnvironment ( Environment :: getVariables ( ) ) ; Environment :: setVariables ( $ variables ) ; return static :: createFromVariables ( $ variables , @ file_get_contents ( 'php://input' ) ) ; }
|
Create HTTPRequest instance from the current environment variables . May throw errors if request is invalid .
|
4,859
|
public static function createFromVariables ( array $ variables , $ input , $ url = null ) { if ( ! isset ( $ url ) ) { $ url = parse_url ( $ variables [ '_SERVER' ] [ 'REQUEST_URI' ] , PHP_URL_PATH ) ; if ( substr ( strtolower ( $ url ) , 0 , strlen ( BASE_URL ) ) === strtolower ( BASE_URL ) ) { $ url = substr ( $ url , strlen ( BASE_URL ) ) ; } } $ request = new HTTPRequest ( $ variables [ '_SERVER' ] [ 'REQUEST_METHOD' ] , $ url , $ variables [ '_GET' ] , $ variables [ '_POST' ] , $ input ) ; if ( ( ! empty ( $ variables [ '_SERVER' ] [ 'HTTPS' ] ) && $ variables [ '_SERVER' ] [ 'HTTPS' ] != 'off' ) || isset ( $ variables [ '_SERVER' ] [ 'SSL' ] ) ) { $ request -> setScheme ( 'https' ) ; } if ( ! empty ( $ variables [ '_SERVER' ] [ 'REMOTE_ADDR' ] ) ) { $ request -> setIP ( $ variables [ '_SERVER' ] [ 'REMOTE_ADDR' ] ) ; } $ headers = static :: extractRequestHeaders ( $ variables [ '_SERVER' ] ) ; foreach ( $ headers as $ header => $ value ) { $ request -> addHeader ( $ header , $ value ) ; } $ session = new Session ( isset ( $ variables [ '_SESSION' ] ) ? $ variables [ '_SESSION' ] : null ) ; $ request -> setSession ( $ session ) ; return $ request ; }
|
Build HTTPRequest from given variables
|
4,860
|
public function LimitSentences ( $ maxSentences = 2 ) { if ( ! is_numeric ( $ maxSentences ) ) { throw new InvalidArgumentException ( "Text::LimitSentence() expects one numeric argument" ) ; } $ value = $ this -> Plain ( ) ; if ( ! $ value ) { return "" ; } $ words = preg_split ( '/\s+/u' , $ value ) ; $ sentences = 0 ; foreach ( $ words as $ i => $ word ) { if ( preg_match ( '/(!|\?|\.)$/' , $ word ) && ! preg_match ( '/(Dr|Mr|Mrs|Ms|Miss|Sr|Jr|No)\.$/i' , $ word ) ) { $ sentences ++ ; if ( $ sentences >= $ maxSentences ) { return implode ( ' ' , array_slice ( $ words , 0 , $ i + 1 ) ) ; } } } if ( $ maxSentences > 1 ) { return $ value ; } else { return $ this -> Summary ( 20 ) ; } }
|
Limit sentences can be controlled by passing an integer .
|
4,861
|
public function Summary ( $ maxWords = 50 , $ add = '...' ) { $ value = $ this -> Plain ( ) ; if ( ! $ value ) { return '' ; } $ sentences = array_filter ( array_map ( function ( $ str ) { return trim ( $ str ) ; } , preg_split ( '@(?<=\.)@' , $ value ) ) ) ; $ wordCount = count ( preg_split ( '#\s+#u' , $ sentences [ 0 ] ) ) ; if ( $ wordCount > $ maxWords ) { return implode ( ' ' , array_slice ( explode ( ' ' , $ sentences [ 0 ] ) , 0 , $ maxWords ) ) . $ add ; } $ result = '' ; do { $ result .= ' ' . array_shift ( $ sentences ) ; if ( $ sentences ) { $ wordCount += count ( preg_split ( '#\s+#u' , $ sentences [ 0 ] ) ) ; } } while ( $ wordCount < $ maxWords && $ sentences && trim ( $ sentences [ 0 ] ) ) ; return trim ( $ result ) ; }
|
Builds a basic summary up to a maximum number of words
|
4,862
|
public function FirstParagraph ( ) { $ value = $ this -> Plain ( ) ; if ( empty ( $ value ) ) { return '' ; } $ paragraphs = preg_split ( '#\n{2,}#' , $ value ) ; return reset ( $ paragraphs ) ; }
|
Get first paragraph
|
4,863
|
public function ContextSummary ( $ characters = 500 , $ keywords = null , $ highlight = true , $ prefix = "... " , $ suffix = "..." ) { if ( ! $ keywords ) { $ keywords = isset ( $ _REQUEST [ 'Search' ] ) ? $ _REQUEST [ 'Search' ] : '' ; } $ text = nl2br ( Convert :: raw2xml ( $ this -> Plain ( ) ) ) ; $ keywords = Convert :: raw2xml ( $ keywords ) ; $ position = empty ( $ keywords ) ? 0 : ( int ) mb_stripos ( $ text , $ keywords ) ; $ position = max ( 0 , $ position - ( $ characters / 2 ) ) ; if ( $ position > 0 ) { $ position = max ( ( int ) mb_strrpos ( mb_substr ( $ text , 0 , $ position ) , ' ' ) , ( int ) mb_strrpos ( mb_substr ( $ text , 0 , $ position ) , "\n" ) ) ; } $ summary = mb_substr ( $ text , $ position , $ characters ) ; $ stringPieces = explode ( ' ' , $ keywords ) ; if ( $ highlight ) { if ( $ stringPieces ) { foreach ( $ stringPieces as $ stringPiece ) { if ( mb_strlen ( $ stringPiece ) > 2 ) { $ summary = preg_replace ( '/' . preg_quote ( $ stringPiece , '/' ) . '/i' , '<mark>$0</mark>' , $ summary ) ; } } } } $ summary = trim ( $ summary ) ; if ( $ position > 0 ) { $ summary = $ prefix . $ summary ; } if ( strlen ( $ text ) > ( $ characters + $ position ) ) { $ summary = $ summary . $ suffix ; } return $ summary ; }
|
Perform context searching to give some context to searches optionally highlighting the search term .
|
4,864
|
protected static function mergeConfiguredEmails ( $ config , $ env ) { $ normalised = [ ] ; $ source = ( array ) static :: config ( ) -> get ( $ config ) ; foreach ( $ source as $ address => $ name ) { if ( $ address && ! is_numeric ( $ address ) ) { $ normalised [ $ address ] = $ name ; } elseif ( $ name ) { $ normalised [ $ name ] = null ; } } $ extra = Environment :: getEnv ( $ env ) ; if ( $ extra ) { $ normalised [ $ extra ] = null ; } return $ normalised ; }
|
Normalise email list from config merged with env vars
|
4,865
|
public static function obfuscate ( $ email , $ method = 'visible' ) { switch ( $ method ) { case 'direction' : Requirements :: customCSS ( 'span.codedirection { unicode-bidi: bidi-override; direction: rtl; }' , 'codedirectionCSS' ) ; return '<span class="codedirection">' . strrev ( $ email ) . '</span>' ; case 'visible' : $ obfuscated = array ( '@' => ' [at] ' , '.' => ' [dot] ' , '-' => ' [dash] ' ) ; return strtr ( $ email , $ obfuscated ) ; case 'hex' : $ encoded = '' ; for ( $ x = 0 ; $ x < strlen ( $ email ) ; $ x ++ ) { $ encoded .= '&#x' . bin2hex ( $ email { $ x } ) . ';' ; } return $ encoded ; default : user_error ( 'Email::obfuscate(): Unknown obfuscation method' , E_USER_NOTICE ) ; return $ email ; } }
|
Encode an email - address to protect it from spambots . At the moment only simple string substitutions which are not 100% safe from email harvesting .
|
4,866
|
public function removeData ( $ name ) { if ( is_array ( $ this -> data ) ) { unset ( $ this -> data [ $ name ] ) ; } else { $ this -> data -> $ name = null ; } return $ this ; }
|
Remove a datum from the message
|
4,867
|
public function setHTMLTemplate ( $ template ) { if ( substr ( $ template , - 3 ) == '.ss' ) { $ template = substr ( $ template , 0 , - 3 ) ; } $ this -> HTMLTemplate = $ template ; return $ this ; }
|
Set the template to render the email with
|
4,868
|
public function setPlainTemplate ( $ template ) { if ( substr ( $ template , - 3 ) == '.ss' ) { $ template = substr ( $ template , 0 , - 3 ) ; } $ this -> plainTemplate = $ template ; return $ this ; }
|
Set the template to render the plain part with
|
4,869
|
public function send ( ) { if ( ! $ this -> getBody ( ) ) { $ this -> render ( ) ; } if ( ! $ this -> hasPlainPart ( ) ) { $ this -> generatePlainPartFromBody ( ) ; } return Injector :: inst ( ) -> get ( Mailer :: class ) -> send ( $ this ) ; }
|
Send the message to the recipients
|
4,870
|
public function render ( $ plainOnly = false ) { if ( $ existingPlainPart = $ this -> findPlainPart ( ) ) { $ this -> getSwiftMessage ( ) -> detach ( $ existingPlainPart ) ; } unset ( $ existingPlainPart ) ; $ htmlPart = $ plainOnly ? null : $ this -> getBody ( ) ; $ plainPart = $ plainOnly ? $ this -> getBody ( ) : null ; $ htmlTemplate = $ this -> getHTMLTemplate ( ) ; $ plainTemplate = $ this -> getPlainTemplate ( ) ; if ( ! $ htmlTemplate && ! $ plainTemplate && ! $ plainPart && ! $ htmlPart ) { return $ this ; } Requirements :: clear ( ) ; if ( $ plainTemplate && ! $ plainPart ) { $ plainPart = $ this -> renderWith ( $ plainTemplate , $ this -> getData ( ) ) ; } if ( ! $ htmlPart && $ htmlTemplate && ( ! $ plainOnly || empty ( $ plainPart ) ) ) { $ htmlPart = $ this -> renderWith ( $ htmlTemplate , $ this -> getData ( ) ) ; } if ( ! $ plainPart && $ htmlPart ) { $ htmlPartObject = DBField :: create_field ( 'HTMLFragment' , $ htmlPart ) ; $ plainPart = $ htmlPartObject -> Plain ( ) ; } Requirements :: restore ( ) ; if ( ! $ plainPart && ! $ htmlPart ) { return $ this ; } if ( $ htmlPart && ! $ plainOnly ) { $ this -> setBody ( $ htmlPart ) ; $ this -> getSwiftMessage ( ) -> setContentType ( 'text/html' ) ; $ this -> getSwiftMessage ( ) -> setCharset ( 'utf-8' ) ; if ( $ plainPart ) { $ this -> getSwiftMessage ( ) -> addPart ( $ plainPart , 'text/plain' , 'utf-8' ) ; } } else { if ( $ plainPart ) { $ this -> setBody ( $ plainPart ) ; } $ this -> getSwiftMessage ( ) -> setContentType ( 'text/plain' ) ; $ this -> getSwiftMessage ( ) -> setCharset ( 'utf-8' ) ; } return $ this ; }
|
Render the email
|
4,871
|
public function generatePlainPartFromBody ( ) { $ plainPart = $ this -> findPlainPart ( ) ; if ( $ plainPart ) { $ this -> getSwiftMessage ( ) -> detach ( $ plainPart ) ; } unset ( $ plainPart ) ; $ this -> getSwiftMessage ( ) -> addPart ( Convert :: xml2raw ( $ this -> getBody ( ) ) , 'text/plain' , 'utf-8' ) ; return $ this ; }
|
Automatically adds a plain part to the email generated from the current Body
|
4,872
|
public function flushCache ( ) { $ ids = $ this -> getMemberIDList ( ) ; foreach ( $ this -> getServices ( ) as $ service ) { $ service -> flushMemberCache ( $ ids ) ; } }
|
Flushes all registered MemberCacheFlusher services
|
4,873
|
protected function getMemberIDList ( ) { if ( ! $ this -> owner || ! $ this -> owner -> exists ( ) ) { return null ; } if ( $ this -> owner instanceof Group ) { return $ this -> owner -> Members ( ) -> column ( 'ID' ) ; } return [ $ this -> owner -> ID ] ; }
|
Get a list of member IDs that need their permissions flushed
|
4,874
|
protected function redirectAfterSuccessfulLogin ( ) { $ this -> getRequest ( ) -> getSession ( ) -> clear ( 'SessionForms.MemberLoginForm.Email' ) -> clear ( 'SessionForms.MemberLoginForm.Remember' ) ; $ member = Security :: getCurrentUser ( ) ; if ( $ member -> isPasswordExpired ( ) ) { return $ this -> redirectToChangePassword ( ) ; } $ backURL = $ this -> getBackURL ( ) ; if ( $ backURL ) { return $ this -> redirect ( $ backURL ) ; } $ defaultLoginDest = Security :: config ( ) -> get ( 'default_login_dest' ) ; if ( $ defaultLoginDest ) { return $ this -> redirect ( $ defaultLoginDest ) ; } if ( $ member ) { $ message = _t ( 'SilverStripe\\Security\\Member.WELCOMEBACK' , 'Welcome Back, {firstname}' , [ 'firstname' => $ member -> FirstName ] ) ; Security :: singleton ( ) -> setSessionMessage ( $ message , ValidationResult :: TYPE_GOOD ) ; } return $ this -> redirectBack ( ) ; }
|
Login in the user and figure out where to redirect the browser .
|
4,875
|
protected function redirectToChangePassword ( ) { $ cp = ChangePasswordForm :: create ( $ this , 'ChangePasswordForm' ) ; $ cp -> sessionMessage ( _t ( 'SilverStripe\\Security\\Member.PASSWORDEXPIRED' , 'Your password has expired. Please choose a new one.' ) , 'good' ) ; $ changedPasswordLink = Security :: singleton ( ) -> Link ( 'changepassword' ) ; return $ this -> redirect ( $ this -> addBackURLParam ( $ changedPasswordLink ) ) ; }
|
Invoked if password is expired and must be changed
|
4,876
|
protected function redirectToChangePassword ( ) { $ changePasswordForm = ChangePasswordForm :: create ( $ this , 'ChangePasswordForm' ) ; $ changePasswordForm -> sessionMessage ( _t ( 'SilverStripe\\Security\\Member.PASSWORDEXPIRED' , 'Your password has expired. Please choose a new one.' ) , 'good' ) ; $ changePasswordURL = $ this -> addBackURLParam ( Security :: singleton ( ) -> Link ( 'changepassword' ) ) ; $ changePasswordURLATT = Convert :: raw2att ( $ changePasswordURL ) ; $ changePasswordURLJS = Convert :: raw2js ( $ changePasswordURL ) ; $ message = _t ( 'SilverStripe\\Security\\CMSMemberLoginForm.PASSWORDEXPIRED' , '<p>Your password has expired. <a target="_top" href="{link}">Please choose a new one.</a></p>' , 'Message displayed to user if their session cannot be restored' , array ( 'link' => $ changePasswordURLATT ) ) ; $ response = HTTPResponse :: create ( ) -> setBody ( <<<PHP<!DOCTYPE html><html><body>$message<script type="application/javascript">setTimeout(function(){top.location.href = "$changePasswordURLJS";}, 0);</script></body></html>PHP ) ; return $ response ; }
|
Redirect the user to the change password form .
|
4,877
|
protected function redirectAfterSuccessfulLogin ( ) { if ( Security :: getCurrentUser ( ) -> isPasswordExpired ( ) ) { return $ this -> redirectToChangePassword ( ) ; } $ url = CMSSecurity :: singleton ( ) -> Link ( 'success' ) ; return $ this -> redirect ( $ url ) ; }
|
Send user to the right location after login
|
4,878
|
public function setItems ( array $ items ) { $ this -> items = $ items ; $ this -> names = array_keys ( $ items ) ; return $ this ; }
|
Sets the list of all items
|
4,879
|
protected function addVariables ( ) { $ varValues = array_values ( $ this -> variables ) ; $ this -> names = array_filter ( $ this -> names , function ( $ name ) use ( $ varValues ) { return ! in_array ( $ name , $ varValues ) ; } ) ; $ this -> priorities = array_map ( function ( $ name ) { return $ this -> resolveValue ( $ name ) ; } , $ this -> priorities ) ; }
|
If variables are defined interpolate their values
|
4,880
|
protected function includeRest ( array $ list ) { $ otherItemsIndex = false ; if ( $ this -> restKey ) { $ otherItemsIndex = array_search ( $ this -> restKey , $ this -> priorities ) ; } if ( $ otherItemsIndex !== false ) { array_splice ( $ this -> priorities , $ otherItemsIndex , 1 , $ list ) ; } else { $ this -> priorities = array_merge ( $ this -> priorities , $ list ) ; } }
|
If the rest key exists in the order array replace it by the unspecified items
|
4,881
|
protected function resolveValue ( $ name ) { return isset ( $ this -> variables [ $ name ] ) ? $ this -> variables [ $ name ] : $ name ; }
|
Ensure variables get converted to their values
|
4,882
|
protected function column ( $ results ) { $ array = array ( ) ; if ( $ results instanceof mysqli_result ) { while ( $ row = $ results -> fetch_array ( ) ) { $ array [ ] = $ row [ 0 ] ; } } else { foreach ( $ results as $ row ) { $ array [ ] = $ row [ 0 ] ; } } return $ array ; }
|
Helper function to quickly extract a column from a mysqi_result
|
4,883
|
public function requireDatabaseVersion ( $ databaseConfig ) { $ version = $ this -> getDatabaseVersion ( $ databaseConfig ) ; $ success = false ; $ error = '' ; if ( $ version ) { $ success = version_compare ( $ version , '5.0' , '>=' ) ; if ( ! $ success ) { $ error = "Your MySQL server version is $version. It's recommended you use at least MySQL 5.0." ; } } else { $ error = "Could not determine your MySQL version." ; } return array ( 'success' => $ success , 'error' => $ error ) ; }
|
Ensure that the MySQL server version is at least 5 . 0 .
|
4,884
|
public function checkDatabasePermissionGrant ( $ database , $ permission , $ grant ) { if ( ! $ this -> checkValidDatabaseName ( $ database ) ) { return false ; } $ sqlDatabase = addcslashes ( $ database , '_%' ) ; $ dbPattern = sprintf ( '((%s)|(%s)|(%s)|(%s))' , preg_quote ( "\"$sqlDatabase\".*" ) , preg_quote ( "\"$database\".*" ) , preg_quote ( '"%".*' ) , preg_quote ( '*.*' ) ) ; $ expression = '/GRANT[ ,\w]+((ALL PRIVILEGES)|(' . $ permission . '(?! ((VIEW)|(ROUTINE)))))[ ,\w]+ON ' . $ dbPattern . '/i' ; return preg_match ( $ expression , $ grant ) ; }
|
Checks if a specified grant proves that the current user has the specified permission on the specified database
|
4,885
|
public function checkDatabasePermission ( $ conn , $ database , $ permission ) { $ grants = $ this -> column ( $ conn -> query ( "SHOW GRANTS FOR CURRENT_USER" ) ) ; foreach ( $ grants as $ grant ) { if ( $ this -> checkDatabasePermissionGrant ( $ database , $ permission , $ grant ) ) { return true ; } } return false ; }
|
Checks if the current user has the specified permission on the specified database
|
4,886
|
public static function raw2htmlname ( $ val ) { if ( is_array ( $ val ) ) { foreach ( $ val as $ k => $ v ) { $ val [ $ k ] = self :: raw2htmlname ( $ v ) ; } return $ val ; } return self :: raw2att ( $ val ) ; }
|
Convert a value to be suitable for an HTML ID attribute . Replaces non supported characters with a space .
|
4,887
|
public static function raw2xml ( $ val ) { if ( is_array ( $ val ) ) { foreach ( $ val as $ k => $ v ) { $ val [ $ k ] = self :: raw2xml ( $ v ) ; } return $ val ; } return htmlspecialchars ( $ val , ENT_QUOTES , 'UTF-8' ) ; }
|
Ensure that text is properly escaped for XML .
|
4,888
|
public static function raw2js ( $ val ) { if ( is_array ( $ val ) ) { foreach ( $ val as $ k => $ v ) { $ val [ $ k ] = self :: raw2js ( $ v ) ; } return $ val ; } return str_replace ( array ( "\\" , '"' , "\n" , "\r" , "'" , '<' , '>' , '&' ) , array ( "\\\\" , '\"' , '\n' , '\r' , "\\'" , "\\x3c" , "\\x3e" , "\\x26" ) , $ val ) ; }
|
Ensure that text is properly escaped for Javascript .
|
4,889
|
public static function xml2raw ( $ val ) { if ( is_array ( $ val ) ) { foreach ( $ val as $ k => $ v ) { $ val [ $ k ] = self :: xml2raw ( $ v ) ; } return $ val ; } if ( strpos ( $ val , '<' ) !== false ) { return self :: html2raw ( $ val ) ; } return html_entity_decode ( $ val , ENT_QUOTES , 'UTF-8' ) ; }
|
Convert XML to raw text .
|
4,890
|
public static function html2raw ( $ data , $ preserveLinks = false , $ wordWrap = 0 , $ config = null ) { $ defaultConfig = array ( 'PreserveLinks' => false , 'ReplaceBoldAsterisk' => true , 'CompressWhitespace' => true , 'ReplaceImagesWithAlt' => true , ) ; if ( isset ( $ config ) ) { $ config = array_merge ( $ defaultConfig , $ config ) ; } else { $ config = $ defaultConfig ; } $ data = preg_replace ( "/<style([^A-Za-z0-9>][^>]*)?>.*?<\/style[^>]*>/is" , '' , $ data ) ; $ data = preg_replace ( "/<script([^A-Za-z0-9>][^>]*)?>.*?<\/script[^>]*>/is" , '' , $ data ) ; if ( $ config [ 'ReplaceBoldAsterisk' ] ) { $ data = preg_replace ( '%<(strong|b)( [^>]*)?>|</(strong|b)>%i' , '*' , $ data ) ; } if ( ! $ preserveLinks && ! $ config [ 'PreserveLinks' ] ) { $ data = preg_replace_callback ( '/<a[^>]*href\s*=\s*"([^"]*)">(.*?)<\/a>/ui' , function ( $ matches ) { return Convert :: html2raw ( $ matches [ 2 ] ) . "[$matches[1]]" ; } , $ data ) ; $ data = preg_replace_callback ( '/<a[^>]*href\s*=\s*([^ ]*)>(.*?)<\/a>/ui' , function ( $ matches ) { return Convert :: html2raw ( $ matches [ 2 ] ) . "[$matches[1]]" ; } , $ data ) ; } if ( $ config [ 'ReplaceImagesWithAlt' ] ) { $ data = preg_replace ( '/<img[^>]*alt *= *"([^"]*)"[^>]*>/i' , ' \\1 ' , $ data ) ; $ data = preg_replace ( '/<img[^>]*alt *= *([^ ]*)[^>]*>/i' , ' \\1 ' , $ data ) ; } if ( $ config [ 'CompressWhitespace' ] ) { $ data = preg_replace ( "/\s+/u" , ' ' , $ data ) ; } $ data = preg_replace ( "/\s*<[Hh][1-6]([^A-Za-z0-9>][^>]*)?> */u" , "\n\n" , $ data ) ; $ data = preg_replace ( "/\s*<[Pp]([^A-Za-z0-9>][^>]*)?> */u" , "\n\n" , $ data ) ; $ data = preg_replace ( "/\s*<[Dd][Ii][Vv]([^A-Za-z0-9>][^>]*)?> */u" , "\n\n" , $ data ) ; $ data = preg_replace ( "/\n\n\n+/" , "\n\n" , $ data ) ; $ data = preg_replace ( '/<[Bb][Rr]([^A-Za-z0-9>][^>]*)?> */' , "\n" , $ data ) ; $ data = preg_replace ( '/<[Tt][Rr]([^A-Za-z0-9>][^>]*)?> */' , "\n" , $ data ) ; $ data = preg_replace ( "/<\/[Tt][Dd]([^A-Za-z0-9>][^>]*)?> */" , ' ' , $ data ) ; $ data = preg_replace ( '/<\/p>/i' , "\n\n" , $ data ) ; $ data = html_entity_decode ( $ data , ENT_QUOTES , 'UTF-8' ) ; if ( ! $ preserveLinks && ! $ config [ 'PreserveLinks' ] ) { $ data = preg_replace ( '/<\/?[^>]*>/' , '' , $ data ) ; } else { $ data = strip_tags ( $ data , '<a>' ) ; } if ( $ wordWrap ) { $ data = wordwrap ( trim ( $ data ) , $ wordWrap ) ; } return trim ( $ data ) ; }
|
Simple conversion of HTML to plaintext .
|
4,891
|
public static function upperCamelToLowerCamel ( $ str ) { $ return = null ; $ matches = null ; if ( preg_match ( '/(^[A-Z]{1,})([A-Z]{1})([a-z]+.*)/' , $ str , $ matches ) ) { $ return = implode ( '' , [ strtolower ( $ matches [ 1 ] ) , $ matches [ 2 ] , $ matches [ 3 ] ] ) ; } elseif ( preg_match ( '/(^[A-Z]{1})([a-z]+.*)/' , $ str , $ matches ) ) { $ return = implode ( '' , [ strtolower ( $ matches [ 1 ] ) , $ matches [ 2 ] ] ) ; } elseif ( preg_match ( '/^[A-Z]+$/' , $ str ) ) { $ return = strtolower ( $ str ) ; } else { $ return = $ str ; } return $ return ; }
|
Converts upper camel case names to lower camel case with leading upper case characters replaced with lower case . Tries to retain word case .
|
4,892
|
public static function memstring2bytes ( $ memString ) { $ unit = preg_replace ( '/[^bkmgtpezy]/i' , '' , $ memString ) ; $ size = preg_replace ( '/[^0-9\.\-]/' , '' , $ memString ) ; if ( $ unit ) { return ( int ) round ( $ size * pow ( 1024 , stripos ( 'bkmgtpezy' , $ unit [ 0 ] ) ) ) ; } return ( int ) round ( $ size ) ; }
|
Turn a memory string such as 512M into an actual number of bytes . Preserves integer values like 1024 or - 1
|
4,893
|
public static function slashes ( $ path , $ separator = DIRECTORY_SEPARATOR , $ multiple = true ) { if ( $ multiple ) { return preg_replace ( '#[/\\\\]+#' , $ separator , $ path ) ; } return str_replace ( [ '/' , '\\' ] , $ separator , $ path ) ; }
|
Convert slashes in relative or asolute filesystem path . Defaults to DIRECTORY_SEPARATOR
|
4,894
|
public function process ( HTTPRequest $ request , callable $ delegate ) { try { $ this -> getAuthenticationHandler ( ) -> authenticateRequest ( $ request ) ; } catch ( ValidationException $ e ) { return new HTTPResponse ( "Bad log-in details: " . $ e -> getMessage ( ) , 400 ) ; } catch ( DatabaseException $ e ) { } return $ delegate ( $ request ) ; }
|
Identify the current user from the request
|
4,895
|
public function formField ( $ title = null , $ name = null , $ hasEmpty = false , $ value = "" , $ emptyString = null ) { if ( ! $ title ) { $ title = $ this -> getName ( ) ; } if ( ! $ name ) { $ name = $ this -> getName ( ) ; } $ field = new DropdownField ( $ name , $ title , $ this -> enumValues ( false ) , $ value ) ; if ( $ hasEmpty ) { $ field -> setEmptyString ( $ emptyString ) ; } return $ field ; }
|
Return a dropdown field suitable for editing this field .
|
4,896
|
public function getEnumObsolete ( ) { $ table = $ this -> getTable ( ) ; $ name = $ this -> getName ( ) ; if ( empty ( $ table ) || empty ( $ name ) ) { return $ this -> getEnum ( ) ; } if ( empty ( self :: $ enum_cache [ $ table ] ) ) { self :: $ enum_cache [ $ table ] = array ( ) ; } if ( ! empty ( self :: $ enum_cache [ $ table ] [ $ name ] ) ) { return self :: $ enum_cache [ $ table ] [ $ name ] ; } $ enumValues = $ this -> getEnum ( ) ; if ( DB :: get_schema ( ) -> hasField ( $ table , $ name ) ) { $ existing = DB :: query ( "SELECT DISTINCT \"{$name}\" FROM \"{$table}\"" ) -> column ( ) ; $ enumValues = array_unique ( array_merge ( $ enumValues , $ existing ) ) ; } self :: $ enum_cache [ $ table ] [ $ name ] = $ enumValues ; return $ enumValues ; }
|
Get the list of enum values including obsolete values still present in the database
|
4,897
|
public function setEnum ( $ enum ) { if ( ! is_array ( $ enum ) ) { $ enum = preg_split ( '/\s*,\s*/' , ltrim ( preg_replace ( '/,\s*\n\s*$/' , '' , $ enum ) ) ) ; } $ this -> enum = array_values ( $ enum ) ; return $ this ; }
|
Set enum options
|
4,898
|
public function handleAction ( GridField $ gridField , $ actionName , $ arguments , $ data ) { switch ( $ actionName ) { case 'addto' : if ( isset ( $ data [ 'relationID' ] ) && $ data [ 'relationID' ] ) { $ gridField -> State -> GridFieldAddRelation = $ data [ 'relationID' ] ; } break ; } }
|
Manipulate the state to add a new relation
|
4,899
|
protected function initBaseDir ( $ basePath ) { if ( $ basePath ) { $ this -> setBaseDir ( $ basePath ) ; } elseif ( defined ( 'BASE_PATH' ) ) { $ this -> setBaseDir ( BASE_PATH ) ; } else { throw new BadMethodCallException ( "No BASE_PATH defined" ) ; } }
|
Init base path or guess if able
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.