MediaWiki  1.23.8
GlobalFunctions.php File Reference

Global functions used everywhere. More...

Go to the source code of this file.

Functions

 mimeTypeMatch ( $type, $avail)
 Checks if a given MIME type matches any of the keys in the given array. More...
 
 swap (&$x, &$y)
 Swap two variables. More...
 
 wfAcceptToPrefs ( $accept, $def=' */*')
 Converts an Accept-* header into an array mapping string values to quality factors. More...
 
 wfAppendQuery ( $url, $query)
 Append a query string to an existing URL, which may or may not already have query string parameters already. More...
 
 wfAppendToArrayIfNotDefault ( $key, $value, $default, &$changed)
 Appends to second array if $value differs from that in $default. More...
 
if(!defined( 'MEDIAWIKI')) wfArrayDiff2 ( $a, $b)
 Like array_diff( $a, $b ) except that it works with two-dimensional arrays. More...
 
 wfArrayDiff2_cmp ( $a, $b)
 
 wfArrayInsertAfter (array $array, array $insert, $after)
 Insert array into another array after the specified KEY More...
 
 wfArrayLookup ( $a, $b)
 Array lookup Returns an array where the values in array $b are replaced by the values in array $a with the corresponding keys. More...
 
 wfArrayMerge ( $array1)
 Backwards array plus for people who haven't bothered to read the PHP manual XXX: will not darn your socks for you. More...
 
 wfArrayToCgi ( $array1, $array2=null, $prefix='')
 This function takes two arrays as input, and returns a CGI-style string, e.g. More...
 
 wfAssembleUrl ( $urlParts)
 This function will reassemble a URL parsed with wfParseURL. More...
 
 wfBacktrace ()
 Get a debug backtrace as a string. More...
 
 wfBaseConvert ( $input, $sourceBase, $destBase, $pad=1, $lowercase=true, $engine='auto')
 Convert an arbitrarily-long digit string from one numeric base to another, optionally zero-padding to a minimum column width. More...
 
 wfBaseName ( $path, $suffix='')
 Return the final portion of a pathname. More...
 
 wfBCP47 ( $code)
 Get the normalised IETF language tag See unit test for examples. More...
 
 wfBoolToStr ( $value)
 Convenience function converts boolean values into "true" or "false" (string) values. More...
 
 wfCanIPUseHTTPS ( $ip)
 Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS. More...
 
 wfCgiToArray ( $query)
 This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns the same string in array form. More...
 
 wfCheckEntropy ()
 Check if there is sufficient entropy in php's built-in session generation. More...
 
 wfCheckLimits ( $deflimit=50, $optionname='rclimit')
 Obtain the offset and limit values from the request string; used in special pages. More...
 
 wfClearOutputBuffers ()
 More legible than passing a 'false' parameter to wfResetOutputBuffers(): More...
 
 wfClientAcceptsGzip ( $force=false)
 
 wfCountDown ( $seconds)
 Count down from $seconds to zero on the terminal, with a one-second pause between showing each number. More...
 
 wfDebug ( $text, $dest='all')
 Sends a line to the debug log if enabled or, optionally, to a comment in output. More...
 
 wfDebugBacktrace ( $limit=0)
 Safety wrapper for debug_backtrace(). More...
 
 wfDebugDieBacktrace ( $msg='')
 Throw a debugging exception. More...
 
 wfDebugLog ( $logGroup, $text, $dest='all')
 Send a line to a supplementary debug log file, if configured, or main debug log if not. More...
 
 wfDebugMem ( $exact=false)
 Send a line giving PHP memory usage. More...
 
 wfDebugTimer ()
 Get microsecond timestamps for debug logs. More...
 
 wfDeprecated ( $function, $version=false, $component=false, $callerOffset=2)
 Throws a warning that $function is deprecated. More...
 
 wfDiff ( $before, $after, $params='-u')
 Returns unified plain-text diff of two texts. More...
 
 wfEmptyMsg ( $key)
 Since wfMsg() and co suck, they don't return false if the message key they looked up didn't exist but instead the key wrapped in <>'s, this function checks for the nonexistence of messages by checking the MessageCache::get() result directly. More...
 
 wfErrorLog ( $text, $file)
 Log to a file without getting "file size exceeded" signals. More...
 
 wfEscapeShellArg ()
 Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell, but the escapeshellarg() function puts single quotes in regardless of OS. More...
 
 wfEscapeWikiText ( $text)
 Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc. More...
 
 wfExpandIRI ( $url)
 Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode characters with their UTF-8 original forms for more compact display and legibility for local audiences. More...
 
 wfExpandIRI_callback ( $matches)
 Private callback for wfExpandIRI. More...
 
 wfExpandUrl ( $url, $defaultProto=PROTO_CURRENT)
 Expand a potentially local URL to a fully-qualified URL. More...
 
 wfFindFile ( $title, $options=array())
 Find a file. More...
 
 wfFixSessionID ()
 Override session_id before session startup if php's built-in session generation code is not secure. More...
 
 wfForeignMemcKey ( $db, $prefix)
 Get a cache key for a foreign DB. More...
 
 wfFormatStackFrame ( $frame)
 Return a string representation of frame. More...
 
 wfGetAllCallers ( $limit=3)
 Return a string consisting of callers in the stack. More...
 
 wfGetCache ( $inputType)
 Get a cache object. More...
 
 wfGetCaller ( $level=2)
 Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. More...
 
wfGetDB ( $db, $groups=array(), $wiki=false)
 Get a Database object. More...
 
 wfGetIP ()
 Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of the chain) More...
 
 wfGetLangConverterCacheStorage ()
 Get the cache object used by the language converter. More...
 
 wfGetLangObj ( $langcode=false)
 Return a Language object from $langcode. More...
 
 wfGetLB ( $wiki=false)
 Get a load balancer object. More...
 
wfGetLBFactory ()
 Get the load balancer factory object. More...
 
 wfGetMainCache ()
 Get the main cache object. More...
 
 wfGetMessageCacheStorage ()
 Get the cache object used by the message cache. More...
 
 wfGetNull ()
 Get a platform-independent path to the null file, e.g. More...
 
 wfGetParserCacheStorage ()
 Get the cache object used by the parser cache. More...
 
 wfGetPrecompiledData ( $name)
 Get an object from the precompiled serialized directory. More...
 
 wfGetScriptUrl ()
 Get the script URL. More...
 
 wfHostname ()
 Fetch server name for use in error reporting etc. More...
 
 wfHttpError ( $code, $label, $desc)
 Provide a simple HTTP error. More...
 
 wfIncrStats ( $key, $count=1)
 Increment a statistics counter. More...
 
 wfIniGetBool ( $setting)
 Safety wrapper around ini_get() for boolean settings. More...
 
 wfInitShellLocale ()
 Workaround for http://bugs.php.net/bug.php?id=45132 escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale. More...
 
 wfIsBadImage ( $name, $contextTitle=false, $blacklist=null)
 Determine if an image exists on the 'bad image list'. More...
 
 wfIsConfiguredProxy ( $ip)
 Checks if an IP matches a proxy we've configured. More...
 
 wfIsDebugRawPage ()
 Returns true if debug logging should be suppressed if $wgDebugRawPage = false. More...
 
 wfIsHHVM ()
 Check if we are running under HHVM. More...
 
 wfIsTrustedProxy ( $ip)
 Checks if an IP is a trusted proxy provider. More...
 
 wfIsWindows ()
 Check if the operating system is Windows. More...
 
 wfLocalFile ( $title)
 Get an object referring to a locally registered file. More...
 
 wfLogDBError ( $text)
 Log for database errors. More...
 
 wfLogProfilingData ()
 
 wfLogWarning ( $msg, $callerOffset=1, $level=E_USER_WARNING)
 Send a warning as a PHP error and the debug log. More...
 
 wfMakeUrlIndexes ( $url)
 Make URL indexes, appropriate for the el_index field of externallinks. More...
 
 wfMatchesDomainList ( $url, $domains)
 Check whether a given URL has a domain that occurs in a given set of domains. More...
 
 wfMemcKey ()
 Get a cache key. More...
 
 wfMemoryLimit ()
 Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;. More...
 
 wfMerge ( $old, $mine, $yours, &$result)
 wfMerge attempts to merge differences between three texts. More...
 
 wfMergeErrorArrays ()
 Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g. More...
 
 wfMessage ( $key)
 This is the function for getting translated interface messages. More...
 
 wfMessageFallback ()
 This function accepts multiple message keys and returns a message instance for the first message which is non-empty. More...
 
 wfMkdirParents ( $dir, $mode=null, $caller=null)
 Make directory, and make all parent directories if they don't exist. More...
 
 wfMsg ( $key)
 Get a message from anywhere, for the current user language. More...
 
 wfMsgExt ( $key, $options)
 Returns message in the requested format. More...
 
 wfMsgForContent ( $key)
 Get a message from anywhere, for the current global language set with $wgLanguageCode. More...
 
 wfMsgForContentNoTrans ( $key)
 Same as above except doesn't transform the message. More...
 
 wfMsgGetKey ( $key, $useDB=true, $langCode=false, $transform=true)
 Fetch a message string value, but don't replace any keys yet. More...
 
 wfMsgHtml ( $key)
 Return an HTML-escaped version of a message. More...
 
 wfMsgNoTrans ( $key)
 Same as above except doesn't transform the message. More...
 
 wfMsgReal ( $key, $args, $useDB=true, $forContent=false, $transform=true)
 Really get a message. More...
 
 wfMsgReplaceArgs ( $message, $args)
 Replace message parameter keys on the given formatted output. More...
 
 wfMsgWikiHtml ( $key)
 Return an HTML version of message Parameter replacements, if any, are done after parsing the wiki-text message, so parameters may contain HTML (eg links or form controls). More...
 
 wfNegotiateType ( $cprefs, $sprefs)
 Returns the 'best' match between a client's requested internet media types and the server's list of available types. More...
 
 wfObjectToArray ( $objOrArray, $recursive=true)
 Recursively converts the parameter (an object) to an array with the same data. More...
 
 wfParseUrl ( $url)
 parse_url() work-alike, but non-broken. More...
 
 wfPercent ( $nr, $acc=2, $round=true)
 
 wfQueriesMustScale ()
 Should low-performance queries be disabled? More...
 
 wfRandom ()
 Get a random decimal value between 0 and 1, in a way not likely to give duplicate values for any realistic number of articles. More...
 
 wfRandomString ( $length=32)
 Get a random string containing a number of pseudo-random hex characters. More...
 
 wfReadOnly ()
 Check whether the wiki is in read-only mode. More...
 
 wfReadOnlyReason ()
 Get the value of $wgReadOnly or the contents of $wgReadOnlyFile. More...
 
 wfRecursiveRemoveDir ( $dir)
 Remove a directory and all its content. More...
 
 wfRelativePath ( $path, $from)
 Generate a relative path name to the given file. More...
 
 wfRemoveDotSegments ( $urlPath)
 Remove all dot-segments in the provided URL path. More...
 
 wfReportTime ()
 Returns a script tag that stores the amount of time it took MediaWiki to handle the request in milliseconds as 'wgBackendResponseTime'. More...
 
 wfResetOutputBuffers ( $resetGzipEncoding=true)
 Clear away any user-level output buffers, discarding contents. More...
 
 wfResetSessionID ()
 Reset the session_id. More...
 
 wfRestoreWarnings ()
 Restore error level to previous value. More...
 
 wfRunHooks ( $event, array $args=array(), $deprecatedVersion=null)
 Call hook functions defined in $wgHooks. More...
 
 wfScript ( $script='index')
 Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScriptExtension etc. More...
 
 wfSetBit (&$dest, $bit, $state=true)
 As for wfSetVar except setting a bit. More...
 
 wfSetupSession ( $sessionId=false)
 Initialise php session. More...
 
 wfSetVar (&$dest, $source, $force=false)
 Sets dest to source and returns the original value of dest If source is NULL, it just returns the value, it doesn't set the variable If force is true, it will set the value even if source is NULL. More...
 
 wfShellExec ( $cmd, &$retval=null, $environ=array(), $limits=array(), $options=array())
 Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported. More...
 
 wfShellExecDisabled ()
 Check if wfShellExec() is effectively disabled via php.ini config. More...
 
 wfShellExecWithStderr ( $cmd, &$retval=null, $environ=array(), $limits=array())
 Execute a shell command, returning both stdout and stderr. More...
 
 wfShellMaintenanceCmd ( $script, array $parameters=array(), array $options=array())
 Alias to wfShellWikiCmd() More...
 
 wfShellWikiCmd ( $script, array $parameters=array(), array $options=array())
 Generate a shell-escaped command line string to run a MediaWiki cli script. More...
 
 wfShorthandToInteger ( $string='')
 Converts shorthand byte notation to integer form. More...
 
 wfShowingResults ( $offset, $limit)
 
 wfSplitWikiID ( $wiki)
 Split a wiki ID into DB name and table prefix. More...
 
 wfStripIllegalFilenameChars ( $name)
 Replace all invalid characters with - Additional characters can be defined in $wgIllegalFileChars (see bug 20489) By default, $wgIllegalFileChars = ':'. More...
 
 wfSuppressWarnings ( $end=false)
 Reference-counted warning suppression. More...
 
 wfTempDir ()
 Tries to get the system directory for temporary files. More...
 
 wfTime ()
 Get the current unix timestamp with microseconds. More...
 
 wfTimestamp ( $outputtype=TS_UNIX, $ts=0)
 Get a timestamp string in one of various formats. More...
 
 wfTimestampNow ()
 Convenience function; returns MediaWiki timestamp for the present time. More...
 
 wfTimestampOrNull ( $outputtype=TS_UNIX, $ts=null)
 Return a formatted timestamp, or null if input is null. More...
 
 wfUnpack ( $format, $data, $length=false)
 Wrapper around php's unpack. More...
 
 wfUrlencode ( $s)
 We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default. More...
 
 wfUrlProtocols ( $includeProtocolRelative=true)
 Returns a regular expression of url protocols. More...
 
 wfUrlProtocolsWithoutProtRel ()
 Like wfUrlProtocols(), but excludes '//' from the protocol list. More...
 
 wfUseMW ( $req_ver)
 This function works like "use VERSION" in Perl except it checks the version of MediaWiki, the program will die with a backtrace if the current version of MediaWiki is less than the version provided. More...
 
 wfUsePHP ( $req_ver)
 This function works like "use VERSION" in Perl, the program will die with a backtrace if the current version of PHP is less than the version provided. More...
 
 wfVarDump ( $var)
 A wrapper around the PHP function var_export(). More...
 
 wfViewPrevNext ( $offset, $limit, $link, $query='', $atend=false)
 Generate (prev x| next x) (20|50|100...) type links for paging. More...
 
 wfWaitForSlaves ( $maxLag=false, $wiki=false, $cluster=false)
 Modern version of wfWaitForSlaves(). More...
 
 wfWarn ( $msg, $callerOffset=1, $level=E_USER_NOTICE)
 Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings. More...
 
 wfWikiID ()
 Get an ASCII string identifying this wiki This is used as a prefix in memcached keys. More...
 

Variables

const TS_DB 2
 MySQL DATETIME (YYYY-MM-DD HH:MM:SS) More...
 
const TS_EXIF 5
 An Exif timestamp (YYYY:MM:DD HH:MM:SS) More...
 
const TS_ISO_8601 4
 ISO 8601 format with no timezone: 1986-02-09T20:00:00Z. More...
 
const TS_ISO_8601_BASIC 9
 ISO 8601 basic format with no timezone: 19860209T200000Z. More...
 
const TS_MW 1
 MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS) More...
 
const TS_ORACLE 6
 Oracle format time. More...
 
const TS_POSTGRES 7
 Postgres format time. More...
 
const TS_RFC2822 3
 RFC 2822 format, for E-mail and HTTP headers. More...
 
const TS_UNIX 0
 Unix time - the number of seconds since 1970-01-01 00:00:00 UTC. More...
 

Detailed Description

Global functions used everywhere.

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. http://www.gnu.org/copyleft/gpl.html

Definition in file GlobalFunctions.php.

Function Documentation

◆ mimeTypeMatch()

mimeTypeMatch (   $type,
  $avail 
)
private

Checks if a given MIME type matches any of the keys in the given array.

Basic wildcards are accepted in the array keys.

Returns the matching MIME type (or wildcard) if a match, otherwise NULL if no match.

Parameters
string$type
array$avail
Returns
string

Definition at line 2318 of file GlobalFunctions.php.

Referenced by GlobalTest\testMimeTypeMatch().

◆ swap()

swap ( $x,
$y 
)

Swap two variables.

Parameters
mixed$x
mixed$y

Definition at line 2547 of file GlobalFunctions.php.

Referenced by GlobalTest\testSwapVarsTest().

◆ wfAcceptToPrefs()

wfAcceptToPrefs (   $accept,
  $def = '*/*' 
)

Converts an Accept-* header into an array mapping string values to quality factors.

Parameters
string$accept
string$defdefault
Returns
float[] Associative array of string => float pairs

Definition at line 2282 of file GlobalFunctions.php.

◆ wfAppendQuery()

◆ wfAppendToArrayIfNotDefault()

wfAppendToArrayIfNotDefault (   $key,
  $value,
  $default,
$changed 
)

Appends to second array if $value differs from that in $default.

Parameters
$keyString|Int
$valueMixed
$defaultMixed
array$changedto alter
Exceptions
MWException

Definition at line 164 of file GlobalFunctions.php.

◆ wfArrayDiff2()

if (!defined('MEDIAWIKI')) wfArrayDiff2 (   $a,
  $b 
)

Like array_diff( $a, $b ) except that it works with two-dimensional arrays.

Parameters
$aarray
$barray
Returns
array

Definition at line 113 of file GlobalFunctions.php.

Referenced by WikiPage\doRollback(), GlobalTest\testWfArrayDiff2(), and UploadBase\verifyTitlePermissions().

◆ wfArrayDiff2_cmp()

wfArrayDiff2_cmp (   $a,
  $b 
)
Parameters
$aarray|string
$barray|string
Returns
int

Definition at line 122 of file GlobalFunctions.php.

◆ wfArrayInsertAfter()

wfArrayInsertAfter ( array  $array,
array  $insert,
  $after 
)

Insert array into another array after the specified KEY

Parameters
array$arrayThe array.
array$insertThe array to insert.
$afterMixed: The key to insert after
Returns
Array

Definition at line 235 of file GlobalFunctions.php.

◆ wfArrayLookup()

wfArrayLookup (   $a,
  $b 
)

Array lookup Returns an array where the values in array $b are replaced by the values in array $a with the corresponding keys.

Deprecated:
since 1.22; use array_intersect_key()
Parameters
$aArray
$bArray
Returns
array

Definition at line 150 of file GlobalFunctions.php.

◆ wfArrayMerge()

wfArrayMerge (   $array1)

Backwards array plus for people who haven't bothered to read the PHP manual XXX: will not darn your socks for you.

Deprecated:
since 1.22; use array_replace()
Parameters
array$array1Initial array to merge.
array[$array2,...] Variable list of arrays to merge.
Returns
array

Definition at line 183 of file GlobalFunctions.php.

◆ wfArrayToCgi()

wfArrayToCgi (   $array1,
  $array2 = null,
  $prefix = '' 
)

◆ wfAssembleUrl()

wfAssembleUrl (   $urlParts)

This function will reassemble a URL parsed with wfParseURL.

This is useful if you need to edit part of a URL and put it back together.

This is the basic structure used (brackets contain keys for $urlParts): [scheme][delimiter][user]:[pass]@[host]:[port][path]?[query]#[fragment]

Todo:
Need to integrate this into wfExpandUrl (bug 32168)
Since
1.19
Parameters
array$urlPartsURL parts, as output from wfParseUrl
Returns
string URL assembled from its component parts

Definition at line 565 of file GlobalFunctions.php.

Referenced by WfAssembleUrlTest\testWfAssembleUrl().

◆ wfBacktrace()

wfBacktrace ( )

Get a debug backtrace as a string.

Returns
string

Definition at line 1886 of file GlobalFunctions.php.

Referenced by MWDebug\deprecated(), and BackupReader\skippedNamespace().

◆ wfBaseConvert()

wfBaseConvert (   $input,
  $sourceBase,
  $destBase,
  $pad = 1,
  $lowercase = true,
  $engine = 'auto' 
)

Convert an arbitrarily-long digit string from one numeric base to another, optionally zero-padding to a minimum column width.

Supports base 2 through 36; digit values 10-36 are represented as lowercase letters a-z. Input is case-insensitive.

Parameters
string$inputInput number
int$sourceBaseBase of the input number
int$destBaseDesired base of the output
int$padMinimum number of digits in the output (pad with zeroes)
bool$lowercaseWhether to output in lowercase or uppercase
string$engineEither "gmp", "bcmath", or "php"
Returns
string|bool The output number as a string, or false on error

Definition at line 3377 of file GlobalFunctions.php.

Referenced by UIDGenerator\__construct(), Revision\base36Sha1(), SwiftFileBackend\doCreateInternal(), PostgreSqlLockManager\doGetLocksOnServer(), SwiftFileBackend\doStoreInternal(), FileBackendTest\doTestDoOperations(), FileBackendTest\doTestDoOperationsFailing(), FileBackendTest\doTestDoOperationsPipeline(), ApiQueryDeletedrevs\execute(), ApiQueryFilearchive\execute(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryRevisions\extractRowInfo(), FileBackendStore\getContainerSuffixes(), ApiQueryImageInfo\getInfo(), JobQueueRedis\getNewJobFields(), ForeignAPIFile\getSha1(), WikiRevision\getSha1(), FSFile\getSha1Base36(), CreateFileOp\getSourceSha1Base36(), StoreFileOp\getSourceSha1Base36(), FileJournal\getTimestampedUUID(), JobQueueDB\insertFields(), UIDGenerator\millisecondsSinceEpochBinary(), UIDGenerator\newTimestampedUID128(), UIDGenerator\newTimestampedUID88(), User\randomPassword(), ApiQueryAllImages\run(), LockManager\sha1Base36Absolute(), UploadStash\stashFile(), ExternalStoreMwstore\store(), WfBaseConvertTest\testDigitToBase10(), WfBaseConvertTest\testDigitToBase16(), WfBaseConvertTest\testDigitToBase2(), WfBaseConvertTest\testDigitToBase3(), WfBaseConvertTest\testDigitToBase36(), WfBaseConvertTest\testDigitToBase5(), WfBaseConvertTest\testDigitToBase8(), WfBaseConvertTest\testIdentity(), WfBaseConvertTest\testInvalid(), WfBaseConvertTest\testLargeNumber(), WfBaseConvertTest\testPadding(), and UIDGeneratorTest\testTimestampedUID().

◆ wfBaseName()

wfBaseName (   $path,
  $suffix = '' 
)

Return the final portion of a pathname.

Reimplemented because PHP5's "basename()" is buggy with multibyte text. http://bugs.php.net/bug.php?id=33898

PHP's basename() only considers '\' a pathchar on Windows and Netware. We'll consider it so always, as we don't want '\s' in our Unix paths either.

Parameters
string$path
string$suffixto remove if present
Returns
string

Definition at line 3302 of file GlobalFunctions.php.

Referenced by ImageBuilder\checkMissingImage(), TestFileOpPerformance\doPerfTest(), and WfBaseNameTest\testBaseName().

◆ wfBCP47()

wfBCP47 (   $code)

Get the normalised IETF language tag See unit test for examples.

Parameters
string$codeThe language code.
Returns
string The language code which complying with BCP 47 standards.

Definition at line 3929 of file GlobalFunctions.php.

Referenced by OutputPage\addAcceptLanguage(), SkinTemplate\buildContentNavigationUrls(), ImagePage\doRenderLangOpt(), OutputPage\getHeadLinksArray(), Language\getHtmlCode(), SkinTemplate\getLanguages(), CoreParserFunctions\language(), Preferences\profilePreferences(), and WfBCP47Test\testBCP47().

◆ wfBoolToStr()

wfBoolToStr (   $value)

Convenience function converts boolean values into "true" or "false" (string) values.

Parameters
bool$value
Returns
string

Definition at line 3780 of file GlobalFunctions.php.

Referenced by LocalSettingsGenerator\__construct(), ApiRsd\formatRsdApiList(), LocalSettingsGenerator\getDefaultText(), MysqlInstaller\getLocalSettings(), and GlobalTest\testClientAcceptsGzipTest().

◆ wfCanIPUseHTTPS()

wfCanIPUseHTTPS (   $ip)

Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.

Parameters
string$ipThe IPv4/6 address in the normal human-readable form
Returns
boolean

Definition at line 4138 of file GlobalFunctions.php.

Referenced by LoginForm\execute(), Preferences\profilePreferences(), and User\requiresHTTPS().

◆ wfCgiToArray()

wfCgiToArray (   $query)

This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns the same string in array form.

This allows compatibility with legacy functions that accept raw query strings instead of nice arrays. Of course, keys and values are urldecode()d.

Parameters
string$queryquery string
Returns
string[] Array version of input

Definition at line 412 of file GlobalFunctions.php.

Referenced by WebRequest\appendQuery(), LoginForm\executeReturnTo(), Linker\link(), Linker\makeBrokenImageLinkObj(), Linker\makeKnownLinkObj(), Linker\makeLinkObj(), OutputPage\returnToMain(), GlobalTest\testCgiRoundTrip(), and GlobalTest\testCgiToArray().

◆ wfCheckEntropy()

wfCheckEntropy ( )

Check if there is sufficient entropy in php's built-in session generation.

Returns
bool true = there is sufficient entropy

Definition at line 3473 of file GlobalFunctions.php.

◆ wfCheckLimits()

wfCheckLimits (   $deflimit = 50,
  $optionname = 'rclimit' 
)

Obtain the offset and limit values from the request string; used in special pages.

Parameters
int$deflimitdefault limit if none supplied
string$optionnameName of a user preference to check against
Returns
array

Definition at line 2063 of file GlobalFunctions.php.

◆ wfClearOutputBuffers()

wfClearOutputBuffers ( )

More legible than passing a 'false' parameter to wfResetOutputBuffers():

Clear away output buffers, but keep the Content-Encoding header produced by ob_gzhandler, if any.

This should be used for HTTP 304 responses, where you need to preserve the Content-Encoding header of the real result, but also need to suppress the output of ob_gzhandler to keep to spec and avoid breaking Firefox in rare cases where the headers and body are broken over two packets.

Definition at line 2270 of file GlobalFunctions.php.

Referenced by OutputPage\checkLastModified().

◆ wfClientAcceptsGzip()

wfClientAcceptsGzip (   $force = false)
Todo:

document

FIXME: We may want to blacklist some broken browsers

Parameters
bool$force
Returns
bool Whereas client accept gzip compression

Definition at line 2029 of file GlobalFunctions.php.

Referenced by HTMLFileCache\loadFromFileCache(), HTMLFileCache\saveToFileCache(), GlobalTest\testClientAcceptsGzipTest(), and wfGzipHandler().

◆ wfCountDown()

wfCountDown (   $seconds)

Count down from $seconds to zero on the terminal, with a one-second pause between showing each number.

For use in command-line scripts.

Parameters
int$seconds

Definition at line 3831 of file GlobalFunctions.php.

Referenced by ResetUserTokens\execute(), UpdateMediaWiki\execute(), and UserOptions\warn().

◆ wfDebug()

wfDebug (   $text,
  $dest = 'all' 
)

Sends a line to the debug log if enabled or, optionally, to a comment in output.

In normal operation this is a NOP.

Controlling globals: $wgDebugLogFile - points to the log file $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output. $wgDebugComments - if on, some debug items may appear in comments in the HTML output.

Parameters
$textString
string | bool$destDestination of the message:
  • 'all': both to the log and HTML (debug toolbar or HTML comments)
  • 'log': only to the log and not in HTML For backward compatibility, it can also take a boolean:
  • true: same as 'all'
  • false: same as 'log'

Definition at line 933 of file GlobalFunctions.php.

Referenced by UploadFromChunks\__construct(), MemcachedPeclBagOStuff\__construct(), UploadFromStash\__construct(), DifferenceEngine\__construct(), ApiMain\__construct(), UploadStashFile\__construct(), Revision\__construct(), DatabaseBase\__construct(), StubObject\_unstub(), LogPage\actionText(), ImageGalleryBase\add(), MediaHandler\addMeta(), LoginForm\addNewAccountInternal(), LinkBatch\addObj(), LocalFileMoveBatch\addOlds(), Skin\afterContentHook(), LoginForm\attemptAutoCreate(), LoginForm\authenticateUserData(), DatabaseBase\begin(), SkinTemplate\buildContentActionUrls(), CurlHttpRequest\canFollowRedirects(), EmailNotification\canSendUserTalkEmail(), AjaxResponse\checkLastModified(), OutputPage\checkLastModified(), UploadBase\checkSvgScriptCallback(), UploadBase\checkXMLEncodingMissmatch(), JobQueueDB\claimOldest(), LocalRepo\cleanupDeletedBatch(), UploadBase\cleanupTempFile(), SpecialEditWatchlist\cleanupWatchlist(), MessageBlobStore\clear(), UploadStash\clear(), DatabaseBase\clearFlag(), CloneDatabase\cloneTableStructure(), Revision\compressRevisionText(), UploadFromChunks\concatenateChunks(), Article\confirmDelete(), UploadBase\createFromRequest(), WikiImporter\debug(), BaseDump\debug(), RecompressTracked\debug(), SVGReader\debug(), BagOStuff\debug(), Profiler\debug(), Block\defaultRetroactiveAutoblock(), Article\delete(), Block\deleteIfExpired(), User\deleteNewtalk(), UploadBase\detectScript(), UploadBase\detectVirus(), WikiDiff3\diff(), FileBackendStore\directoryExists(), BitmapMetadataHandler\doApp13(), Block\doAutoblock(), JobQueueDB\doBatchPushInternal(), FileBackendStore\doClean(), WikiPage\doDeleteArticleReal(), WikiPage\doEditContent(), WikiPage\doEditUpdates(), MockImageHandler\doFakeTransform(), MemcLockManager\doFreeLocksOnServer(), MemcLockManager\doGetLocksOnServer(), JobQueueDB\doPop(), FileBackendStore\doPrepare(), FileBackendStore\doPublish(), WikiFilePage\doPurge(), DatabaseMssql\doQuery(), DatabaseOracle\doQuery(), Block\doRetroactiveAutoblock(), UserrightsPage\doSaveUserGroups(), FileBackendStore\doSecure(), BitmapHandler\doTransform(), DjVuHandler\doTransform(), LoadBalancer\doWait(), WikiRevision\downloadSource(), MWCryptRand\driftHash(), DatabaseSqlite\duplicateTableStructure(), ZipDirectoryReader\error(), CLDRPluralRuleEvaluator\evaluateCompiled(), SpecialUserlogout\execute(), ApiUpload\execute(), ChangesFeed\execute(), SpecialUpload\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), LocalFileRestoreBatch\execute(), PoolWorkArticleView\fallback(), Article\fetchContentObject(), DatabaseMssql\fieldExists(), DatabaseMssql\fieldInfo(), WikiDiff3\find_middle_snake(), FormatMetadata\flattenArrayReal(), ContribsPager\formatRow(), FileRepo\freeTemp(), ParserCache\get(), LCStoreCDB\get(), Interwiki\getAllPrefixesCached(), User\getBlockedStatus(), CoreParserFunctions\getCachedRevisionObject(), PoolWorkArticleView\getCachedWork(), RedisConnectionPool\getConnection(), LoadBalancer\getConnection(), ContextSource\getContext(), Action\getContext(), SpecialPage\getContext(), Article\getContext(), SpecialVersion\getCreditsForExtension(), SqlBagOStuff\getDB(), File\getDescriptionText(), FileBackendStore\getDirectoryList(), FSFileBackend\getDirectoryListInternal(), UploadStash\getFile(), FileBackendStore\getFileList(), FSFileBackend\getFileListInternal(), FileBackendStore\getFileStat(), DoubleRedirectJob\getFinalDestination(), IcuCollation\getFirstLetterData(), WikiFilePage\getForeignCategories(), GenderCache\getGenderOf(), MediaHandler\getHandler(), Interwiki\getInterwikiCacheEntry(), ParserCache\getKey(), DatabaseMysqlBase\getLag(), BitmapHandler\getMagickVersion(), LoadBalancer\getMasterPos(), GIFHandler\getMetadata(), JpegHandler\getMetadata(), PNGHandler\getMetadata(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), TiffHandler\getMetadata(), SvgHandler\getMetadata(), DjVuHandler\getMetadata(), DjVuHandler\getMetaTree(), Title\getNsText(), SpecialPageFactory\getPage(), WikiPage\getParserOutput(), SpecialEmailUser\getPermissionsError(), UserCache\getProp(), FSFile\getProps(), File\getPropsFromPath(), LoadBalancer\getReaderIndex(), Title\getRestrictionTypes(), ExternalStoreDB\getSlave(), DatabaseMysqlBase\getSlavePos(), SpecialEmailUser\getTarget(), ForeignAPIRepo\getThumbError(), ForeignAPIRepo\getThumbUrl(), UploadStashFile\getThumbUrl(), ForeignAPIRepo\getThumbUrlFromCache(), Title\getTitleValue(), File\getViewURL(), XCFHandler\getXCFMetaData(), SqlBagOStuff\handleReadError(), SqlBagOStuff\handleWriteError(), MWCryptRand\hashAlgo(), OutputPage\haveCacheVaryCookies(), ForeignAPIRepo\httpGet(), WikiRevision\importLogItem(), WikiRevision\importOldRevision(), WikiRevision\importUpload(), ChronologyProtector\initLB(), Block\insert(), MessageBlobStore\insertMessageBlob(), ExternalStore\insertWithFallback(), User\isBlockedFrom(), FileCacheBase\isCacheGood(), DjVuHandler\isEnabled(), SvgHandler\isEnabled(), FileDependency\isExpired(), LocalisationCache\isExpired(), Block\isExpired(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), Title\isValidMoveTarget(), Block\isWhitelistedFromAutoblocks(), MessageCache\load(), SiteStats\loadAndLazyInit(), ChangesFeed\loadFromCache(), LocalFile\loadFromCache(), HTMLFileCache\loadFromFileCache(), User\loadFromId(), AjaxResponse\loadFromMemcached(), User\loadFromSession(), User\loadOptions(), Revision\loadText(), DatabaseMysqlBase\lock(), Linker\makeExternalImage(), Linker\makeExternalLink(), Linker\makeImageLink(), SqlBagOStuff\markServerDown(), DatabaseMysqlBase\masterPosWait(), User\matchEditToken(), Skin\newFromKey(), ImportStreamSource\newFromURL(), SVGReader\notice(), RawAction\onView(), DatabaseMysqlBase\open(), LoadBalancer\openConnection(), DatabaseSqlite\openFile(), LoadBalancer\openForeignConnection(), UploadDumper\outputItem(), SearchSqlite\parseQuery(), SearchMySQL\parseQuery(), SearchPostgres\parseQuery(), BacklinkCache\partition(), DiffHistoryBlob\patch(), AjaxDispatcher\performAction(), ApiUpload\performStash(), User\pingLimiter(), FileBackendStore\preloadFileStat(), SkinTemplate\prepareQuickTemplate(), SpecialUpload\processUpload(), LocalFile\purgeThumbList(), DatabaseBase\query(), BacklinkCache\queryLinks(), SvgHandler\rasterize(), TextPassDumper\readDump(), TestFileIterator\readNextTest(), MWCryptRand\realGenerate(), LocalisationCache\recache(), LocalFile\recordUpload2(), UploadStash\removeFileNoAuth(), WikiPage\replaceSectionContent(), DatabaseOracle\reportQueryError(), DatabaseBase\reportQueryError(), Http\request(), MediaWiki\restInPeace(), LoadBalancer\reuseConnection(), SavepointPostgres\rollback(), JpegHandler\rotate(), BitmapHandler\rotate(), DoubleRedirectJob\run(), DataUpdate\runUpdates(), RequestContext\sanitizeLangCode(), ParserCache\save(), FileCacheBase\saveText(), HTMLFileCache\saveToFileCache(), MessageCache\saveToLocal(), SearchPostgres\searchQuery(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), OutputPage\sendCacheControl(), UserMailer\sendWithPear(), ApiMain\setCacheMode(), DatabaseBase\setFlag(), LanguageClassesTestCase\setUp(), UploadFromUrlTestSuite\setupUploadDir(), ChronologyProtector\shutdown(), ChronologyProtector\shutdownLB(), RedisConnectionPool\singleton(), LoadBalancer\sleep(), User\spreadBlock(), UploadStash\stashFile(), FileRepo\storeBatch(), DatabaseMssql\tableExists(), GlobalTest\testDebugFunctionTest(), ApiUploadTest\testUploadChunks(), WikiImporter\throwXmlError(), SVGReader\throwXmlError(), MWTidy\tidy(), File\transform(), BitmapHandler\transformCustom(), BitmapHandler\transformGd(), BitmapHandler\transformImageMagick(), BitmapHandler\transformImageMagickExt(), LocalisationCacheBulkLoad\trimCache(), SpecialUploadStash\tryClearStashedUploads(), Article\tryFileCache(), PageArchive\undelete(), PageArchive\undeleteRevisions(), Block\update(), UploadFromChunks\updateChunkStatus(), MessageBlobStore\updateMessage(), MessageBlobStore\updateModule(), User\updateNewtalk(), OldLocalFile\upgradeRow(), LocalFile\upgradeRow(), HTMLFileCache\useFileCache(), LogEventsList\userCanBitfield(), Revision\userCanBitfield(), SvgHandler\validateParam(), ImageHandler\validateThumbParams(), UploadBase\verifyExtension(), UploadBase\verifyFile(), UploadBase\verifyMimeType(), Article\view(), WikiImporter\warn(), SVGReader\warn(), and wfGzipHandler().

◆ wfDebugBacktrace()

wfDebugBacktrace (   $limit = 0)

Safety wrapper for debug_backtrace().

With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat murky circumstances, which may be triggered in part by stub objects or other fancy talking'.

Will return an empty array if Zend Optimizer is detected or if debug_backtrace is disabled, otherwise the output from debug_backtrace() (trimmed).

Parameters
int$limitThis parameter can be used to limit the number of stack frames returned
Returns
array of backtrace information

Definition at line 1852 of file GlobalFunctions.php.

Referenced by MWDebug\getCallerDescription().

◆ wfDebugDieBacktrace()

wfDebugDieBacktrace (   $msg = '')

Throw a debugging exception.

This function previously once exited the process, but now throws an exception instead, with similar results.

Deprecated:
since 1.22; just throw an MWException yourself
Parameters
string$msgmessage shown when dying.
Exceptions
MWException

Definition at line 1774 of file GlobalFunctions.php.

◆ wfDebugLog()

wfDebugLog (   $logGroup,
  $text,
  $dest = 'all' 
)

Send a line to a supplementary debug log file, if configured, or main debug log if not.

To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to a string filename or an associative array mapping 'destination' to the desired filename. The associative array may also contain a 'sample' key with an integer value, specifying a sampling factor.

Since
1.23 support for sampling log messages via $wgDebugLogGroups.
Parameters
string$logGroup
string$text
string | bool$destDestination of the message:
  • 'all': both to the log and HTML (debug toolbar or HTML comments)
  • 'log': only to the log and not in HTML
  • 'private': only to the specifc log if set in $wgDebugLogGroups and discarded otherwise For backward compatibility, it can also take a boolean:
  • true: same as 'all'
  • false: same as 'private'

Definition at line 1040 of file GlobalFunctions.php.

Referenced by RedisConnRef\__call(), LocalisationCache\__construct(), MWMemcached\_debugprint(), MWMemcached\_error_log(), MediaWikiPHPUnitTestListener\addError(), MediaWikiPHPUnitTestListener\addFailure(), MediaWikiPHPUnitTestListener\addIncompleteTest(), MediaWikiPHPUnitTestListener\addSkippedTest(), AutoLoader\autoload(), ExternalStoreDB\batchFetchBlobs(), RCCacheEntryFactory\buildCLink(), MemcachedPeclBagOStuff\checkResult(), UploadBase\checkWarnings(), FileBackendStore\concatenate(), UploadFromChunks\concatenateChunks(), IPTC\convIPTCHelper(), MediaWikiParserTest\debug(), Exif\debug(), Exif\debugFile(), Profiler\debugGroup(), MemcachedBagOStuff\debugLog(), JobQueueRedis\doAck(), XMPReader\doAttribs(), JobQueueRedis\doBatchPush(), FileBackendMultiWrite\doOperationsInternal(), JobQueueRedis\doPop(), BitmapHandler\doTransform(), DjVuHandler\doTransform(), PoolWorkArticleView\doWork(), XMPReader\endElement(), XMPReader\endElementModeLi(), XMPReader\endElementNested(), MediaWikiPHPUnitTestListener\endTest(), MediaWikiPHPUnitTestListener\endTestSuite(), CheckUsernames\execute(), LocalFileMoveBatch\execute(), SpecialRunJobs\executeJobs(), PoolWorkArticleView\fallback(), ExternalStoreDB\fetchBlob(), ResourceLoader\filter(), IPTC\getCharset(), LocalisationCache\getCompiledPluralRules(), RedisConnectionPool\getConnection(), ResourceLoaderWikiModule\getContent(), ContentHandler\getContentText(), ResourceLoaderModule\getDefinitionMtime(), ContentHandler\getForModelID(), RequestContext\getLanguage(), LocalFileMoveBatch\getMoveTriplets(), MessageCache\getMsgFromNamespace(), LoadBalancer\getRandomNonLagged(), LoadBalancer\getReaderIndex(), ResourceLoaderFileModule\getStyles(), SpecialSearch\goResult(), RedisConnectionPool\handleError(), SqlBagOStuff\handleReadError(), FSFileBackend\handleWarning(), SqlBagOStuff\handleWriteError(), SquidUpdate\HTCPPurge(), User\inDnsBlacklist(), ExternalStore\insertWithFallback(), User\isCreatableName(), User\isValidUserName(), MessageCache\loadFromDB(), User\loadFromSession(), Revision\loadText(), SquidPurgeClient\log(), PoolCounterWork\logError(), RedisBagOStuff\logError(), MediaHandler\logErrorForExternalProcess(), MWExceptionHandler\logException(), FileOp\logFailure(), ApiMain\logRequest(), RedisConnRef\luaEval(), MediaWiki\main(), ResourceLoader\makeModuleResponse(), LocalFile\move(), MediaWikiSite\normalizePageName(), SwiftFileBackend\onError(), IPTC\parse(), XMPReader\parse(), XMPReader\parseExtended(), User\pingLimiter(), Preprocessor_Hash\preprocessToObj(), Preprocessor_DOM\preprocessToObj(), SquidUpdate\purge(), ResourceLoaderFileModule\readStyleFile(), RedisConnectionPool\reauthenticateConnection(), MediaHandler\removeBadFile(), LocalFileMoveBatch\removeNonexistentFiles(), MWExceptionHandler\rollbackMasterChangesAndLog(), SquidPurgeClientPool\run(), RunJobs\runJobsLog(), XMPReader\saveValue(), MWDebug\sendMessage(), WebResponse\setcookie(), XMPReader\startElement(), XMPReader\startElementModeInitial(), XMPReader\startElementModeSeq(), XMPReader\startElementModeSimple(), MediaWikiPHPUnitTestListener\startTest(), MediaWikiPHPUnitTestListener\startTestSuite(), IPTC\timeHelper(), MediaWiki\triggerJobs(), XMPValidate\validateBoolean(), XMPValidate\validateClosed(), XMPValidate\validateDate(), XMPValidate\validateFlash(), XMPValidate\validateGPS(), XMPValidate\validateInteger(), XMPValidate\validateLangCode(), XMPValidate\validateRating(), and XMPValidate\validateRational().

◆ wfDebugMem()

wfDebugMem (   $exact = false)

Send a line giving PHP memory usage.

Parameters
bool$exactprint exact values instead of kilobytes (default: false)

Definition at line 1010 of file GlobalFunctions.php.

Referenced by GlobalTest\testDebugFunctionTest().

◆ wfDebugTimer()

wfDebugTimer ( )

Get microsecond timestamps for debug logs.

Returns
string

Definition at line 993 of file GlobalFunctions.php.

◆ wfDeprecated()

wfDeprecated (   $function,
  $version = false,
  $component = false,
  $callerOffset = 2 
)

Throws a warning that $function is deprecated.

Parameters
$functionString
string | bool$versionVersion of MediaWiki that the function was deprecated in (Added in 1.19).
string | bool$componentAdded in 1.19.
$callerOffsetinteger: How far up the call stack is the original caller. 2 = function that called the function that called wfDeprecated (Added in 1.20)
Returns
null
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 1127 of file GlobalFunctions.php.

Referenced by Skin\__call(), DatabaseSqlite\__construct(), FileBackend\__construct(), StubContLang\__construct(), DatabaseOracle\__construct(), RawPage\__construct(), OutputPage\__construct(), ImageGallery\__construct(), DatabaseBase\__construct(), FormatExif\__construct(), DeprecatedGlobal\_newObject(), HTMLForm\addJS(), MWFunction\call(), MWFunction\callArray(), RecentChange\cleanupForIRC(), LoadBalancer\closeConnecton(), Skin\commonPrintStylesheet(), ContentHandler\deprecated(), User\edits(), User\editToken(), Title\escapeCanonicalURL(), Title\escapeFullURL(), Title\escapeLocalURL(), WikiPage\estimateRevisionCount(), IcuCollation\findLowerBound(), ApiPageSet\finishPageSetGeneration(), Title\fixUrlQueryArgs(), ApiQueryUsers\getAutoGroups(), LogEventsList\getDisplayTitle(), Title\getEscapedText(), Linker\getExternalLinkAttributes(), Language\getFallbackLanguageCode(), SpecialPage\getFile(), ApiQuery\getGenerators(), SpecialPageFactory\getGroup(), DatabaseMysqlBase\getLagFromProcesslist(), ContextSource\getLang(), Action\getLang(), DerivativeContext\getLang(), RequestContext\getLang(), SpecialPage\getLang(), LBFactory\getLBFactoryClass(), MWException\getLogId(), MWException\getLogMessage(), ApiQuery\getModules(), File\getPropsFromPath(), ApiMain\getShowVersions(), User\getSkin(), OutputPage\getStatusMessage(), Skin\getUsableSkins(), ArchivedFile\getUserText(), MediaWikiTestCase\hideDeprecated(), Article\info(), WikiPage\isBigDeletion(), MWNamespace\isMain(), OutputPage\isUserJsAllowed(), User\isValidEmailAddr(), ApiParse\languagesHtml(), Linker\link(), Article\loadContent(), RecentChange\loadFromCurRow(), Preferences\loadOldSearchNs(), LogPage\logHeader(), LogPage\logName(), Skin\makeGlobalVariablesScript(), UserrightsPage\makeGroupNameListForLog(), Linker\makeKnownLinkObj(), Linker\makeLinkObj(), Xml\namespaceSelector(), RecentChange\newFromCurRow(), RecentChange\notifyRC2UDP(), OutputPage\out(), WikiPage\preSaveTransform(), BagOStuff\replace(), Article\revert(), Article\rollback(), Hooks\run(), XmlDumpWriter\schemaVersion(), RecentChange\sendToUDP(), OutputPage\setAllowedModules(), SpecialPageFactory\setGroup(), DerivativeContext\setLang(), RequestContext\setLang(), ParserOptions\setSkin(), File\sha1Base36(), LogEventsList\showHeader(), Preferences\trySetUserEmail(), Title\updateTitleProtection(), ChangesList\usePatrol(), Title\userCanRead(), ImageGalleryBase\useSkin(), wfExtractThumbParams(), and OutputPage\wrapWikiMsg().

◆ wfDiff()

wfDiff (   $before,
  $after,
  $params = '-u' 
)

Returns unified plain-text diff of two texts.

Useful for machine processing of diffs.

Parameters
string$beforethe text before the changes.
string$afterthe text after the changes.
string$paramscommand-line options for the diff command.
Returns
string Unified diff of $before and $after

Definition at line 3173 of file GlobalFunctions.php.

Referenced by Parser_DiffTest\__call(), and CompareParsers\processRevision().

◆ wfEmptyMsg()

wfEmptyMsg (   $key)

Since wfMsg() and co suck, they don't return false if the message key they looked up didn't exist but instead the key wrapped in <>'s, this function checks for the nonexistence of messages by checking the MessageCache::get() result directly.

Deprecated:
since 1.18. Use Message::isDisabled().
Parameters
string$keyThe message key looked up
Returns
bool True if the message doesn't exist.

Definition at line 1760 of file GlobalFunctions.php.

◆ wfErrorLog()

wfErrorLog (   $text,
  $file 
)

Log to a file without getting "file size exceeded" signals.

Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will send lines to the specified port, prefixed by the specified prefix and a space.

Parameters
$textString
string$filefilename
Exceptions
MWException

Definition at line 1168 of file GlobalFunctions.php.

Referenced by RecompressTracked\logToFile(), and UDPRCFeedEngine\send().

◆ wfEscapeShellArg()

◆ wfEscapeWikiText()

wfEscapeWikiText (   $text)

Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.

making its way through. This is achieved by substituting certain characters with HTML entities. As required by the callers, "<nowiki>" is not used.

Parameters
string$texttext to be escaped
Returns
String

Definition at line 2077 of file GlobalFunctions.php.

Referenced by MediaHandler\addMeta(), CoreParserFunctions\basepagename(), CoreParserFunctions\basepagenamee(), SpecialContributions\contributionsSub(), CoreParserFunctions\defaultsort(), Article\delete(), LoginForm\displaySuccessfulAction(), FileDeleteForm\doDelete(), Article\doDelete(), WikiPage\doDeleteArticleReal(), SpecialUnblock\execute(), SpecialRandomInCategory\execute(), SpecialMergeHistory\execute(), FileDuplicateSearchPage\execute(), SpecialSearch\formHeader(), CoreParserFunctions\fullpagename(), CoreParserFunctions\fullpagenamee(), CategoryViewer\getImageSection(), CategoryViewer\getPagesSection(), SpecialBlock\maybeAlterFormDefaults(), SpecialPasswordReset\onSubmit(), SpecialBlock\onSuccess(), ImagePage\openShowImage(), CoreParserFunctions\pagename(), CoreParserFunctions\pagenamee(), SpecialBlock\postText(), FileDeleteForm\prepareMessage(), LoginForm\processLogin(), MediaWikiPageLinkRenderer\renderWikitextLink(), CoreParserFunctions\rootpagename(), CoreParserFunctions\rootpagenamee(), ProtectionForm\show(), SpecialSearch\showCreateLink(), UserrightsPage\showEditUserGroupsForm(), SpecialUndelete\showHistory(), Article\showMissingArticle(), SpecialSearch\showResults(), CoreParserFunctions\subjectpagename(), CoreParserFunctions\subjectpagenamee(), CoreParserFunctions\subpagename(), CoreParserFunctions\subpagenamee(), CoreParserFunctions\talkpagename(), CoreParserFunctions\talkpagenamee(), and SpecialBlock\validateTarget().

◆ wfExpandIRI()

wfExpandIRI (   $url)

Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode characters with their UTF-8 original forms for more compact display and legibility for local audiences.

Todo:
handle punycode domains too
Parameters
$urlstring
Returns
string

Definition at line 825 of file GlobalFunctions.php.

Referenced by Skin\printSource(), and GlobalTest\testExpandIRI().

◆ wfExpandIRI_callback()

wfExpandIRI_callback (   $matches)

Private callback for wfExpandIRI.

Parameters
array$matches
Returns
string

Definition at line 838 of file GlobalFunctions.php.

◆ wfExpandUrl()

wfExpandUrl (   $url,
  $defaultProto = PROTO_CURRENT 
)

Expand a potentially local URL to a fully-qualified URL.

Assumes $wgServer is correct.

The meaning of the PROTO_* constants is as follows: PROTO_HTTP: Output a URL starting with http:// PROTO_HTTPS: Output a URL starting with https:// PROTO_RELATIVE: Output a URL starting with // (protocol-relative URL) PROTO_CURRENT: Output a URL starting with either http:// or https:// , depending on which protocol was used for the current incoming request PROTO_CANONICAL: For URLs without a domain, like /w/index.php , use $wgCanonicalServer. For protocol-relative URLs, use the protocol of $wgCanonicalServer PROTO_INTERNAL: Like PROTO_CANONICAL, but uses $wgInternalServer instead of $wgCanonicalServer

Todo:
this won't work with current-path-relative URLs like "subdir/foo.html", etc.
Parameters
string$urleither fully-qualified or a local path + query
$defaultProtoMixed: one of the PROTO_* constants. Determines the protocol to use if $url or $wgServer is protocol-relative
Returns
string Fully-qualified URL, current-path-relative URL or false if no valid URL can be constructed

Definition at line 497 of file GlobalFunctions.php.

Referenced by ResourceLoaderFileModule\__construct(), MWHttpRequest\__construct(), EmailNotification\composeCommonMailtext(), ApiQueryExternalLinks\execute(), ApiQueryLangLinks\execute(), ApiQueryIWLinks\execute(), SquidUpdate\expand(), ApiQueryInfo\extractPageInfo(), CoreParserFunctions\filepath(), ApiParse\formatIWLinks(), ApiParse\formatLangLinks(), File\getCanonicalUrl(), Title\getCanonicalURL(), SpecialVersion\getEntryPointInfo(), RevertFileAction\getFormFields(), WebRequest\getFullRequestURL(), File\getFullUrl(), Title\getFullURL(), OutputPage\getHeadLinksArray(), ApiQueryImageInfo\getInfo(), LocalRepo\getInfo(), Title\getInternalURL(), ApiRsd\getRsdApiList(), ForeignAPIRepo\httpGet(), ResourceLoader\makeLoaderURL(), RevertFileAction\onSuccess(), outHeader(), outItem(), OutputPage\output(), SpecialUploadStash\outputRemoteScaledThumb(), MediaWiki\performRequest(), FileDeleteForm\prepareMessage(), CSSMin\remapOne(), ApiQueryExtLinksUsage\run(), WfExpandUrlTest\testWfExpandUrl(), File\transform(), and wfStreamThumb().

◆ wfFindFile()

wfFindFile (   $title,
  $options = array() 
)

Find a file.

Shortcut for RepoGroup::singleton()->findFile()

Parameters
string$titleor Title object
array$optionsAssociative array of options: time: requested time for an archived image, or false for the current version. An image object will be returned which was created at the specified time.

ignoreRedirect: If true, do not follow file redirects

private: If true, return restricted (deleted) files if the current user is allowed to view them. Otherwise, such files will not be found.

bypassCache: If true, do not use the process-local cache of File objects

Returns
File, or false if the file does not exist

Definition at line 3702 of file GlobalFunctions.php.

Referenced by UploadFromUrlTest\deleteFile(), ApiTestCaseUpload\deleteFileByTitle(), SpecialRedirect\dispatchFile(), MovePageForm\doSubmit(), ApiMove\execute(), DeleteBatch\execute(), ApiImageRotate\execute(), FileDuplicateSearchPage\execute(), CoreParserFunctions\filepath(), SearchEngine\getNearMatchInternal(), SearchResult\initFromTitle(), Title\isAlwaysKnown(), WikiFilePage\loadFile(), ImagePage\loadFile(), Linker\makeBrokenImageLinkObj(), Linker\makeMediaLinkObj(), Linker\makeThumbLink2(), ApiQuery\outputGeneralPageInfo(), UploadDumper\outputItem(), SpecialSearch\showHit(), TraditionalImageGallery\toHTML(), and Title\validateFileMoveOperation().

◆ wfFixSessionID()

wfFixSessionID ( )

Override session_id before session startup if php's built-in session generation code is not secure.

Definition at line 3485 of file GlobalFunctions.php.

◆ wfForeignMemcKey()

wfForeignMemcKey (   $db,
  $prefix 
)

Get a cache key for a foreign DB.

Parameters
string$db
string$prefix
string[$args,...]
Returns
string

Definition at line 3597 of file GlobalFunctions.php.

Referenced by JobQueueGroup\executeReadyPeriodicTasks(), JobQueueGroup\getCachedConfigVar(), JobQueueFederated\getCacheKey(), JobQueueDB\getCacheKey(), JobQueueRedis\getQueueKey(), JobQueue\getRootJobCacheKey(), and UserRightsProxy\invalidateCache().

◆ wfFormatStackFrame()

wfFormatStackFrame (   $frame)

Return a string representation of frame.

Parameters
$frameArray
Returns
string

Definition at line 1973 of file GlobalFunctions.php.

◆ wfGetAllCallers()

wfGetAllCallers (   $limit = 3)

Return a string consisting of callers in the stack.

Useful sometimes for profiling specific points.

Parameters
int$limitThe maximum depth of the stack frame to return, or false for the entire stack.
Returns
String

Definition at line 1958 of file GlobalFunctions.php.

Referenced by MWCryptRand\realGenerate().

◆ wfGetCache()

◆ wfGetCaller()

wfGetCaller (   $level = 2)

Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie.

FUNCTION) wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller() wfGetCaller( 3 ) is the parent of that.

Parameters
$levelInt
Returns
string
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 1941 of file GlobalFunctions.php.

Referenced by StubObject\_unstub(), MediaWikiTestCase\assertSelect(), WfGetCallerTest\callerOne(), MediaWikiParserTest\debug(), WfGetCallerTest\intermediateFunction(), MWDebug\log(), DatabaseBase\onTransactionIdle(), DatabaseBase\onTransactionPreCommitOrIdle(), and WfGetCallerTest\testZero().

◆ wfGetDB()

& wfGetDB (   $db,
  $groups = array(),
  $wiki = false 
)

Get a Database object.

Parameters
int$dbIndex of the connection to get. May be DB_MASTER for the master (for write queries), DB_SLAVE for potentially lagged read queries, or an integer >= 0 for a particular server.
string | string[]$groupsQuery groups. An array of group names that this query belongs to. May contain a single string if the query is only in one group.
string | bool$wikiThe wiki ID, or false for the current wiki

Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request will always return the same object, unless the underlying connection or load balancer is manually destroyed.

Note 2: use $this->getDB() in maintenance scripts that may be invoked by updater to ensure that a proper database is being updated.

Returns
DatabaseBase
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 3659 of file GlobalFunctions.php.

Referenced by SearchDatabase\__construct(), DeletedContribsPager\__construct(), SqlDataUpdate\__construct(), LogPager\__construct(), Block\__construct(), ImageListPager\__construct(), IndexPager\__construct(), SiteStatsInit\__construct(), MergeHistoryPager\__construct(), OutputPage\addCategoryLinks(), User\addGroup(), LinkCache\addLinkObj(), ApiQueryLogEvents\addLogParams(), LogPage\addRelations(), ChangeTags\addTags(), User\addToDatabase(), WatchedItem\addWatch(), MediaWikiTestCase\assertSelect(), ImageListPager\buildQueryConds(), ImageBuilder\buildTable(), SiteStatsUpdate\cacheUpdate(), UserOptions\CHANGER(), CheckStorage\check(), TrackBlobs\checkIntegrity(), User\checkNewtalk(), Orphans\checkOrphans(), RevisionDeleter\checkRevisionExistence(), Orphans\checkSeparation(), RecompressTracked\checkTrackingTable(), Orphans\checkWidows(), CleanupSpam\cleanupArticle(), SpecialEditWatchlist\cleanupWatchlist(), MessageBlobStore\clear(), User\clearAllNotifications(), SpecialEditWatchlist\clearWatchlist(), ViewCountUpdate\collect(), CgzCopyTransaction\commit(), WikiPage\commitRollback(), CompressOld\compressOldPages(), CompressOld\compressPage(), CompressOld\compressWithConcat(), TestORMRowTest\constructorTestProvider(), Title\countRevisionsBetween(), SearchEngine\create(), User\createNew(), ConvertLinks\createTempTable(), Block\defaultRetroactiveAutoblock(), PrefixSearch\defaultSearchBackend(), SearchMySQL\delete(), Block\delete(), DifferenceEngine\deletedLink(), RefreshLinks\deleteLinksFromNonexistent(), User\deleteNewtalk(), NukePage\deleteRevisions(), Title\deleteTitleProtection(), FixSlaveDesync\desyncFixPage(), SpecialUndelete\diffHeader(), SiteStatsInit\doAllAndCommit(), RecompressTracked\doAllOrphans(), RecompressTracked\doAllPages(), WikiPage\doCascadeProtectionUpdates(), CategoryViewer\doCategoryQuery(), PopulateFilearchiveSha1\doDBUpdates(), FixExtLinksProtocolRelative\doDBUpdates(), PopulateParentId\doDBUpdates(), PopulateImageSha1\doDBUpdates(), DeleteArchivedFilesImplementation\doDelete(), DeleteArchivedRevisionsImplementation\doDelete(), DeleteOldRevisions\doDelete(), FileDeleteForm\doDelete(), WikiPage\doDeleteArticleReal(), WatchedItem\doDuplicateEntries(), WikiPage\doEditContent(), SpecialExport\doExport(), SpecialRecentChangesLinked\doMainQuery(), RecompressTracked\doOrphanList(), RecompressTracked\doPage(), PopulateCategory\doPopulateCategory(), WikiPage\doPurge(), UserCache\doQuery(), GenderCache\doQuery(), LinkBatch\doQuery(), WikiPage\doQuickEditContent(), ReassignEdits\doReassignEdits(), RefreshLinks\doRefreshLinks(), MovePageForm\doSubmit(), HTMLCacheUpdate\doUpdate(), ViewCountUpdate\doUpdate(), SiteStatsUpdate\doUpdate(), WikiPage\doUpdateRestrictions(), DeferredUpdates\doUpdates(), UpdateSearchIndex\doUpdateSearchIndex(), LinkHolderArray\doVariants(), Title\estimateRevisionCount(), TidyUpBug37714\execute(), StorageTypeStats\execute(), CleanupPreferences\execute(), ApiSetNotificationTimestamp\execute(), CheckBadRedirects\execute(), GetSlaveServer\execute(), BenchmarkDeleteTruncate\execute(), CheckImages\execute(), ClearInterwikiCache\execute(), FixUserRegistration\execute(), SpecialStatistics\execute(), DumpRev\execute(), DeleteRevision\execute(), DeleteSelfExternals\execute(), UpdateLogging\execute(), CleanupAncientTables\execute(), DeleteDefaultMessages\execute(), MigrateUserGroup\execute(), BatchedQueryRunner\execute(), CleanupSpam\execute(), ConvertUserOptions\execute(), DeleteOrphanedRevisions\execute(), DumpSisterSites\execute(), GetTextMaint\execute(), InitEditCount\execute(), NukePage\execute(), RemoveUnusedAccounts\execute(), CheckUsernames\execute(), CleanupRemovedModules\execute(), DeleteImageCache\execute(), AlterSharedConstraints\execute(), SpecialPagesWithProp\execute(), RebuildAll\execute(), UpdateArticleCount\execute(), UpdateRestrictions\execute(), UpdateSpecialPages\execute(), InitSiteStats\execute(), PatchSql\execute(), ResetUserTokens\execute(), OrphanStats\execute(), FixDoubleRedirects\execute(), EraseArchivedFile\execute(), RefreshFileHeaders\execute(), RenameDbPrefix\execute(), ShowSiteStats\execute(), FixBug20757\execute(), AttachLatest\execute(), FixTimestamps\execute(), DumpLinks\execute(), UpdateDoubleWidthSearch\execute(), DeleteArchivedRevisions\execute(), FetchText\execute(), DeleteBatch\execute(), RebuildFileCache\execute(), NamespaceConflictChecker\execute(), RebuildTextIndex\execute(), SqliteMaintenance\execute(), ConvertLinks\execute(), NukeNS\execute(), MoveBatch\execute(), ImageBuilder\execute(), RefreshImageMetadata\execute(), UpdateMediaWiki\execute(), DeleteEqualMessages\execute(), QueryPage\execute(), QueryPage\fetchFromCache(), UploadDumper\fetchLocal(), Revision\fetchRevision(), HistoryAction\fetchRevisions(), UploadDumper\fetchUsed(), TitleCleanup\fileExists(), TrackBlobs\findOrphanBlobs(), FixSlaveDesync\findPageLatestCorruption(), RecompressTracked\finishIncompleteMoves(), RefreshLinks\fixLinksFromArticle(), RefreshLinks\fixRedirect(), DoubleRedirectJob\fixRedirects(), EditPageTest\forceRevisionDate(), ApiEditPageTest\forceRevisionDate(), WikiPage\formatExpiry(), Language\formatExpiry(), DoubleRedirectsPage\formatResult(), SpecialProtectedtitles\formatRow(), LCStoreDB\get(), Interwiki\getAllPrefixesDB(), Title\getAuthorsBetween(), ContentHandler\getAutoDeleteReason(), Block\getBlocksForIPList(), Title\getBrokenLinksFrom(), QueryPage\getCachedTimestamp(), Title\getCascadeProtectionSources(), WikiPage\getCategories(), WikiPage\getContributors(), RevDel_RevisionList\getCurrent(), AllmessagesTablePager\getCustomisedStatuses(), Block\getDatabaseArray(), ResourceLoaderWikiModule\getDB(), SqlBagOStuff\getDB(), UserRightsProxy\getDB(), BacklinkCache\getDB(), SpecialWatchlist\getDB(), ChangesListSpecialPage\getDB(), Maintenance\getDB(), User\getEditCount(), ProtectionForm\getExpiry(), ResourceLoaderModule\getFileDependencies(), DoubleRedirectJob\getFinalDestination(), User\getFirstEditTimestamp(), Title\getFirstRevision(), User\getFormerGroups(), MessageBlobStore\getFromDB(), WikiPage\getHiddenCategories(), DeleteImageCache\getImageCount(), WikiPage\getLastNAuthors(), PageArchive\getLastRevisionText(), SpecialExport\getLinks(), Title\getLinksFrom(), Title\getLinksTo(), ForeignDBViaLBRepo\getMasterDB(), LocalRepo\getMasterDB(), Category\getMembers(), SpecialRandomInCategory\getMinAndMaxForCat(), SpecialStatistics\getMostViewedPages(), ResourceLoaderModule\getMsgBlobMtime(), ApiQuery\getNamedDB(), User\getNewMessageLinks(), Title\getNextRevisionID(), Title\getNotificationTimestamp(), WikiPage\getOldestRevision(), SpecialExport\getPagesFromCategory(), SpecialExport\getPagesFromNamespace(), Title\getParentCategories(), PageArchive\getPreviousRevision(), Title\getPreviousRevisionID(), BrokenRedirectsPage\getQueryInfo(), NewFilesPager\getQueryInfo(), WithoutInterwikiPage\getQueryInfo(), UsersPager\getQueryInfo(), SpecialRandomInCategory\getQueryInfo(), LinkSearchPage\getQueryInfo(), ImageListPager\getQueryInfoReal(), Block\getRangeCond(), QueryPage\getRecacheDB(), Revision\getRecentChange(), Title\getRedirectsHere(), WikiPage\getRedirectTarget(), BenchmarkParse\getRevIdForTime(), PageArchive\getRevision(), FixBug20757\getRevTextMap(), Linker\getRollbackEditCount(), RollbackEdits\getRollbackTitles(), ForeignDBViaLBRepo\getSlaveDB(), LocalRepo\getSlaveDB(), ResourceLoaderFileModule\getStyles(), Title\getSubpages(), HistoryBlobStub\getText(), HistoryBlobCurStub\getText(), TrackBlobs\getTextClause(), PageArchive\getTextFromRow(), Revision\getTimestampFromId(), Revision\getTitle(), Title\getTitleProtection(), Title\getTouched(), MessageBlobStore\getUpdatesForMessage(), SpecialEditWatchlist\getWatchlist(), SpecialEditWatchlist\getWatchlistInfo(), BackupReader\handleUpload(), User\idForName(), User\idFromName(), WikiImporter\importLogItem(), WikiRevision\importLogItem(), WikiRevision\importOldRevision(), WikiImporter\importRevision(), CheckStorage\importRevision(), WikiImporter\importUpload(), User\incEditCount(), User\initEditCount(), Block\initFromRow(), Category\initialize(), BackupDumper\initProgress(), TrackBlobs\initTrackingTable(), Block\insert(), ManualLogEntry\insert(), MessageBlobStore\insertMessageBlob(), WikiPage\insertProtectNullRevision(), WikiPage\insertRedirectEntry(), User\invalidateCache(), Title\invalidateCache(), HTMLCacheUpdateJob\invalidateTitles(), WikiPage\isCountable(), PageArchive\isDeleted(), Title\isDeleted(), Title\isDeletedQuick(), RemoveUnusedAccounts\isInactiveAccount(), Title\isNewPage(), Title\isSingleRevRedirect(), SiteStats\jobs(), ImageCleanup\killRow(), PageArchive\listAllPages(), ChangeTags\listDefinedTags(), PageArchive\listFiles(), PageArchive\listPagesByPrefix(), PageArchive\listRevisions(), SiteStats\load(), WatchedItem\load(), ArchivedFile\load(), Interwiki\load(), SiteStats\loadAndLazyInit(), User\loadFromDatabase(), MessageCache\loadFromDB(), User\loadGroups(), User\loadOptions(), WikiPage\loadPageData(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), DifferenceEngine\loadRevisionData(), SiteSQLStore\loadSites(), Revision\loadText(), Profiler\logData(), LinkFilter\makeLikeArray(), DifferenceEngine\markPatrolledLink(), SpecialMergeHistory\merge(), SpecialActiveUsers\mergeActiveUsers(), SearchMySQL\minSearchLength(), ChangeTags\modifyDisplayQuery(), TitleCleanup\moveIllegalPage(), TitleCleanup\moveInconsistentPage(), RecompressTracked\moveTextRow(), Title\moveTo(), moveToExternal(), Title\moveToInternal(), LinkSearchPage\mungeQuery(), Title\nameOf(), RecentChange\newFromConds(), Revision\newFromConds(), User\newFromConfirmationCode(), Block\newFromID(), WikiPage\newFromID(), Title\newFromID(), UserArray\newFromIDs(), Title\newFromIDs(), SquidUpdate\newFromLinksTo(), Revision\newFromTitle(), Block\newLoad(), EmailNotification\notifyOnPageChange(), SiteStats\numberingroup(), SpecialPasswordReset\onSubmit(), InfoAction\pageCounts(), InfoAction\pageInfo(), SiteStats\pagesInNs(), SpecialBlock\parseExpiryInput(), ImageCleanup\pokeFile(), ResourceLoader\preloadModuleInfo(), SkinTemplate\prepareQuickTemplate(), Block\purgeExpired(), RecentChange\purgeExpiredChanges(), Title\purgeExpiredRestrictions(), PurgeList\purgeNamespace(), PurgeRedundantText(), ImagePage\queryImageLinks(), DoubleRedirectsPage\reallyGetQueryInfo(), RecentChange\reallyMarkPatrolled(), RebuildRecentchanges\rebuildRecentChangesTablePass1(), RebuildRecentchanges\rebuildRecentChangesTablePass2(), RebuildRecentchanges\rebuildRecentChangesTablePass3(), RebuildRecentchanges\rebuildRecentChangesTablePass4(), QueryPage\recache(), SiteStatsInit\refresh(), Category\refreshCounts(), RevDel_List\reloadFromMaster(), User\removeGroup(), WatchlistCleanup\removeWatch(), WatchedItem\removeWatch(), LinkHolderArray\replaceInternal(), WikiPage\replaceSectionContent(), ImportReporter\reportPage(), RevisionListBase\reset(), MediaWikiTestCase\resetDB(), WatchedItem\resetNotificationTimestamp(), resolveStub(), resolveStubs(), CheckStorage\restoreText(), MediaWikiTestCase\run(), TableCleanup\runTable(), RecentChange\save(), LogPage\saveContent(), User\saveOptions(), User\saveSettings(), EraseArchivedFile\scrubAllVersions(), RandomPage\selectRandomPageFromDB(), SpecialRandomInCategory\selectRandomPageFromDB(), RevDel_RevisionItem\setBits(), RevDel_ArchiveItem\setBits(), RevDel_ArchivedRevisionItem\setBits(), RevDel_FileItem\setBits(), RevDel_ArchivedFileItem\setBits(), RevDel_LogItem\setBits(), WikiPageTest_ContentHandlerUseDB\setUp(), RevisionTest_ContentHandlerUseDB\setUp(), DatabaseTest\setUp(), LinksUpdateTest\setUp(), TestORMRowTest\setUp(), RevisionDeleteUser\setUsernameBitfields(), RevDel_List\setVisibility(), SpecialAllpages\showChunk(), MovePageForm\showForm(), SpecialWhatLinksHere\showIndirectLinks(), SpecialBlockList\showList(), LogEventsList\showLogExtract(), Article\showPatrolFooter(), SpecialPrefixindex\showPrefixChunk(), SpecialAllpages\showToplevel(), SpecialVersion\softwareInformation(), LCStoreDB\startWrite(), RevDel_LogList\suggestTarget(), RecompressTracked\syncDBs(), ChangeTags\tagUsageStatistics(), TestORMRowTest\tearDown(), TitlePermissionTest\testActionPermissions(), WikiPageTest\testDoDeleteArticle(), WikiPageTest\testDoDeleteUpdates(), WikiPageTest\testDoEdit(), WikiPageTest\testDoEditContent(), RevisionStorageTest\testNewNullRevision(), DatabaseTest\testStoredFunctions(), RevisionStorageTest\testUserWasLastToEdit(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), SiteStatsUpdate\tryDBUpdateInternal(), ResourceLoader\tryRespondFromFileCache(), PageArchive\undeleteRevisions(), SpecialEditWatchlist\unwatchTitles(), SearchOracle\update(), SearchSqlite\update(), SearchMySQL\update(), Block\update(), WikiPage\updateCategoryCounts(), MessageBlobStore\updateMessage(), MessageBlobStore\updateModule(), User\updateNewtalk(), Block\updateTimestamp(), SearchOracle\updateTitle(), SearchSqlite\updateTitle(), SearchMySQL\updateTitle(), UserOptions\USAGER(), Revision\userWasLastToEdit(), and SpecialEditWatchlist\watchTitles().

◆ wfGetIP()

wfGetIP ( )

Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of the chain)

Deprecated:
in 1.19; call $wgRequest->getIP() directly.
Returns
string

Definition at line 4151 of file GlobalFunctions.php.

◆ wfGetLangConverterCacheStorage()

wfGetLangConverterCacheStorage ( )

Get the cache object used by the language converter.

Returns
BagOStuff

Definition at line 3996 of file GlobalFunctions.php.

◆ wfGetLangObj()

wfGetLangObj (   $langcode = false)

Return a Language object from $langcode.

Parameters
$langcodeMixed: either:
  • a Language object
  • code of the language to get the message for, if it is a valid code create a language for that language, if it is a string but not a valid code then make a basic language object
  • a boolean: if it's false then use the global object for the current user's language (as a fallback for the old parameter functionality), or if it is true then use global object for the wiki's content language.
Returns
Language object

Definition at line 1352 of file GlobalFunctions.php.

Referenced by Skin\doEditSectionLink(), SpecialAllmessages\execute(), MessageCache\get(), DateFormatter\getInstance(), JavaScriptContentHandler\getPageLanguage(), CssContentHandler\getPageLanguage(), ContentHandler\getPageLanguage(), Title\getPageLanguage(), CssContentHandler\getPageViewLanguage(), JavaScriptContentHandler\getPageViewLanguage(), DifferenceEngine\setTextLanguage(), ContentHandlerTest\testGetPageLanguage(), and Linker\tocList().

◆ wfGetLB()

◆ wfGetLBFactory()

◆ wfGetMainCache()

◆ wfGetMessageCacheStorage()

wfGetMessageCacheStorage ( )

Get the cache object used by the message cache.

Returns
BagOStuff

Definition at line 3976 of file GlobalFunctions.php.

Referenced by UploadFromUrlTestSuite\setUp(), and MessageCache\singleton().

◆ wfGetNull()

wfGetNull ( )

Get a platform-independent path to the null file, e.g.

/dev/null

Returns
string

Definition at line 3789 of file GlobalFunctions.php.

Referenced by MWTidy\execExternalTidy(), and Dump7ZipOutput\setup7zCommand().

◆ wfGetParserCacheStorage()

wfGetParserCacheStorage ( )

Get the cache object used by the parser cache.

Returns
BagOStuff

Definition at line 3986 of file GlobalFunctions.php.

Referenced by PurgeParserCache\execute(), and UploadFromUrlTestSuite\setUp().

◆ wfGetPrecompiledData()

wfGetPrecompiledData (   $name)

Get an object from the precompiled serialized directory.

Parameters
string$name
Returns
mixed The variable on success, false on failure

Definition at line 3561 of file GlobalFunctions.php.

Referenced by Language\getCaseMaps(), IcuCollation\getFirstLetterData(), and Language\transformUsingPairFile().

◆ wfGetScriptUrl()

wfGetScriptUrl ( )

Get the script URL.

Returns
string script URL

Definition at line 3755 of file GlobalFunctions.php.

◆ wfHostname()

wfHostname ( )

Fetch server name for use in error reporting etc.

Use real server name if available, so we know which machine in a server farm generated the current page.

Returns
string

Definition at line 1786 of file GlobalFunctions.php.

Referenced by DifferenceEngine\debug(), BitmapHandler\doTransform(), DjVuHandler\doTransform(), MWCryptRand\initialRandomState(), Profiler\logData(), MediaHandler\logErrorForExternalProcess(), RecompressTracked\logToFile(), DatabaseMysqlBase\open(), LoadBalancer\openForeignConnection(), and wfThumbError().

◆ wfHttpError()

wfHttpError (   $code,
  $label,
  $desc 
)

Provide a simple HTTP error.

Parameters
$codeInt|String
$labelString
$descString

Definition at line 2191 of file GlobalFunctions.php.

Referenced by RawAction\getRawText(), AjaxDispatcher\performAction(), and MWException\report().

◆ wfIncrStats()

wfIncrStats (   $key,
  $count = 1 
)

◆ wfIniGetBool()

wfIniGetBool (   $setting)

Safety wrapper around ini_get() for boolean settings.

The values returned from ini_get() are pre-normalized for settings set via php.ini or php_flag/php_admin_flag... but not for those set via php_value/php_admin_value.

It's fairly common for people to use php_value instead of php_flag, which can leave you with an 'off' setting giving a false positive for code that just takes the ini_get() return value as a boolean.

To make things extra interesting, setting via php_value accepts "true" and "yes" as true, but php.ini and php_flag consider them false. :) Unrecognized values go false... again opposite PHP's own coercion from string to bool.

Luckily, 'properly' set settings will always come back as '0' or '1', so we only have to worry about them and the 'improper' settings.

I frickin' hate PHP... :P

Parameters
string$setting
Returns
bool

Definition at line 2685 of file GlobalFunctions.php.

Referenced by CurlHttpRequest\canFollowRedirects(), MWHttpRequest\canMakeRequests(), Installer\envCheckCache(), Installer\envCheckMagicQuotes(), Installer\envCheckMagicSybase(), Installer\envCheckMbstring(), Installer\envCheckRegisterGlobals(), Installer\envCheckSafeMode(), MWHttpRequestTester\factory(), MWHttpRequest\factory(), UploadBase\isEnabled(), ObjectCache\newAccelerator(), UserMailer\send(), and WebInstaller\startSession().

◆ wfInitShellLocale()

wfInitShellLocale ( )

Workaround for http://bugs.php.net/bug.php?id=45132 escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale.

Definition at line 3037 of file GlobalFunctions.php.

◆ wfIsBadImage()

wfIsBadImage (   $name,
  $contextTitle = false,
  $blacklist = null 
)

Determine if an image exists on the 'bad image list'.

The format of MediaWiki:Bad_image_list is as follows:

  • Only list items (lines starting with "*") are considered
  • The first link on a line must be a link to a bad image
  • Any subsequent links on the same line are considered to be exceptions, i.e. articles where the image may occur inline.
Parameters
string$namethe image name to check
Title | bool$contextTitleThe page on which the image occurs, if known
string$blacklistwikitext of a file blacklist
Returns
bool

Definition at line 4064 of file GlobalFunctions.php.

Referenced by GlobalWithDBTest\testWfIsBadImage(), and TraditionalImageGallery\toHTML().

◆ wfIsConfiguredProxy()

wfIsConfiguredProxy (   $ip)

Checks if an IP matches a proxy we've configured.

Parameters
string$ip
Returns
bool
Since
1.23 Supports CIDR ranges in $wgSquidServersNoPurge

Definition at line 4178 of file GlobalFunctions.php.

◆ wfIsDebugRawPage()

wfIsDebugRawPage ( )

Returns true if debug logging should be suppressed if $wgDebugRawPage = false.

Returns
bool

Definition at line 969 of file GlobalFunctions.php.

◆ wfIsHHVM()

wfIsHHVM ( )

Check if we are running under HHVM.

Returns
bool

Definition at line 2537 of file GlobalFunctions.php.

Referenced by MWDebug\getDebugInfo(), UploadForm\getSourceSection(), UploadBase\isEnabled(), and MWInit\isHipHop().

◆ wfIsTrustedProxy()

wfIsTrustedProxy (   $ip)

Checks if an IP is a trusted proxy provider.

Useful to tell if X-Forwarded-For data is possibly bogus. Squid cache servers for the site are whitelisted.

Parameters
string$ip
Returns
bool

Definition at line 4165 of file GlobalFunctions.php.

Referenced by Block\getBlocksForIPList().

◆ wfIsWindows()

◆ wfLocalFile()

◆ wfLogDBError()

wfLogDBError (   $text)

Log for database errors.

Parameters
string$textdatabase error message.

Definition at line 1087 of file GlobalFunctions.php.

Referenced by DatabaseBase\begin(), DatabaseMysqlBase\open(), DatabaseBase\query(), LoadBalancer\reportConnectionError(), and DatabaseBase\reportQueryError().

◆ wfLogProfilingData()

wfLogProfilingData ( )
Todo:
document

Definition at line 1226 of file GlobalFunctions.php.

Referenced by MWExceptionHandler\handle(), and MediaWiki\restInPeace().

◆ wfLogWarning()

wfLogWarning (   $msg,
  $callerOffset = 1,
  $level = E_USER_WARNING 
)

Send a warning as a PHP error and the debug log.

This is intended for logging warnings in production. For logging development warnings, use WfWarn instead.

Parameters
$msgString: message to send
$callerOffsetInteger: number of items to go back in the backtrace to find the correct caller (1 = function calling wfLogWarning, ...)
$levelInteger: PHP error level; defaults to E_USER_WARNING

Definition at line 1154 of file GlobalFunctions.php.

Referenced by Skin\getSkinNames().

◆ wfMakeUrlIndexes()

wfMakeUrlIndexes (   $url)

Make URL indexes, appropriate for the el_index field of externallinks.

Parameters
$urlString
Returns
array

Definition at line 848 of file GlobalFunctions.php.

Referenced by LinksUpdate\getExternalInsertions(), LinkFilterTest\testMakeLikeArrayWithValidPatterns(), and GlobalTest\testMakeUrlIndexes().

◆ wfMatchesDomainList()

wfMatchesDomainList (   $url,
  $domains 
)

Check whether a given URL has a domain that occurs in a given set of domains.

Parameters
string$urlURL
array$domainsArray of domains (strings)
Returns
bool True if the host part of $url ends in one of the strings in $domains

Definition at line 902 of file GlobalFunctions.php.

Referenced by Skin\addToSidebarPlain(), and GlobalTest\testWfMatchesDomainList().

◆ wfMemcKey()

wfMemcKey ( )

Get a cache key.

Parameters
string[$args,...]
Returns
string

Definition at line 3580 of file GlobalFunctions.php.

Referenced by LoginForm\addNewAccountInternal(), Skin\buildSidebar(), FileCacheBase\cacheMissKey(), MessageCache\clear(), LoginForm\clearLoginThrottle(), User\clearSharedCache(), SpecialStatistics\execute(), ShowCacheStats\execute(), DeleteImageCache\execute(), ChangesFeed\execute(), FormatMetadata\fetchExtendedMetadata(), ResourceLoader\filter(), LCStoreAccel\finishWrite(), LCStoreAccel\get(), WikiPage\getCachedLastEditTime(), Skin\getCachedNotice(), SiteSQLStore\getCacheKey(), SpecialVersion\getCreditsForExtension(), ResourceLoaderModule\getDefinitionMtime(), DifferenceEngine\getDiffBodyCacheKey(), IcuCollation\getFirstLetterData(), ResourceLoaderModule\getHashMtime(), DateFormatter\getInstance(), Interwiki\getInterwikiCacheEntry(), ObjectCacheSessionHandler\getKey(), LoadMonitorMySQL\getLagTimes(), ResourceLoaderFileModule\getLESSCacheKey(), MessageCache\getMsgFromNamespace(), User\getNewtalk(), BacklinkCache\getNumLinks(), ParserCache\getOptionsKey(), ParserCache\getParserOutputKey(), SiteStatsUpdate\getTypeCacheKey(), LoginForm\incLoginThrottle(), FileCacheBase\incrMissesRecent(), InfoAction\invalidateCache(), Block\isWhitelistedFromAutoblocks(), ChangeTags\listDefinedTags(), Interwiki\load(), MessageCache\load(), User\loadFromId(), Revision\loadText(), MessageCache\lock(), ApiMain\makeHelpMsg(), SiteStats\numberingroup(), InfoAction\pageInfo(), BacklinkCache\partition(), User\pingLimiter(), Preprocessor_Hash\preprocessToObj(), Preprocessor_DOM\preprocessToObj(), LoginForm\processLogin(), RebuildRecentchanges\purgeFeeds(), JobQueueGroup\queuesHaveJobs(), MessageCache\replace(), User\saveToCache(), MessageCache\saveToCaches(), StatCounter\sendDeltasMemc(), LCStoreAccel\set(), WikiPage\setCachedLastEditTime(), User\setNewtalk(), BagOStuffTest\setUp(), Article\showPatrolFooter(), SpecialAllpages\showToplevel(), LCStoreAccel\startWrite(), BagOStuffTest\testAdd(), BagOStuffTest\testGet(), BagOStuffTest\testGetMulti(), BagOStuffTest\testIncr(), BagOStuffTest\testMerge(), SiteStatsUpdate\tryDBUpdateInternal(), ResourceLoaderModule\validateScriptFile(), and wfThumbAttemptKey().

◆ wfMemoryLimit()

wfMemoryLimit ( )

Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;.

Returns
int Value the memory limit was set to.

Definition at line 3870 of file GlobalFunctions.php.

◆ wfMerge()

wfMerge (   $old,
  $mine,
  $yours,
$result 
)

wfMerge attempts to merge differences between three texts.

Returns true for a clean merge and false for failure or a conflict.

Parameters
string$old
string$mine
string$yours
string$result
Returns
bool

Definition at line 3095 of file GlobalFunctions.php.

Referenced by TextContentHandler\merge3(), and GlobalTest\testMerge().

◆ wfMergeErrorArrays()

wfMergeErrorArrays ( )

Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g.

wfMergeErrorArrays( array( array( 'x' ) ), array( array( 'x', '2' ) ), array( array( 'x' ) ), array( array( 'y' ) ) ); returns: array( array( 'x', '2' ), array( 'x' ), array( 'y' ) )

Parameters
array[$array1,...]
Returns
array

Definition at line 213 of file GlobalFunctions.php.

Referenced by SpecialImport\execute(), Title\isValidMoveOperation(), and DifferenceEngine\showDiffPage().

◆ wfMessage()

wfMessage (   $key)

This is the function for getting translated interface messages.

See also
Message class for documentation how to use them.
https://www.mediawiki.org/wiki/Manual:Messages_API

This function replaces all old wfMsg* functions.

Parameters
string$keyMessage key
mixed[$params,...] Normal message parameters
Returns
Message
Since
1.17
See also
Message::__construct

Definition at line 1401 of file GlobalFunctions.php.

◆ wfMessageFallback()

wfMessageFallback ( )

This function accepts multiple message keys and returns a message instance for the first message which is non-empty.

If all messages are empty then an instance of the first message key is returned.

Parameters
string|string[][$keys,...] Message keys
Returns
Message
Since
1.18
See also
Message::newFallbackSequence

Definition at line 1422 of file GlobalFunctions.php.

Referenced by SkinTemplate\buildContentNavigationUrls(), FileRepo\getDisplayName(), ImagePage\openShowImage(), and SkinTemplate\tabAction().

◆ wfMkdirParents()

wfMkdirParents (   $dir,
  $mode = null,
  $caller = null 
)

Make directory, and make all parent directories if they don't exist.

Parameters
string$dirfull path to directory to create
int$modeChmod value to use, default is $wgDirectoryMode
string$calleroptional caller param for debugging.
Exceptions
MWException
Returns
bool
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 2590 of file GlobalFunctions.php.

Referenced by FileCacheBase\checkCacheDirs(), TextPassDumperTest\checkpointHelper(), SqliteInstaller\dataDirOKmaybeCreate(), FSFileBackend\doPrepareInternal(), FSLockManager\doSingleLock(), BitmapHandler\doTransform(), DjVuHandler\doTransform(), SvgHandler\doTransform(), MediaWikiTestCase\getNewTempDirectory(), ImageCleanup\pokeFile(), MessageCache\saveToLocal(), UploadFromUrlTestSuite\setupUploadDir(), LCStoreCDB\startWrite(), and GlobalTest\testWfMkdirParents().

◆ wfMsg()

wfMsg (   $key)

Get a message from anywhere, for the current user language.

Use wfMsgForContent() instead if the message should NOT change depending on the user preferences.

Deprecated:
since 1.18
Parameters
string$keylookup key for the message, usually defined in languages/Language.php

Parameters to the message, which can be used to insert variable text into it, can be passed to this function in the following formats:

  • One per argument, starting at the second parameter
  • As an array in the second parameter These are not shown in the function definition.
Returns
String

Definition at line 1446 of file GlobalFunctions.php.

◆ wfMsgExt()

wfMsgExt (   $key,
  $options 
)

Returns message in the requested format.

Deprecated:
since 1.18
Parameters
string$keykey of the message
array$optionsprocessing rules. Can take the following options: parse: parses wikitext to HTML parseinline: parses wikitext to HTML and removes the surrounding p's added by parser or tidy escape: filters message through htmlspecialchars escapenoentities: same, but allows entity references like &#160; through replaceafter: parameters are substituted after parsing or escaping parsemag: transform the message using magic phrases content: fetch message for content language instead of interface Also can accept a single associative argument, of the form 'language' => 'xx': language: Language object or language code to fetch message for (overridden by content). Behavior for conflicting options (e.g., parse+parseinline) is undefined.
Returns
String

Definition at line 1678 of file GlobalFunctions.php.

◆ wfMsgForContent()

wfMsgForContent (   $key)

Get a message from anywhere, for the current global language set with $wgLanguageCode.

Use this if the message should NOT change dependent on the language set in the user's preferences. This is the case for most text written into logs, as well as link targets (such as the name of the copyright policy page). Link titles, on the other hand, should be shown in the UI language.

Note that MediaWiki allows users to change the user interface language in their preferences, but a single installation typically only contains content in one language.

Be wary of this distinction: If you use wfMsg() where you should use wfMsgForContent(), a user of the software may have to customize potentially hundreds of messages in order to, e.g., fix a link in every possible language.

Deprecated:
since 1.18
Parameters
string$keylookup key for the message, usually defined in languages/Language.php
Returns
String

Definition at line 1495 of file GlobalFunctions.php.

◆ wfMsgForContentNoTrans()

wfMsgForContentNoTrans (   $key)

Same as above except doesn't transform the message.

Deprecated:
since 1.18
Parameters
$keyString
Returns
String

Definition at line 1518 of file GlobalFunctions.php.

◆ wfMsgGetKey()

wfMsgGetKey (   $key,
  $useDB = true,
  $langCode = false,
  $transform = true 
)

Fetch a message string value, but don't replace any keys yet.

Deprecated:
since 1.18
Parameters
string$key
bool$useDB
string | bool$langCodeCode of the language to get the message for, or behaves as a content language switch if it is a boolean.
bool$transformWhether to parse magic words, etc.
Returns
string

Definition at line 1567 of file GlobalFunctions.php.

◆ wfMsgHtml()

wfMsgHtml (   $key)

Return an HTML-escaped version of a message.

Parameter replacements, if any, are done after the HTML-escaping, so parameters may contain HTML (eg links or form controls). Be sure to pre-escape them if you really do want plaintext, or just wrap the whole thing in htmlspecialchars().

Deprecated:
since 1.18
Parameters
string$key
string[$args,...] Parameters
Returns
string

Definition at line 1623 of file GlobalFunctions.php.

◆ wfMsgNoTrans()

wfMsgNoTrans (   $key)

Same as above except doesn't transform the message.

Deprecated:
since 1.18
Parameters
$keyString
Returns
String

Definition at line 1462 of file GlobalFunctions.php.

◆ wfMsgReal()

wfMsgReal (   $key,
  $args,
  $useDB = true,
  $forContent = false,
  $transform = true 
)

Really get a message.

Deprecated:
since 1.18
Parameters
string$keykey to get.
array$args
bool$useDB
string | bool$forContentLanguage code, or false for user lang, true for content lang.
bool$transformWhether or not to transform the message.
Returns
string The requested message.

Definition at line 1545 of file GlobalFunctions.php.

◆ wfMsgReplaceArgs()

wfMsgReplaceArgs (   $message,
  $args 
)

Replace message parameter keys on the given formatted output.

Parameters
string$message
array$args
Returns
string
Access:\n private

Definition at line 1590 of file GlobalFunctions.php.

Referenced by WikiPage\commitRollback(), MWException\msg(), DBConnectionError\msg(), and ApiMain\reallyMakeHelpMsg().

◆ wfMsgWikiHtml()

wfMsgWikiHtml (   $key)

Return an HTML version of message Parameter replacements, if any, are done after parsing the wiki-text message, so parameters may contain HTML (eg links or form controls).

Be sure to pre-escape them if you really do want plaintext, or just wrap the whole thing in htmlspecialchars().

Deprecated:
since 1.18
Parameters
string$key
string[$args,...] Parameters
Returns
string

Definition at line 1644 of file GlobalFunctions.php.

◆ wfNegotiateType()

wfNegotiateType (   $cprefs,
  $sprefs 
)

Returns the 'best' match between a client's requested internet media types and the server's list of available types.

Each list should be an associative array of type to preference (preference is a float between 0.0 and 1.0). Wildcards in the types are acceptable.

Parameters
array$cprefsclient's acceptable type list
array$sprefsserver's offered types
Returns
string
Todo:
FIXME: Doesn't handle params like 'text/plain; charset=UTF-8' XXX: generalize to negotiate other stuff

Definition at line 2346 of file GlobalFunctions.php.

Referenced by GlobalTest\testNegotiateType().

◆ wfObjectToArray()

wfObjectToArray (   $objOrArray,
  $recursive = true 
)

Recursively converts the parameter (an object) to an array with the same data.

Parameters
$objOrArrayObject|Array
$recursiveBool
Returns
Array

Definition at line 258 of file GlobalFunctions.php.

◆ wfParseUrl()

wfParseUrl (   $url)

parse_url() work-alike, but non-broken.

Differences:

1) Does not raise warnings on bad URLs (just returns false). 2) Handles protocols that don't use :// (e.g., mailto: and news:, as well as protocol-relative URLs) correctly. 3) Adds a "delimiter" element to the array, either '://', ':' or '//' (see (2)).

Parameters
string$urla URL to parse
Returns
string[] Bits of the URL in an associative array, per PHP docs
Examples
/src/includes/rcfeed/RedisPubSubFeedEngine.php.

Definition at line 755 of file GlobalFunctions.php.

Referenced by MWHttpRequest\__construct(), LinkSearchPage\execute(), WikiReference\getDisplayName(), UploadFromUrl\isAllowedHost(), LinkFilter\makeLikeArray(), UserMailer\makeMsgId(), WfAssembleUrlTest\provideURLParts(), SquidPurgeClient\queuePurge(), RedisPubSubFeedEngine\send(), SpecialSearch\showInterwikiHit(), WfParseUrlTest\testWfParseUrl(), and MediaWiki\triggerJobs().

◆ wfPercent()

wfPercent (   $nr,
  $acc = 2,
  $round = true 
)
Parameters
number$nrThe number to format
int$accThe number of digits after the decimal point, default 2
bool$roundWhether or not to round the value, default true
Returns
string

Definition at line 2657 of file GlobalFunctions.php.

Referenced by profile_point\display(), DeleteImageCache\execute(), TestRecorder\reportPercentage(), and GlobalTest\testWfPercentTest().

◆ wfQueriesMustScale()

wfQueriesMustScale ( )

Should low-performance queries be disabled?

Returns
bool

Definition at line 3723 of file GlobalFunctions.php.

◆ wfRandom()

wfRandom ( )

Get a random decimal value between 0 and 1, in a way not likely to give duplicate values for any realistic number of articles.

Returns
string

Definition at line 281 of file GlobalFunctions.php.

Referenced by RandomPage\getRandomTitle(), SpecialRandomInCategory\getRandomTitle(), WikiPage\insertOn(), ApiQueryRandom\run(), and GlobalTest\testRandom().

◆ wfRandomString()

wfRandomString (   $length = 32)

Get a random string containing a number of pseudo-random hex characters.

Note
This is not secure, if you are trying to generate some sort of token please use MWCryptRand instead.
Parameters
int$lengthThe length of the string to generate
Returns
String
Since
1.20

Definition at line 300 of file GlobalFunctions.php.

Referenced by MemcLockManager\__construct(), RedisLockManager\__construct(), DBLockManager\__construct(), JobQueueAggregatorRedis\doGetAllReadyWikiQueues(), MockFileBackend\doGetLocalCopyMulti(), JobQueueDB\doPop(), TempFSFile\factory(), MWExceptionHandler\getLogId(), UIDGenerator\newUUIDv4(), UploadSourceAdapter\registerSource(), JobQueueTest\setUp(), and JobQueueTest\testRootDeduplication().

◆ wfReadOnly()

◆ wfReadOnlyReason()

wfReadOnlyReason ( )

Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.

Returns
string|bool: String when in read-only mode; false otherwise

Definition at line 1322 of file GlobalFunctions.php.

Referenced by ReadOnlyError\__construct(), ProtectionForm\__construct(), WikiPage\doUpdateRestrictions(), and ReadOnlyErrorTest\testConstruction().

◆ wfRecursiveRemoveDir()

wfRecursiveRemoveDir (   $dir)

Remove a directory and all its content.

Does not hide error.

Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 2632 of file GlobalFunctions.php.

Referenced by TextPassDumperTest\checkpointHelper(), MediaWikiTestCase\setUp(), and MediaWikiTestCase\tearDown().

◆ wfRelativePath()

wfRelativePath (   $path,
  $from 
)

Generate a relative path name to the given file.

May explode on non-matching case-insensitive paths, funky symlinks, etc.

Parameters
string$pathabsolute destination path including target filename
string$fromAbsolute source path, directory only
Returns
string

Definition at line 3326 of file GlobalFunctions.php.

Referenced by UploadDumper\outputItem().

◆ wfRemoveDotSegments()

wfRemoveDotSegments (   $urlPath)

Remove all dot-segments in the provided URL path.

For example, '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see RFC3986 section 5.2.4.

Todo:
Need to integrate this into wfExpandUrl (bug 32168)
Parameters
string$urlPathURL path, potentially containing dot-segments
Returns
string URL path with all dot-segments removed

Definition at line 617 of file GlobalFunctions.php.

Referenced by WfRemoveDotSegmentsTest\testWfRemoveDotSegments().

◆ wfReportTime()

wfReportTime ( )

Returns a script tag that stores the amount of time it took MediaWiki to handle the request in milliseconds as 'wgBackendResponseTime'.

If $wgShowHostnames is true, the script will also set 'wgHostname' to the hostname of the server handling the request.

Returns
string

Definition at line 1826 of file GlobalFunctions.php.

Referenced by ApiMain\executeActionWithErrorHandling(), and SkinTemplate\prepareQuickTemplate().

◆ wfResetOutputBuffers()

wfResetOutputBuffers (   $resetGzipEncoding = true)

Clear away any user-level output buffers, discarding contents.

Suitable for 'starting afresh', for instance when streaming relatively large amounts of data without buffering, or wanting to output image files without ob_gzhandler's compression.

The optional $resetGzipEncoding parameter controls suppression of the Content-Encoding header sent by ob_gzhandler; by default it is left. See comments for wfClearOutputBuffers() for why it would be used.

Note that some PHP configuration options may add output buffer layers which cannot be removed; these are left in place.

Parameters
$resetGzipEncodingBool

Definition at line 2226 of file GlobalFunctions.php.

Referenced by SpecialExport\execute(), StreamFile\prepareForStream(), and ResourceLoader\tryRespondLastModified().

◆ wfResetSessionID()

wfResetSessionID ( )

Reset the session_id.

Since
1.22

Definition at line 3511 of file GlobalFunctions.php.

Referenced by LoginForm\renewSessionId().

◆ wfRestoreWarnings()

wfRestoreWarnings ( )

Restore error level to previous value.

Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 2417 of file GlobalFunctions.php.

Referenced by UIDGenerator\__construct(), SVGReader\__construct(), TempFSFile\__destruct(), DatabaseOracle\__destruct(), MWMemcached\_connect_sock(), Exif\charCodeString(), MediaWikiTestCase\checkHasDiff3(), DjVuTest\checkIfToolExists(), OutputPage\checkLastModified(), UploadBase\checkXMLEncodingMissmatch(), FileCacheBase\clearCache(), SquidPurgeClient\close(), TextPassDumper\closeSpawn(), MediaHandler\convertMetadataVersion(), IPTC\convIPTCHelper(), SqliteInstaller\dataDirOKmaybeCreate(), DiffHistoryBlob\diff(), Installer\dirIsExecutable(), Installer\disableTimeLimit(), FileBackendStore\doConcatenate(), SpecialExport\doExport(), FileBackendStore\doGetFileContentsMulti(), SquidPurgeClient\doReads(), FSLockManager\doSingleLock(), MemoryFileBackend\doStoreInternal(), SwiftFileBackend\doStoreInternal(), SquidPurgeClient\doWrites(), Installer\envCheckPCRE(), CheckImages\execute(), JSParseHelper\execute(), RebuildFileCache\execute(), CologneBlueTemplate\execute(), ModernTemplate\execute(), CommandLineInstaller\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), TempFSFile\factory(), DatabaseMysqlBase\fetchObject(), DatabasePostgres\fetchObject(), DatabaseMysqlBase\fetchRow(), StatsOutput\formatPercent(), WikiStatsOutput\formatPercent(), ContribsPager\formatRow(), DatabaseMysqlBase\freeResult(), WebInstallerOutput\getCSS(), Installer\getExistingLocalSettings(), GitInfo\getHeadViewUrl(), ImageHandler\getImageSize(), ApiQueryImageInfo\getInfo(), SquidPurgeClient\getIP(), MachineReadableRCFeedFormatter\getLine(), MessageCache\getLocalCache(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), DjVuHandler\getMetaTree(), DatabaseLogEntry\getParameters(), WebRequest\getPathInfo(), IcuCollation\getPrimarySortKey(), ExifBitmapHandler\getRotationForExif(), FSFile\getSha1Base36(), SquidPurgeClient\getSocket(), IcuCollation\getSortKey(), StoreFileOp\getSourceSha1Base36(), SpecialVersion\getSvnInfo(), TextPassDumper\getTextSpawned(), FSFile\getTimestamp(), DjVuHandler\getUnserializedMetadata(), MediaWikiTestCase\hideDeprecated(), Language\iconv(), MWCryptRand\initialRandomState(), DatabaseOracle\insertOneRow(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), DatabaseMysqlBase\lastError(), Installer\locateExecutable(), ImportStreamSource\newFromFile(), DatabaseMysqlBase\numRows(), SpecialUnlockdb\onSubmit(), SpecialLockdb\onSubmit(), DatabaseMysqlBase\open(), DatabaseMssql\open(), DatabaseOracle\open(), XMPReader\parse(), DiffHistoryBlob\patch(), DatabaseInstaller\populateInterwikiTable(), Preprocessor_DOM\preprocessToObj(), FileRepo\publishBatch(), TempFSFile\purge(), LocalisationCache\readPHPFile(), MWCryptRand\realGenerate(), Sanitizer\removeHTMLtags(), SquidPurgeClientPool\run(), ContentHandler\runLegacyHooks(), MessageCache\saveToLocal(), JpegMetadataExtractor\segmentSplitter(), DatabaseOracle\selectDB(), UserMailer\send(), StatCounter\sendDeltasUDP(), DatabaseBase\sourceFile(), RecompressTracked\startSlaveProcs(), FileRepo\storeBatch(), StreamFile\stream(), MWDebugTest\tearDown(), JavaScriptMinifierTest\testJavaScriptMinifierOutput(), GlobalTest\testWfMkdirParents(), MediaWiki_I18N\translate(), MediaWiki\triggerJobs(), SvgHandler\unpackMetadata(), SqlBagOStuff\unserialize(), DatabaseOracle\update(), Language\userAdjust(), and wfStreamThumb().

◆ wfRunHooks()

wfRunHooks (   $event,
array  $args = array(),
  $deprecatedVersion = null 
)

Call hook functions defined in $wgHooks.

Parameters
string$eventevent name
array$argsparameters passed to hook functions
string | null$deprecatedVersionoptionally mark hook as deprecated with version number
Returns
bool True if no handler aborted the hook

Definition at line 4010 of file GlobalFunctions.php.

Referenced by ExtensionsTestSuite\__construct(), LinksUpdate\__construct(), DatabaseUpdater\__construct(), RedirectSpecialArticle\__construct(), DatabaseOracle\__construct(), ResourceLoader\__construct(), UploadForm\__construct(), EmailNotification\actuallyNotifyOnPageChange(), OutputPage\addCategoryLinks(), User\addGroup(), LoginForm\addNewAccount(), LoginForm\addNewAccountInternal(), LoginForm\addNewAccountMailPassword(), OutputPage\addParserOutput(), OutputPage\addParserOutputNoText(), Skin\afterContentHook(), LoginForm\attemptAutoCreate(), SpecialChangeEmail\attemptChange(), SpecialChangePassword\attemptReset(), LoginForm\authenticateUserData(), BenchmarkHooks\benchHooks(), Skin\bottomScripts(), SkinTemplate\buildContentNavigationUrls(), ProtectionForm\buildForm(), SkinTemplate\buildNavUrls(), SkinTemplate\buildPersonalUrls(), SpecialEditWatchlist\buildRemoveLine(), Skin\buildSidebar(), ContentHandler\canBeUsedOn(), User\canSendEmail(), EmailNotification\canSendUserTalkEmail(), Autopromote\checkCondition(), ApiMain\checkExecutePermissions(), OutputPage\checkLastModified(), User\checkPasswordValidity(), Title\checkPermissionHooks(), Title\checkQuickPermissions(), Title\checkReadPermissions(), User\clearNotification(), WikiPage\commitRollback(), User\comparePasswords(), Article\confirmDelete(), User\confirmEmail(), AbstractContent\convert(), UploadBase\createFromRequest(), User\crypt(), Block\doAutoblock(), FileDeleteForm\doDelete(), WikiPage\doDeleteArticleReal(), WikiPage\doEditContent(), Skin\doEditSectionLink(), WikiPage\doEditUpdates(), WikiImporter\doImport(), Language\doMagicHook(), SpecialRecentChangesLinked\doMainQuery(), SpecialWatchlist\doMainQuery(), SpecialRecentChanges\doMainQuery(), ChangesListSpecialPage\doMainQuery(), RecentChange\doMarkPatrolled(), RevDel_RevisionList\doPostCommitUpdates(), WikiPage\doPurge(), WikiPage\doQuickEditContent(), RefreshLinks\doRefreshLinks(), Block\doRetroactiveAutoblock(), UserrightsPage\doSaveUserGroups(), MovePageForm\doSubmit(), BitmapHandler\doTransform(), WatchAction\doUnwatch(), LinksUpdate\doUpdate(), WikiPage\doUpdateRestrictions(), LinkHolderArray\doVariants(), WatchAction\doWatch(), WikiExporter\dumpFrom(), ApiCreateAccount\execute(), ApiUndelete\execute(), SpecialUserlogout\execute(), ApiEditPage\execute(), ApiLogout\execute(), ApiParse\execute(), SpecialContributions\execute(), SpecialStatistics\execute(), SpecialLog\execute(), ApiLogin\execute(), SpecialEmailUser\execute(), SpecialUpload\execute(), ApiQuery\execute(), ApiMain\executeAction(), ApiPageSet\executeInternal(), ApiQueryInfo\extractPageInfo(), Collation\factory(), Article\fetchContentObject(), FormatMetadata\fetchExtendedMetadata(), WikiImporter\finishImportPage(), Linker\formatAutocommentsCallback(), UsersPager\formatRow(), ContribsPager\formatRow(), MessageCache\get(), LegacyLogFormatter\getActionLinks(), User\getAllRights(), Autopromote\getAutopromoteGroups(), User\getBlockedStatus(), OutputPage\getCacheVaryCookies(), MWNamespace\getCanonicalNamespaces(), Title\getCanonicalURL(), Title\getCategorySortkey(), CheckLanguageCLI\getCheckBlacklist(), BacklinkCache\getConditions(), ResourceLoaderStartUpModule\getConfig(), Skin\getCopyright(), SpecialRecentChanges\getCustomFilters(), SpecialWatchlist\getCustomFilters(), ChangesListSpecialPage\getCustomFilters(), ContentHandler\getDefaultModelFor(), User\getDefaultOptions(), UsersPager\getDefaultQuery(), WikiPage\getDeletionUpdates(), DifferenceEngine\getDiffBody(), MagicWord\getDoubleUnderscoreArray(), Title\getEditNotices(), User\getEffectiveGroups(), User\getEmail(), User\getEmailAuthenticationTimestamp(), FormatMetadata\getExtendedMetadataFromHook(), SpecialVersion\getExtensionCredits(), SpecialVersion\getExtensionTypes(), SpecialRecentChanges\getExtraOptions(), FormAction\getForm(), FormSpecialPage\getForm(), SpecialChangePassword\getFormFields(), SpecialBlock\getFormFields(), ContentHandler\getForModelID(), Title\getFullURL(), LocalFile\getHistory(), MWTimestamp\getHumanTimestamp(), User\getImplicitGroups(), Title\getInternalURL(), XMPInfo\getItems(), OutputPage\getJSVars(), RequestContext\getLanguage(), SkinTemplate\getLanguages(), PreferencesForm\getLegend(), IRCColourfulRCFeedFormatter\getLine(), SpecialPageFactory\getList(), Title\getLocalURL(), Language\getMessagesFileName(), MediaHandler\getMetadataVersion(), MessageCache\getMsgFromNamespace(), Language\getNamespaces(), SearchEngine\getNearMatch(), SearchEngine\getNearMatchInternal(), User\getNewMessageLinks(), Skin\getNewtalks(), UsersPager\getPageHeader(), ContentHandler\getPageLanguage(), QueryPage\getPages(), WebRequest\getPathInfo(), SpecialEmailUser\getPermissionsError(), Skin\getPoweredBy(), Preferences\getPreferences(), BacklinkCache\getPrefix(), SpecialSearch\getProfileForm(), LonelyPagesPage\getQueryInfo(), WantedPagesPage\getQueryInfo(), UsersPager\getQueryInfo(), HistoryPager\getQueryInfo(), NewPagesPager\getQueryInfo(), RandomPage\getRandomTitle(), MWTimestamp\getRelativeTimestamp(), Title\getRestrictionTypes(), XMPReader\getResults(), User\getRights(), ApiRsd\getRsdApiList(), SpecialSearch\getSearchProfiles(), BaseTemplate\getSidebar(), Skin\getSiteNotice(), RequestContext\getSkin(), UploadForm\getSourceSection(), Language\getSpecialPageAliases(), Title\getSquidURLs(), ResourceLoaderStartUpModule\getStartupModulesUrl(), DeletedContributionsPage\getSubTitle(), ApiQueryUsers\getTokenFunctions(), ApiQueryRevisions\getTokenFunctions(), ApiQueryRecentChanges\getTokenFunctions(), ApiQueryInfo\getTokenFunctions(), SpecialResetTokens\getTokensList(), ApiTokens\getTokenTypes(), BaseTemplate\getToolbox(), MagicWord\getVariableIDs(), GitInfo\getViewers(), SpecialVersion\getwgVersionLinked(), SpecialSearch\goResult(), ApiMain\handleException(), WikiImporter\handleLogItem(), WikiImporter\handlePage(), WikiImporter\handleRevision(), WikiImporter\handleUpload(), OutputPage\headElement(), HistoryPager\historyLine(), LinksUpdate\incrTableUpdate(), ChangesList\initChangesListRows(), SearchResult\initFromTitle(), MediaWiki\initializeArticle(), ChangesList\insertArticleLink(), Revision\insertOn(), User\invalidateEmail(), UploadFromUrl\isAllowedUrl(), Title\isAlwaysKnown(), User\isBlockedFrom(), User\isBlockedGlobally(), Title\isCssOrJsPage(), User\isEmailConfirmed(), User\isEveryoneAllowed(), Article\isFileCacheable(), MWNamespace\isMovable(), Title\isMovable(), User\isUsableName(), Title\isValidMoveOperation(), Linker\link(), ChangeTags\listDefinedTags(), Interwiki\load(), User\load(), User\loadDefaults(), ImagePage\loadFile(), User\loadFromDatabase(), User\loadFromSession(), ImageGalleryBase\loadModes(), User\loadOptions(), DifferenceEngine\loadRevisionIds(), User\logout(), LoginForm\mailPasswordInternal(), LoginForm\mainLoginForm(), Linker\makeExternalImage(), Linker\makeExternalLink(), Linker\makeImageLink(), SpecialMergeHistory\merge(), Title\moveTo(), Title\moveToInternal(), ChangesList\newFromContext(), UserArray\newFromResult(), TitleArray\newFromResult(), Article\newFromTitle(), BitmapHandler\normaliseParams(), SpecialPasswordReset\onSubmit(), RawAction\onView(), InfoAction\onView(), HistoryAction\onView(), XmlDumpWriter\openPage(), ImagePage\openShowImage(), ParserOptions\optionsHash(), OutputPage\output(), WikiPage\pageData(), MediaWiki\performAction(), MediaWiki\performRequest(), UploadBase\performUpload(), User\pingLimiter(), SpecialSearch\powerSearchBox(), WikiPage\prepareContentForEdit(), SkinTemplate\prepareQuickTemplate(), SpecialBlock\preText(), SpecialBlock\processForm(), SpecialUpload\processUpload(), LocalFile\purgeOldThumbnails(), LocalFile\purgeThumbnails(), LocalisationCache\recache(), OldChangesList\recentChangesLine(), LocalFile\recordUpload2(), User\removeGroup(), CologneBlueTemplate\renderAfterPortlet(), BaseTemplate\renderAfterPortlet(), DifferenceEngine\renderNewRevision(), MessageCache\replace(), LinkHolderArray\replaceInternal(), SearchEngine\replacePrefixes(), WikitextContent\replaceSection(), ImportReporter\reportPage(), User\requiresHTTPS(), LoginForm\resetLoginForm(), User\resetPasswordExpiration(), SpecialPage\run(), ContentHandler\runLegacyHooks(), RecentChange\save(), ProtectionForm\save(), User\saveOptions(), User\saveSettings(), SearchEngine\searchableNamespaces(), PrefixSearch\searchBackend(), UserMailer\send(), WebResponse\setcookie(), User\setCookies(), User\setEmail(), User\setEmailAuthenticationTimestamp(), Article\setOldSubtitle(), SpecialNewpages\setup(), SkinVector\setupSkinUserCss(), EditAction\show(), SpecialSearch\showCreateLink(), DifferenceEngine\showDiffPage(), SpecialUndelete\showHistory(), SpecialSearch\showHit(), SpecialBlockList\showList(), SpecialBookSources\showList(), LogEventsList\showLogExtract(), ProtectionForm\showLogExtract(), Article\showMissingArticle(), Article\showRedirectedFromHeader(), SpecialSearch\showResults(), SpecialUndelete\showRevision(), ImagePage\showTOC(), Article\showViewFooter(), SpecialVersion\softwareInformation(), SpecialEmailUser\submit(), Skin\subPageSubtitle(), LoginForm\successfulCreation(), LoginForm\successfulLogin(), SkinTemplate\tabAction(), HooksTest\testOldStyleHooks(), TraditionalImageGallery\toHTML(), ThumbnailImage\toHtml(), MonoBookTemplate\toolbox(), File\transform(), Preferences\tryFormSubmit(), PageArchive\undelete(), SpecialUndelete\undelete(), PageArchive\undeleteRevisions(), SpecialEditWatchlist\unwatchTitles(), WikiPage\updateCategoryCounts(), Linker\userToolLinks(), Sanitizer\validateEmail(), UploadBase\verifyFile(), UploadBase\verifyUpload(), CategoryPage\view(), ImagePage\view(), Article\view(), wfExtractThumbParams(), and XmlDumpWriter\writeRevision().

◆ wfScript()

wfScript (   $script = 'index')

Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScriptExtension etc.

except for 'index' and 'load' which use $wgScript/$wgLoadScript

Parameters
string$scriptscript filename, sans extension
Returns
string

Definition at line 3739 of file GlobalFunctions.php.

Referenced by ResourceLoader\__construct(), SpecialPage\addFeedLinks(), SpecialRedirect\dispatchPage(), SpecialRedirect\dispatchRevision(), SpecialContributions\execute(), RedirectSpecialPage\execute(), SpecialRecentChanges\execute(), SpecialVersion\getEntryPointInfo(), OutputPage\getHeadLinksArray(), SearchEngine\getOpenSearchTemplate(), ApiRsd\getRsdApiList(), ResourceLoaderStartUpModule\getStartupModulesUrl(), ApiFormatBase\initPrinter(), ApiTestCase\setUp(), and MediaWiki\triggerJobs().

◆ wfSetBit()

wfSetBit ( $dest,
  $bit,
  $state = true 
)

As for wfSetVar except setting a bit.

Parameters
$destInt
$bitInt
$stateBool
Returns
bool

Definition at line 2156 of file GlobalFunctions.php.

Referenced by DatabaseBase\bufferResults(), DatabaseBase\debug(), and DatabaseBase\ignoreErrors().

◆ wfSetupSession()

◆ wfSetVar()

wfSetVar ( $dest,
  $source,
  $force = false 
)

Sets dest to source and returns the original value of dest If source is NULL, it just returns the value, it doesn't set the variable If force is true, it will set the value even if source is NULL.

Parameters
$destMixed
$sourceMixed
$forceBool
Returns
Mixed

Definition at line 2139 of file GlobalFunctions.php.

Referenced by DatabaseBase\dbSchema(), ParserOptions\disableContentConversion(), ParserOptions\disableTitleConversion(), OutputPage\enableClientCache(), ParserOptions\enableLimitReport(), DatabaseBase\errorCount(), LinkCache\forUpdate(), Block\fromMaster(), SpecialPage\including(), Block\isAutoblocking(), Block\isHardblock(), SpecialPage\listed(), LoadBalancer\parentInfo(), OutputPage\parserOptions(), DatabaseMssql\prepareStatements(), ParserOutput\preventClickjacking(), Block\prevents(), DatabaseMssql\scrollableCursor(), ParserOptions\setAllowExternalImages(), ParserOptions\setAllowExternalImagesFrom(), ParserOptions\setAllowSpecialInclusion(), CacheTime\setCacheTime(), ParserOutput\setCategoryLinks(), ParserOptions\setCleanSignatures(), CacheTime\setContainsOldMagic(), ParserOptions\setDateFormat(), ParserOptions\setEditSection(), ParserOutput\setEditSectionTokens(), ParserOptions\setEnableImageWhitelist(), ParserOptions\setExpensiveParserFunctionLimit(), ParserOptions\setExternalLinkTarget(), OutputPage\setFileVersion(), ParserOutput\setIndexPolicy(), ParserOptions\setInterfaceMessage(), ParserOptions\setInterwikiMagic(), ParserOptions\setIsPreview(), ParserOptions\setIsPrintable(), ParserOptions\setIsSectionPreview(), ParserOutput\setLanguageLinks(), SpecialPage\setListed(), ParserOptions\setMaxGeneratedPPNodeCount(), ParserOptions\setMaxIncludeSize(), ParserOptions\setMaxPPNodeCount(), ParserOptions\setMaxTemplateDepth(), WikiImporter\setNoticeCallback(), ParserOptions\setNumberHeadings(), ParserOptions\setPreSaveTransform(), ParserOptions\setRemoveComments(), OutputPage\setRevisionId(), OutputPage\setRevisionTimestamp(), ParserOutput\setSections(), ParserOptions\setStubThreshold(), ParserOptions\setTargetLanguage(), ParserOptions\setTemplateCallback(), ParserOutput\setText(), ParserOptions\setThumbSize(), ParserOptions\setTidy(), ParserOutput\setTimestamp(), ParserOptions\setTimestamp(), ParserOutput\setTitleText(), ParserOutput\setTOCEnabled(), ParserOutput\setTOCHTML(), ParserOptions\setUserLang(), DatabaseBase\tablePrefix(), and LoadBalancer\waitTimeout().

◆ wfShellExec()

wfShellExec (   $cmd,
$retval = null,
  $environ = array(),
  $limits = array(),
  $options = array() 
)

Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported.

Parameters
string$cmdCommand line, properly escaped for shell.
&$retvalnull|Mixed optional, will receive the program's exit code. (non-zero is usually failure). If there is an error from read, select, or proc_open(), this will be set to -1.
array$environoptional environment variables which should be added to the executed command environment.
array$limitsoptional array with limits(filesize, memory, time, walltime) this overwrites the global wgMaxShell* limits.
array$optionsArray of options:
  • duplicateStderr: Set this to true to duplicate stderr to stdout, including errors from limit.sh
Returns
string collected stdout as a string
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 2804 of file GlobalFunctions.php.

Referenced by UIDGenerator\__construct(), MediaWikiTestCase\checkHasGzip(), DjVuHandler\doTransform(), Installer\envCheckShellLocale(), DifferenceEngine\generateTextDiffBody(), SiteConfiguration\getConfig(), GitInfo\getHeadCommitDate(), BitmapHandler\getMagickVersion(), Installer\locateExecutable(), Maintenance\readlineEmulation(), WfShellExecTest\testBug67870(), RandomImageGenerator\writeImageWithApi(), and RandomImageGenerator\writeImageWithCommandLine().

◆ wfShellExecDisabled()

wfShellExecDisabled ( )

Check if wfShellExec() is effectively disabled via php.ini config.

Returns
bool|string False or one of (safemode,disabled)
Since
1.22

Definition at line 2766 of file GlobalFunctions.php.

◆ wfShellExecWithStderr()

wfShellExecWithStderr (   $cmd,
$retval = null,
  $environ = array(),
  $limits = array() 
)

Execute a shell command, returning both stdout and stderr.

Convenience function, as all the arguments to wfShellExec can become unwieldy.

Note
This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
Parameters
string$cmdCommand line, properly escaped for shell.
&$retvalnull|Mixed optional, will receive the program's exit code. (non-zero is usually failure)
array$environoptional environment variables which should be added to the executed command environment.
array$limitsoptional array with limits(filesize, memory, time, walltime) this overwrites the global wgShellMax* limits.
Returns
string collected stdout and stderr as a string

Definition at line 3029 of file GlobalFunctions.php.

Referenced by UploadBase\detectVirus(), SvgHandler\rasterize(), JpegHandler\rotate(), BitmapHandler\rotate(), BitmapHandler\transformCustom(), and BitmapHandler\transformImageMagick().

◆ wfShellMaintenanceCmd()

wfShellMaintenanceCmd (   $script,
array  $parameters = array(),
array  $options = array() 
)

Alias to wfShellWikiCmd()

See also
wfShellWikiCmd()

Definition at line 3055 of file GlobalFunctions.php.

Referenced by GlobalTest\testWfShellMaintenanceCmd().

◆ wfShellWikiCmd()

wfShellWikiCmd (   $script,
array  $parameters = array(),
array  $options = array() 
)

Generate a shell-escaped command line string to run a MediaWiki cli script.

Note that $parameters should be a flat array and an option with an argument should consist of two consecutive items in the array (do not use "--option value").

Parameters
string$scriptMediaWiki cli script path
array$parametersArguments and options to the script
array$optionsAssociative array of options: 'php': The path to the php executable 'wrapper': Path to a PHP wrapper to handle the maintenance script
Returns
string

Definition at line 3071 of file GlobalFunctions.php.

Referenced by CleanupSpam\execute(), SiteConfiguration\getConfig(), and MWDocGen\init().

◆ wfShorthandToInteger()

wfShorthandToInteger (   $string = '')

Converts shorthand byte notation to integer form.

Parameters
string$string
Returns
int

Definition at line 3898 of file GlobalFunctions.php.

Referenced by Installer\envCheckMemory(), UploadForm\getSourceSection(), WfShorthandToIntegerTest\testWfShorthandToInteger(), GlobalTest\testWfShorthandToInteger(), and UploadFromFile\verifyUpload().

◆ wfShowingResults()

wfShowingResults (   $offset,
  $limit 
)
Todo:
document
Parameters
int$offset
int$limit
Returns
string

Definition at line 1988 of file GlobalFunctions.php.

◆ wfSplitWikiID()

◆ wfStripIllegalFilenameChars()

wfStripIllegalFilenameChars (   $name)

Replace all invalid characters with - Additional characters can be defined in $wgIllegalFileChars (see bug 20489) By default, $wgIllegalFileChars = ':'.

Parameters
string$nameFilename to process
Returns
string

Definition at line 3853 of file GlobalFunctions.php.

Referenced by UploadBase\getTitle(), and Title\validateFileMoveOperation().

◆ wfSuppressWarnings()

wfSuppressWarnings (   $end = false)

Reference-counted warning suppression.

Parameters
$endBool
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 2387 of file GlobalFunctions.php.

Referenced by UIDGenerator\__construct(), SVGReader\__construct(), TempFSFile\__destruct(), DatabaseOracle\__destruct(), MWMemcached\_connect_sock(), SqliteMaintenance\backup(), Exif\charCodeString(), MediaWikiTestCase\checkHasDiff3(), DjVuTest\checkIfToolExists(), OutputPage\checkLastModified(), UploadBase\checkXMLEncodingMissmatch(), FileCacheBase\clearCache(), SquidPurgeClient\close(), TextPassDumper\closeSpawn(), MediaHandler\convertMetadataVersion(), IPTC\convIPTCHelper(), SqliteInstaller\dataDirOKmaybeCreate(), DiffHistoryBlob\diff(), Installer\dirIsExecutable(), Installer\disableTimeLimit(), FileBackendStore\doConcatenate(), SpecialExport\doExport(), FileBackendStore\doGetFileContentsMulti(), SquidPurgeClient\doReads(), FSLockManager\doSingleLock(), MemoryFileBackend\doStoreInternal(), SwiftFileBackend\doStoreInternal(), SquidPurgeClient\doWrites(), Installer\envCheckPCRE(), CheckImages\execute(), JSParseHelper\execute(), RebuildFileCache\execute(), CologneBlueTemplate\execute(), ModernTemplate\execute(), MonoBookTemplate\execute(), CommandLineInstaller\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), TempFSFile\factory(), DatabaseMysqlBase\fetchObject(), DatabasePostgres\fetchObject(), DatabaseMysqlBase\fetchRow(), StatsOutput\formatPercent(), WikiStatsOutput\formatPercent(), ContribsPager\formatRow(), DatabaseMysqlBase\freeResult(), WebInstallerOutput\getCSS(), Installer\getExistingLocalSettings(), GitInfo\getHeadViewUrl(), ImageHandler\getImageSize(), ApiQueryImageInfo\getInfo(), SquidPurgeClient\getIP(), MachineReadableRCFeedFormatter\getLine(), MessageCache\getLocalCache(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), DjVuHandler\getMetaTree(), DatabaseLogEntry\getParameters(), WebRequest\getPathInfo(), IcuCollation\getPrimarySortKey(), ExifBitmapHandler\getRotationForExif(), FSFile\getSha1Base36(), SquidPurgeClient\getSocket(), IcuCollation\getSortKey(), StoreFileOp\getSourceSha1Base36(), SpecialVersion\getSvnInfo(), TextPassDumper\getTextSpawned(), FSFile\getTimestamp(), DjVuHandler\getUnserializedMetadata(), MediaWikiTestCase\hideDeprecated(), Language\iconv(), MWCryptRand\initialRandomState(), DatabaseOracle\insertOneRow(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), DatabaseMysqlBase\lastError(), Installer\locateExecutable(), ImportStreamSource\newFromFile(), DatabaseMysqlBase\numRows(), SpecialUnlockdb\onSubmit(), SpecialLockdb\onSubmit(), DatabaseMysqlBase\open(), DatabaseMssql\open(), DatabaseOracle\open(), XMPReader\parse(), DiffHistoryBlob\patch(), DatabaseInstaller\populateInterwikiTable(), Preprocessor_DOM\preprocessToObj(), FileRepo\publishBatch(), TempFSFile\purge(), LocalisationCache\readPHPFile(), MWCryptRand\realGenerate(), Sanitizer\removeHTMLtags(), SquidPurgeClientPool\run(), ContentHandler\runLegacyHooks(), MessageCache\saveToLocal(), JpegMetadataExtractor\segmentSplitter(), DatabaseOracle\selectDB(), UserMailer\send(), StatCounter\sendDeltasUDP(), MWDebugTest\setUp(), DatabaseBase\sourceFile(), RecompressTracked\startSlaveProcs(), FileRepo\storeBatch(), StreamFile\stream(), JavaScriptMinifierTest\testJavaScriptMinifierOutput(), GlobalTest\testWfMkdirParents(), MediaWiki_I18N\translate(), MediaWiki\triggerJobs(), SvgHandler\unpackMetadata(), SqlBagOStuff\unserialize(), DatabaseOracle\update(), Language\userAdjust(), and wfStreamThumb().

◆ wfTempDir()

◆ wfTime()

wfTime ( )

Get the current unix timestamp with microseconds.

Useful for profiling

Deprecated:
since 1.22; call microtime() directly
Returns
Float

Definition at line 2124 of file GlobalFunctions.php.

◆ wfTimestamp()

wfTimestamp (   $outputtype = TS_UNIX,
  $ts = 0 
)

Get a timestamp string in one of various formats.

Parameters
$outputtypeMixed: A timestamp in one of the supported formats, the function will autodetect which format is supplied and act accordingly.
$tsMixed: optional timestamp to convert, default 0 for the current time
Returns
Mixed: String / false The same date in the format specified in $outputtype or false

Definition at line 2483 of file GlobalFunctions.php.

Referenced by Block\__construct(), BlockTest\addDBData(), ApiQueryLogEvents\addLogParams(), SpecialRecentChanges\buildMainQueryConds(), FileCacheBase\cacheTimestamp(), SiteStatsUpdate\cacheUpdate(), AjaxResponse\checkLastModified(), OutputPage\checkLastModified(), User\checkTemporaryPassword(), WikiPage\commitRollback(), User\confirmationToken(), FileBackendMultiWrite\consistencyCheck(), LanguageWa\date(), Language\date(), DifferenceEngine\debug(), DatabaseBase\decodeExpiry(), LocalFile\decodeRow(), SqlBagOStuff\deleteObjectsExpiringBefore(), SpecialUndelete\diffHeader(), MemoryFileBackend\doCopyInternal(), MemoryFileBackend\doCreateInternal(), FSFileBackend\doGetFileStat(), DBFileJournal\doLogChangeBatch(), SpecialActiveUsers\doQueryCacheUpdate(), MysqlUpdater\doSchemaRestructuring(), MemoryFileBackend\doStoreInternal(), FileBackendTest\doTestGetFileStat(), ApiProtect\execute(), ApiUndelete\execute(), ApiEditPage\execute(), ApiSetNotificationTimestamp\execute(), ApiQueryDeletedrevs\execute(), SpecialExport\execute(), ApiQueryFilearchive\execute(), RemoveUnusedAccounts\execute(), ApiBlock\execute(), ApiQueryBlocks\execute(), UploadStashCleanup\execute(), FixTimestamps\execute(), ApiQueryImageInfo\execute(), PurgeParserCache\execute(), ApiQueryAllUsers\execute(), BenchmarkParse\execute(), UpdateSearchIndex\execute(), ApiFeedWatchlist\execute(), LocalFileRestoreBatch\execute(), CacheTime\expired(), User\expirePassword(), ApiQueryInfo\extractPageInfo(), ApiQueryWatchlist\extractRowInfo(), ApiQueryContributions\extractRowInfo(), ApiQueryLogEvents\extractRowInfo(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryRevisions\extractRowInfo(), HistoryAction\feedEmpty(), FeedUtils\formatDiff(), Language\formatExpiry(), SpecialUndelete\formatFileRow(), SpecialMergeHistory\formatRevisionRow(), SpecialUndelete\formatRevisionRow(), AtomFeed\formatTime(), RevDel_RevisionItem\getApiData(), RevDel_FileItem\getApiData(), Block\getAutoblockExpiry(), CacheTime\getCacheTime(), NewUsersLogFormatter\getComment(), ApiQueryUserInfo\getCurrentUserInfo(), ProtectionForm\getExpiry(), FormatMetadata\getExtendedMetadataFromFile(), User\getFirstEditTimestamp(), MessageBlobStore\getFromDB(), ResourceLoaderModule\getHashMtime(), ApiQueryImageInfo\getInfo(), MachineReadableRCFeedFormatter\getLine(), PNGMetadataExtractor\getMetadata(), SpecialRandomInCategory\getMinAndMaxForCat(), ResourceLoaderUserCSSPrefsModule\getModifiedTime(), ResourceLoaderUserOptionsModule\getModifiedTime(), ResourceLoaderStartUpModule\getModifiedTime(), ResourceLoaderStartUpModule\getModuleRegistrations(), ResourceLoaderModule\getMsgBlobMtime(), User\getPasswordExpired(), Block\getPermissionsError(), PageArchive\getPreviousRevision(), RawAction\getRawText(), ResourceLoaderStartUpModule\getStartupModulesUrl(), MockFSFile\getTimestamp(), FSFile\getTimestamp(), RevisionItemBase\getTimestamp(), ForeignAPIFile\getTimestamp(), DatabaseLogEntry\getTimestamp(), RCDatabaseLogEntry\getTimestamp(), ArchivedFile\getTimestamp(), ManualLogEntry\getTimestamp(), WikiPage\getTimestamp(), Revision\getTimestamp(), FileJournal\getTimestampedUUID(), Revision\getTimestampFromId(), ResourceLoaderWikiModule\getTitleMtimes(), Block\initFromRow(), Language\internalUserTimeAndDate(), User\isEmailConfirmationPending(), SqlBagOStuff\isExpired(), RecentChange\isInRCLifespan(), User\isPasswordReminderThrottled(), User\loadDefaults(), ChangesFeed\loadFromCache(), RecentChange\loadFromCurRow(), MessageCache\loadFromDB(), WikiPage\loadFromRow(), RecentChange\loadFromRow(), User\loadFromRow(), WikiPage\loadPageData(), SpecialUndelete\loadRequest(), FormatMetadata\makeFormattedData(), OutputPage\makeResourceLoaderLink(), SpecialBlock\maybeAlterFormDefaults(), SpecialMergeHistory\merge(), SpecialActiveUsers\mergeActiveUsers(), User\newTouchedTimestamp(), OutputPage\output(), SpecialBlock\parseExpiryInput(), DatabasePostgres\pg_array_parse(), ResourceLoader\preloadModuleInfo(), StreamFile\prepareForStream(), TableCleanup\progress(), ImageBuilder\progress(), LocalFile\publishTo(), QueryPage\recache(), LocalFile\recordUpload2(), User\resetPasswordExpiration(), ApiQueryProtectedTitles\run(), ApiQueryWatchlistRaw\run(), ApiQueryDuplicateFiles\run(), ApiQueryCategories\run(), ApiQueryCategoryMembers\run(), ApiQuerySearch\run(), ApiQueryQueryPage\run(), RefreshLinksJob\runForTitle(), RunJobs\runJobsLog(), ChangesFeed\saveToCache(), ApiMain\sendCacheHeaders(), ResourceLoader\sendResponseHeaders(), WikiPage\setCachedLastEditTime(), FileBackendStore\setFileCache(), OutputPage\setLastModified(), WikiPage\setTimestamp(), WikiRevision\setTimestamp(), TextPassDumper\showReport(), BackupDumper\showReport(), UpdateLogging\sync(), EditPageTest\testAutoMerge(), WfTimestampTest\testHttpDate(), WfTimestampTest\testNormalTimestamps(), WfTimestampTest\testOldTimestamps(), WfTimestampTest\testTimestampParameter(), TitlePermissionTest\testUserBlock(), Language\time(), Language\timeanddate(), IPTC\timeHelper(), DatabaseOracle\timestamp(), DatabaseBase\timestamp(), ResourceLoader\tryRespondFromFileCache(), ResourceLoader\tryRespondLastModified(), WikiPage\updateIfNewerOn(), Block\updateTimestamp(), XMPValidate\validateDate(), wfStreamThumb(), and XmlDumpWriter\writeTimestamp().

◆ wfTimestampNow()

◆ wfTimestampOrNull()

wfTimestampOrNull (   $outputtype = TS_UNIX,
  $ts = null 
)

Return a formatted timestamp, or null if input is null.

For dealing with nullable timestamp columns in the database.

Parameters
int$outputtype
string$ts
Returns
string

Definition at line 2501 of file GlobalFunctions.php.

Referenced by Autopromote\checkCondition(), ApiQueryUsers\execute(), OutputPage\getJSVars(), JobSpecification\getReleaseTimestamp(), Job\getReleaseTimestamp(), WikiPage\loadFromRow(), and User\loadFromRow().

◆ wfUnpack()

wfUnpack (   $format,
  $data,
  $length = false 
)

Wrapper around php's unpack.

Parameters
string$formatThe format string (See php's docs)
string$dataA binary string of binary data
int | bool$lengthThe minimum length of $data or false. This is to prevent reading beyond the end of $data. false to disable the check.

Also be careful when using this function to read unsigned 32 bit integer because php might make it negative.

Exceptions
MWExceptionif $data not long enough, or if unpack fails
Returns
array Associative array of the extracted data

Definition at line 4028 of file GlobalFunctions.php.

Referenced by JpegMetadataExtractor\doPSIR(), BmpHandler\getImageSize(), XCFHandler\getXCFMetaData(), JpegMetadataExtractor\jpegExtractMarker(), and JpegMetadataExtractor\segmentSplitter().

◆ wfUrlencode()

wfUrlencode (   $s)

We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.

According to RFC 1738, all of the following should be safe:

;:&=$-_.+!*'(),

But + is not safe because it's used to indicate a space; &= are only safe in paths and not in queries (and we don't distinguish here); ' seems kind of scary; and urlencode() doesn't touch -_. to begin with. Plus, although / is reserved, we don't care. So the list we unescape is:

;:$!*(),/

However, IIS7 redirects fail when the url contains a colon (Bug 22709), so no fancy : for IIS7.

%2F in the page titles seems to fatally break for some reason.

Parameters
$sString:
Returns
string

Definition at line 330 of file GlobalFunctions.php.

Referenced by FileRepo\getDescriptionRenderUrl(), FileRepo\getDescriptionUrl(), Title\getLocalURL(), MediaWikiPageLinkRenderer\getPageUrl(), MediaWikiSite\getPageUrl(), Title\getPrefixedURL(), Title\getSubpageUrlForm(), Interwiki\getURL(), ApiMain\logRequest(), LoginForm\mainLoginForm(), Title\makeTitle(), CoreParserFunctions\namespacee(), CoreParserFunctions\nse(), Title\secureAndSplit(), CoreParserFunctions\speciale(), CoreParserFunctions\subjectspacee(), CoreParserFunctions\talkspacee(), GlobalTest\testUrlencode(), and WfUrlencodeTest\verifyEncodingFor().

◆ wfUrlProtocols()

wfUrlProtocols (   $includeProtocolRelative = true)

Returns a regular expression of url protocols.

Parameters
bool$includeProtocolRelativeIf false, remove '//' from the returned protocol list. DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
Returns
String

Definition at line 695 of file GlobalFunctions.php.

Referenced by Skin\addToSidebarPlain(), ResourceLoaderStartUpModule\getConfig(), Skin\makeInternalOrExternalUrl(), Sanitizer\safeEncodeAttribute(), and Sanitizer\validateAttributes().

◆ wfUrlProtocolsWithoutProtRel()

wfUrlProtocolsWithoutProtRel ( )

Like wfUrlProtocols(), but excludes '//' from the protocol list.

Use this if you need a regex that matches all URL protocols but does not match protocol- relative URLs

Returns
String

Definition at line 740 of file GlobalFunctions.php.

Referenced by ApiFormatBase\formatHTML(), and Language\markNoConversion().

◆ wfUseMW()

wfUseMW (   $req_ver)

This function works like "use VERSION" in Perl except it checks the version of MediaWiki, the program will die with a backtrace if the current version of MediaWiki is less than the version provided.

This is useful for extensions which due to their nature are not kept in sync with releases

Note: Due to the behavior of PHP's version_compare() which is used in this function, if you want to allow the 'wmf' development versions add a 'c' (or any single letter other than 'a', 'b' or 'p') as a post-fix to your targeted version number. For example if you wanted to allow any variation of 1.22 use ‘wfUseMW( '1.22c’ )‘. Using an 'a’ or 'b' instead of 'c' will not result in the same comparison due to the internal logic of version_compare().

See also
perldoc -f use
Parameters
string | number$req_verThe version to check, can be a string, an integer, or a float
Exceptions
MWException

Definition at line 3282 of file GlobalFunctions.php.

◆ wfUsePHP()

wfUsePHP (   $req_ver)

This function works like "use VERSION" in Perl, the program will die with a backtrace if the current version of PHP is less than the version provided.

This is useful for extensions which due to their nature are not kept in sync with releases, and might depend on other versions of PHP than the main code

Note: PHP might die due to parsing errors in some cases before it ever manages to call this function, such is life

See also
perldoc -f use
Parameters
string | number$req_verThe version to check, can be a string, an integer, or a float
Exceptions
MWException

Definition at line 3252 of file GlobalFunctions.php.

◆ wfVarDump()

wfVarDump (   $var)

A wrapper around the PHP function var_export().

Either print it or add it to the regular output ($wgOut).

Parameters
$varmixed A PHP variable to dump.

Definition at line 2174 of file GlobalFunctions.php.

◆ wfViewPrevNext()

wfViewPrevNext (   $offset,
  $limit,
  $link,
  $query = '',
  $atend = false 
)

Generate (prev x| next x) (20|50|100...) type links for paging.

Parameters
string$offset
int$limit
string$link
string$queryoptional URL query parameter string
bool$atendoptional param for specified if this is the last page
Returns
string
Deprecated:
in 1.19; use Language::viewPrevNext() instead

Definition at line 2003 of file GlobalFunctions.php.

◆ wfWaitForSlaves()

wfWaitForSlaves (   $maxLag = false,
  $wiki = false,
  $cluster = false 
)

Modern version of wfWaitForSlaves().

Instead of looking at replication lag and waiting for it to go down, this waits for the slaves to catch up to the master position. Use this when updating very large numbers of rows, as in maintenance scripts, to avoid causing too much lag. Of course, this is a no-op if there are no slaves.

Parameters
int | bool$maxLag(deprecated)
string | bool$wikiWiki identifier accepted by wfGetLB
string | bool$clusterCluster name accepted by LBFactory. Default: false.

Definition at line 3804 of file GlobalFunctions.php.

Referenced by CompressOld\compressWithConcat(), RefreshLinks\deleteLinksFromNonexistent(), PopulateRecentChangesSource\doDBUpdates(), PopulateFilearchiveSha1\doDBUpdates(), FixExtLinksProtocolRelative\doDBUpdates(), PopulateParentId\doDBUpdates(), PopulateLogSearch\doDBUpdates(), PopulateLogUsertext\doDBUpdates(), PopulateImageSha1\doDBUpdates(), PopulateRevisionLength\doLenUpdates(), PopulateCategory\doPopulateCategory(), SpecialActiveUsers\doQueryCacheUpdate(), RefreshLinks\doRefreshLinks(), PopulateRevisionSha1\doSha1LegacyUpdates(), PopulateRevisionSha1\doSha1Updates(), UpdateSpecialPages\doSpecialPageCacheUpdates(), MysqlUpdater\doTemplatelinksUpdate(), JobQueueDB\doWaitForBackups(), TidyUpBug37714\execute(), WaitForSlave\execute(), DeleteSelfExternals\execute(), DeleteDefaultMessages\execute(), MigrateUserGroup\execute(), BatchedQueryRunner\execute(), MwSql\execute(), ConvertUserOptions\execute(), InitEditCount\execute(), CleanupRemovedModules\execute(), UpdateRestrictions\execute(), UpdateSpecialPages\execute(), ResetUserTokens\execute(), DeleteBatch\execute(), RunJobs\execute(), MoveBatch\execute(), RefreshImageMetadata\execute(), UpdateCollation\execute(), UpdateMediaWiki\execute(), DeleteEqualMessages\execute(), moveToExternal(), resolveStubs(), BackupReader\showReport(), UpdateLogging\sync(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), and FixBug20757\waitForSlaves().

◆ wfWarn()

wfWarn (   $msg,
  $callerOffset = 1,
  $level = E_USER_NOTICE 
)

Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.

To log warnings in production, use wfLogWarning() instead.

Parameters
string$msgmessage to send
$callerOffsetInteger: number of items to go back in the backtrace to find the correct caller (1 = function calling wfWarn, ...)
$levelInteger: PHP error level; defaults to E_USER_NOTICE; only used when $wgDevelopmentWarnings is true

Definition at line 1141 of file GlobalFunctions.php.

Referenced by TextContent\__construct(), Exif\__construct(), Action\__construct(), DatabaseBase\begin(), DatabaseBase\close(), DatabaseBase\commit(), MWTidy\execExternalTidy(), MWTidy\execInternalTidy(), ForeignAPIRepo\fileExistsBatch(), CacheHelper\getCachedValue(), WikiPage\getContentModel(), Action\getContext(), ParserCache\getKey(), SpecialPageFactory\getLocalNameFor(), BacklinkJobUtils\partitionBacklinkJob(), Autopromote\recCheckCondition(), DatabaseBase\rollback(), and ContentHandler\runLegacyHooks().

◆ wfWikiID()

Variable Documentation

◆ TS_DB

◆ TS_EXIF

const TS_EXIF 5

An Exif timestamp (YYYY:MM:DD HH:MM:SS)

See also
http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the DateTime tag and page 36 for the DateTimeOriginal and DateTimeDigitized tags.

Definition at line 2457 of file GlobalFunctions.php.

Referenced by PNGMetadataExtractor\getMetadata(), MWTimestampTest\provideValidTimestamps(), IPTC\timeHelper(), and XMPValidate\validateDate().

◆ TS_ISO_8601

◆ TS_ISO_8601_BASIC

◆ TS_MW

const TS_MW 1

MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)

Definition at line 2431 of file GlobalFunctions.php.

Referenced by Block\__construct(), BlockTest\addDBData(), SwiftFileBackend\buildFileObjectListing(), SpecialRecentChanges\buildMainQueryConds(), FileCacheBase\cacheTimestamp(), AjaxResponse\checkLastModified(), OutputPage\checkLastModified(), WikiPage\commitRollback(), User\confirmationToken(), LanguageWa\date(), Language\date(), LocalFile\decodeRow(), SpecialUndelete\diffHeader(), MemoryFileBackend\doCopyInternal(), MemoryFileBackend\doCreateInternal(), FSFileBackend\doGetFileStat(), SwiftFileBackend\doGetFileStatMulti(), MemoryFileBackend\doStoreInternal(), ApiProtect\execute(), ApiUndelete\execute(), ApiEditPage\execute(), SpecialExport\execute(), PurgeParserCache\execute(), BenchmarkParse\execute(), ApiFeedWatchlist\execute(), UpdateSearchIndex\execute(), LocalFileRestoreBatch\execute(), CacheTime\expired(), User\expirePassword(), HistoryAction\feedEmpty(), FeedUtils\formatDiff(), SpecialUndelete\formatFileRow(), SpecialMergeHistory\formatRevisionRow(), SpecialUndelete\formatRevisionRow(), SpecialProtectedtitles\formatRow(), Block\getAutoblockExpiry(), CacheTime\getCacheTime(), Title\getCascadeProtectionSources(), NewUsersLogFormatter\getComment(), ProtectionForm\getExpiry(), User\getFirstEditTimestamp(), MessageBlobStore\getFromDB(), Language\getHumanTimestamp(), Block\getPermissionsError(), PageArchive\getPreviousRevision(), MockFSFile\getTimestamp(), FSFile\getTimestamp(), RevisionItemBase\getTimestamp(), ForeignAPIFile\getTimestamp(), DatabaseLogEntry\getTimestamp(), RCDatabaseLogEntry\getTimestamp(), ArchivedFile\getTimestamp(), ManualLogEntry\getTimestamp(), WikiPage\getTimestamp(), Revision\getTimestamp(), FileJournal\getTimestampedUUID(), Revision\getTimestampFromId(), Block\initFromRow(), Language\internalUserTimeAndDate(), User\loadDefaults(), RecentChange\loadFromCurRow(), MessageCache\loadFromDB(), WikiPage\loadFromRow(), RecentChange\loadFromRow(), User\loadFromRow(), WikiPage\loadPageData(), SpecialUndelete\loadRequest(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), FormatMetadata\makeFormattedData(), SpecialMergeHistory\merge(), User\newTouchedTimestamp(), SpecialBlock\parseExpiryInput(), WfTimestampTest\provideNormalTimestamps(), WfTimestampTest\provideOldTimestamps(), MWTimestampTest\provideValidTimestamps(), LocalFile\publishTo(), LocalFile\recordUpload2(), WatchedItem\resetNotificationTimestamp(), User\resetPasswordExpiration(), RefreshLinksJob\runForTitle(), ChangesFeed\saveToCache(), WikiPage\setCachedLastEditTime(), WikiPage\setTimestamp(), WikiRevision\setTimestamp(), EditPageTest\testAutoMerge(), MWTimestampTest\testConstructWithNoTimestamp(), WfTimestampTest\testHttpDate(), TitlePermissionTest\testUserBlock(), MWTimestampTest\testValidParse(), Language\time(), Language\timeanddate(), DatabaseBase\timestamp(), ResourceLoader\tryRespondFromFileCache(), and WikiPage\updateIfNewerOn().

◆ TS_ORACLE

const TS_ORACLE 6

Oracle format time.

Definition at line 2462 of file GlobalFunctions.php.

Referenced by MWTimestampTest\provideValidTimestamps(), and DatabaseOracle\timestamp().

◆ TS_POSTGRES

const TS_POSTGRES 7

◆ TS_RFC2822

◆ TS_UNIX

const TS_UNIX 0

Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.

Definition at line 2426 of file GlobalFunctions.php.

Referenced by ApiQueryLogEvents\addLogParams(), SiteStatsUpdate\cacheUpdate(), Autopromote\checkCondition(), User\checkTemporaryPassword(), FileBackendMultiWrite\consistencyCheck(), SqlBagOStuff\deleteObjectsExpiringBefore(), DBFileJournal\doLogChangeBatch(), SpecialActiveUsers\doQueryCacheUpdate(), FileBackendTest\doTestGetFileStat(), RemoveUnusedAccounts\execute(), UploadStashCleanup\execute(), FixTimestamps\execute(), ApiQueryAllUsers\execute(), LocalFileRestoreBatch\execute(), AtomFeed\formatTime(), Block\getAutoblockExpiry(), OutputPage\getJSVars(), MachineReadableRCFeedFormatter\getLine(), SpecialRandomInCategory\getMinAndMaxForCat(), ResourceLoaderUserCSSPrefsModule\getModifiedTime(), ResourceLoaderUserOptionsModule\getModifiedTime(), ResourceLoaderStartUpModule\getModifiedTime(), ResourceLoaderStartUpModule\getModuleRegistrations(), ResourceLoaderModule\getMsgBlobMtime(), User\getPasswordExpired(), JobSpecification\getReleaseTimestamp(), Job\getReleaseTimestamp(), ResourceLoaderWikiModule\getTitleMtimes(), SqlBagOStuff\isExpired(), RecentChange\isInRCLifespan(), User\isPasswordReminderThrottled(), ChangesFeed\loadFromCache(), SpecialActiveUsers\mergeActiveUsers(), ResourceLoader\preloadModuleInfo(), StreamFile\prepareForStream(), WfTimestampTest\provideNormalTimestamps(), WfTimestampTest\provideOldTimestamps(), MWTimestampTest\provideValidTimestamps(), QueryPage\recache(), RefreshLinksJob\runForTitle(), FileBackendStore\setFileCache(), UpdateLogging\sync(), EditPageTest\testAutoMerge(), WfTimestampTest\testTimestampParameter(), IPTC\timeHelper(), ResourceLoader\tryRespondLastModified(), XMPValidate\validateDate(), and wfStreamThumb().