MediaWiki REL1_31
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.
 
 wfAcceptToPrefs ( $accept, $def=' */*')
 Converts an Accept-* header into an array mapping string values to quality factors.
 
 wfAppendQuery ( $url, $query)
 Append a query string to an existing URL, which may or may not already have query string parameters already.
 
 wfAppendToArrayIfNotDefault ( $key, $value, $default, &$changed)
 Appends to second array if $value differs from that in $default.
 
 wfArrayDiff2 ( $a, $b)
 Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
 
 wfArrayDiff2_cmp ( $a, $b)
 
 wfArrayFilter (array $arr, callable $callback)
 Like array_filter with ARRAY_FILTER_USE_BOTH, but works pre-5.6.
 
 wfArrayFilterByKey (array $arr, callable $callback)
 Like array_filter with ARRAY_FILTER_USE_KEY, but works pre-5.6.
 
 wfArrayInsertAfter (array $array, array $insert, $after)
 Insert array into another array after the specified KEY
 
 wfArrayPlus2d (array $baseArray, array $newValues)
 Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
 
 wfArrayToCgi ( $array1, $array2=null, $prefix='')
 This function takes one or two arrays as input, and returns a CGI-style string, e.g.
 
 wfAssembleUrl ( $urlParts)
 This function will reassemble a URL parsed with wfParseURL.
 
 wfBacktrace ( $raw=null)
 Get a debug backtrace as a string.
 
 wfBaseName ( $path, $suffix='')
 Return the final portion of a pathname.
 
 wfBCP47 ( $code)
 Get the normalised IETF language tag See unit test for examples.
 
 wfBoolToStr ( $value)
 Convenience function converts boolean values into "true" or "false" (string) values.
 
 wfCanIPUseHTTPS ( $ip)
 Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
 
 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.
 
 wfClearOutputBuffers ()
 More legible than passing a 'false' parameter to wfResetOutputBuffers():
 
 wfClientAcceptsGzip ( $force=false)
 Whether the client accept gzip encoding.
 
 wfConfiguredReadOnlyReason ()
 Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
 
 wfCountDown ( $seconds)
 Count down from $seconds to zero on the terminal, with a one-second pause between showing each number.
 
 wfDebug ( $text, $dest='all', array $context=[])
 Sends a line to the debug log if enabled or, optionally, to a comment in output.
 
 wfDebugBacktrace ( $limit=0)
 Safety wrapper for debug_backtrace().
 
 wfDebugLog ( $logGroup, $text, $dest='all', array $context=[])
 Send a line to a supplementary debug log file, if configured, or main debug log if not.
 
 wfDebugMem ( $exact=false)
 Send a line giving PHP memory usage.
 
 wfDeprecated ( $function, $version=false, $component=false, $callerOffset=2)
 Throws a warning that $function is deprecated.
 
 wfDiff ( $before, $after, $params='-u')
 Returns unified plain-text diff of two texts.
 
 wfErrorLog ( $text, $file, array $context=[])
 Log to a file without getting "file size exceeded" signals.
 
 wfEscapeShellArg ()
 Version of escapeshellarg() that works better on Windows.
 
 wfEscapeWikiText ( $text)
 Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
 
 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.
 
 wfExpandIRI_callback ( $matches)
 Private callback for wfExpandIRI.
 
 wfExpandUrl ( $url, $defaultProto=PROTO_CURRENT)
 Expand a potentially local URL to a fully-qualified URL.
 
 wfFindFile ( $title, $options=[])
 Find a file.
 
 wfForeignMemcKey ( $db, $prefix)
 Make a cache key for a foreign DB.
 
 wfFormatStackFrame ( $frame)
 Return a string representation of frame.
 
 wfGetAllCallers ( $limit=3)
 Return a string consisting of callers in the stack.
 
 wfGetCache ( $cacheType)
 Get a specific cache object.
 
 wfGetCaller ( $level=2)
 Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie.
 
 wfGetDB ( $db, $groups=[], $wiki=false)
 Get a Database object.
 
 wfGetLangObj ( $langcode=false)
 Return a Language object from $langcode.
 
 wfGetLB ( $wiki=false)
 Get a load balancer object.
 
 wfGetLBFactory ()
 Get the load balancer factory object.
 
 wfGetMainCache ()
 Get the main cache object.
 
 wfGetMessageCacheStorage ()
 Get the cache object used by the message cache.
 
 wfGetNull ()
 Get a platform-independent path to the null file, e.g.
 
 wfGetParserCacheStorage ()
 Get the cache object used by the parser cache.
 
 wfGetPrecompiledData ( $name)
 Get an object from the precompiled serialized directory.
 
 wfGetRusage ()
 Get system resource usage of current request context.
 
 wfGetScriptUrl ()
 Get the script URL.
 
 wfGlobalCacheKey ()
 Make a cache key with database-agnostic prefix.
 
 wfHostname ()
 Fetch server name for use in error reporting etc.
 
 wfHttpError ( $code, $label, $desc)
 Provide a simple HTTP error.
 
 wfIncrStats ( $key, $count=1)
 Increment a statistics counter.
 
 wfIniGetBool ( $setting)
 Safety wrapper around ini_get() for boolean settings.
 
 wfInitShellLocale ()
 Formerly set the locale for locale-sensitive operations.
 
 wfIsBadImage ( $name, $contextTitle=false, $blacklist=null)
 Determine if an image exists on the 'bad image list'.
 
 wfIsCLI ()
 Check if we are running from the commandline.
 
 wfIsDebugRawPage ()
 Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
 
 wfIsHHVM ()
 Check if we are running under HHVM.
 
 wfIsInfinity ( $str)
 Determine input string is represents as infinity.
 
 wfIsWindows ()
 Check if the operating system is Windows.
 
 wfLoadExtension ( $ext, $path=null)
 Load an extension.
 
 wfLoadExtensions (array $exts)
 Load multiple extensions at once.
 
 wfLoadSkin ( $skin, $path=null)
 Load a skin.
 
 wfLoadSkins (array $skins)
 Load multiple skins at once.
 
 wfLocalFile ( $title)
 Get an object referring to a locally registered file.
 
 wfLogDBError ( $text, array $context=[])
 Log for database errors.
 
 wfLogProfilingData ()
 
 wfLogWarning ( $msg, $callerOffset=1, $level=E_USER_WARNING)
 Send a warning as a PHP error and the debug log.
 
 wfMakeUrlIndexes ( $url)
 Make URL indexes, appropriate for the el_index field of externallinks.
 
 wfMatchesDomainList ( $url, $domains)
 Check whether a given URL has a domain that occurs in a given set of domains.
 
 wfMemcKey ()
 Make a cache key for the local wiki.
 
 wfMemoryLimit ()
 Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit.
 
 wfMerge ( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
 wfMerge attempts to merge differences between three texts.
 
 wfMergeErrorArrays ()
 Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g.
 
 wfMessage ( $key)
 This is the function for getting translated interface messages.
 
 wfMessageFallback ()
 This function accepts multiple message keys and returns a message instance for the first message which is non-empty.
 
 wfMkdirParents ( $dir, $mode=null, $caller=null)
 Make directory, and make all parent directories if they don't exist.
 
 wfMsgReplaceArgs ( $message, $args)
 Replace message parameter keys on the given formatted output.
 
 wfNegotiateType ( $cprefs, $sprefs)
 Returns the 'best' match between a client's requested internet media types and the server's list of available types.
 
 wfObjectToArray ( $objOrArray, $recursive=true)
 Recursively converts the parameter (an object) to an array with the same data.
 
 wfParseUrl ( $url)
 parse_url() work-alike, but non-broken.
 
 wfPercent ( $nr, $acc=2, $round=true)
 
 wfQueriesMustScale ()
 Should low-performance queries be disabled?
 
 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.
 
 wfRandomString ( $length=32)
 Get a random string containing a number of pseudo-random hex characters.
 
 wfReadOnly ()
 Check whether the wiki is in read-only mode.
 
 wfReadOnlyReason ()
 Check if the site is in read-only mode and return the message if so.
 
 wfRecursiveRemoveDir ( $dir)
 Remove a directory and all its content.
 
 wfRelativePath ( $path, $from)
 Generate a relative path name to the given file.
 
 wfRemoveDotSegments ( $urlPath)
 Remove all dot-segments in the provided URL path.
 
 wfReportTime ()
 Returns a script tag that stores the amount of time it took MediaWiki to handle the request in milliseconds as 'wgBackendResponseTime'.
 
 wfResetOutputBuffers ( $resetGzipEncoding=true)
 Clear away any user-level output buffers, discarding contents.
 
 wfResetSessionID ()
 Reset the session id.
 
 wfRestoreWarnings ()
 
 wfRunHooks ( $event, array $args=[], $deprecatedVersion=null)
 Call hook functions defined in $wgHooks.
 
 wfScript ( $script='index')
 Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScriptPath etc.
 
 wfSetBit (&$dest, $bit, $state=true)
 As for wfSetVar except setting a bit.
 
 wfSetupSession ( $sessionId=false)
 Initialise php session.
 
 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.
 
 wfShellExec ( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
 Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported.
 
 wfShellExecDisabled ()
 Check if wfShellExec() is effectively disabled via php.ini config.
 
 wfShellExecWithStderr ( $cmd, &$retval=null, $environ=[], $limits=[])
 Execute a shell command, returning both stdout and stderr.
 
 wfShellWikiCmd ( $script, array $parameters=[], array $options=[])
 Generate a shell-escaped command line string to run a MediaWiki cli script.
 
 wfShorthandToInteger ( $string='', $default=-1)
 Converts shorthand byte notation to integer form.
 
 wfShowingResults ( $offset, $limit)
 
 wfSplitWikiID ( $wiki)
 Split a wiki ID into DB name and table prefix.
 
 wfStringToBool ( $val)
 Convert string value to boolean, when the following are interpreted as true:
 
 wfStripIllegalFilenameChars ( $name)
 Replace all invalid characters with '-'.
 
 wfSuppressWarnings ( $end=false)
 Reference-counted warning suppression.
 
 wfTempDir ()
 Tries to get the system directory for temporary files.
 
 wfThumbIsStandard (File $file, array $params)
 Returns true if these thumbnail parameters match one that MediaWiki requests from file description pages and/or parser output.
 
 wfTimestamp ( $outputtype=TS_UNIX, $ts=0)
 Get a timestamp string in one of various formats.
 
 wfTimestampNow ()
 Convenience function; returns MediaWiki timestamp for the present time.
 
 wfTimestampOrNull ( $outputtype=TS_UNIX, $ts=null)
 Return a formatted timestamp, or null if input is null.
 
 wfTransactionalTimeLimit ()
 Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit.
 
 wfUnpack ( $format, $data, $length=false)
 Wrapper around php's unpack.
 
 wfUrlencode ( $s)
 We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
 
 wfUrlProtocols ( $includeProtocolRelative=true)
 Returns a regular expression of url protocols.
 
 wfUrlProtocolsWithoutProtRel ()
 Like wfUrlProtocols(), but excludes '//' from the protocol list.
 
 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.
 
 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.
 
 wfVarDump ( $var)
 A wrapper around the PHP function var_export().
 
 wfWaitForSlaves ( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
 Waits for the replica DBs to catch up to the master position.
 
 wfWarn ( $msg, $callerOffset=1, $level=E_USER_NOTICE)
 Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
 
 wfWikiID ()
 Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
 

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 )

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
Access:\n private

Definition at line 1890 of file GlobalFunctions.php.

References $type.

Referenced by GlobalTest\testMimeTypeMatch(), and wfNegotiateType().

◆ 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 1854 of file GlobalFunctions.php.

◆ wfAppendQuery()

◆ wfAppendToArrayIfNotDefault()

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

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

Parameters
string | int$key
mixed$value
mixed$default
array&$changedArray to alter
Exceptions
MWException

Definition at line 183 of file GlobalFunctions.php.

References $value.

◆ wfArrayDiff2()

wfArrayDiff2 ( $a,
$b )

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

Parameters
array$a
array$b
Returns
array

Definition at line 111 of file GlobalFunctions.php.

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

◆ wfArrayDiff2_cmp()

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

Definition at line 120 of file GlobalFunctions.php.

References key.

◆ wfArrayFilter()

wfArrayFilter ( array $arr,
callable $callback )

Like array_filter with ARRAY_FILTER_USE_BOTH, but works pre-5.6.

Parameters
array$arr
callable$callbackWill be called with the array value and key (in that order) and should return a bool which will determine whether the array element is kept.
Returns
array

Definition at line 150 of file GlobalFunctions.php.

Referenced by WfArrayFilterTest\testWfArrayFilter(), and wfArrayFilterByKey().

◆ wfArrayFilterByKey()

wfArrayFilterByKey ( array $arr,
callable $callback )

Like array_filter with ARRAY_FILTER_USE_KEY, but works pre-5.6.

Parameters
array$arr
callable$callbackWill be called with the array key and should return a bool which will determine whether the array element is kept.
Returns
array

Definition at line 168 of file GlobalFunctions.php.

References wfArrayFilter().

Referenced by MediaWiki\Shell\Command\execute(), SpecialNewpages\formatRow(), ContribsPager\formatRow(), DeletedContribsPager\formatRow(), EnhancedChangesList\getLineData(), HistoryPager\historyLine(), LogEventsList\logLine(), EnhancedChangesList\recentChangesBlockLine(), OldChangesList\recentChangesLine(), and WfArrayFilterTest\testWfArrayFilterByKey().

◆ 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.
mixed$afterThe key to insert after
Returns
array

Definition at line 238 of file GlobalFunctions.php.

References $keys, and $output.

Referenced by ApiComparePages\getAllowedParams(), DeletedContributionsPage\getSubTitle(), and UpdateExtensionJsonSchema\updateTo2().

◆ wfArrayPlus2d()

wfArrayPlus2d ( array $baseArray,
array $newValues )

Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).

Values that exist in both values will be combined with += (all values of the array of $newValues will be added to the values of the array of $baseArray, while values, that exists in both, the value of $baseArray will be used).

Parameters
array$baseArrayThe array where you want to add the values of $newValues to
array$newValuesAn array with new values
Returns
array The combined array
Since
1.26

Definition at line 3427 of file GlobalFunctions.php.

References $name.

Referenced by HTMLUserTextField\__construct(), ExtensionRegistry\exportExtractedData(), GadgetDefinitionContent\getAssocArray(), and WfArrayPlus2dTest\testWfArrayPlus2d().

◆ wfArrayToCgi()

◆ 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 (see T34168)
Since
1.19
Parameters
array$urlPartsURL parts, as output from wfParseUrl
Returns
string URL assembled from its component parts

Definition at line 597 of file GlobalFunctions.php.

References $result.

Referenced by WfAssembleUrlTest\testWfAssembleUrl(), and wfExpandUrl().

◆ wfBacktrace()

wfBacktrace ( $raw = null)

Get a debug backtrace as a string.

Parameters
bool | null$rawIf true, the return value is plain text. If false, HTML. Defaults to $wgCommandLineMode if unset.
Returns
string
Since
1.25 Supports $raw parameter.

Definition at line 1510 of file GlobalFunctions.php.

References $line, $wgCommandLineMode, and wfDebugBacktrace().

Referenced by MWDebug\deprecated(), and MediaWiki\Storage\RevisionStore\getTitle().

◆ wfBaseName()

wfBaseName ( $path,
$suffix = '' )

Return the final portion of a pathname.

Reimplemented because PHP5's "basename()" is buggy with multibyte text. https://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$suffixString to remove if present
Returns
string

Definition at line 2579 of file GlobalFunctions.php.

References $matches.

Referenced by Exif\__construct(), ImageBuilder\checkMissingImage(), TestFileOpPerformance\doPerfTest(), ImportImages\execute(), WfBaseNameTest\testBaseName(), wfRelativePath(), and wfStripIllegalFilenameChars().

◆ wfBCP47()

wfBCP47 ( $code)

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

See mediawiki.language.bcp47 for the JavaScript implementation.

Deprecated
since 1.31, use LanguageCode::bcp47() directly.
Parameters
string$codeThe language code.
Returns
string The language code which complying with BCP 47 standards.

Definition at line 3128 of file GlobalFunctions.php.

References $code.

◆ wfBoolToStr()

wfBoolToStr ( $value)

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

Parameters
bool$value
Returns
string

Definition at line 2931 of file GlobalFunctions.php.

References $value.

Referenced by ApiRsd\formatRsdApiList(), 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
bool

Definition at line 3308 of file GlobalFunctions.php.

Referenced by LoginSignupSpecialPage\execute(), MediaWiki\Preferences\DefaultPreferencesFactory\getFormDescriptor(), 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 422 of file GlobalFunctions.php.

References $keys, $query, $ret, $value, and list.

Referenced by SkinTemplate\buildPersonalUrls(), Linker\link(), Linker\makeBrokenImageLinkObj(), SpecialChangeEmail\onSuccess(), OutputPage\returnToMain(), LoginHelper\showReturnToPage(), MediaWiki\Storage\SqlBlobStore\splitBlobAddress(), SpecialCreateAccount\successfulAction(), GlobalTest\testCgiRoundTrip(), and GlobalTest\testCgiToArray().

◆ 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 1842 of file GlobalFunctions.php.

References wfResetOutputBuffers().

Referenced by ApiMain\checkConditionalRequestHeaders(), and OutputPage\checkLastModified().

◆ wfClientAcceptsGzip()

wfClientAcceptsGzip ( $force = false)

Whether the client accept gzip encoding.

Uses the Accept-Encoding header to check if the client supports gzip encoding. Use this when considering to send a gzip-encoded response to the client.

Parameters
bool$forceForces another check even if we already have a cached result.
Returns
bool

Definition at line 1609 of file GlobalFunctions.php.

References $result, and wfDebug().

Referenced by MediaWiki\OutputHandler\handleGzip(), HTMLFileCache\loadFromFileCache(), HTMLFileCache\saveToFileCache(), and GlobalTest\testClientAcceptsGzipTest().

◆ wfConfiguredReadOnlyReason()

wfConfiguredReadOnlyReason ( )

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

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

Definition at line 1286 of file GlobalFunctions.php.

Referenced by FileBackendGroup\initFromGlobals(), and JobQueueGroup\singleton().

◆ 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.

Deprecated
since 1.31, use Maintenance::countDown()
Parameters
int$seconds

Definition at line 3005 of file GlobalFunctions.php.

◆ wfDebug()

wfDebug ( $text,
$dest = 'all',
array $context = [] )

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.

Since
1.25 support for additional context data
Parameters
string$text
string | bool$destDestination of the message:
  • 'all': both to the log and HTML (debug toolbar or HTML comments)
  • 'private': excluded from HTML output For backward compatibility, it can also take a boolean:
  • true: same as 'all'
  • false: same as 'private'
array$contextAdditional logging context data

Definition at line 994 of file GlobalFunctions.php.

References $context, $wgDebugLogPrefix, $wgDebugRawPage, $wgDebugTimestamps, and wfIsDebugRawPage().

Referenced by Parser\__construct(), ApiMain\__construct(), DifferenceEngine\__construct(), SearchUpdate\__construct(), UploadStashFile\__construct(), PageArchive\__construct(), UploadFromStash\__construct(), QuickTemplate\__construct(), UploadFromChunks\__construct(), StubObject\_unstub(), LogPage\actionText(), ImageGalleryBase\add(), ParserTestRunner\addArticle(), MediaHandler\addMeta(), LinkBatch\addObj(), LocalFileMoveBatch\addOlds(), ParserOutput\addTrackingCategory(), Skin\afterContentHook(), Parser\braceSubstitution(), SkinTemplate\buildContentActionUrls(), SimpleCaptcha\buildRegexes(), EmailNotification\canSendUserTalkEmail(), CategoryTree\capDepth(), AjaxResponse\checkLastModified(), OutputPage\checkLastModified(), UploadBase\checkSvgScriptCallback(), UploadBase\checkXMLEncodingMissmatch(), JobQueueDB\claimOldest(), LocalRepo\cleanupDeletedBatch(), UploadBase\cleanupTempFile(), SpecialEditWatchlist\cleanupWatchlist(), UploadStash\clear(), CloneDatabase\cloneTableStructure(), MediaWiki\Storage\SqlBlobStore\compressData(), UploadFromChunks\concatenateChunks(), Article\confirmDelete(), SimpleCaptcha\confirmEditMerged(), SimpleCaptcha\confirmEmailUser(), DjVuImage\convertDumpToXML(), UploadBase\createFromRequest(), WikiImporter\debug(), SVGReader\debug(), RecompressTracked\debug(), SectionProfiler\debug(), BaseDump\debug(), Block\defaultRetroactiveAutoblock(), Article\delete(), Block\deleteIfExpired(), User\deleteNewtalk(), ChangeTags\deleteTagEverywhere(), UploadBase\detectScript(), UploadBase\detectVirus(), DiffEngine\diffInternal(), Parser\disableCache(), BitmapMetadataHandler\doApp13(), Block\doAutoblock(), JobQueueDB\doBatchPushInternal(), SimpleCaptcha\doConfirmEdit(), WikiPage\doDeleteArticleReal(), WikiPage\doEditUpdates(), MockImageHandler\doFakeTransform(), WikiFilePage\doPurge(), DatabaseOracle\doQuery(), Block\doRetroactiveAutoblock(), UserrightsPage\doSaveUserGroups(), PdfHandler\doTransform(), DjVuHandler\doTransform(), TransformationalImageHandler\doTransform(), EditPage\edit(), ZipDirectoryReader\error(), ChangesFeed\execute(), SpecialUpload\execute(), SpecialUserLogout\execute(), ApiUpload\execute(), LocalFileRestoreBatch\execute(), DjVuHandler\extractTreesFromMetadata(), PoolWorkArticleView\fallback(), Article\fetchContentObject(), IcuCollation\fetchFirstLetterData(), MediaWikiGadgetsDefinitionRepo\fetchStructuredList(), DiffEngine\find_middle_snake(), BlockLevelPass\findColonNoLinks(), WikiImporter\finishImportPage(), FormatMetadata\flattenArrayReal(), ContribsPager\formatRow(), DeletedContribsPager\formatRow(), FileRepo\freeTemp(), ParserCache\get(), LCStoreCDB\get(), MediaWiki\Interwiki\ClassicInterwikiLookup\getAllPrefixesCached(), User\getBlockedStatus(), CoreParserFunctions\getCachedRevisionObject(), PoolWorkArticleView\getCachedWork(), Action\getContext(), ContextSource\getContext(), Article\getContext(), Profiler\getContext(), SpecialPage\getContext(), SpecialVersion\getCreditsForExtension(), File\getDescriptionText(), ForeignDBFile\getDescriptionText(), UploadStash\getFile(), DoubleRedirectJob\getFinalDestination(), WikiFilePage\getForeignCategories(), GenderCache\getGenderOf(), MediaHandlerFactory\getHandler(), DjVuImage\getInfo(), SpecialUpload\getInitialPageText(), MediaWiki\Interwiki\ClassicInterwikiLookup\getInterwikiCacheEntry(), ParserCache\getKey(), TransformationalImageHandler\getMagickVersion(), RequestContext\getMainAndWarn(), PdfHandler\getMetaArray(), SvgHandler\getMetadata(), GIFMetadataExtractor\getMetadata(), PNGMetadataExtractor\getMetadata(), GIFHandler\getMetadata(), JpegHandler\getMetadata(), PNGHandler\getMetadata(), TiffHandler\getMetadata(), DjVuHandler\getMetadata(), DjVuHandler\getMetaTree(), DjVuImage\getMultiPageInfo(), WebRequestUpload\getName(), Title\getNsText(), DjVuImage\getPageInfo(), WikiPage\getParserOutput(), SpecialEmailUser\getPermissionsError(), EditPage\getPreloadedContent(), UserCache\getProp(), Title\getRestrictionTypes(), ExternalStoreDB\getSlave(), SpecialEmailUser\getTarget(), ForeignAPIRepo\getThumbError(), ForeignAPIRepo\getThumbUrl(), UploadStashFile\getThumbUrl(), ForeignAPIRepo\getThumbUrlFromCache(), Title\getTitleValue(), Parser\getUserSig(), Parser\getVariableValue(), File\getViewURL(), XCFHandler\getXCFMetaData(), VersionChecker\handleExtensionDependency(), MediaWiki\OutputHandler\handleGzip(), OutputPage\haveCacheVaryCookies(), ThumbnailRenderJob\hitThumbUrl(), ForeignAPIRepo\httpGet(), EditPage\importFormData(), WikiRevision\importLogItem(), SimpleCaptcha\injectEmailUser(), Block\insert(), ExternalStore\insertWithFallback(), EditPage\internalAttemptSave(), User\isBlockedFrom(), FileCacheBase\isCacheGood(), MediaWiki\Shell\Shell\isDisabled(), PdfHandler\isEnabled(), DjVuHandler\isEnabled(), SvgHandler\isEnabled(), LocalisationCache\isExpired(), Block\isExpired(), FileDependency\isExpired(), ExifBitmapHandler\isMetadataValid(), GIFHandler\isMetadataValid(), PNGHandler\isMetadataValid(), WebPHandler\isMetadataValid(), Title\isValidMoveTarget(), MovePage\isValidMoveTarget(), Block\isWhitelistedFromAutoblocks(), FancyCaptcha\keyMatch(), MessageCache\load(), SiteStats\loadAndLazyInit(), ChangesFeed\loadFromCache(), User\loadFromCache(), HTMLFileCache\loadFromFileCache(), AjaxResponse\loadFromMemcached(), User\loadFromSession(), User\loadOptions(), Linker\makeExternalImage(), Linker\makeExternalLink(), Linker\makeImageLink(), Linker\makeMediaLinkFile(), SimpleCaptcha\needCreateAccountCaptcha(), ImportStreamSource\newFromURL(), WikiImporter\notice(), RawAction\onView(), UploadDumper\outputItem(), ApiBase\parseMsg(), SearchMySQL\parseQuery(), SearchSqlite\parseQuery(), SearchPostgres\parseQuery(), BacklinkCache\partition(), DiffHistoryBlob\patch(), AjaxDispatcher\performAction(), ApiUpload\performStash(), FancyCaptcha\pickImageDir(), FancyCaptcha\pickImageFromDir(), MediaWiki\preOutputCommit(), SkinTemplate\prepareQuickTemplate(), SpecialUpload\processUpload(), LocalFile\purgeThumbList(), BacklinkCache\queryLinks(), SvgHandler\rasterize(), TextPassDumper\readDump(), LocalisationCache\recache(), LocalFile\recordUpload2(), Cite\recursiveFetchRefsFromDB(), UploadStash\removeFileNoAuth(), Parser\renderImageGallery(), WikiPage\replaceSectionAtRev(), Parser\replaceVariables(), MediaWiki\restInPeace(), DjVuImage\retrieveMetaData(), BitmapHandler\rotate(), JpegHandler\rotate(), DoubleRedirectJob\run(), ThumbnailRenderJob\run(), ParserTestRunner\runTest(), ParserCache\save(), FileCacheBase\saveText(), HTMLFileCache\saveToFileCache(), SearchPostgres\searchQuery(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), OutputPage\sendCacheControl(), UserMailer\sendInternal(), UserMailer\sendWithPear(), ApiMain\setCacheMode(), LanguageClassesTestCase\setUp(), ParserTestTopLevelSuite\setUp(), SimpleCaptcha\shouldCheck(), ViewAction\show(), LocalRepo\skipWriteOperationIfSha1(), User\spreadBlock(), UploadStash\stashFile(), FileRepo\storeBatch(), ParserTestTopLevelSuite\tearDown(), ParserTestRunner\teardownDatabase(), GlobalTest\testDebugFunctionTest(), ApiUploadTest\testUploadChunks(), WikiImporter\throwXmlError(), MediaWiki\Tidy\RaggettBase\tidy(), MediaWiki\Tidy\RemexDriver\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(), User\updateNewtalk(), LocalFile\upgradeRow(), OldLocalFile\upgradeRow(), HTMLFileCache\useFileCache(), MediaWiki\Storage\RevisionRecord\userCanBitfield(), LogEventsList\userCanBitfield(), SpecialEmailUser\validateTarget(), ImageHandler\validateThumbParams(), UploadBase\verifyExtension(), UploadBase\verifyFile(), UploadBase\verifyMimeType(), Article\view(), WikiImporter\warn(), wfClientAcceptsGzip(), wfDebugBacktrace(), wfDebugMem(), wfDiff(), wfGetLangObj(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfRecursiveRemoveDir(), and wfTimestamp().

◆ wfDebugBacktrace()

wfDebugBacktrace ( $limit = 0)

Safety wrapper for debug_backtrace().

Will return an empty array 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 Array of backtrace information

Definition at line 1482 of file GlobalFunctions.php.

References wfDebug().

Referenced by MWDebug\getCallerDescription(), wfBacktrace(), wfGetAllCallers(), and wfGetCaller().

◆ wfDebugLog()

wfDebugLog ( $logGroup,
$text,
$dest = 'all',
array $context = [] )

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. Sampled log events will be emitted with a 1 in N random chance.

Since
1.23 support for sampling log messages via $wgDebugLogGroups.
1.25 support for additional context data
1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
Parameters
string$logGroup
string$text
string | bool$destDestination of the message:
  • 'all': both to the log and HTML (debug toolbar or HTML comments)
  • 'private': only to the specific 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'
array$contextAdditional logging context data

Definition at line 1087 of file GlobalFunctions.php.

References $context.

Referenced by LocalisationCache\__construct(), GitInfo\__construct(), MediaWikiPHPUnitTestListener\addError(), MediaWikiPHPUnitTestListener\addFailure(), MediaWikiPHPUnitTestListener\addIncompleteTest(), MediaWikiPHPUnitTestListener\addSkippedTest(), AutoLoader\autoload(), ExternalStoreDB\batchFetchBlobs(), RCCacheEntryFactory\buildCLink(), RCCacheEntryFactory\buildDiffLink(), SpamRegexBatch\buildSafeRegexes(), BaseBlacklist\buildSharedBlacklists(), ApiMain\checkBotReadOnly(), EmailBlacklist\checkUser(), BaseBlacklist\clearCache(), UploadFromChunks\concatenateChunks(), IPTC\convIPTCHelper(), Exif\debug(), RenameuserSQL\debug(), ParserTestTopLevelSuite\debug(), Exif\debugFile(), SectionProfiler\debugGroup(), WebPHandler\decodeLosslessChunkHeader(), WebPHandler\decodeLossyChunkHeader(), JobQueueRedis\doAck(), JobQueueRedis\doBatchPush(), FileBackendMultiWrite\doOperationsInternal(), JobQueueRedis\doPop(), PdfHandler\doTransform(), DjVuHandler\doTransform(), SvgHandler\doTransform(), TransformationalImageHandler\doTransform(), MediaWikiPHPUnitTestListener\endTest(), MediaWikiPHPUnitTestListener\endTestSuite(), LocalFileMoveBatch\execute(), CheckUsernames\execute(), WebPHandler\extractMetadata(), WebPHandler\extractMetadataFromChunks(), PoolWorkArticleView\fallback(), ExternalStoreDB\fetchBlob(), SpamBlacklist\filter(), FormatMetadata\formatCoords(), Message\formatListParam(), DifferenceEngine\generateTextDiffBody(), ParserCache\get(), BaseBlacklist\getArticleText(), IPTC\getCharset(), LocalisationCache\getCompiledPluralRules(), ResourceLoaderWikiModule\getContentObj(), ContentHandler\getContentText(), EditPage\getContextTitle(), ContentHandler\getForModelID(), BaseBlacklist\getHttpText(), ResourceLoaderImage\getImageData(), ParserCache\getKey(), RequestContext\getLanguage(), LocalFileMoveBatch\getMoveTriplets(), BaseBlacklist\getSharedBlacklists(), ResourceLoaderFileModule\getTemplates(), RequestContext\getTitle(), WebResponse\header(), CdnCacheUpdate\HTCPPurge(), User\inDnsBlacklist(), CreatePdfThumbnailsJob\insertJobs(), ExternalStore\insertWithFallback(), EditPage\internalAttemptSave(), User\isCreatableName(), MessageCache\load(), TitleBlacklist\load(), MessageCache\loadFromDB(), SimpleCaptcha\log(), SquidPurgeClient\log(), ReCaptchaNoCaptcha\logCheckError(), MWLBFactory\logDeprecation(), PoolCounterWork\logError(), MediaHandler\logErrorForExternalProcess(), JobQueueFederated\logException(), ApiBase\logFeatureUsage(), ApiMain\logRequest(), SpamBlacklist\logUrlChange(), Parser\makeLimitReport(), TitleBlacklistEntry\matches(), ApiMain\matchRequestedHeaders(), MediaWiki\maybeDoHttpsRedirect(), LocalFile\move(), MediaWiki\Site\MediaWikiPageNameNormalizer\normalizePageName(), IPTC\parse(), MessageCache\parse(), GitInfo\precomputeValues(), MediaWiki\preOutputCommit(), CdnCacheUpdate\purge(), ResourceLoaderFileModule\readStyleFile(), UploadFromUrl\reallyFetchFile(), MediaHandler\removeBadFile(), LocalFileMoveBatch\removeNonexistentFiles(), FileBackendMultiWrite\resyncFiles(), CreatePdfThumbnailsJob\run(), RenameUserJob\run(), SquidPurgeClientPool\run(), ResourceLoaderModule\saveFileDependencies(), UploadFromUrl\saveTempFileChunk(), MWDebug\sendMessage(), WebResponse\setCookie(), MediaWikiPHPUnitTestListener\startTest(), MediaWikiPHPUnitTestListener\startTestSuite(), WebResponse\statusHeader(), IPTC\timeHelper(), and SpamBlacklistHooks\validate().

◆ wfDebugMem()

wfDebugMem ( $exact = false)

Send a line giving PHP memory usage.

Parameters
bool$exactPrint exact byte values instead of kibibytes (default: false)

Definition at line 1052 of file GlobalFunctions.php.

References wfDebug().

Referenced by GlobalTest\testDebugFunctionTest().

◆ wfDeprecated()

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

Throws a warning that $function is deprecated.

Parameters
string$function
string | bool$versionVersion of MediaWiki that the function was deprecated in (Added in 1.19).
string | bool$componentAdded in 1.19.
int$callerOffsetHow far up the call stack is the original caller. 2 = function that called the function that called wfDeprecated (Added in 1.20)
Returns
null

Definition at line 1123 of file GlobalFunctions.php.

Referenced by MailAddress\__construct(), ApiResult\__construct(), UsageException\__construct(), Block\__construct(), LoginForm\__construct(), MediaWiki\Widget\Search\SimpleSearchResultWidget\__construct(), MediaWiki\Widget\Search\SimpleSearchResultSetWidget\__construct(), DeprecatedGlobal\_newObject(), ApiQueryLogEvents\addLogParams(), MediaWiki\Session\SessionManager\autoCreateUser(), Job\batchInsert(), buildHeadItem(), Hooks\callHook(), LoginForm\clearCreateaccountToken(), LoginForm\clearLoginThrottle(), LoginForm\clearLoginToken(), codepointToUtf8(), ConfirmEditHooks\confirmEditSetup(), User\createNew(), Preferences\datetimePreferences(), ApiBase\dieUsage(), ApiBase\dieUsageMsg(), ApiBase\dieUsageMsgOrDebug(), Article\doEditContent(), Preferences\editingPreferences(), OutputPage\enableSectionEditLinks(), Maintenance\error(), Title\escapeFragmentForURL(), Sanitizer\escapeIdReferenceList(), escapeSingleString(), FancyCaptcha\estimateCaptchaCount(), Revision\fetchRevision(), Preferences\filesPreferences(), SpecialRecentChanges\filterByCategories(), Title\fixUrlQueryArgs(), DummyLinker\formatSize(), Linker\formatSize(), DummyLinker\formatTemplates(), Linker\formatTemplates(), Preferences\generateSkinOptions(), UsageException\getCodeString(), ApiUsageException\getCodeString(), LoginForm\getCreateaccountToken(), ParserOptions\getEditSection(), ParserOutput\getEditSectionTokens(), DifferenceEngine\getEngine(), ApiBase\getErrorFromStatus(), HTMLForm\getErrors(), LoginSignupSpecialPage\getFakeTemplate(), ApiBase\getFinalDescription(), ApiBase\getFinalSummary(), Message\getFormat(), ReCaptcha\getFormInformation(), User\getGroupMember(), User\getGroupName(), User\getGroupPage(), ActorMigration\getInsertValuesWithTempTable(), DateFormatter\getInstance(), ApiPageSet\getInvalidTitles(), JsonContent\getJsonData(), MWLBFactory\getLBFactoryClass(), DummyLinker\getLinkColour(), Linker\getLinkColour(), MWExceptionHandler\getLogId(), LoginForm\getLoginToken(), UsageException\getMessageArray(), ApiUsageException\getMessageArray(), SpecialPageFactory\getPage(), Revision\getRawComment(), Revision\getRawUser(), Revision\getRawUserText(), Title\getSkinFromCssJsSubpage(), MediaHandler\getStreamHeaders(), File\getStreamHeaders(), StripState\getSubState(), SpecialEmailUser\getTarget(), SpecialPage\getTitle(), ParserOutput\getTOCEnabled(), hexSequenceToUtf8(), MediaWikiTestCase\hideDeprecated(), LoginForm\incLoginThrottle(), LoginForm\incrementLoginThrottle(), Job\insert(), CommentStore\insertWithTempTable(), Title\isCssJsSubpage(), Title\isCssOrJsPage(), Title\isCssSubpage(), Title\isJsSubpage(), User\isLocallyBlockedProxy(), EditPage\isOouiEnabled(), Parser\isValidHalfParsedText(), ParserOptions\legacyOptions(), Linker\link(), Revision\loadFromId(), User\makeGroupLinkHTML(), User\makeGroupLinkWiki(), StripState\merge(), SkinTemplate\outputPage(), Revision\pageJoinCond(), ApiBase\parseMsg(), OutputPage\parserOptions(), prepare(), WikiPage\prepareContentForEdit(), ApiBase\profileDBIn(), ApiBase\profileDBOut(), Preferences\profilePreferences(), Preferences\rcPreferences(), ExtensionRegistry\readFromQueue(), ResourceLoaderFileModule\readStyleFiles(), Preferences\renderingPreferences(), ApiBase\safeProfileOut(), Preferences\searchPreferences(), OutputPage\sectionEditLinksEnabled(), Revision\selectArchiveFields(), Block\selectFields(), RecentChange\selectFields(), ArchivedFile\selectFields(), LocalFile\selectFields(), OldLocalFile\selectFields(), WikiPage\selectFields(), Revision\selectFields(), User\selectFields(), Revision\selectPageFields(), Revision\selectTextFields(), Revision\selectUserFields(), Parser\serializeHalfParsedText(), MediaWikiI18N\set(), LoginForm\setCreateaccountToken(), ParserOptions\setEditSection(), ParserOutput\setEditSectionTokens(), DeferredUpdates\setImmediateMode(), LoginForm\setLoginToken(), QuickTemplate\setRef(), ParserOutput\setTOCEnabled(), QuickTemplate\setTranslator(), ApiBase\setWarning(), ParserOptions\setWrapOutputClass(), MimeMagic\singleton(), Preferences\skinPreferences(), UploadFromChunks\stashFile(), UploadBase\stashFileGetKey(), UploadFromChunks\stashFileGetKey(), UploadBase\stashSession(), UploadFromChunks\stashSession(), EditPage\submit(), SpecialEmailUser\submit(), MediaWikiI18N\translate(), Parser\unserializeHalfParsedText(), EmailNotification\updateWatchlistTimestamp(), Revision\userJoinCond(), utf8ToCodepoint(), utf8ToHexSequence(), SpecialEmailUser\validateTarget(), Preferences\watchlistPreferences(), wfErrorLog(), wfInitShellLocale(), wfResetSessionID(), wfRunHooks(), wfSetupSession(), wfShellExecDisabled(), wfUsePHP(), OutputPage\wrapWikiMsg(), and MediaWiki\Session\PHPSessionHandler\write().

◆ wfDiff()

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

Returns unified plain-text diff of two texts.

"Useful" for machine processing of diffs.

Deprecated
since 1.25, use DiffEngine/UnifiedDiffFormatter directly
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 2442 of file GlobalFunctions.php.

References $params, $wgDiff, wfDebug(), and wfTempDir().

Referenced by ParserDiffTest\__call(), CompareParserCache\execute(), and CompareParsers\processRevision().

◆ wfErrorLog()

wfErrorLog ( $text,
$file,
array $context = [] )

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.

Since
1.25 support for additional context data
Parameters
string$text
string$fileFilename
array$contextAdditional logging context data
Exceptions
MWException
Deprecated
since 1.25 Use \MediaWiki\Logger\LegacyLogger::emit or UDPTransport

Definition at line 1167 of file GlobalFunctions.php.

References $context, and wfDeprecated().

◆ 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 1643 of file GlobalFunctions.php.

References $wgEnableMagicLinks, and $wgUrlProtocols.

Referenced by MalformedTitleException\__construct(), MediaHandler\addMeta(), CoreParserFunctions\basepagename(), CoreParserFunctions\basepagenamee(), Parser\braceSubstitution(), SpecialPageLanguage\changePageLanguage(), ApiMain\checkAsserts(), ApiQueryImageInfo\checkParameterNormalise(), SpecialContributions\contributionsSub(), ApiMain\createPrinterByName(), CoreParserFunctions\defaultsort(), Article\delete(), CoreParserFunctions\displaytitle(), Article\doDelete(), FileDeleteForm\doDelete(), WikiPage\doDeleteArticleReal(), ApiCSPReport\error(), ApiMain\errorMessagesFromException(), FileDuplicateSearchPage\execute(), SpecialMergeHistory\execute(), SpecialUnblock\execute(), ApiQueryTitleBlacklist\execute(), ApiAMCreateAccount\execute(), ApiClientLogin\execute(), ApiComparePages\execute(), ApiEditPage\execute(), ApiExpandTemplates\execute(), ApiLinkAccount\execute(), ApiMergeHistory\execute(), ApiMove\execute(), ApiOptions\execute(), ApiParse\execute(), ApiProtect\execute(), ApiQueryAllMessages\execute(), ApiQueryLogEvents\execute(), ApiQueryContributions\execute(), ApiUndelete\execute(), ApiUserrights\execute(), ApiValidatePassword\execute(), PasswordReset\execute(), ApiQueryRevisionsBase\extractRevisionInfo(), CoreParserFunctions\fullpagename(), CoreParserFunctions\fullpagenamee(), ApiComparePages\getDiffContent(), ApiFeedRecentChanges\getFeedObject(), CategoryViewer\getImageSection(), ApiErrorFormatter\getMessageFromException(), ApiBase\getModuleFromPath(), CategoryViewer\getPagesSection(), ApiRollback\getRbTitle(), ApiRollback\getRbUser(), ApiBase\getTitleFromTitleOrPageId(), ApiBase\getTitleOrPageId(), Parser\getUserSig(), Parser\getVariableValue(), ApiBase\getWatchlistUser(), EditPage\importFormData(), MediaWiki\Auth\LegacyHookPreAuthenticationProvider\makeFailResponse(), SpecialBlock\maybeAlterFormDefaults(), ApiQueryImageInfo\mergeThumbParams(), SpecialRandomInCategory\onSubmit(), SpecialBlock\onSuccess(), ImagePage\openShowImage(), ImageListPager\outputUserDoesNotExist(), CoreParserFunctions\pagename(), CoreParserFunctions\pagenamee(), ApiBase\parseMsgInternal(), ApiBase\parseMultiValue(), SpecialBlock\postText(), ApiQueryBase\prefixedTitlePartToKey(), FileDeleteForm\prepareMessage(), ApiQueryBlocks\prepareUsername(), CoreParserFunctions\rootpagename(), CoreParserFunctions\rootpagenamee(), ApiQueryCategories\run(), ApiQueryImages\run(), ApiQueryLinks\run(), ApiQueryRevisions\run(), ApiMain\setupModule(), ProtectionForm\show(), SpecialSearch\showCreateLink(), UserrightsPage\showEditUserGroupsForm(), SpecialUndelete\showHistory(), EditPage\showIntro(), Article\showMissingArticle(), SpecialSearch\showResults(), LoginSignupSpecialPage\showSuccessPage(), EditPage\spamPageWithContent(), CoreParserFunctions\subjectpagename(), CoreParserFunctions\subjectpagenamee(), CoreParserFunctions\subpagename(), CoreParserFunctions\subpagenamee(), CoreParserFunctions\talkpagename(), CoreParserFunctions\talkpagenamee(), CoreParserFunctionsTest\testGender(), DifferenceEngine\textDiff(), ApiQueryBase\titlePartToKey(), ApiFileRevert\validateParameters(), SpecialBlock\validateTarget(), ApiBase\validateTimestamp(), and ApiBase\validateUser().

◆ 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
string$url
Returns
string

Definition at line 883 of file GlobalFunctions.php.

References wfExpandUrl().

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

◆ wfExpandIRI_callback()

wfExpandIRI_callback ( $matches)

Private callback for wfExpandIRI.

Parameters
array$matches
Returns
string

Definition at line 896 of file GlobalFunctions.php.

References $matches.

◆ 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
string | int | null$defaultProtoOne of the PROTO_* constants. Determines the protocol to use if $url or $wgServer is protocol-relative
Returns
string|false Fully-qualified URL, current-path-relative URL or false if no valid URL can be constructed

Definition at line 521 of file GlobalFunctions.php.

References $wgCanonicalServer, $wgHttpsPort, $wgInternalServer, $wgRequest, $wgServer, PROTO_CANONICAL, PROTO_CURRENT, PROTO_HTTP, PROTO_HTTPS, PROTO_INTERNAL, wfAssembleUrl(), wfParseUrl(), and wfRemoveDotSegments().

Referenced by MWHttpRequest\__construct(), DumpCategoriesAsRdf\addDumpHeader(), ApiQuerySiteinfo\appendGeneralInfo(), ApiQuerySiteinfo\appendInterwikiMap(), ApiQuerySiteinfo\appendRightsInfo(), EmailNotification\composeCommonMailtext(), SpecialApiHelp\execute(), ApiQueryExternalLinks\execute(), ApiQueryIWLinks\execute(), ApiQueryLangLinks\execute(), CdnCacheUpdate\expand(), ApiQueryInfo\extractPageInfo(), CoreParserFunctions\filepath(), MediaWiki\Widget\Search\InterwikiSearchResultSetWidget\footerHtml(), ApiParse\formatIWLinks(), ApiParse\formatLangLinks(), Title\getCanonicalURL(), File\getCanonicalUrl(), SpecialVersion\getEntryPointInfo(), RevertAction\getFormFields(), WebRequest\getFullRequestURL(), Title\getFullURL(), File\getFullUrl(), OutputPage\getHeadLinksArray(), ApiQueryImageInfo\getInfo(), LocalRepo\getInfo(), Title\getInternalURL(), ApiRsd\getRsdApiList(), FeedItem\getUniqueIdUnescaped(), MediaWiki\Widget\Search\SimpleSearchResultSetWidget\headerHtml(), ForeignAPIRepo\httpGet(), BaseBlacklist\isLocalSource(), MediaWiki\Widget\Search\InterwikiSearchResultSetWidget\iwIcon(), RevertAction\onSuccess(), RSSFeed\outHeader(), AtomFeed\outHeader(), RSSFeed\outItem(), AtomFeed\outItem(), OutputPage\output(), SpecialUploadStash\outputRemoteScaledThumb(), MediaWiki\performAction(), FileDeleteForm\prepareMessage(), ApiMainTest\provideExceptionErrors(), CSSMin\remapOne(), ApiQueryExtLinksUsage\run(), ApiOpenSearch\search(), SearchSuggestion\setSuggestedTitle(), MediaWiki\shouldDoHttpRedirect(), EditPage\showIntro(), ApiMain\substituteResultWithError(), SpecialSearchTest\testSubPageRedirect(), WfExpandUrlTest\testWfExpandUrl(), File\transform(), MediaWiki\tryNormaliseRedirect(), wfExpandIRI(), and wfStreamThumb().

◆ wfFindFile()

◆ wfForeignMemcKey()

wfForeignMemcKey ( $db,
$prefix )

Make a cache key for a foreign DB.

Must match what wfMemcKey() would produce in context of the foreign wiki.

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

Definition at line 2729 of file GlobalFunctions.php.

References $args.

Referenced by JobQueueDB\getCacheKey(), JobQueue\getRootJobCacheKey(), and GlobalTest\testWfForeignMemcKey().

◆ wfFormatStackFrame()

wfFormatStackFrame ( $frame)

Return a string representation of frame.

Parameters
array$frame
Returns
string

Definition at line 1578 of file GlobalFunctions.php.

Referenced by wfGetCaller().

◆ 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 1563 of file GlobalFunctions.php.

References wfDebugBacktrace().

Referenced by MediaWiki\Session\SessionBackend\addData(), MediaWiki\Session\SessionBackend\dirty(), EditPage\getContextTitle(), RequestContext\getTitle(), MessageCache\parse(), ApiBase\parseMsg(), OutputPage\parserOptions(), and MediaWiki\Session\SessionBackend\renew().

◆ wfGetCache()

wfGetCache ( $cacheType)

Get a specific cache object.

Parameters
int | string$cacheTypeA CACHE_* constants, or other key in $wgObjectCaches
Returns
BagOStuff

Definition at line 3138 of file GlobalFunctions.php.

Referenced by JobQueue\__construct(), SpecialVersion\getCreditsForExtension(), CacheHelper\initCaching(), ForkController\initChild(), and CacheHelper\saveCache().

◆ 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
int$level
Returns
string

Definition at line 1547 of file GlobalFunctions.php.

References wfDebugBacktrace(), and wfFormatStackFrame().

Referenced by StubObject\_unstub(), DeferredUpdates\addCallableUpdate(), MediaWikiTestCase\assertSelect(), WfGetCallerTest\callerOne(), ParserTestRunner\checkSetupDone(), ParserTestTopLevelSuite\debug(), MediaWiki\Shell\Command\execute(), WfGetCallerTest\intermediateFunction(), MWDebug\log(), WfGetCallerTest\testZero(), MediaWiki\HeaderCallback\warnIfHeadersSent(), wfShellExec(), and wfShellExecWithStderr().

◆ wfGetDB()

wfGetDB ( $db,
$groups = [],
$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_REPLICA 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_REPLICA) 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.

Todo
Replace calls to wfGetDB with calls to LoadBalancer::getConnection() on an injected instance of LoadBalancer.
Returns
\Wikimedia\Rdbms\Database

Definition at line 2812 of file GlobalFunctions.php.

References wfGetLB().

Referenced by LogPager\__construct(), Block\__construct(), SpecialRandomrootpage\__construct(), DeletedContribsPager\__construct(), ImageListPager\__construct(), ContribsPager\__construct(), IndexPager\__construct(), SearchDatabase\__construct(), MergeHistoryPager\__construct(), MergeHistory\__construct(), Pingback\acquireLock(), OutputPage\addCategoryLinksToLBAndGetResult(), BotPasswordTest\addDBData(), ApiComparePagesTest\addDBDataOnce(), MediaWiki\Session\BotPasswordSessionProviderTest\addDBDataOnce(), LinkCache\addLinkObj(), LogPage\addRelations(), User\addToDatabase(), MediaWikiTestCase\assertSelect(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\beginPrimaryAuthentication(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\beginPrimaryAuthentication(), MediaWiki\Auth\EmailNotificationSecondaryAuthenticationProvider\beginSecondaryAccountCreation(), ImageListPager\buildQueryConds(), SpecialPageLanguage\changePageLanguage(), CheckStorage\check(), User\checkAndSetTouched(), Pingback\checkIfSent(), TrackBlobs\checkIntegrity(), User\checkNewtalk(), RenameUserCleanup\checkRenameLog(), RevisionDeleter\checkRevisionExistence(), RecompressTracked\checkTrackingTable(), MediaWiki\Tests\Maintenance\DeleteAutoPatrolLogsTest\cleanLoggingTable(), CgzCopyTransaction\commit(), WikiPage\commitRollback(), Title\countRevisionsBetween(), SearchEngineFactory\create(), User\createNew(), ChangesListSpecialPageTest\createUsers(), Block\defaultRetroactiveAutoblock(), PrefixSearch\defaultSearchBackend(), ChangeTags\defineTag(), SearchMySQL\delete(), Block\delete(), Article\delete(), UserGroupMembership\delete(), DifferenceEngine\deletedLink(), User\deleteNewtalk(), ChangeTags\deleteTagEverywhere(), Title\deleteTitleProtection(), SpecialUndelete\diffHeader(), RecompressTracked\doAllOrphans(), RecompressTracked\doAllPages(), UsersPager\doBatchLookups(), CategoryViewer\doCategoryQuery(), WikiPage\doCreate(), FileDeleteForm\doDelete(), WikiPage\doDeleteArticleReal(), SpecialExport\doExport(), SpecialRecentChangesLinked\doMainQuery(), WikiPage\doModify(), RecompressTracked\doOrphanList(), RecompressTracked\doPage(), PopulateInterwiki\doPopulate(), GenderCache\doQuery(), LinkBatch\doQuery(), UserCache\doQuery(), ReplaceTextSearch\doSearchQuery(), SpecialInterwiki\doSubmit(), MovePageForm\doSubmit(), WikiPage\doUpdateRestrictions(), LinkHolderArray\doVariants(), Title\estimateRevisionCount(), SpecialRenameuser\execute(), SpecialLog\execute(), CleanupArchiveUserText\execute(), Cleanup\execute(), ApiSetNotificationTimestamp\execute(), ParserTestsMaintenance\execute(), QueryPage\fetchFromCache(), HistoryAction\fetchRevisions(), Parser\fetchScaryTemplateMaybeFromCache(), ChangesListSpecialPageTest\fetchUsers(), TrackBlobs\findOrphanBlobs(), User\findUsersByGroup(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\finishAccountCreation(), RecompressTracked\finishIncompleteMoves(), DoubleRedirectJob\fixRedirects(), ApiEditPageTest\forceRevisionDate(), EditPageTest\forceRevisionDate(), Language\formatExpiry(), ApiResult\formatExpiry(), DoubleRedirectsPage\formatResult(), LCStoreDB\get(), MediaWiki\Interwiki\ClassicInterwikiLookup\getAllPrefixesDB(), PageProps\getAllProperties(), BaseBlacklist\getArticleText(), Title\getAuthorsBetween(), ContentHandler\getAutoDeleteReason(), EditPage\getBaseRevision(), SpecialBlockList\getBlockListPager(), Block\getBlocksForIPList(), Title\getBrokenLinksFrom(), QueryPage\getCachedTimestamp(), Title\getCascadeProtectionSources(), WikiPage\getCategories(), TimelessTemplate\getCategories(), RCDatabaseLogEntry\getComment(), ApiCategoryTree\getConditionalRequestData(), ResourceLoaderWikiModule\getContentObj(), WikiPage\getContributors(), RevDelRevisionList\getCurrent(), SpamBlacklist\getCurrentLinks(), AllMessagesTablePager\getCustomisedStatuses(), RangeChronologicalPagerTest\getDateRangeCondProvider(), UserRightsProxy\getDB(), Maintenance\getDB(), ApiBase\getDB(), BacklinkCache\getDB(), LinksDeletionUpdate\getDB(), LinksUpdate\getDB(), ResourceLoaderWikiModule\getDB(), ChangesListSpecialPage\getDB(), SpecialRecentChanges\getDB(), SpecialWatchlist\getDB(), LocalRepo\getDBFactory(), User\getEditCount(), ResourceLoaderModule\getFileDependencies(), DoubleRedirectJob\getFinalDestination(), User\getFirstEditTimestamp(), Title\getFirstRevision(), User\getFormerGroups(), GadgetDefinitionNamespaceRepo\getGadget(), GadgetDefinitionNamespaceRepo\getGadgetIds(), WikiPage\getHiddenCategories(), SpecialActiveUsers\getIntroText(), EditPage\getLastDelete(), PageArchive\getLastRevisionText(), SpecialExport\getLinks(), Title\getLinksFrom(), SimpleCaptcha\getLinksFromTracker(), Title\getLinksTo(), DifferenceEngine\getMarkPatrolledLinkInfo(), LocalRepo\getMasterDB(), SpecialReplaceText\getMatchingTitles(), Category\getMembers(), UserGroupMembership\getMembership(), UserGroupMembership\getMembershipsForUser(), SpecialRandomInCategory\getMinAndMaxForCat(), MessageCache\getMsgFromNamespace(), ApiQuery\getNamedDB(), ActorMigration\getNewActorId(), User\getNewMessageLinks(), SpecialNuke\getNewPages(), Pingback\getOrCreatePingbackId(), SpecialExport\getPagesFromCategory(), SpecialExport\getPagesFromNamespace(), Title\getParentCategories(), PageArchive\getPreviousRevision(), PageProps\getProperties(), SpecialRandomInCategory\getQueryInfo(), SpecialGadgetUsage\getQueryInfo(), DeletedContribsPager\getQueryInfo(), NewFilesPager\getQueryInfo(), UsersPager\getQueryInfo(), BrokenRedirectsPage\getQueryInfo(), LinkSearchPage\getQueryInfo(), MediaStatisticsPage\getQueryInfo(), UncategorizedCategoriesPage\getQueryInfo(), UnwatchedpagesPage\getQueryInfo(), WantedPagesPage\getQueryInfo(), WithoutInterwikiPage\getQueryInfo(), Block\getRangeCond(), QueryPage\getRecacheDB(), Title\getRedirectsHere(), WikiPage\getRedirectTarget(), Title\getRelativeRevisionID(), LocalRepo\getReplicaDB(), PageArchive\getRevision(), OutputPage\getRlClient(), Linker\getRollbackEditCount(), Cite\getStoredReferences(), Title\getSubpages(), MIMEsearchPage\getSuggestionsForTypes(), HistoryBlobStub\getText(), HistoryBlobCurStub\getText(), TrackBlobs\getTextClause(), PageArchive\getTextFromRow(), Title\getTitleProtectionInternal(), Title\getTouched(), SpecialUpload\getUploadForm(), PasswordReset\getUsersByEmail(), User\idForName(), User\idFromName(), WikiRevision\importLogItem(), CheckStorage\importRevision(), User\incEditCount(), User\incEditCountImmediate(), User\initEditCount(), Block\initFromRow(), Category\initialize(), BackupDumper\initProgress(), TrackBlobs\initTrackingTable(), UserGroupMembership\insert(), Block\insert(), ManualLogEntry\insert(), MediaWiki\Tests\Maintenance\DeleteAutoPatrolLogsTest\insertLoggingData(), WikiPage\insertProtectNullRevision(), WikiPage\insertRedirect(), WikiPage\insertRedirectEntry(), Title\invalidateCache(), HTMLCacheUpdateJob\invalidateTitles(), Title\isBigDeletion(), WikiPage\isCountable(), PageArchive\isDeleted(), Title\isDeleted(), Title\isDeletedQuick(), Title\isNewPage(), Title\isSingleRevRedirect(), Block\isWhitelistedFromAutoblocks(), ApiStashEdit\lastEditTime(), LogPager\limitPerformer(), PageArchive\listAllPages(), ChangeTags\listExplicitlyDefinedTags(), PageArchive\listFiles(), PageArchive\listPagesByPrefix(), PageArchive\listPagesBySearch(), PageArchive\listRevisions(), ChangeTags\listSoftwareActivatedTags(), ChangeTags\listSoftwareDefinedTags(), User\load(), MediaWiki\Interwiki\ClassicInterwikiLookup\load(), ArchivedFile\load(), User\loadFromCache(), User\loadFromDatabase(), MessageCache\loadFromDB(), RecentChange\loadFromRow(), ArchivedFile\loadFromRow(), MediaWikiGadgetsDefinitionRepo\loadGadgets(), User\loadGroups(), WikiPage\loadLastEdit(), User\loadOptions(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), DifferenceEngine\loadRevisionData(), WikiPage\lockAndGetLatest(), RenameuserSQL\lockUserAndGetId(), ProfilerOutputDb\log(), ChangeTags\logTagManagementAction(), LocalIdLookup\lookupCentralIds(), LocalIdLookup\lookupUserNames(), LinkFilter\makeLikeArray(), RevisionDbTestBase\makeRevisionWithProps(), Pingback\markSent(), EditPage\mergeChangesIntoContent(), SearchMySQL\minSearchLength(), ChangeTags\modifyDisplayQuery(), MovePage\move(), RecompressTracked\moveTextRow(), moveToExternal(), MovePage\moveToInternal(), LinkSearchPage\mungeQuery(), Title\nameOf(), RecentChange\newFromConds(), User\newFromConfirmationCode(), Block\newFromID(), Title\newFromID(), WikiPage\newFromID(), Title\newFromIDs(), UserArray\newFromIDs(), UserArray\newFromNames(), Block\newLoad(), User\newSystemUser(), ChangesListSpecialPageTest\normalizeCondition(), RecentChange\notifyEdit(), RecentChange\notifyNew(), InterwikiHooks\onInterwikiLoadPrefix(), CategoryTreeHooks\onSpecialTrackingCategoriesPreprocess(), HistoryAction\onView(), ImagePage\openShowImage(), InfoAction\pageCounts(), ApiStashEdit\parseAndStash(), ClassicInterwikiLookupTest\populateDB(), InterwikiTest\populateDB(), ReplaceTextSearch\prefixCondition(), ResourceLoader\preloadModuleInfo(), WikiPage\prepareContentForEdit(), ActorMigrationTest\provideInsertRoundTrip(), CommentStoreTest\provideInsertRoundTrip(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData(), ManualLogEntry\publish(), Block\purgeExpired(), Title\purgeExpiredRestrictions(), RecentChangesUpdateJob\purgeExpiredRows(), SpecialPagesWithProp\queryExistingProps(), ImagePage\queryImageLinks(), DoubleRedirectsPage\reallyGetQueryInfo(), RecentChange\reallyMarkPatrolled(), RebuildRecentchanges\rebuildRecentChangesTablePass5(), QueryPage\recache(), MessageBlobStore\recacheMessageBlob(), Category\refreshCounts(), ChangeTagsList\reloadFromMaster(), RevDelList\reloadFromMaster(), RenameuserSQL\rename(), CategoryTree\renderChildren(), CategoryTree\renderParents(), LinkHolderArray\replaceInternal(), ImportReporter\reportPage(), RevisionListBase\reset(), resolveStub(), resolveStubs(), CheckStorage\restoreText(), RenameUserJob\run(), CategoryFinder\run(), DeleteLinksJob\run(), MediaWikiTestCase\run(), RecentChange\save(), LogPage\saveContent(), ResourceLoaderModule\saveFileDependencies(), User\saveOptions(), User\saveSettings(), UserNamePrefixSearch\search(), SpecialRandomInCategory\selectRandomPageFromDB(), RandomPage\selectRandomPageFromDB(), RevDelArchivedFileItem\setBits(), RevDelArchivedRevisionItem\setBits(), RevDelArchiveItem\setBits(), RevDelFileItem\setBits(), RevDelLogItem\setBits(), RevDelRevisionItem\setBits(), TestUser\setPasswordForUser(), PagePropsTest\setProperties(), ApiQueryRecentChangesIntegrationTest\setUp(), LinksUpdateTest\setUp(), PageArchiveTest\setUp(), DatabaseIntegrationTest\setUp(), ParserTestTopLevelSuite\setUp(), ParserTestRunner\setupDatabase(), ApiParseTest\setupInterwiki(), MediaWikiShell\setupLegacy(), RevisionDeleteUser\setUsernameBitfields(), RevDelList\setVisibility(), SpecialAllPages\showChunk(), SpecialInterwiki\showForm(), MovePageForm\showForm(), SpecialReplaceText\showForm(), SpecialWhatLinksHere\showIndirectLinks(), EditPage\showIntro(), SpecialInterwiki\showList(), LogEventsList\showLogExtract(), Article\showMissingArticle(), Article\showPatrolFooter(), SpecialPrefixindex\showPrefixChunk(), UserOptionsMaintenance\showUsageStats(), SpecialVersion\softwareInformation(), LCStoreDB\startWrite(), Parser\statelessFetchRevision(), RevDelLogList\suggestTarget(), RecompressTracked\syncDBs(), ChangeTags\tagUsageStatistics(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testAccountCreation(), MediaWiki\Auth\AuthManagerTest\testAccountCreation(), MediaWiki\Auth\AuthManagerTest\testAccountCreationLogging(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testAuthentication(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testAuthentication(), MediaWiki\Auth\AuthManagerTest\testAutoAccountCreation(), ApiBlockTest\testBlockWithEmailBlock(), ApiBlockTest\testBlockWithExpiry(), ApiBlockTest\testBlockWithHide(), ApiBlockTest\testBlockWithTag(), ApiLoginTest\testBotPassword(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testCountRevisionsByPageId(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testCountRevisionsByTitle(), EditPageTest\testCreatePageTrx(), ApiDeleteTest\testDeleteWithTag(), WikiPageDbTestBase\testDoDeleteArticle(), WikiPageDbTestBase\testDoDeleteUpdates(), WikiPageDbTestBase\testDoEditContent(), SiteStatsUpdateTest\testDoUpdate(), ApiEditPageTest\testEditWithTag(), UserTest\testExperienceLevel(), MediaWiki\Tests\Maintenance\DeleteAutoPatrolLogsTest\testFromId(), ReverseChronologicalPagerTest\testGetDateCond(), TitleTest\testGetFragmentForURL(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testGetParentLengths(), RevisionDbTestBase\testGetParentLengths_multipleRevIds(), RevisionDbTestBase\testGetParentLengths_noRevIds(), RevisionDbTestBase\testGetParentLengths_oneRevId(), BotPasswordTest\testGetPassword(), ResourceLoaderWikiModuleTest\testGetPreloadedBadTitle(), ResourceLoaderWikiModuleTest\testGetPreloadedTitleInfo(), ResourceLoaderWikiModuleTest\testGetPreloadedTitleInfoEmpty(), RevisionDbTestBase\testInsertOn(), RevisionDbTestBase\testInsertOn_exceptionOnNoPage(), RevisionDbTestBase\testInsertOn_success(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testInsertRevisionOn_blobAddressExists(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testInsertRevisionOn_failures(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testInsertRevisionOn_successes(), RevisionDbTestBase\testLoadFromId(), RevisionDbTestBase\testLoadFromPageId(), RevisionDbTestBase\testLoadFromPageIdWithLatestRevId(), RevisionDbTestBase\testLoadFromPageIdWithNotLatestRevId(), RevisionDbTestBase\testLoadFromTimestamp(), RevisionDbTestBase\testLoadFromTitle(), RevisionDbTestBase\testLoadFromTitleWithLatestRevId(), RevisionDbTestBase\testLoadFromTitleWithNotLatestRevId(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testLoadRevisionFromId(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testLoadRevisionFromPageId(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testLoadRevisionFromTimestamp(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testLoadRevisionFromTitle(), ChangeTagsTest\testModifyDisplayQuery(), RevisionDbTestBase\testNewFromArchiveRow(), RevisionDbTestBase\testNewFromArchiveRowOverrides(), MediaWiki\Session\UserInfoTest\testNewFromId(), RevisionDbTestBase\testNewFromRow(), RevisionDbTestBase\testNewKnownCurrent(), RevisionDbTestBase\testNewKnownCurrent_returnsFalseWhenTitleDoesntExist(), RevisionDbTestBase\testNewKnownCurrent_withPageId(), RevisionDbTestBase\testNewNullRevision(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewNullRevision(), RevisionDbTestBase\testNewNullRevision_badPage(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewNullRevision_nonExistingTitle(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewRevisionFromArchiveRow(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testNewRevisionFromArchiveRow_legacyEncoding(), LBFactoryTest\testNiceDomains(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testProviderChangeAuthenticationData(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testProviderChangeAuthenticationData(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testProviderChangeAuthenticationDataEmail(), ChangesListSpecialPageTest\testRcHidebyothersFilter(), ChangesListSpecialPageTest\testRcHidemyselfFilter(), MessageCacheTest\testReplaceMsg(), MediaWiki\Tests\Maintenance\DeleteAutoPatrolLogsTest\testRun(), PrefixSearchTest\testSearch(), PrefixSearchTest\testSearchWithOffset(), MultiWriteBagOStuffTest\testSetDelayed(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testSetPasswordResetFlag(), DatabaseIntegrationTest\testStoredFunctions(), MultiWriteBagOStuffTest\testSyncMerge(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testTestUserCanAuthenticate(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testTestUserCanAuthenticate(), LBFactoryTest\testTrickyDomain(), PageArchiveTest\testUndeleteRevisions(), ApiEditPageTest\testUndoAfterToInvalidRev(), ApiEditPageTest\testUndoWithSwappedRevisions(), ImportTest\testUnknownUserHandling(), EditPageTest\testUpdatePageTrx(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserExists(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\testUserExists(), RevisionDbTestBase\testUserWasLastToEdit(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testUserWasLastToEdit_false(), MediaWiki\Tests\Storage\RevisionStoreDbTest\testUserWasLastToEdit_true(), ApiUserrightsTest\testWithTag(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), ResourceLoader\tryRespondFromFileCache(), ChangeTags\undefineTag(), PageArchive\undeleteRevisions(), SearchMySQL\update(), SearchOracle\update(), SearchSqlite\update(), Block\update(), RecentChangesUpdateJob\updateActiveUsers(), WikiPage\updateCategoryCounts(), User\updateNewtalk(), UserOptionsMaintenance\updateOptions(), RenameUserCleanup\updateTable(), ChangeTags\updateTags(), ChangeTags\updateTagSummaryRow(), ChangeTags\updateTagsWithChecks(), Block\updateTimestamp(), SearchMySQL\updateTitle(), SearchOracle\updateTitle(), SearchSqlite\updateTitle(), ActivityUpdateJob\updateWatchlistNotification(), Revision\userWasLastToEdit(), and ApiTag\validateLogId().

◆ wfGetLangObj()

wfGetLangObj ( $langcode = false)

Return a Language object from $langcode.

Parameters
Language | string | bool$langcodeEither:
  • 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

Definition at line 1306 of file GlobalFunctions.php.

References $wgContLang, $wgLang, $wgLanguageCode, and wfDebug().

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

◆ wfGetLB()

◆ wfGetLBFactory()

wfGetLBFactory ( )

Get the load balancer factory object.

Deprecated
since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.
Returns
\Wikimedia\Rdbms\LBFactory

Definition at line 2841 of file GlobalFunctions.php.

◆ wfGetMainCache()

◆ wfGetMessageCacheStorage()

wfGetMessageCacheStorage ( )

Get the cache object used by the message cache.

Returns
BagOStuff

Definition at line 3157 of file GlobalFunctions.php.

References $wgMessageCacheType.

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 2940 of file GlobalFunctions.php.

References wfIsWindows().

Referenced by MediaWiki\Tidy\RaggettExternal\cleanWrapped(), and Dump7ZipOutput\setup7zCommand().

◆ wfGetParserCacheStorage()

wfGetParserCacheStorage ( )

Get the cache object used by the parser cache.

Deprecated
since 1.30, use MediaWikiServices::getParserCache()->getCacheStorage()
Returns
BagOStuff

Definition at line 3168 of file GlobalFunctions.php.

References $wgParserCacheType.

◆ 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 2692 of file GlobalFunctions.php.

References $blob, $IP, and unserialize().

Referenced by IcuCollation\fetchFirstLetterData(), and Language\transformUsingPairFile().

◆ wfGetRusage()

wfGetRusage ( )

Get system resource usage of current request context.

Invokes the getrusage(2) system call, requesting RUSAGE_SELF if on PHP5 or RUSAGE_THREAD if on HHVM. Returns false if getrusage is not available.

Since
1.24
Returns
array|bool Resource usage data or false if no data available.

Definition at line 3448 of file GlobalFunctions.php.

Referenced by JobRunner\getMaxRssKb(), SectionProfiler\getTime(), and ParserOutput\getTimes().

◆ wfGetScriptUrl()

wfGetScriptUrl ( )

Get the script URL.

Returns
string Script URL

Definition at line 2906 of file GlobalFunctions.php.

◆ wfGlobalCacheKey()

wfGlobalCacheKey ( )

Make a cache key with database-agnostic prefix.

Doesn't have a wiki-specific namespace. Uses a generic 'global' prefix instead. Must have a prefix as otherwise keys that use a database name in the first segment will clash with wfMemcKey/wfForeignMemcKey.

Deprecated
since 1.30 Call makeGlobalKey on a BagOStuff instance
Since
1.26
Parameters
string$args,...
Returns
string

Definition at line 2750 of file GlobalFunctions.php.

Referenced by SimpleCaptcha\badLoginKey(), SimpleCaptcha\badLoginPerUserKey(), and GlobalTest\testWfGlobalCacheKey().

◆ wfHostname()

◆ wfHttpError()

wfHttpError ( $code,
$label,
$desc )

Provide a simple HTTP error.

Parameters
int | string$code
string$label
string$desc

Definition at line 1751 of file GlobalFunctions.php.

References $code, $wgOut, HttpStatus\header(), and print.

Referenced by SpecialRunJobs\execute(), RawAction\getRawText(), MWExceptionRenderer\output(), AjaxDispatcher\performAction(), MWException\report(), and FancyCaptcha\showImage().

◆ wfIncrStats()

wfIncrStats ( $key,
$count = 1 )

Increment a statistics counter.

Parameters
string$key
int$count
Returns
void

Definition at line 1252 of file GlobalFunctions.php.

Referenced by ParserCache\get(), DifferenceEngine\getDiffBody(), ParserCache\getKey(), and WikiPage\getParserOutput().

◆ 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 2172 of file GlobalFunctions.php.

References wfStringToBool().

Referenced by MediaWiki\Http\HttpRequestFactory\canMakeRequests(), MWHttpRequest\canMakeRequests(), MediaWiki\Http\HttpRequestFactory\create(), MWHttpRequestTester\factory(), UploadBase\isEnabled(), WebInstaller\startSession(), and MediaWiki\Session\PHPSessionHandlerTest\testInstall().

◆ wfInitShellLocale()

wfInitShellLocale ( )

Formerly set the locale for locale-sensitive operations.

This is now done in Setup.php.

Deprecated
since 1.30, no longer needed
See also
$wgShellLocale

Definition at line 2316 of file GlobalFunctions.php.

References wfDeprecated().

◆ 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 3238 of file GlobalFunctions.php.

References $cache, $line, $lines, $name, wfFindFile(), and wfMessage().

Referenced by ApiQueryImageInfo\execute(), ImageMap\render(), GlobalWithDBTest\testWfIsBadImage(), and TraditionalImageGallery\toHTML().

◆ wfIsCLI()

◆ wfIsDebugRawPage()

wfIsDebugRawPage ( )

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

Returns
bool

Definition at line 1028 of file GlobalFunctions.php.

References $cache.

Referenced by wfDebug(), and wfLogProfilingData().

◆ wfIsHHVM()

wfIsHHVM ( )

◆ wfIsInfinity()

wfIsInfinity ( $str)

◆ wfIsWindows()

◆ wfLoadExtension()

wfLoadExtension ( $ext,
$path = null )

Load an extension.

This queues an extension to be loaded through the ExtensionRegistry system.

Parameters
string$extName of the extension to load
string | null$pathAbsolute path of where to find the extension.json file
Since
1.25

Definition at line 45 of file GlobalFunctions.php.

References $wgExtensionDirectory, and ExtensionRegistry\getInstance().

◆ wfLoadExtensions()

wfLoadExtensions ( array $exts)

Load multiple extensions at once.

Same as wfLoadExtension, but more efficient if you are loading multiple extensions.

If you want to specify custom paths, you should interact with ExtensionRegistry directly.

See also
wfLoadExtension
Parameters
string[]$extsArray of extension names to load
Since
1.25

Definition at line 66 of file GlobalFunctions.php.

References $ext, $wgExtensionDirectory, and ExtensionRegistry\getInstance().

◆ wfLoadSkin()

wfLoadSkin ( $skin,
$path = null )

Load a skin.

See also
wfLoadExtension
Parameters
string$skinName of the extension to load
string | null$pathAbsolute path of where to find the skin.json file
Since
1.25

Definition at line 82 of file GlobalFunctions.php.

References $wgStyleDirectory, and ExtensionRegistry\getInstance().

◆ wfLoadSkins()

wfLoadSkins ( array $skins)

Load multiple skins at once.

See also
wfLoadExtensions
Parameters
string[]$skinsArray of extension names to load
Since
1.25

Definition at line 97 of file GlobalFunctions.php.

References $wgStyleDirectory, and ExtensionRegistry\getInstance().

◆ wfLocalFile()

◆ wfLogDBError()

wfLogDBError ( $text,
array $context = [] )

Log for database errors.

Since
1.25 support for additional context data
Parameters
string$textDatabase error message.
array$contextAdditional logging context data

Definition at line 1105 of file GlobalFunctions.php.

References $context.

◆ wfLogProfilingData()

◆ 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
string$msgMessage to send
int$callerOffsetNumber of items to go back in the backtrace to find the correct caller (1 = function calling wfLogWarning, ...)
int$levelPHP error level; defaults to E_USER_WARNING

Definition at line 1150 of file GlobalFunctions.php.

Referenced by ChangesListSpecialPage\areFiltersInConflict(), MediaWiki\Storage\SqlBlobStore\compressData(), Language\convertGrammar(), MediaWiki\Storage\SqlBlobStore\decompressData(), WikiPage\doDeleteArticleReal(), Revision\ensureTitle(), CommentStore\getCommentInternal(), SpecialPageFactory\getPage(), SiteImporter\handleException(), OutputPage\parserOptions(), DifferenceEngine\textDiff(), OutputPage\transformFilePath(), and wfMkdirParents().

◆ wfMakeUrlIndexes()

wfMakeUrlIndexes ( $url)

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

Parameters
string$url
Returns
array

Definition at line 906 of file GlobalFunctions.php.

References wfParseUrl().

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$url
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 960 of file GlobalFunctions.php.

References wfParseUrl().

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

◆ wfMemcKey()

◆ wfMemoryLimit()

wfMemoryLimit ( )

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

Returns
int Resulting value of the memory limit.

Definition at line 3045 of file GlobalFunctions.php.

References $wgMemoryLimit, wfDebug(), and wfShorthandToInteger().

◆ wfMerge()

wfMerge ( $old,
$mine,
$yours,
& $result,
& $mergeAttemptResult = null )

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
string&$mergeAttemptResult
Returns
bool

Definition at line 2359 of file GlobalFunctions.php.

References $wgDiff3, wfDebug(), and wfTempDir().

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

◆ wfMergeErrorArrays()

wfMergeErrorArrays ( )

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

wfMergeErrorArrays( [ [ 'x' ] ], [ [ 'x', '2' ] ], [ [ 'x' ] ], [ [ 'y' ] ] ); returns: [ [ 'x', '2' ], [ 'x' ], [ 'y' ] ]

Parameters
array$array1,...
Returns
array

Definition at line 211 of file GlobalFunctions.php.

References $args, $out, and $params.

Referenced by MergeHistory\checkPermissions(), MovePage\checkPermissions(), SpecialImport\execute(), Title\isValidMoveOperation(), SpecialChangeContentModel\onSubmit(), 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 | string[] | MessageSpecifier$keyMessage key, or array of keys, or a MessageSpecifier
mixed$params,...Normal message parameters
Returns
Message
Since
1.17
See also
Message::__construct

Definition at line 1355 of file GlobalFunctions.php.

References $params.

◆ 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 1380 of file GlobalFunctions.php.

References $args.

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

◆ wfMkdirParents()

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

◆ 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 1393 of file GlobalFunctions.php.

References $args.

Referenced by WikiPage\commitRollback(), MWException\msg(), and MWExceptionRenderer\msg().

◆ 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 1918 of file GlobalFunctions.php.

References $type, and mimeTypeMatch().

Referenced by GlobalTest\testNegotiateType().

◆ wfObjectToArray()

wfObjectToArray ( $objOrArray,
$recursive = true )

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

Parameters
object | array$objOrArray
bool$recursive
Returns
array

Definition at line 261 of file GlobalFunctions.php.

References $value, and wfObjectToArray().

Referenced by GadgetDefinitionContent\getAssocArray(), and wfObjectToArray().

◆ 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 (see (2)). 4) Verifies that the protocol is on the $wgUrlProtocols whitelist. 5) Rejects some invalid URLs that parse_url doesn't, e.g. the empty string or URLs starting with a line feed character.

Parameters
string$urlA URL to parse
Returns
string[]|bool Bits of the URL in an associative array, or false on failure. Possible fields:
  • scheme: URI scheme (protocol), e.g. 'http', 'mailto'. Lowercase, always present, but can be an empty string for protocol-relative URLs.
  • delimiter: either '://', ':' or '//'. Always present.
  • host: domain name / IP. Always present, but could be an empty string, e.g. for file: URLs.
  • user: user name, e.g. for HTTP Basic auth URLs such as http://user:pass@example.com/ Missing when there is no username.
  • pass: password, same as above.
  • path: path including the leading /. Will be missing when empty (e.g. 'http://example.com')
  • query: query string (as a string; see wfCgiToArray() for parsing it), can be missing.
  • fragment: the part after #, can be missing.

Definition at line 801 of file GlobalFunctions.php.

References $query, $wgUrlProtocols, and list.

Referenced by MWHttpRequest\__construct(), SpecialInterwiki\doSubmit(), LinkSearchPage\execute(), ApiAMCreateAccount\execute(), ApiClientLogin\execute(), ApiLinkAccount\execute(), MediaWiki\Widget\Search\InterwikiSearchResultSetWidget\footerHtml(), WikiMap\getCanonicalServerInfoForAllWikis(), WikiReference\getDisplayName(), WikiMap\getWikiFromUrl(), WikiMap\getWikiWikiReferenceFromSites(), MediaWiki\Widget\Search\SimpleSearchResultSetWidget\headerHtml(), ThumbnailRenderJob\hitThumbUrl(), UploadFromUrl\isAllowedHost(), MediaWiki\Widget\Search\InterwikiSearchResultSetWidget\iwIcon(), SpamBlacklist\logUrlChange(), LinkFilter\makeLikeArray(), UserMailer\makeMsgId(), WfAssembleUrlTest\provideURLParts(), SquidPurgeClient\queuePurge(), RedisPubSubFeedEngine\send(), AbstractChangesListSpecialPageTestCase\testValidateOptions(), WfParseUrlTest\testWfParseUrl(), MediaWiki\triggerAsyncJobs(), wfExpandUrl(), wfMakeUrlIndexes(), and wfMatchesDomainList().

◆ wfPercent()

wfPercent ( $nr,
$acc = 2,
$round = true )
Parameters
int$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 2144 of file GlobalFunctions.php.

References $ret.

Referenced by profile_point\display(), ParserTestPrinter\reportPercentage(), and GlobalTest\testWfPercentTest().

◆ wfQueriesMustScale()

wfQueriesMustScale ( )

Should low-performance queries be disabled?

Returns
bool

Definition at line 2874 of file GlobalFunctions.php.

References $wgMiserMode, SiteStats\edits(), SiteStats\pages(), and SiteStats\users().

Referenced by RenameuserSQL\__construct().

◆ 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.

Note
This is designed for use in relation to Special:RandomPage and the page_random database field.
Returns
string

Definition at line 287 of file GlobalFunctions.php.

Referenced by CompareParserCache\execute(), SpecialRandomInCategory\getRandomTitle(), RandomPage\getRandomTitle(), InputBox\getSearchForm(), InputBox\getSearchForm2(), 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 305 of file GlobalFunctions.php.

Referenced by MockFileBackend\doGetLocalCopyMulti(), JobQueueDB\doPop(), SvgHandler\doTransform(), GenerateFancyCaptchas\execute(), BenchmarkLruHash\execute(), BenchmarkSanitizer\execute(), MakeTestEdits\execute(), TestUserRegistry\getImmutableTestUser(), MockLocalRepo\getLocalCopy(), MockLocalRepo\getLocalReference(), TestUserRegistry\getMutableTestUser(), WebRequest\getRequestId(), StripState\merge(), UIDGenerator\newUUIDv4(), UploadSourceAdapter\registerSource(), FileBackendTest\setUp(), WANObjectCacheTest\testBusyValue(), WANObjectCacheTest\testCheckKeyInitHoldoff(), GlobalVarConfigTest\testConstructor(), WANObjectCacheTest\testDelete(), MediaWiki\Auth\LegacyHookPreAuthenticationProvider\testForAuthentication(), ReplicatedBagOStuffTest\testGet(), ReplicatedBagOStuffTest\testGetAbsent(), WANObjectCacheTest\testGetMulti(), WANObjectCacheTest\testGetMultiCheckKeys(), WANObjectCacheTest\testGetMultiWithSetCallback(), WANObjectCacheTest\testGetMultiWithUnionSetCallback(), WANObjectCacheTest\testGetNotExists(), WANObjectCacheTest\testGetWithSetCallback(), WANObjectCacheTest\testGetWithSetCallback_versions(), WANObjectCacheTest\testGetWithSeveralCheckKeys(), GlobalVarConfigTest\testHas(), WANObjectCacheTest\testInterimHoldOffCaching(), WANObjectCacheTest\testLockTSE(), WANObjectCacheTest\testLockTSESlow(), WANObjectCacheTest\testPreemtiveRefresh(), WANObjectCacheTest\testProcessCache(), GlobalTest\testRandomString(), WANObjectCacheTest\testReap(), JobQueueTest\testRootDeduplication(), FileBackendTest\testSanitizeOpHeaders(), ReplicatedBagOStuffTest\testSet(), WANObjectCacheTest\testSetAndGet(), MultiWriteBagOStuffTest\testSetDelayed(), MultiWriteBagOStuffTest\testSetImmediate(), WANObjectCacheTest\testSetOver(), WANObjectCacheTest\testSetWithLag(), WANObjectCacheTest\testStaleSet(), MultiWriteBagOStuffTest\testSyncMerge(), WANObjectCacheTest\testTouchKeys(), and WANObjectCacheTest\testWritePending().

◆ wfReadOnly()

◆ wfReadOnlyReason()

wfReadOnlyReason ( )

Check if the site is in read-only mode and return the message if so.

This checks wfConfiguredReadOnlyReason() and the main load balancer for replica DB lag. This may result in DB connection being made.

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

Definition at line 1275 of file GlobalFunctions.php.

Referenced by ReadOnlyError\__construct(), ProtectionForm\__construct(), ApiQuerySiteinfo\appendGeneralInfo(), MediaWiki\Auth\AuthManager\autoCreateUser(), MediaWiki\Auth\AuthManager\checkAccountCreatePermissions(), ApiBase\dieReadOnly(), WikiPage\doUpdateRestrictions(), EditPage\showHeader(), ReadOnlyErrorTest\testConstruction(), and GlobalTest\testReadOnlyGlobalChange().

◆ wfRecursiveRemoveDir()

wfRecursiveRemoveDir ( $dir)

◆ 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 2603 of file GlobalFunctions.php.

References $path, and wfBaseName().

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 (see T34168)
Parameters
string$urlPathURL path, potentially containing dot-segments
Returns
string URL path with all dot-segments removed

Definition at line 649 of file GlobalFunctions.php.

References $output.

Referenced by CSSMin\remapOne(), WfRemoveDotSegmentsTest\testWfRemoveDotSegments(), and wfExpandUrl().

◆ 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 1459 of file GlobalFunctions.php.

References $wgShowHostnames, and wfHostname().

Referenced by 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
bool$resetGzipEncoding

Definition at line 1788 of file GlobalFunctions.php.

References $wgDisableOutputCompression.

Referenced by SpecialExport\execute(), SpecialUploadStash\outputContents(), ResourceLoader\tryRespondNotModified(), and wfClearOutputBuffers().

◆ wfResetSessionID()

wfResetSessionID ( )

Reset the session id.

Deprecated
since 1.27, use MediaWiki\Session\SessionManager instead
Since
1.22

Definition at line 2645 of file GlobalFunctions.php.

References wfDeprecated(), and wfSetupSession().

◆ wfRestoreWarnings()

wfRestoreWarnings ( )

◆ wfRunHooks()

wfRunHooks ( $event,
array $args = [],
$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
Deprecated
since 1.25 - use Hooks::run

Definition at line 3183 of file GlobalFunctions.php.

References $args, and wfDeprecated().

Referenced by HooksTest\testOldStyleHooks().

◆ wfScript()

◆ wfSetBit()

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

As for wfSetVar except setting a bit.

Parameters
int&$dest
int$bit
bool$state
Returns
bool

Definition at line 1716 of file GlobalFunctions.php.

◆ wfSetupSession()

wfSetupSession ( $sessionId = false)

Initialise php session.

Deprecated
since 1.27, use MediaWiki\Session\SessionManager instead. Generally, "using" SessionManager will be calling ->getSessionById() or ::getGlobalSession() (depending on whether you were passing $sessionId here), then calling $session->persist().
Parameters
bool | string$sessionId

Definition at line 2670 of file GlobalFunctions.php.

References wfDeprecated().

Referenced by wfResetSessionID().

◆ wfSetVar()

◆ wfShellExec()

wfShellExec ( $cmd,
& $retval = null,
$environ = [],
$limits = [],
$options = [] )

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

Parameters
string | string[]$cmdIf string, a properly shell-escaped command line, or an array of unescaped arguments, in which case each value will be escaped Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
null | mixed&$retvalOptional, 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
  • profileMethod: By default this function will profile based on the calling method. Set this to a string for an alternative method to profile from
Returns
string Collected stdout as a string
Deprecated
since 1.30 use class MediaWiki\Shell\Shell

Definition at line 2250 of file GlobalFunctions.php.

References $options, $retval, and wfGetCaller().

Referenced by UIDGenerator\__construct(), DjVuHandler\doTransform(), GenerateFancyCaptchas\execute(), ParserTestPrinter\quickDiff(), Maintenance\readlineEmulation(), DjVuImage\retrieveMetaData(), WfShellExecTest\testBug67870(), JpegPixelFormatTest\testPixelFormatRendering(), wfShellExecWithStderr(), RandomImageGenerator\writeImageWithApi(), and RandomImageGenerator\writeImageWithCommandLine().

◆ wfShellExecDisabled()

wfShellExecDisabled ( )

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

Returns
bool|string False or 'disabled'
Since
1.22
Deprecated
since 1.30 use MediaWiki\Shell::isDisabled()

Definition at line 2222 of file GlobalFunctions.php.

References wfDeprecated().

◆ wfShellExecWithStderr()

wfShellExecWithStderr ( $cmd,
& $retval = null,
$environ = [],
$limits = [] )

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 | string[]$cmdIf string, a properly shell-escaped command line, or an array of unescaped arguments, in which case each value will be escaped Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
null | mixed&$retvalOptional, 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 wgMaxShell* limits.
Returns
string Collected stdout and stderr as a string
Deprecated
since 1.30 use class MediaWiki\Shell\Shell

Definition at line 2303 of file GlobalFunctions.php.

References $retval, wfGetCaller(), and wfShellExec().

Referenced by UploadBase\detectVirus(), PdfHandler\doTransform(), TransformationalImageHandler\getMagickVersion(), SvgHandler\rasterize(), BitmapHandler\rotate(), JpegHandler\rotate(), JpegHandler\swapICCProfile(), BitmapHandler\transformCustom(), and BitmapHandler\transformImageMagick().

◆ wfShellWikiCmd()

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

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").

Deprecated
since 1.31, use Shell::makeScriptCommand()
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 2334 of file GlobalFunctions.php.

References $options, and $wgPhpCli.

Referenced by CleanupSpam\execute(), and GlobalTest\testWfShellWikiCmd().

◆ wfShorthandToInteger()

wfShorthandToInteger ( $string = '',
$default = -1 )

Converts shorthand byte notation to integer form.

Parameters
string$string
int$defaultReturned if $string is empty
Returns
int

Definition at line 3094 of file GlobalFunctions.php.

References $last.

Referenced by Installer\envCheckMemory(), UploadBase\getMaxPhpUploadSize(), WebRequestUpload\isIniSizeOverflow(), WfShorthandToIntegerTest\testWfShorthandToInteger(), GlobalTest\testWfShorthandToInteger(), and wfMemoryLimit().

◆ wfShowingResults()

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

Definition at line 1596 of file GlobalFunctions.php.

References wfMessage().

◆ wfSplitWikiID()

wfSplitWikiID ( $wiki)

Split a wiki ID into DB name and table prefix.

Parameters
string$wiki
Returns
array

Definition at line 2779 of file GlobalFunctions.php.

Referenced by ForeignDBViaLBRepo\__construct(), JobQueueDB\getCacheKey(), JobQueueRedis\getQueueKey(), and JobQueue\getRootJobCacheKey().

◆ wfStringToBool()

wfStringToBool ( $val)

Convert string value to boolean, when the following are interpreted as true:

  • on
  • true
  • yes
  • Any number, except 0 All other strings are interpreted as false.
Parameters
string$val
Returns
bool
Since
1.31

Definition at line 2188 of file GlobalFunctions.php.

Referenced by WfStringToBoolTest\testStr2Bool(), and wfIniGetBool().

◆ wfStripIllegalFilenameChars()

wfStripIllegalFilenameChars ( $name)

Replace all invalid characters with '-'.

Additional characters can be defined in $wgIllegalFileChars (see T22489). By default, $wgIllegalFileChars includes ':', '/', '\'.

Parameters
string$nameFilename to process
Returns
string

Definition at line 3027 of file GlobalFunctions.php.

References $name, $wgIllegalFileChars, and wfBaseName().

Referenced by UploadBase\getTitle(), and MovePage\isValidFileMove().

◆ wfSuppressWarnings()

wfSuppressWarnings ( $end = false)

Reference-counted warning suppression.

Deprecated
since 1.26, use Wikimedia\suppressWarnings() directly
Parameters
bool$end

Definition at line 1960 of file GlobalFunctions.php.

Referenced by QuickArrayReader\__construct(), SpamBlacklist\filter(), PdfHandler\formatMetadata(), PdfHandler\getMetaArray(), TitleBlacklistEntry\matches(), QuickArrayReader\parseScalar(), ImageMap\render(), TitleBlacklist\validate(), and SpamRegexBatch\validateRegexes().

◆ wfTempDir()

wfTempDir ( )

Tries to get the system directory for temporary files.

First $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP environment variables are then checked in sequence, then sys_get_temp_dir(), then upload_tmp_dir from php.ini.

NOTE: When possible, use instead the tmpfile() function to create temporary files to avoid race conditions on file creation, etc.

Returns
string

Definition at line 2057 of file GlobalFunctions.php.

References $wgTmpDirectory, and TempFSFile\getUsableTempDirectory().

Referenced by UIDGenerator\__construct(), UploadFromChunks\concatenateChunks(), FileBackendGroup\config(), ParserTestRunner\createRepoGroup(), MockFileBackend\doGetLocalCopyMulti(), FileBackendTest\doTestDoOperationsPipeline(), SvgHandler\doTransform(), ImportableUploadRevisionImporter\downloadSource(), WikiImporter\dumpTemp(), GenerateFancyCaptchas\execute(), ApiImageRotate\execute(), HHVMMakeRepo\execute(), MWDocGen\execute(), TempFSFile\factory(), MockLocalRepo\getLocalCopy(), MockLocalRepo\getLocalReference(), MediaWikiTestCase\getNewTempFile(), ParserEditTests\getOutputFileName(), UIDGenerator\getSequentialPerNodeIDs(), FileBackendGroup\guessMimeInternal(), JobRunner\loadBackoffs(), UploadFromUrl\makeTemporaryFile(), File\makeTransformTmpFile(), ClassicInterwikiLookupTest\populateCDB(), FileBackendTest\provider_testStore(), ParserTestPrinter\quickDiff(), ResourceLoaderImage\rasterize(), CheckStorage\restoreText(), MigrateFileRepoLayoutTest\setUp(), WebPHandlerTest\setUp(), JobRunner\syncBackoffDeltas(), CSSMinTest\testGetMimeType(), DifferenceEngine\textDiff(), wfDiff(), and wfMerge().

◆ wfThumbIsStandard()

wfThumbIsStandard ( File $file,
array $params )

Returns true if these thumbnail parameters match one that MediaWiki requests from file description pages and/or parser output.

$params is considered non-standard if they involve a non-standard width or any non-default parameters aside from width and page number. The number of possible files with standard parameters is far less than that of all combinations; rate-limiting for them can thus be more generious.

Parameters
File$file
array$params
Returns
bool
Since
1.24 Moved from thumb.php to GlobalFunctions in 1.25

Definition at line 3341 of file GlobalFunctions.php.

References $handler, $params, $value, $wgImageLimits, $wgResponsiveImages, and $wgThumbLimits.

Referenced by WfThumbIsStandardTest\testIsStandard(), and wfStreamThumb().

◆ wfTimestamp()

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

Get a timestamp string in one of various formats.

Parameters
mixed$outputtypeA timestamp in one of the supported formats, the function will autodetect which format is supplied and act accordingly.
mixed$tsOptional timestamp to convert, default 0 for the current time
Returns
string|bool String / false The same date in the format specified in $outputtype or false

Definition at line 1980 of file GlobalFunctions.php.

References $ret, and wfDebug().

Referenced by Block\__construct(), MediaWiki\Storage\RevisionArchiveRecord\__construct(), MediaWiki\Storage\RevisionStoreRecord\__construct(), OutputPage\adaptCdnTTL(), DumpCategoriesAsRdf\addDumpHeader(), User\addGroup(), UserRightsProxy\addGroup(), LinkCache\addLinkObj(), ApiMain\addRequestedFields(), ApiQuerySiteinfo\appendExtensions(), ApiQuerySiteinfo\appendGeneralInfo(), ChangesListSpecialPage\buildQuery(), ApiStashEdit\buildStashValue(), FileCacheBase\cacheTimestamp(), ApiStashEdit\checkCache(), ApiMain\checkConditionalRequestHeaders(), AjaxResponse\checkLastModified(), OutputPage\checkLastModified(), WikiPage\commitRollback(), User\confirmationToken(), FileBackendMultiWrite\consistencyCheck(), LanguageWa\date(), Language\date(), DifferenceEngine\debug(), JobRunner\debugCallback(), LocalFile\decodeRow(), SqlBagOStuff\deleteObjectsExpiringBefore(), SpecialUndelete\diffHeader(), MemoryFileBackend\doCopyInternal(), MemoryFileBackend\doCreateInternal(), DBFileJournal\doLogChangeBatch(), MysqlUpdater\doSchemaRestructuring(), MemoryFileBackend\doStoreInternal(), FileBackendTest\doTestGetFileStat(), DefaultPreferencesFactoryTest\emailAuthenticationProvider(), SpecialExport\execute(), ApiEditPage\execute(), ApiFeedWatchlist\execute(), ApiMergeHistory\execute(), ApiProtect\execute(), ApiQueryAllUsers\execute(), ApiQueryBlocks\execute(), ApiQueryDeletedrevs\execute(), ApiQueryFilearchive\execute(), ApiQueryImageInfo\execute(), ApiQueryContributions\execute(), ApiQueryUsers\execute(), ApiSetNotificationTimestamp\execute(), ApiUndelete\execute(), LocalFileRestoreBatch\execute(), BenchmarkParse\execute(), UploadStashCleanup\execute(), FixTimestamps\execute(), GenerateSitemap\execute(), ImportTextFiles\execute(), PurgeParserCache\execute(), RemoveUnusedAccounts\execute(), UpdateSearchIndex\execute(), JobRunner\executeJob(), CacheTime\expired(), UserrightsPage\expiryToTimestamp(), ApiQueryWatchlist\extractOutputData(), ApiQueryInfo\extractPageInfo(), ApiQueryRevisionsBase\extractRevisionInfo(), ApiQueryLogEvents\extractRowInfo(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryContributions\extractRowInfo(), HistoryAction\feedEmpty(), MediaWiki\Logger\LegacyLogger\formatAsWfDebugLog(), FeedUtils\formatDiff(), Language\formatExpiry(), ApiResult\formatExpiry(), SpecialUndelete\formatFileRow(), LogFormatter\formatParameterValueForApi(), SpecialMergeHistory\formatRevisionRow(), SpecialUndelete\formatRevisionRow(), AtomFeed\formatTime(), RSSFeed\formatTime(), ImageListPager\formatValue(), GenerateSitemap\generateLimit(), RevDelArchivedFileItem\getApiData(), RevDelFileItem\getApiData(), RevDelRevisionItem\getApiData(), Block\getAutoblockExpiry(), ApiQueryUserInfo\getBlockInfo(), CacheTime\getCacheTime(), NewUsersLogFormatter\getComment(), ApiQueryUserInfo\getCurrentUserInfo(), LocalFile\getDescriptionTouched(), User\getExperienceLevel(), ProtectionForm\getExpiry(), FormatMetadata\getExtendedMetadataFromFile(), ApiQueryRecentChangesIntegrationTest\getExternalRC(), ApiQueryWatchlistIntegrationTest\getExternalRC(), User\getFirstEditTimestamp(), ApiQueryImageInfo\getInfo(), SpecialActiveUsers\getIntroText(), LogFormatter\getIRCActionText(), OutputPage\getJSVars(), MachineReadableRCFeedFormatter\getLine(), BlockLogFormatter\getMessageParameters(), PNGMetadataExtractor\getMetadata(), SpecialRandomInCategory\getMinAndMaxForCat(), ApiParamInfo\getModuleInfo(), MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\getNewPasswordExpiry(), BlockLogFormatter\getParametersForApi(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\getPasswordResetData(), PageArchive\getPreviousRevision(), ActiveUsersPager\getQueryInfo(), ContribsPager\getQueryInfo(), NewFilesPager\getQueryInfo(), RawAction\getRawText(), ApiQuerySearch\getSearchResultData(), ImageHistoryList\getThumbForLine(), ArchivedFile\getTimestamp(), ForeignAPIFile\getTimestamp(), FSFile\getTimestamp(), DatabaseLogEntry\getTimestamp(), RCDatabaseLogEntry\getTimestamp(), ManualLogEntry\getTimestamp(), WikiPage\getTimestamp(), RevisionItemBase\getTimestamp(), MockFSFile\getTimestamp(), FileJournal\getTimestampedUUID(), MediaWiki\Storage\RevisionStore\getTimestampFromId(), WANCacheReapUpdate\getTitleChangeEvents(), User\getTouched(), Parser\getVariableValue(), ApiQueryInfo\getVisitingWatcherInfo(), ForeignAPIRepo\httpGet(), ImageHistoryList\imageHistoryLine(), Block\initFromRow(), UserGroupMembership\initFromRow(), Language\internalUserTimeAndDate(), User\isEmailConfirmationPending(), SqlBagOStuff\isExpired(), RecentChange\isInRCLifespan(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\isTimestampValid(), User\loadDefaults(), ChangesFeed\loadFromCache(), LocalFile\loadFromCache(), User\loadFromCache(), MessageCache\loadFromDB(), WikiPage\loadFromRow(), RecentChange\loadFromRow(), User\loadFromRow(), SpecialUndelete\loadRequest(), GenerateSitemap\main(), FormatMetadata\makeFormattedData(), MediaWiki\Session\Token\match(), SpecialBlock\maybeAlterFormDefaults(), User\newTouchedTimestamp(), OutputPage\output(), InfoAction\pageCounts(), ApiStashEdit\parseAndStash(), SpecialBlock\parseExpiryInput(), User\pingLimiter(), PdfImage\postProcessDump(), TableCleanup\progress(), ImageBuilder\progress(), ApiMainTest\provideCheckConditionalRequestHeaders(), ApiBaseTest\provideGetParameterFromSettings(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), LanguageTest\provideTranslateBlockExpiry(), LocalFile\publishTo(), RebuildRecentchanges\rebuildRecentChangesTablePass1(), QueryPage\recache(), LocalFile\recordUpload2(), ManageJobs\repushAbandoned(), ApiQueryCategories\run(), ApiQueryCategoryMembers\run(), ApiQueryDuplicateFiles\run(), ApiQueryProtectedTitles\run(), ApiQueryQueryPage\run(), ApiQueryWatchlistRaw\run(), CategoryMembershipChangeJob\run(), RefreshLinksJob\runForTitle(), ChangesFeed\saveToCache(), ApiMain\sendCacheHeaders(), ResourceLoader\sendResponseHeaders(), Block\setCookie(), OutputPage\setLastModified(), MediaWiki\Storage\MutableRevisionRecord\setTimestamp(), WikiRevision\setTimestamp(), WikiPage\setTimestamp(), UserGroupMembershipTest\setUp(), BackupDumper\showReport(), TextPassDumper\showReport(), UpdateLogging\sync(), UserTest\testAutoblockCookieInfiniteExpiry(), UserTest\testAutoblockCookies(), EditPageTest\testAutoMerge(), ApiBlockTest\testBlockWithExpiry(), BlockTest\testBug26425BlockTimestampDefaultsToTime(), ApiMainTest\testCheckConditionalRequestHeadersFailed(), RangeChronologicalPagerTest\testGetDateCond(), MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProviderTest\testGetNewPasswordExpiry(), ApiBaseTest\testGetParameterFromSettings(), WfTimestampTest\testHttpDate(), RevisionDbTestBase\testInsertOn(), WfTimestampTest\testNormalTimestamps(), WfTimestampTest\testOldTimestamps(), JobQueueTest\testRootDeduplication(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testSetPasswordResetFlag(), WfTimestampTest\testTimestampParameter(), ApiEditPageTest\testUndoWithSwappedRevisions(), TitlePermissionTest\testUserBlock(), Language\time(), Language\timeanddate(), IPTC\timeHelper(), DatabaseOracle\timestamp(), MediaWiki\Session\Token\toString(), ApiUpload\transformWarnings(), ResourceLoader\tryRespondFromFileCache(), RecentChangesUpdateJob\updateActiveUsers(), WikiPage\updateIfNewerOn(), Block\updateTimestamp(), ApiStructureTest\validateDefault(), ApiBase\validateTimestamp(), EditPage\wasDeletedSinceLastEdit(), wfStreamThumb(), wfTimestampOrNull(), and XmlDumpWriter\writeTimestamp().

◆ wfTimestampNow()

wfTimestampNow ( )

Convenience function; returns MediaWiki timestamp for the present time.

Returns
string

Definition at line 2009 of file GlobalFunctions.php.

Referenced by CategoryMembershipChange\__construct(), LinksDeletionUpdate\__construct(), EditPageTest\assertEdit(), User\confirmEmail(), MediaWiki\Preferences\DefaultPreferencesFactory\datetimePreferences(), Block\doAutoblock(), WikiPage\doCreate(), SpecialWatchlist\doHeader(), WikiPage\doModify(), PoolWorkArticleView\doWork(), SpecialExport\execute(), ApiEditPage\execute(), ApiProtect\execute(), ApiUserrights\execute(), GenerateSitemap\execute(), ImportTextFiles\execute(), MigrateFileRepoLayout\execute(), PPFuzzTest\execute(), ResetUserEmail\execute(), UpdateSearchIndex\execute(), LogFormatterTestCase\expandDatabaseRow(), SqlBagOStuff\expireAll(), FormatMetadata\fetchExtendedMetadata(), Title\getCascadeProtectionSources(), MediaWiki\Preferences\DefaultPreferencesFactory\getDateOptions(), ApiCategoryTree\getHTML(), Parser\getRevisionTimestamp(), ManualLogEntry\getTimestamp(), ParserOptions\getTimestamp(), EditPage\importFormData(), MediaWiki\Storage\RevisionStore\initializeMutableRevisionFromArray(), ManualLogEntry\insert(), HTMLCacheUpdateJob\invalidateTitles(), MessageCache\isCacheExpired(), Block\isExpired(), UserGroupMembership\isExpired(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), Job\newRootJobParams(), SpecialLockdb\onSubmit(), SpecialRecentChanges\optionsPanel(), RSSFeed\outHeader(), AtomFeed\outHeader(), WikiPage\prepareContentForEdit(), SpecialBlock\processForm(), WikiImporter\processRevision(), ManageJobs\repushAbandoned(), ParserCache\save(), ProtectionForm\save(), LogPage\saveContent(), HTMLFileCache\saveToFileCache(), UserrightsPage\saveUserGroups(), AjaxResponse\storeInMemcached(), EditPageTest\testAutoMerge(), BlockTest\testBlockedUserCanNotCreateAccount(), EditPageTest\testCheckDirectEditingDisallowed_forNonTextContent(), BlockTest\testCrappyCrossWikiBlocks(), MessageTest\testExpiryParams(), RevisionDbTestBase\testGetTimestamp(), LanguageTest\testSprintfDateNoTtlIfNotNeeded(), BlockTest\testSystemBlocks(), and MediaWiki\Tests\Storage\RevisionStoreDbTest\testUserWasLastToEdit_true().

◆ wfTimestampOrNull()

◆ wfTransactionalTimeLimit()

wfTransactionalTimeLimit ( )

Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit.

Returns
int Prior time limit
Since
1.26

Definition at line 3073 of file GlobalFunctions.php.

References $wgTransactionalTimeLimit.

Referenced by RollbackAction\onView(), Action\useTransactionalTimeLimit(), ApiBase\useTransactionalTimeLimit(), and SpecialPage\useTransactionalTimeLimit().

◆ 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 3202 of file GlobalFunctions.php.

References $result.

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:

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

RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved character which should not be encoded. More importantly, google chrome always converts %7E back to ~, and converting it in this function can cause a redirect loop (T105265).

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 (see T24709), so no fancy : for IIS7.

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

Parameters
string$s
Returns
string

Definition at line 340 of file GlobalFunctions.php.

References $s.

Referenced by Title\__wakeup(), OutputPage\addHelpLink(), CoreParserFunctions\basepagenamee(), FileRepo\getDescriptionRenderUrl(), FileRepo\getDescriptionUrl(), LoginSignupSpecialPage\getFakeTemplate(), WikiReference\getLocalUrl(), Title\getLocalURL(), MediaWikiSite\getPageUrl(), Title\getPrefixedURL(), LoginSignupSpecialPage\getReturnToQueryStringFragment(), Title\getSubpageUrlForm(), ParserOutput\getText(), Interwiki\getURL(), Parser\getVariableValue(), ApiBase\logFeatureUsage(), ApiMain\logRequest(), Title\makeTitle(), CoreParserFunctions\namespacee(), CoreParserFunctions\nse(), CoreParserFunctions\rootpagenamee(), 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 727 of file GlobalFunctions.php.

References $retval, and $wgUrlProtocols.

Referenced by Parser\__construct(), Skin\addToSidebarPlain(), ResourceLoaderStartUpModule\getConfigSettings(), Skin\makeInternalOrExternalUrl(), Sanitizer\safeEncodeAttribute(), Sanitizer\validateAttributes(), and wfUrlProtocolsWithoutProtRel().

◆ 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 772 of file GlobalFunctions.php.

References wfUrlProtocols().

Referenced by Parser\doMagicLinks(), 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
Deprecated
since 1.26, use the "requires" property of extension.json
Parameters
string | int | float$req_verThe version to check, can be a string, an integer, or a float
Exceptions
MWException

Definition at line 2559 of file GlobalFunctions.php.

References $wgVersion.

◆ 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 | int | float$req_verThe version to check, can be a string, an integer, or a float
Deprecated
since 1.30
Exceptions
MWException

Definition at line 2528 of file GlobalFunctions.php.

References wfDeprecated().

◆ wfVarDump()

wfVarDump ( $var)

A wrapper around the PHP function var_export().

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

Parameters
mixed$varA PHP variable to dump.

Definition at line 1734 of file GlobalFunctions.php.

References $s, $wgOut, and print.

◆ wfWaitForSlaves()

wfWaitForSlaves ( $ifWritesSince = null,
$wiki = false,
$cluster = false,
$timeout = null )

Waits for the replica DBs 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 replica DBs.

By default this waits on the main DB cluster of the current wiki. If $cluster is set to "*" it will wait on all DB clusters, including external ones. If the lag being waiting on is caused by the code that does this check, it makes since to use $ifWritesSince, particularly if cluster is "*", to avoid excess overhead.

Never call this function after a big DB write that is still in a transaction. This only makes sense after the possible lag inducing changes were committed.

Parameters
float | null$ifWritesSinceOnly wait if writes were done since this UNIX timestamp
string | bool$wikiWiki identifier accepted by wfGetLB
string | bool$clusterCluster name accepted by LBFactory. Default: false.
int | null$timeoutMax wait time. Default: 1 day (cli), ~10 seconds (web)
Returns
bool Success (able to connect and no timeouts reached)
Deprecated
since 1.27 Use LBFactory::waitForReplication

Definition at line 2966 of file GlobalFunctions.php.

References $e, wfIsCLI(), and wfWikiID().

Referenced by NamespaceConflictChecker\checkLinkTable(), CleanupUsersWithNoId\cleanup(), CleanupInvalidDbKeys\cleanupTable(), CompressOld\compressWithConcat(), RefreshLinks\deleteLinksFromNonexistent(), RefreshLinks\dfnCheckInterval(), FixExtLinksProtocolRelative\doDBUpdates(), MigrateActors\doDBUpdates(), PopulateArchiveRevId\doDBUpdates(), PopulateBacklinkNamespace\doDBUpdates(), PopulateFilearchiveSha1\doDBUpdates(), PopulateImageSha1\doDBUpdates(), PopulateLogSearch\doDBUpdates(), PopulateParentId\doDBUpdates(), PopulateRecentChangesSource\doDBUpdates(), RefreshLinks\doRefreshLinks(), CleanupArchiveUserText\execute(), UploadStashCleanup\execute(), ConvertUserOptions\execute(), DeleteBatch\execute(), DeleteDefaultMessages\execute(), DeleteEqualMessages\execute(), FixUserRegistration\execute(), ImportImages\execute(), InitEditCount\execute(), MakeTestEdits\execute(), PopulateCategory\execute(), RefreshImageMetadata\execute(), RemoveInvalidEmails\execute(), ResetUserTokens\execute(), BatchedQueryRunner\execute(), MwSql\execute(), TidyUpBug37714\execute(), UpdateMediaWiki\execute(), UpdateCollation\execute(), UpdateRestrictions\execute(), FixDefaultJsonContentPages\handleRow(), MigrateComments\migrate(), MigrateActors\migrate(), MigrateActors\migrateLogSearch(), MigrateActors\migrateToTemp(), MigrateComments\migrateToTemp(), moveToExternal(), RefreshLinks\refreshCategory(), UpdateSpecialPages\reopenAndWaitForReplicas(), resolveStubs(), BackupReader\showReport(), UpdateLogging\sync(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), and PopulateContentModel\updatePageRows().

◆ wfWarn()

◆ wfWikiID()

wfWikiID ( )

Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.

Returns
string

Definition at line 2763 of file GlobalFunctions.php.

References $wgDBname, and $wgDBprefix.

Referenced by ApiMain\__construct(), MediaWiki\Logger\Monolog\WikiProcessor\__invoke(), ApiQuerySiteinfo\appendGeneralInfo(), MediaWiki\Storage\RevisionStore\checkDatabaseWikiId(), UserDupes\checkDupes(), JobRunner\commitMasterChanges(), FileBackendGroup\config(), ParserTestRunner\createRepoGroup(), WikiPage\doDeleteUpdates(), WikiPage\doEditUpdates(), MysqlUpdater\doTemplatelinksUpdate(), AttachLatest\execute(), CleanupInvalidDbKeys\execute(), CopyJobQueue\execute(), CreateAndPromote\execute(), GenerateSitemap\execute(), InitEditCount\execute(), SyncFileBackend\execute(), UpdateMediaWiki\execute(), UpdateSearchIndex\execute(), UserrightsPage\fetchUser(), MediaWiki\Logger\LegacyLogger\formatAsWfDebugLog(), MediaWiki\Logger\LegacyLogger\formatAsWfLogDBError(), MediaWiki\Interwiki\ClassicInterwikiLookup\getAllPrefixesCached(), FancyCaptcha\getBackend(), User\getCacheKey(), WikiMap\getCanonicalServerInfoForAllWikis(), SiteConfiguration\getConfig(), ObjectCache\getDefaultKeyspace(), MediaWiki\Interwiki\ClassicInterwikiLookup\getInterwikiCacheEntry(), MachineReadableRCFeedFormatter\getLine(), FileBackendDBRepoWrapperTest\getMocks(), User\getNewMessageLinks(), User\getNewMessageRevisionId(), Skin\getNewtalks(), Profiler\getProfileID(), MediaWiki\getUrlDomainDistance(), Title\invalidateCache(), LocalIdLookup\isAttached(), ApiMain\logRequest(), RecompressTracked\logToFile(), UserMailer\makeMsgId(), EnqueueJob\newFromLocalJobs(), JobQueueMemoryTest\newJobQueue(), InterwikiHooks\onInterwikiLoadPrefix(), TextPassDumper\openSpawn(), ClassicInterwikiLookupTest\populateHash(), TableCleanup\progress(), WikiMapTest\provideGetWikiIdFromDomain(), RecentChangesUpdateJob\purgeExpiredRows(), RefreshLinksJob\run(), JobRunner\run(), FileBackendTest\setUp(), LocalFileTest\setUp(), MigrateFileRepoLayoutTest\setUp(), StoreBatchTest\setUp(), JobQueueTest\setUp(), MediaWikiMediaTestCase\setUp(), UploadFromUrlTestSuite\setUp(), SpecialInterwiki\showList(), BackupDumper\showReport(), TextPassDumper\showReport(), LockManagerGroup\singleton(), RecompressTracked\startReplicaProcs(), ExternalStoreMwstore\store(), FileBackendTest\testAsyncWrites(), FileTest\testGenerateBucketsIfNeeded(), ResourceLoaderWikiModuleTest\testGetPreloadedTitleInfo(), FileTest\testGetThumbnailSource(), JobQueueTest\testGetWiki(), LocalIdLookupTest\testIsAttached(), RevisionTest\testLoadFromTitle(), LBFactoryTest\testNiceDomains(), FileBackendTest\testReadAffinity(), FileBackendTest\testSanitizeOpHeaders(), RecentChangesUpdateJob\updateActiveUsers(), and wfWaitForSlaves().