MediaWiki  1.29.1
GlobalFunctions.php File Reference

Global functions used everywhere. More...

Go to the source code of this file.

Functions

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

Detailed Description

Global functions used everywhere.

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

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

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

Definition in file GlobalFunctions.php.

Function Documentation

◆ mimeTypeMatch()

mimeTypeMatch (   $type,
  $avail 
)
private

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

Basic wildcards are accepted in the array keys.

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

Parameters
string$type
array$avail
Returns
string

Definition at line 1904 of file GlobalFunctions.php.

Referenced by GlobalTest\testMimeTypeMatch().

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

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

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

◆ wfArrayDiff2_cmp()

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

Definition at line 187 of file GlobalFunctions.php.

◆ wfArrayInsertAfter()

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

Insert array into another array after the specified KEY

Parameters
array$arrayThe array.
array$insertThe array to insert.
mixed$afterThe key to insert after
Returns
array

Definition at line 269 of file GlobalFunctions.php.

Referenced by 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 3682 of file GlobalFunctions.php.

Referenced by 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 628 of file GlobalFunctions.php.

Referenced by WfAssembleUrlTest\testWfAssembleUrl().

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

Referenced by MWDebug\deprecated().

◆ wfBaseConvert()

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

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

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

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

Definition at line 2875 of file GlobalFunctions.php.

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

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

◆ wfBCP47()

wfBCP47 (   $code)

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

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

Definition at line 3370 of file GlobalFunctions.php.

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

◆ wfBoolToStr()

wfBoolToStr (   $value)

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

Parameters
bool$value
Returns
string

Definition at line 3179 of file GlobalFunctions.php.

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

◆ wfCanIPUseHTTPS()

wfCanIPUseHTTPS (   $ip)

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

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

Definition at line 3564 of file GlobalFunctions.php.

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

◆ wfCgiToArray()

wfCgiToArray (   $query)

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

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

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

Definition at line 453 of file GlobalFunctions.php.

Referenced by Linker\link(), Linker\makeBrokenImageLinkObj(), SpecialChangeEmail\onSuccess(), OutputPage\returnToMain(), LoginHelper\showReturnToPage(), 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 1856 of file GlobalFunctions.php.

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

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

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

Parameters
int$seconds

Definition at line 3250 of file GlobalFunctions.php.

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

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

Referenced by QuickTemplate\__construct(), PageArchive\__construct(), UploadFromChunks\__construct(), UploadFromStash\__construct(), DifferenceEngine\__construct(), ApiMain\__construct(), Revision\__construct(), UploadStashFile\__construct(), StubObject\_unstub(), LogPage\actionText(), ImageGalleryBase\add(), MediaHandler\addMeta(), LinkBatch\addObj(), LocalFileMoveBatch\addOlds(), ParserOutput\addTrackingCategory(), Skin\afterContentHook(), SkinTemplate\buildContentActionUrls(), SimpleCaptcha\buildRegexes(), EmailNotification\canSendUserTalkEmail(), AjaxResponse\checkLastModified(), OutputPage\checkLastModified(), JobQueueDB\claimOldest(), LocalRepo\cleanupDeletedBatch(), SpecialEditWatchlist\cleanupWatchlist(), UploadStash\clear(), CloneDatabase\cloneTableStructure(), Revision\compressRevisionText(), UploadFromChunks\concatenateChunks(), Article\confirmDelete(), SimpleCaptcha\confirmEditMerged(), SimpleCaptcha\confirmEmailUser(), BaseDump\debug(), WikiImporter\debug(), RecompressTracked\debug(), SVGReader\debug(), SectionProfiler\debug(), Block\defaultRetroactiveAutoblock(), Article\delete(), Block\deleteIfExpired(), User\deleteNewtalk(), ChangeTags\deleteTagEverywhere(), DiffEngine\diffInternal(), BitmapMetadataHandler\doApp13(), Block\doAutoblock(), JobQueueDB\doBatchPushInternal(), SimpleCaptcha\doConfirmEdit(), WikiPage\doDeleteArticleReal(), WikiPage\doEditUpdates(), MockImageHandler\doFakeTransform(), WikiFilePage\doPurge(), DatabaseOracle\doQuery(), Block\doRetroactiveAutoblock(), UserrightsPage\doSaveUserGroups(), TransformationalImageHandler\doTransform(), PdfHandler\doTransform(), DjVuHandler\doTransform(), WikiRevision\downloadSource(), EditPage\edit(), ZipDirectoryReader\error(), ApiUpload\execute(), SpecialUserLogout\execute(), ChangesFeed\execute(), SpecialUpload\execute(), LocalFileRestoreBatch\execute(), PoolWorkArticleView\fallback(), Article\fetchContentObject(), IcuCollation\fetchFirstLetterData(), MediaWikiGadgetsDefinitionRepo\fetchStructuredList(), DiffEngine\find_middle_snake(), BlockLevelPass\findColonNoLinks(), WikiImporter\finishImportPage(), FormatMetadata\flattenArrayReal(), DeletedContribsPager\formatRow(), ContribsPager\formatRow(), FileRepo\freeTemp(), LCStoreCDB\get(), ParserCache\get(), MediaWiki\Interwiki\ClassicInterwikiLookup\getAllPrefixesCached(), User\getBlockedStatus(), CoreParserFunctions\getCachedRevisionObject(), PoolWorkArticleView\getCachedWork(), ContextSource\getContext(), Profiler\getContext(), Action\getContext(), SpecialPage\getContext(), Article\getContext(), SpecialVersion\getCreditsForExtension(), ForeignDBFile\getDescriptionText(), File\getDescriptionText(), UploadStash\getFile(), DoubleRedirectJob\getFinalDestination(), WikiFilePage\getForeignCategories(), GenderCache\getGenderOf(), MediaHandlerFactory\getHandler(), SpecialUpload\getInitialPageText(), MediaWiki\Interwiki\ClassicInterwikiLookup\getInterwikiCacheEntry(), ParserCache\getKey(), ResourceLoaderContext\getLanguage(), TransformationalImageHandler\getMagickVersion(), RequestContext\getMainAndWarn(), PdfHandler\getMetaArray(), GIFHandler\getMetadata(), PNGHandler\getMetadata(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), TiffHandler\getMetadata(), JpegHandler\getMetadata(), DjVuHandler\getMetadata(), SvgHandler\getMetadata(), DjVuHandler\getMetaTree(), WebRequestUpload\getName(), Title\getNsText(), WikiPage\getParserOutput(), SpecialEmailUser\getPermissionsError(), EditPage\getPreloadedContent(), CollationFa\getPrimarySortKey(), UserCache\getProp(), Title\getRestrictionTypes(), ExternalStoreDB\getSlave(), SpecialEmailUser\getTarget(), ForeignAPIRepo\getThumbError(), ForeignAPIRepo\getThumbUrl(), UploadStashFile\getThumbUrl(), ForeignAPIRepo\getThumbUrlFromCache(), Title\getTitleValue(), File\getViewURL(), XCFHandler\getXCFMetaData(), VersionChecker\handleExtensionDependency(), OutputPage\haveCacheVaryCookies(), ThumbnailRenderJob\hitThumbUrl(), ForeignAPIRepo\httpGet(), EditPage\importFormData(), WikiRevision\importLogItem(), WikiRevision\importOldRevision(), WikiRevision\importUpload(), SimpleCaptcha\injectEmailUser(), Block\insert(), ExternalStore\insertWithFallback(), EditPage\internalAttemptSave(), User\isBlockedFrom(), FileCacheBase\isCacheGood(), PdfHandler\isEnabled(), DjVuHandler\isEnabled(), SvgHandler\isEnabled(), FileDependency\isExpired(), LocalisationCache\isExpired(), Block\isExpired(), WebPHandler\isMetadataValid(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), MovePage\isValidMoveTarget(), Title\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(), RawAction\onView(), UploadDumper\outputItem(), ApiBase\parseMsg(), SearchSqlite\parseQuery(), SearchMySQL\parseQuery(), SearchPostgres\parseQuery(), BacklinkCache\partition(), DiffHistoryBlob\patch(), AjaxDispatcher\performAction(), ApiUpload\performStash(), FancyCaptcha\pickImageDir(), FancyCaptcha\pickImageFromDir(), User\pingLimiter(), MediaWiki\preOutputCommit(), SkinTemplate\prepareQuickTemplate(), SpecialUpload\processUpload(), LocalFile\purgeThumbList(), BacklinkCache\queryLinks(), SvgHandler\rasterize(), TextPassDumper\readDump(), LocalisationCache\recache(), LocalFile\recordUpload2(), UploadStash\removeFileNoAuth(), WikiPage\replaceSectionAtRev(), Http\request(), MediaWiki\restInPeace(), PdfImage\retrieveMetaData(), JpegHandler\rotate(), BitmapHandler\rotate(), ThumbnailRenderJob\run(), DoubleRedirectJob\run(), RequestContext\sanitizeLangCode(), ParserCache\save(), FileCacheBase\saveText(), HTMLFileCache\saveToFileCache(), SearchPostgres\searchQuery(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), OutputPage\sendCacheControl(), UserMailer\sendInternal(), UserMailer\sendWithPear(), ApiMain\setCacheMode(), LanguageClassesTestCase\setUp(), ParserTestTopLevelSuite\setUp(), UploadFromUrlTestSuite\setupUploadDir(), SimpleCaptcha\shouldCheck(), ViewAction\show(), LocalRepo\skipWriteOperationIfSha1(), User\spreadBlock(), UploadStash\stashFile(), FileRepo\storeBatch(), ParserTestTopLevelSuite\tearDown(), 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(), OldLocalFile\upgradeRow(), LocalFile\upgradeRow(), HTMLFileCache\useFileCache(), LogEventsList\userCanBitfield(), Revision\userCanBitfield(), SvgHandler\validateParam(), ImageHandler\validateThumbParams(), Article\view(), WikiImporter\warn(), and wfGzipHandler().

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

Referenced by MWDebug\getCallerDescription().

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

Referenced by GitInfo\__construct(), LocalisationCache\__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(), ParserTestTopLevelSuite\debug(), RenameuserSQL\debug(), Exif\debug(), Exif\debugFile(), SectionProfiler\debugGroup(), WebPHandler\decodeLosslessChunkHeader(), WebPHandler\decodeLossyChunkHeader(), JobQueueRedis\doAck(), JobQueueRedis\doBatchPush(), FileBackendMultiWrite\doOperationsInternal(), JobQueueRedis\doPop(), TransformationalImageHandler\doTransform(), PdfHandler\doTransform(), DjVuHandler\doTransform(), SvgHandler\doTransform(), MediaWikiPHPUnitTestListener\endTest(), MediaWikiPHPUnitTestListener\endTestSuite(), CheckUsernames\execute(), LocalFileMoveBatch\execute(), WebPHandler\extractMetadata(), WebPHandler\extractMetadataFromChunks(), PoolWorkArticleView\fallback(), ExternalStoreDB\fetchBlob(), Revision\fetchText(), SpamBlacklist\filter(), DifferenceEngine\generateTextDiffBody(), ParserCache\get(), BaseBlacklist\getArticleText(), IPTC\getCharset(), LocalisationCache\getCompiledPluralRules(), ResourceLoaderWikiModule\getContentObj(), ContentHandler\getContentText(), ContentHandler\getForModelID(), BaseBlacklist\getHttpText(), ResourceLoaderImage\getImageData(), ParserCache\getKey(), RequestContext\getLanguage(), LocalFileMoveBatch\getMoveTriplets(), BaseBlacklist\getSharedBlacklists(), ResourceLoaderFileModule\getTemplates(), RequestContext\getTitle(), CdnCacheUpdate\HTCPPurge(), User\inDnsBlacklist(), CreatePdfThumbnailsJob\insertJobs(), ExternalStore\insertWithFallback(), EditPage\internalAttemptSave(), User\isCreatableName(), TitleBlacklist\load(), MessageCache\load(), MessageCache\loadFromDB(), SquidPurgeClient\log(), SimpleCaptcha\log(), PoolCounterWork\logError(), MediaHandler\logErrorForExternalProcess(), JobQueueFederated\logException(), ApiBase\logFeatureUsage(), ApiMain\logRequest(), SpamBlacklist\logUrlChange(), MediaWiki\main(), TitleBlacklistEntry\matches(), ApiMain\matchRequestedHeaders(), LocalFile\move(), MediaWiki\Site\MediaWikiPageNameNormalizer\normalizePageName(), IPTC\parse(), MessageCache\parse(), User\pingLimiter(), GitInfo\precomputeValues(), MediaWiki\preOutputCommit(), CdnCacheUpdate\purge(), ResourceLoaderFileModule\readStyleFile(), UploadFromUrl\reallyFetchFile(), MediaHandler\removeBadFile(), LocalFileMoveBatch\removeNonexistentFiles(), FileBackendMultiWrite\resyncFiles(), CreatePdfThumbnailsJob\run(), SquidPurgeClientPool\run(), ResourceLoaderModule\saveFileDependencies(), UploadFromUrl\saveTempFileChunk(), MWDebug\sendMessage(), WebResponse\setCookie(), MediaWikiPHPUnitTestListener\startTest(), MediaWikiPHPUnitTestListener\startTestSuite(), 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 1057 of file GlobalFunctions.php.

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
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 1128 of file GlobalFunctions.php.

Referenced by StripState\__construct(), MailAddress\__construct(), WikiImporter\__construct(), Block\__construct(), ApiResult\__construct(), OutputPage\__construct(), LoginForm\__construct(), DeprecatedGlobal\_newObject(), OutputPage\addExtensionStyle(), ApiQueryLogEvents\addLogParams(), OutputPage\addParserOutputNoText(), WatchedItem\addWatch(), MediaWiki\Session\SessionManager\autoCreateUser(), Job\batchInsert(), buildHeadItem(), User\clearCookie(), LoginForm\clearCreateaccountToken(), LoginForm\clearLoginThrottle(), LoginForm\clearLoginToken(), ConfirmEditHooks\confirmEditSetup(), User\createNew(), Article\doEditContent(), WatchedItem\duplicateEntries(), FancyCaptcha\estimateCaptchaCount(), Title\fixUrlQueryArgs(), DummyLinker\formatSize(), Linker\formatSize(), DummyLinker\formatTemplates(), Linker\formatTemplates(), WatchedItem\fromUserTitle(), LoginForm\getCreateaccountToken(), User\getEditTokenTimestamp(), HTMLForm\getErrors(), OutputPage\getExtStyle(), LoginSignupSpecialPage\getFakeTemplate(), ReCaptcha\getFormInformation(), User\getGroupMember(), User\getGroupName(), User\getGroupPage(), OutputPage\getHeadLinks(), ApiPageSet\getInvalidTitles(), JsonContent\getJsonData(), WikiPage\getLastPurgeTimestamp(), Article\getLastPurgeTimestamp(), MWLBFactory\getLBFactoryClass(), DummyLinker\getLinkColour(), Linker\getLinkColour(), SpecialPageFactory\getList(), MWExceptionHandler\getLogId(), LoginForm\getLoginToken(), ApiBase\getModuleProfileName(), SearchEngine\getOpenSearchTemplate(), SpecialPageFactory\getPage(), User\getPasswordFactory(), ApiBase\getProfileDBTime(), ApiBase\getProfileTime(), Revision\getRawComment(), Revision\getRawUser(), Revision\getRawUserText(), Title\getTitleInvalidRegex(), MediaWikiTestCase\hideDeprecated(), LoginForm\incLoginThrottle(), LoginForm\incrementLoginThrottle(), VFormHTMLForm\isVForm(), HTMLForm\isVForm(), WatchedItem\isWatched(), Linker\link(), ChangeTags\listExtensionActivatedTags(), ChangeTags\listExtensionDefinedTags(), User\makeGroupLinkHTML(), User\makeGroupLinkWiki(), Article\onArticleCreate(), Article\onArticleDelete(), Article\onArticleEdit(), SkinTemplate\outputPage(), prepare(), ApiBase\profileDBIn(), ApiBase\profileDBOut(), OutputPage\rateLimited(), ExtensionRegistry\readFromQueue(), ResourceLoaderFileModule\readStyleFiles(), WatchedItem\removeWatch(), MagicWord\replaceMultiple(), Hooks\run(), ApiBase\safeProfileOut(), Article\selectFields(), User\setCookie(), LoginForm\setCreateaccountToken(), User\setExtendedLoginCookie(), DeferredUpdates\setImmediateMode(), LoginForm\setLoginToken(), Skin\showIPinHeader(), UploadFromChunks\stashFile(), UploadFromChunks\stashFileGetKey(), UploadFromChunks\stashSession(), SpecialEmailUser\submit(), DifferenceEngine\textDiff(), SiteStats\views(), wfExtractThumbParams(), 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 2665 of file GlobalFunctions.php.

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

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

Referenced by MediaHandler\addMeta(), CoreParserFunctions\basepagename(), CoreParserFunctions\basepagenamee(), SpecialPageLanguage\changePageLanguage(), ApiMain\checkAsserts(), ApiQueryImageInfo\checkParameterNormalise(), SpecialContributions\contributionsSub(), ApiMain\createPrinterByName(), CoreParserFunctions\defaultsort(), Article\delete(), CoreParserFunctions\displaytitle(), FileDeleteForm\doDelete(), Article\doDelete(), WikiPage\doDeleteArticleReal(), ApiCSPReport\error(), ApiMain\errorMessagesFromException(), ApiValidatePassword\execute(), ApiProtect\execute(), ApiUndelete\execute(), ApiMove\execute(), ApiMergeHistory\execute(), ApiExpandTemplates\execute(), ApiQueryTitleBlacklist\execute(), ApiEditPage\execute(), ApiQueryAllMessages\execute(), ApiParse\execute(), ApiQueryLogEvents\execute(), SpecialUnblock\execute(), ApiQueryContributions\execute(), ApiUserrights\execute(), ApiAMCreateAccount\execute(), ApiLinkAccount\execute(), ApiClientLogin\execute(), FileDuplicateSearchPage\execute(), SpecialMergeHistory\execute(), PasswordReset\execute(), ApiQueryRevisionsBase\extractRevisionInfo(), CoreParserFunctions\fullpagename(), CoreParserFunctions\fullpagenamee(), ApiFeedRecentChanges\getFeedObject(), CategoryViewer\getImageSection(), ApiErrorFormatter\getMessageFromException(), ApiBase\getModuleFromPath(), CategoryViewer\getPagesSection(), ApiRollback\getRbTitle(), ApiRollback\getRbUser(), ApiBase\getTitleFromTitleOrPageId(), ApiBase\getTitleOrPageId(), ApiBase\getWatchlistUser(), EditPage\importFormData(), MediaWiki\Auth\LegacyHookPreAuthenticationProvider\makeFailResponse(), SpecialBlock\maybeAlterFormDefaults(), ApiQueryImageInfo\mergeThumbParams(), PPFrame_Hash\newChild(), PPFrame_DOM\newChild(), SpecialRandomInCategory\onSubmit(), SpecialBlock\onSuccess(), ImagePage\openShowImage(), ImageListPager\outputUserDoesNotExist(), CoreParserFunctions\pagename(), CoreParserFunctions\pagenamee(), ApiBase\parseMsgInternal(), ApiBase\parseMultiValue(), SpecialBlock\postText(), ApiQueryBase\prefixedTitlePartToKey(), FileDeleteForm\prepareMessage(), ApiQueryBlocks\prepareUsername(), ApiComparePages\revisionOrTitleOrId(), CoreParserFunctions\rootpagename(), CoreParserFunctions\rootpagenamee(), ApiQueryImages\run(), ApiQueryCategories\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(), 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 888 of file GlobalFunctions.php.

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

◆ wfExpandIRI_callback()

wfExpandIRI_callback (   $matches)

Private callback for wfExpandIRI.

Parameters
array$matches
Returns
string

Definition at line 901 of file GlobalFunctions.php.

◆ wfExpandUrl()

wfExpandUrl (   $url,
  $defaultProto = PROTO_CURRENT 
)

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

Assumes $wgServer is correct.

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

Todo:
this won't work with current-path-relative URLs like "subdir/foo.html", etc.
Parameters
string$urlEither fully-qualified or a local path + query
string$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 552 of file GlobalFunctions.php.

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

◆ wfFindFile()

◆ wfFixSessionID()

wfFixSessionID ( )
Deprecated:
since 1.27, PHP's session generation isn't used with MediaWiki\Session\SessionManager

Definition at line 2885 of file GlobalFunctions.php.

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

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

◆ wfGetAllCallers()

wfGetAllCallers (   $limit = 3)

Return a string consisting of callers in the stack.

Useful sometimes for profiling specific points.

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

Definition at line 1577 of file GlobalFunctions.php.

Referenced by MediaWiki\Session\SessionBackend\addData(), MediaWiki\Session\SessionBackend\dirty(), 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 3398 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
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 1561 of file GlobalFunctions.php.

Referenced by StubObject\_unstub(), DeferredUpdates\addCallableUpdate(), MediaWikiTestCase\assertSelect(), WfGetCallerTest\callerOne(), ParserTestTopLevelSuite\debug(), WfGetCallerTest\intermediateFunction(), MWDebug\log(), WfGetCallerTest\testZero(), and MediaWiki\HeaderCallback\warnIfHeadersSent().

◆ 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
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 3060 of file GlobalFunctions.php.

Referenced by SpecialRandomrootpage\__construct(), MergeHistoryPager\__construct(), SearchDatabase\__construct(), DeletedContribsPager\__construct(), ContribsPager\__construct(), ImageListPager\__construct(), LogPager\__construct(), MergeHistory\__construct(), Block\__construct(), IndexPager\__construct(), SiteStatsInit\__construct(), Pingback\acquireLock(), OutputPage\addCategoryLinksToLBAndGetResult(), BotPasswordTest\addDBData(), 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(), SiteStatsUpdate\cacheUpdate(), SpecialPageLanguage\changePageLanguage(), UserOptions\CHANGER(), CheckStorage\check(), User\checkAndSetTouched(), Pingback\checkIfSent(), TrackBlobs\checkIntegrity(), User\checkNewtalk(), RenameUserCleanup\checkRenameLog(), RevisionDeleter\checkRevisionExistence(), RecompressTracked\checkTrackingTable(), User\clearAllNotifications(), User\clearSharedCache(), SpecialEditWatchlist\clearWatchlist(), CgzCopyTransaction\commit(), WikiPage\commitRollback(), Title\countRevisionsBetween(), SearchEngineFactory\create(), User\createNew(), ChangesListSpecialPageTest\createUsers(), Block\defaultRetroactiveAutoblock(), PrefixSearch\defaultSearchBackend(), ChangeTags\defineTag(), UserGroupMembership\delete(), SearchMySQL\delete(), Block\delete(), Article\delete(), DifferenceEngine\deletedLink(), User\deleteNewtalk(), ChangeTags\deleteTagEverywhere(), Title\deleteTitleProtection(), SpecialUndelete\diffHeader(), SpecialRedirect\dispatchLog(), SiteStatsInit\doAllAndCommit(), 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(), UserCache\doQuery(), GenderCache\doQuery(), LinkBatch\doQuery(), SpecialInterwiki\doSubmit(), MovePageForm\doSubmit(), WikiPage\doUpdateRestrictions(), LinkHolderArray\doVariants(), Title\estimateRevisionCount(), CleanupArchiveUserText\execute(), SpecialRenameuser\execute(), ApiSetNotificationTimestamp\execute(), ParserTestsMaintenance\execute(), QueryPage\fetchFromCache(), Revision\fetchRevision(), HistoryAction\fetchRevisions(), Revision\fetchText(), ChangesListSpecialPageTest\fetchUsers(), TrackBlobs\findOrphanBlobs(), User\findUsersByGroup(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\finishAccountCreation(), RecompressTracked\finishIncompleteMoves(), DoubleRedirectJob\fixRedirects(), EditPageTest\forceRevisionDate(), ApiEditPageTest\forceRevisionDate(), ApiResult\formatExpiry(), Language\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(), ResourceLoaderWikiModule\getContentObj(), WikiPage\getContributors(), RevDelRevisionList\getCurrent(), SpamBlacklist\getCurrentLinks(), AllMessagesTablePager\getCustomisedStatuses(), Block\getDatabaseArray(), ResourceLoaderWikiModule\getDB(), BacklinkCache\getDB(), UserRightsProxy\getDB(), SqlBagOStuff\getDB(), LinksDeletionUpdate\getDB(), SpecialRecentChanges\getDB(), SpecialWatchlist\getDB(), ApiBase\getDB(), ChangesListSpecialPage\getDB(), LinksUpdate\getDB(), Maintenance\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(), Category\getMembers(), UserGroupMembership\getMembership(), UserGroupMembership\getMembershipsForUser(), SpecialRandomInCategory\getMinAndMaxForCat(), MessageCache\getMsgFromNamespace(), ApiQuery\getNamedDB(), User\getNewMessageLinks(), SpecialNuke\getNewPages(), Title\getNextRevisionID(), Pingback\getOrCreatePingbackId(), SpecialExport\getPagesFromCategory(), SpecialExport\getPagesFromNamespace(), Title\getParentCategories(), PageArchive\getPreviousRevision(), Title\getPreviousRevisionID(), PageProps\getProperties(), WantedPagesPage\getQueryInfo(), NewFilesPager\getQueryInfo(), BrokenRedirectsPage\getQueryInfo(), MediaStatisticsPage\getQueryInfo(), UnwatchedpagesPage\getQueryInfo(), UncategorizedCategoriesPage\getQueryInfo(), SpecialGadgetUsage\getQueryInfo(), WithoutInterwikiPage\getQueryInfo(), UsersPager\getQueryInfo(), LinkSearchPage\getQueryInfo(), SpecialRandomInCategory\getQueryInfo(), ImageListPager\getQueryInfoReal(), Block\getRangeCond(), QueryPage\getRecacheDB(), Revision\getRecentChange(), Title\getRedirectsHere(), WikiPage\getRedirectTarget(), LocalRepo\getReplicaDB(), PageArchive\getRevision(), OutputPage\getRlClient(), Linker\getRollbackEditCount(), Title\getSubpages(), MIMEsearchPage\getSuggestionsForTypes(), HistoryBlobStub\getText(), HistoryBlobCurStub\getText(), TrackBlobs\getTextClause(), PageArchive\getTextFromRow(), Revision\getTimestampFromId(), Title\getTitleProtectionInternal(), Title\getTouched(), SpecialUpload\getUploadForm(), PasswordReset\getUsersByEmail(), User\idForName(), User\idFromName(), WikiRevision\importLogItem(), WikiRevision\importOldRevision(), CheckStorage\importRevision(), User\incEditCount(), User\incEditCountImmediate(), User\initEditCount(), Block\initFromRow(), Category\initialize(), BackupDumper\initProgress(), TrackBlobs\initTrackingTable(), UserGroupMembership\insert(), Block\insert(), ManualLogEntry\insert(), 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(), PageArchive\listAllPages(), ChangeTags\listExplicitlyDefinedTags(), PageArchive\listFiles(), PageArchive\listPagesByPrefix(), PageArchive\listPagesBySearch(), PageArchive\listRevisions(), ChangeTags\listSoftwareActivatedTags(), ChangeTags\listSoftwareDefinedTags(), SiteStats\load(), ArchivedFile\load(), MediaWiki\Interwiki\ClassicInterwikiLookup\load(), SiteStats\loadAndLazyInit(), User\loadFromCache(), User\loadFromDatabase(), MessageCache\loadFromDB(), User\loadGroups(), WikiPage\loadLastEdit(), User\loadOptions(), WikiPage\loadPageData(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), DifferenceEngine\loadRevisionData(), WikiPage\lockAndGetLatest(), RenameuserSQL\lockUserAndGetId(), ProfilerOutputDb\log(), ChangeTags\logTagManagementAction(), LocalIdLookup\lookupCentralIds(), LocalIdLookup\lookupUserNames(), LinkFilter\makeLikeArray(), RevisionStorageTest\makeRevision(), Pingback\markSent(), EditPage\mergeChangesIntoContent(), SearchMySQL\minSearchLength(), ChangeTags\modifyDisplayQuery(), MovePage\move(), RecompressTracked\moveTextRow(), moveToExternal(), MovePage\moveToInternal(), LinkSearchPage\mungeQuery(), Title\nameOf(), RecentChange\newFromConds(), Revision\newFromConds(), User\newFromConfirmationCode(), WikiPage\newFromID(), Block\newFromID(), Title\newFromID(), UserArray\newFromIDs(), Title\newFromIDs(), UserArray\newFromNames(), Revision\newFromPageId(), Revision\newFromTitle(), Block\newLoad(), User\newSystemUser(), RecentChange\notifyEdit(), RecentChange\notifyNew(), SiteStats\numberingroup(), InterwikiHooks\onInterwikiLoadPrefix(), HistoryAction\onView(), ImagePage\openShowImage(), InfoAction\pageCounts(), SiteStats\pagesInNs(), ApiStashEdit\parseAndStash(), ClassicInterwikiLookupTest\populateDB(), InterwikiTest\populateDB(), WikiPage\prepareContentForEdit(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData(), ManualLogEntry\publish(), UserGroupMembership\purgeExpired(), Block\purgeExpired(), Title\purgeExpiredRestrictions(), RecentChangesUpdateJob\purgeExpiredRows(), SpecialPagesWithProp\queryExistingProps(), ImagePage\queryImageLinks(), DoubleRedirectsPage\reallyGetQueryInfo(), RecentChange\reallyMarkPatrolled(), RebuildRecentchanges\rebuildRecentChangesTablePass5(), QueryPage\recache(), MessageBlobStore\recacheMessageBlob(), SiteStatsInit\refresh(), Category\refreshCounts(), ChangeTagsList\reloadFromMaster(), RevDelList\reloadFromMaster(), RenameuserSQL\rename(), LinkHolderArray\replaceInternal(), WikiPage\replaceSectionContent(), ImportReporter\reportPage(), RevisionListBase\reset(), resolveStub(), resolveStubs(), CheckStorage\restoreText(), RenameUserJob\run(), DeleteLinksJob\run(), CategoryFinder\run(), MediaWikiTestCase\run(), RecentChange\save(), LogPage\saveContent(), ResourceLoaderModule\saveFileDependencies(), User\saveOptions(), User\saveSettings(), UserNamePrefixSearch\search(), RandomPage\selectRandomPageFromDB(), SpecialRandomInCategory\selectRandomPageFromDB(), RevDelArchivedRevisionItem\setBits(), RevDelArchiveItem\setBits(), RevDelLogItem\setBits(), RevDelArchivedFileItem\setBits(), RevDelRevisionItem\setBits(), RevDelFileItem\setBits(), TestUser\setPasswordForUser(), TestPageProps\setProperties(), WikiPageTestContentHandlerUseDB\setUp(), RevisionTestContentHandlerUseDB\setUp(), DatabaseTest\setUp(), LinksUpdateTest\setUp(), ParserTestTopLevelSuite\setUp(), RevisionDeleteUser\setUsernameBitfields(), RevDelList\setVisibility(), SpecialAllPages\showChunk(), SpecialInterwiki\showForm(), MovePageForm\showForm(), SpecialWhatLinksHere\showIndirectLinks(), EditPage\showIntro(), SpecialInterwiki\showList(), LogEventsList\showLogExtract(), Article\showMissingArticle(), Article\showPatrolFooter(), SpecialPrefixindex\showPrefixChunk(), SpecialVersion\softwareInformation(), LCStoreDB\startWrite(), 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(), ApiLoginTest\testBotPassword(), RevisionStorageTest\testConstructFromRow(), EditPageTest\testCreatePageTrx(), WikiPageTest\testDoDeleteArticle(), WikiPageTest\testDoDeleteUpdates(), WikiPageTest\testDoEditContent(), UserTest\testExperienceLevel(), ReverseChronologicalPagerTest\testGetDateCond(), BotPasswordTest\testGetPassword(), ResourceLoaderWikiModuleTest\testGetPreloadedBadTitle(), ResourceLoaderWikiModuleTest\testGetPreloadedTitleInfo(), ResourceLoaderWikiModuleTest\testGetPreloadedTitleInfoEmpty(), RevisionStorageTest\testNewFromArchiveRow(), MediaWiki\Session\UserInfoTest\testNewFromId(), RevisionStorageTest\testNewFromRow(), RevisionStorageTest\testNewNullRevision(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testProviderChangeAuthenticationData(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testProviderChangeAuthenticationData(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testProviderChangeAuthenticationDataEmail(), MessageCacheTest\testReplaceMsg(), MultiWriteBagOStuffTest\testSetDelayed(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testSetPasswordResetFlag(), DatabaseTest\testStoredFunctions(), MultiWriteBagOStuffTest\testSyncMerge(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testTestUserCanAuthenticate(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProviderTest\testTestUserCanAuthenticate(), EditPageTest\testUpdatePageTrx(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserExists(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\testUserExists(), RevisionStorageTest\testUserWasLastToEdit(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), SiteStatsUpdate\tryDBUpdateInternal(), ChangeTags\undefineTag(), PageArchive\undeleteRevisions(), SearchOracle\update(), SearchSqlite\update(), SearchMySQL\update(), Block\update(), RecentChangesUpdateJob\updateActiveUsers(), WikiPage\updateCategoryCounts(), User\updateNewtalk(), RenameUserCleanup\updateTable(), ChangeTags\updateTags(), ChangeTags\updateTagSummaryRow(), ChangeTags\updateTagsWithChecks(), Block\updateTimestamp(), SearchOracle\updateTitle(), SearchSqlite\updateTitle(), SearchMySQL\updateTitle(), ActivityUpdateJob\updateWatchlistNotification(), UserOptions\USAGER(), 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 1321 of file GlobalFunctions.php.

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

◆ wfGetLB()

◆ wfGetLBFactory()

◆ wfGetMainCache()

◆ wfGetMessageCacheStorage()

wfGetMessageCacheStorage ( )

Get the cache object used by the message cache.

Returns
BagOStuff

Definition at line 3417 of file GlobalFunctions.php.

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

◆ wfGetNull()

wfGetNull ( )

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

/dev/null

Returns
string

Definition at line 3188 of file GlobalFunctions.php.

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

◆ wfGetParserCacheStorage()

wfGetParserCacheStorage ( )

Get the cache object used by the parser cache.

Returns
BagOStuff

Definition at line 3427 of file GlobalFunctions.php.

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

◆ wfGetPrecompiledData()

wfGetPrecompiledData (   $name)

Get an object from the precompiled serialized directory.

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

Definition at line 2942 of file GlobalFunctions.php.

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

◆ wfGetScriptUrl()

wfGetScriptUrl ( )

Get the script URL.

Returns
string Script URL

Definition at line 3154 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.

Since
1.26
Parameters
string$args,...
Returns
string

Definition at line 2998 of file GlobalFunctions.php.

Referenced by SimpleCaptcha\badLoginKey(), SimpleCaptcha\badLoginPerUserKey(), MediaWiki\Auth\Throttler\clear(), MediaWiki\Auth\Throttler\increase(), makeCacheKey(), 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 1765 of file GlobalFunctions.php.

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

Referenced by MWHttpRequest\canMakeRequests(), Installer\envCheckCache(), MWHttpRequest\factory(), MWHttpRequestTester\factory(), WebInstaller\startSession(), and MediaWiki\Session\PHPSessionHandlerTest\testInstall().

◆ wfInitShellLocale()

wfInitShellLocale ( )

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

Definition at line 2540 of file GlobalFunctions.php.

◆ wfIsBadImage()

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

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

The format of MediaWiki:Bad_image_list is as follows:

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

Definition at line 3496 of file GlobalFunctions.php.

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

◆ wfIsDebugRawPage()

wfIsDebugRawPage ( )

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

Returns
bool

Definition at line 1033 of file GlobalFunctions.php.

◆ wfIsHHVM()

wfIsHHVM ( )

Check if we are running under HHVM.

Returns
bool

Definition at line 2046 of file GlobalFunctions.php.

Referenced by TidySupport\__construct(), Installer\doEnvironmentChecks(), MWDebug\getDebugInfo(), MWTidy\singleton(), and SpecialVersion\softwareInformation().

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

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

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

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

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

◆ wfLogProfilingData()

wfLogProfilingData ( )
Todo:
document

Definition at line 1182 of file GlobalFunctions.php.

Referenced by MediaWikiPHPUnitBootstrap\__destruct(), and MediaWiki\restInPeace().

◆ wfLogWarning()

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

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

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

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

Referenced by ChangesListSpecialPage\areFiltersInConflict(), Revision\compressRevisionText(), Language\convertGrammar(), Revision\decompressRevisionText(), WikiPage\doDeleteArticleReal(), SpecialPageFactory\getPage(), SiteImporter\handleException(), OutputPage\parserOptions(), and OutputPage\transformFilePath().

◆ wfMakeUrlIndexes()

wfMakeUrlIndexes (   $url)

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

Parameters
string$url
Returns
array

Definition at line 911 of file GlobalFunctions.php.

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

◆ wfMatchesDomainList()

wfMatchesDomainList (   $url,
  $domains 
)

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

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

Definition at line 965 of file GlobalFunctions.php.

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

◆ wfMemcKey()

wfMemcKey ( )

Make a cache key for the local wiki.

Parameters
string$args,...
Returns
string

Definition at line 2961 of file GlobalFunctions.php.

Referenced by PoolWorkArticleView\__construct(), MediaWiki\Session\SessionBackend\__construct(), MediaWiki\Auth\AuthManager\autoCreateUser(), Preprocessor\cacheGetTree(), FileCacheBase\cacheMissKey(), Preprocessor\cacheSetTree(), CaptchaCacheStore\clear(), MessageCache\clear(), BaseBlacklist\clearCache(), MediaWiki\Session\TestBagOStuff\deleteSession(), WikiPage\doDeleteArticleReal(), ChangesFeed\execute(), FormatMetadata\fetchExtendedMetadata(), MediaWiki\Session\SessionManager\generateSessionId(), Skin\getCachedNotice(), CachingSiteStore\getCacheKey(), InfoAction\getCacheKey(), MediaWikiGadgetsDefinitionRepo\getCheckKey(), SpecialVersion\getCreditsForExtension(), DifferenceEngine\getDiffBodyCacheKey(), MediaWiki\Session\SessionManager\getEmptySessionInternal(), ApiHelp\getHelp(), TitleBlacklist\getHttp(), BaseBlacklist\getLocalBlacklists(), MessageCache\getLocalCache(), ParserCache\getOptionsKey(), ParserCache\getParserOutputKey(), MediaWiki\Session\TestBagOStuff\getSession(), MediaWiki\Session\SessionManager\getSessionById(), MediaWiki\Session\TestBagOStuff\getSessionFromBackend(), BaseBlacklist\getSharedBlacklists(), User\getTouched(), SiteStatsUpdate\getTypeCacheKey(), MessageCache\getValidationHash(), BaseBlacklist\getWhitelists(), FileCacheBase\incrMissesRecent(), TitleBlacklist\invalidate(), Block\isWhitelistedFromAutoblocks(), ChangeTags\listExplicitlyDefinedTags(), ChangeTags\listSoftwareActivatedTags(), ChangeTags\listSoftwareDefinedTags(), TitleBlacklist\load(), MessageCache\load(), MessageCache\loadFromDBWithLock(), ExtensionRegistry\loadFromQueue(), MediaWiki\Session\SessionManager\loadSessionInfoFromStore(), TitleBlacklist\loadWhitelist(), SiteStats\numberingroup(), User\pingLimiter(), RebuildRecentchanges\purgeFeeds(), Article\purgePatrolFooterCache(), ChangeTags\purgeTagCacheAll(), ChangeTags\purgeTagUsageCache(), MessageCache\replace(), MediaWiki\Session\SessionBackend\resetId(), CaptchaCacheStore\retrieve(), MediaWiki\Session\SessionBackend\save(), MessageCache\saveToCaches(), MessageCache\saveToLocalCache(), MediaWiki\Session\TestBagOStuff\setRawSession(), BagOStuffTest\setUp(), Article\showMissingArticle(), Article\showPatrolFooter(), CaptchaCacheStore\store(), ChangeTags\tagUsageStatistics(), BagOStuffTest\testAdd(), MediaWiki\Auth\AuthManagerTest\testAutoAccountCreation(), BagOStuffTest\testChangeTTL(), BagOStuffTest\testGet(), BagOStuffTest\testGetMulti(), BagOStuffTest\testGetScopedLock(), BagOStuffTest\testGetWithSetCallback(), BagOStuffTest\testIncr(), BagOStuffTest\testIncrWithInit(), BagOStuffTest\testMerge(), MediaWiki\Session\SessionBackendTest\testUnpersist(), GlobalTest\testWfMemcKey(), User\touch(), SiteStatsUpdate\tryDBUpdateInternal(), and MediaWiki\Session\SessionBackend\unpersist().

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

◆ wfMerge()

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

wfMerge attempts to merge differences between three texts.

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

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

Definition at line 2587 of file GlobalFunctions.php.

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

◆ wfMergeErrorArrays()

wfMergeErrorArrays ( )

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

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

Parameters
array$array1,...
Returns
array

Definition at line 242 of file GlobalFunctions.php.

Referenced by MovePage\checkPermissions(), MergeHistory\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 1370 of file GlobalFunctions.php.

◆ wfMessageFallback()

wfMessageFallback ( )

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

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

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

Definition at line 1395 of file GlobalFunctions.php.

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

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

Referenced by GlobalTest\testNegotiateType().

◆ wfObjectToArray()

wfObjectToArray (   $objOrArray,
  $recursive = true 
)

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

Parameters
object | array$objOrArray
bool$recursive
Returns
array

Definition at line 292 of file GlobalFunctions.php.

Referenced by GadgetDefinitionContent\getAssocArray().

◆ wfParseUrl()

wfParseUrl (   $url)

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

Differences:

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

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

Definition at line 818 of file GlobalFunctions.php.

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

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

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

◆ wfQueriesMustScale()

wfQueriesMustScale ( )

Should low-performance queries be disabled?

Returns
bool

Definition at line 3122 of file GlobalFunctions.php.

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

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

Referenced by MockFileBackend\doGetLocalCopyMulti(), JobQueueDB\doPop(), SvgHandler\doTransform(), MakeTestEdits\execute(), GenerateFancyCaptchas\execute(), TestUserRegistry\getImmutableTestUser(), MockLocalRepo\getLocalCopy(), MockLocalRepo\getLocalReference(), TestUserRegistry\getMutableTestUser(), WebRequest\getRequestId(), MWExceptionHandler\handleFatalError(), 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\testGetNotExists(), WANObjectCacheTest\testGetWithSetCallback(), WANObjectCacheTest\testGetWithSetCallback_versions(), WANObjectCacheTest\testGetWithSeveralCheckKeys(), GlobalVarConfigTest\testHas(), WANObjectCacheTest\testLockTSE(), WANObjectCacheTest\testLockTSESlow(), 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 1290 of file GlobalFunctions.php.

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

◆ wfRecursiveRemoveDir()

wfRecursiveRemoveDir (   $dir)

Remove a directory and all its content.

Does not hide error.

Parameters
string$dir
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 2123 of file GlobalFunctions.php.

Referenced by TextPassDumperDatabaseTest\checkpointHelper(), GenerateFancyCaptchas\execute(), MediaWikiTestCase\setUp(), and MediaWikiTestCase\tearDown().

◆ wfRelativePath()

wfRelativePath (   $path,
  $from 
)

Generate a relative path name to the given file.

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

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

Definition at line 2822 of file GlobalFunctions.php.

Referenced by UploadDumper\outputItem().

◆ wfRemoveDotSegments()

wfRemoveDotSegments (   $urlPath)

Remove all dot-segments in the provided URL path.

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

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

Definition at line 680 of file GlobalFunctions.php.

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

◆ wfReportTime()

wfReportTime ( )

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

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

Returns
string

Definition at line 1475 of file GlobalFunctions.php.

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

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

◆ wfResetSessionID()

wfResetSessionID ( )

Reset the session id.

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

Definition at line 2895 of file GlobalFunctions.php.

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

Referenced by HooksTest\testOldStyleHooks().

◆ wfScript()

wfScript (   $script = 'index')

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

◆ wfSetVar()

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

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

Parameters
mixed$dest
mixed$source
bool$force
Returns
mixed

Definition at line 1713 of file GlobalFunctions.php.

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

◆ 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

Definition at line 2297 of file GlobalFunctions.php.

Referenced by UIDGenerator\__construct(), DjVuHandler\doTransform(), Installer\envCheckShellLocale(), GenerateFancyCaptchas\execute(), SiteConfiguration\getConfig(), GitInfo\getHeadCommitDate(), Maintenance\getTermSize(), Installer\locateExecutable(), ParserTestPrinter\quickDiff(), Maintenance\readlineEmulation(), PdfImage\retrieveMetaData(), WfShellExecTest\testBug67870(), JpegPixelFormatTest\testPixelFormatRendering(), DifferenceEngine\textDiff(), 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

Definition at line 2262 of file GlobalFunctions.php.

◆ 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

Definition at line 2531 of file GlobalFunctions.php.

Referenced by PdfHandler\doTransform(), TransformationalImageHandler\getMagickVersion(), SvgHandler\rasterize(), JpegHandler\rotate(), BitmapHandler\rotate(), ExifBitmapHandler\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").

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

Referenced by CleanupSpam\execute(), SiteConfiguration\getConfig(), MWDocGen\init(), 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 3339 of file GlobalFunctions.php.

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

◆ wfShowingResults()

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

Definition at line 1610 of file GlobalFunctions.php.

◆ wfSplitWikiID()

wfSplitWikiID (   $wiki)

Split a wiki ID into DB name and table prefix.

Parameters
string$wiki
Returns
array

Definition at line 3027 of file GlobalFunctions.php.

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

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

Referenced by MovePage\isValidFileMove().

◆ wfSuppressWarnings()

◆ 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
Examples
/src/tests/phpunit/MediaWikiTestCase.php.

Definition at line 2061 of file GlobalFunctions.php.

Referenced by UIDGenerator\__construct(), UploadFromChunks\concatenateChunks(), FileBackendGroup\config(), MockFileBackend\doGetLocalCopyMulti(), FileBackendTest\doTestDoOperationsPipeline(), SvgHandler\doTransform(), WikiRevision\downloadSource(), WikiImporter\dumpTemp(), ApiImageRotate\execute(), HHVMMakeRepo\execute(), GenerateFancyCaptchas\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(), InterwikiTest\populateCDB(), FileBackendTest\provider_testStore(), ParserTestPrinter\quickDiff(), ResourceLoaderImage\rasterize(), CheckStorage\restoreText(), WebPHandlerTest\setUp(), MigrateFileRepoLayoutTest\setUp(), UploadStashTest\setUp(), JobRunner\syncBackoffDeltas(), and DifferenceEngine\textDiff().

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

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

Referenced by Block\__construct(), OutputPage\adaptCdnTTL(), BlockTest\addDBData(), UserRightsProxy\addGroup(), User\addGroup(), LinkCache\addLinkObj(), ApiMain\addRequestedFields(), SpecialRecentChanges\buildQuery(), ApiStashEdit\buildStashValue(), FileCacheBase\cacheTimestamp(), SiteStatsUpdate\cacheUpdate(), 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(), ApiTestCase\doApiRequestWithToken(), MemoryFileBackend\doCopyInternal(), MemoryFileBackend\doCreateInternal(), DBFileJournal\doLogChangeBatch(), MysqlUpdater\doSchemaRestructuring(), MemoryFileBackend\doStoreInternal(), FileBackendTest\doTestGetFileStat(), ApiProtect\execute(), ApiUndelete\execute(), ApiMergeHistory\execute(), ApiSetNotificationTimestamp\execute(), ApiEditPage\execute(), ApiQueryBlocks\execute(), ApiQueryDeletedrevs\execute(), SpecialExport\execute(), ApiQueryFilearchive\execute(), RemoveUnusedAccounts\execute(), UploadStashCleanup\execute(), FixTimestamps\execute(), ApiQueryImageInfo\execute(), ApiQueryAllUsers\execute(), ImportTextFiles\execute(), PurgeParserCache\execute(), ApiFeedWatchlist\execute(), UpdateSearchIndex\execute(), BenchmarkParse\execute(), ApiQueryUsers\execute(), LocalFileRestoreBatch\execute(), JobRunner\executeJob(), CacheTime\expired(), UserrightsPage\expiryToTimestamp(), ApiQueryWatchlist\extractOutputData(), ApiQueryInfo\extractPageInfo(), ApiQueryRevisionsBase\extractRevisionInfo(), ApiQueryLogEvents\extractRowInfo(), ApiQueryContributions\extractRowInfo(), ApiQueryRecentChanges\extractRowInfo(), HistoryAction\feedEmpty(), MediaWiki\Logger\LegacyLogger\formatAsWfDebugLog(), FeedUtils\formatDiff(), ApiResult\formatExpiry(), Language\formatExpiry(), SpecialUndelete\formatFileRow(), LogFormatter\formatParameterValueForApi(), SpecialMergeHistory\formatRevisionRow(), SpecialUndelete\formatRevisionRow(), AtomFeed\formatTime(), ImageListPager\formatValue(), RevDelArchivedFileItem\getApiData(), RevDelRevisionItem\getApiData(), RevDelFileItem\getApiData(), Block\getAutoblockExpiry(), ApiQueryUserInfo\getBlockInfo(), CacheTime\getCacheTime(), NewUsersLogFormatter\getComment(), ApiQueryUserInfo\getCurrentUserInfo(), LocalFile\getDescriptionTouched(), User\getExperienceLevel(), ProtectionForm\getExpiry(), FormatMetadata\getExtendedMetadataFromFile(), 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(), RawAction\getRawText(), ApiQuerySearch\getSearchResultData(), ImageHistoryList\getThumbForLine(), MockFSFile\getTimestamp(), FSFile\getTimestamp(), RevisionItemBase\getTimestamp(), ForeignAPIFile\getTimestamp(), DatabaseLogEntry\getTimestamp(), RCDatabaseLogEntry\getTimestamp(), ArchivedFile\getTimestamp(), WikiPage\getTimestamp(), ManualLogEntry\getTimestamp(), Revision\getTimestamp(), FileJournal\getTimestampedUUID(), Revision\getTimestampFromId(), WANCacheReapUpdate\getTitleChangeEvents(), User\getTouched(), ContribsPager\getUserCond(), ApiQueryInfo\getVisitingWatcherInfo(), ForeignAPIRepo\httpGet(), ImageHistoryList\imageHistoryLine(), UserGroupMembership\initFromRow(), Block\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(), FormatMetadata\makeFormattedData(), MediaWiki\Session\Token\match(), SpecialBlock\maybeAlterFormDefaults(), User\newTouchedTimestamp(), OutputPage\output(), InfoAction\pageCounts(), ApiStashEdit\parseAndStash(), SpecialBlock\parseExpiryInput(), PdfImage\postProcessDump(), TableCleanup\progress(), ImageBuilder\progress(), ApiMainTest\provideCheckConditionalRequestHeaders(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), LanguageTest\provideTranslateBlockExpiry(), LocalFile\publishTo(), RebuildRecentchanges\rebuildRecentChangesTablePass1(), QueryPage\recache(), LocalFile\recordUpload2(), ManageJobs\repushAbandoned(), CategoryMembershipChangeJob\run(), ApiQueryProtectedTitles\run(), ApiQueryCategories\run(), ApiQueryWatchlistRaw\run(), ApiQueryDuplicateFiles\run(), ApiQueryQueryPage\run(), ApiQueryCategoryMembers\run(), RefreshLinksJob\runForTitle(), ChangesFeed\saveToCache(), ApiMain\sendCacheHeaders(), Block\setCookie(), OutputPage\setLastModified(), WikiRevision\setTimestamp(), WikiPage\setTimestamp(), UserGroupMembershipTest\setUp(), TextPassDumper\showReport(), BackupDumper\showReport(), UpdateLogging\sync(), UserTest\testAutoblockCookieInfiniteExpiry(), UserTest\testAutoblockCookies(), EditPageTest\testAutoMerge(), MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProviderTest\testGetNewPasswordExpiry(), WfTimestampTest\testHttpDate(), WfTimestampTest\testNormalTimestamps(), WfTimestampTest\testOldTimestamps(), JobQueueTest\testRootDeduplication(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProviderTest\testSetPasswordResetFlag(), WfTimestampTest\testTimestampParameter(), TitlePermissionTest\testUserBlock(), Language\time(), Language\timeanddate(), IPTC\timeHelper(), DatabaseOracle\timestamp(), MediaWiki\Session\Token\toString(), ApiUpload\transformWarnings(), RecentChangesUpdateJob\updateActiveUsers(), WikiPage\updateIfNewerOn(), Block\updateTimestamp(), ApiBase\validateTimestamp(), EditPage\wasDeletedSinceLastEdit(), wfStreamThumb(), and XmlDumpWriter\writeTimestamp().

◆ wfTimestampNow()

wfTimestampNow ( )

Convenience function; returns MediaWiki timestamp for the present time.

Returns
string

Definition at line 2023 of file GlobalFunctions.php.

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

◆ wfTimestampOrNull()

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

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

Referenced by RollbackAction\onView(), Action\useTransactionalTimeLimit(), SpecialPage\useTransactionalTimeLimit(), and ApiBase\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 3460 of file GlobalFunctions.php.

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

◆ wfUrlencode()

wfUrlencode (   $s)

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

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

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

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

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(), Interwiki\getURL(), 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 758 of file GlobalFunctions.php.

Referenced by Skin\addToSidebarPlain(), ResourceLoaderStartUpModule\getConfigSettings(), and Skin\makeInternalOrExternalUrl().

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

Referenced by 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 2778 of file GlobalFunctions.php.

◆ wfUsePHP()

wfUsePHP (   $req_ver)

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

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

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

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

Definition at line 2748 of file GlobalFunctions.php.

◆ wfVarDump()

wfVarDump (   $var)

A wrapper around the PHP function var_export().

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

Parameters
mixed$varA PHP variable to dump.

Definition at line 1748 of file GlobalFunctions.php.

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

Referenced by NamespaceConflictChecker\checkLinkTable(), CleanupInvalidDbKeys\cleanupTable(), CompressOld\compressWithConcat(), RefreshLinks\deleteLinksFromNonexistent(), RefreshLinks\dfnCheckInterval(), PopulateRecentChangesSource\doDBUpdates(), PopulateBacklinkNamespace\doDBUpdates(), PopulateFilearchiveSha1\doDBUpdates(), PopulateParentId\doDBUpdates(), FixExtLinksProtocolRelative\doDBUpdates(), PopulateLogUsertext\doDBUpdates(), PopulateLogSearch\doDBUpdates(), PopulateImageSha1\doDBUpdates(), PopulateRevisionLength\doLenUpdates(), RefreshLinks\doRefreshLinks(), PopulateRevisionSha1\doSha1LegacyUpdates(), PopulateRevisionSha1\doSha1Updates(), UpdateSpecialPages\doSpecialPageCacheUpdates(), TidyUpBug37714\execute(), CleanupArchiveUserText\execute(), RemoveInvalidEmails\execute(), DeleteSelfExternals\execute(), FixUserRegistration\execute(), DeleteDefaultMessages\execute(), InitEditCount\execute(), MakeTestEdits\execute(), MigrateUserGroup\execute(), UpdateSpecialPages\execute(), UpdateRestrictions\execute(), UploadStashCleanup\execute(), ConvertUserOptions\execute(), BatchedQueryRunner\execute(), DeleteBatch\execute(), MwSql\execute(), ResetUserTokens\execute(), MoveBatch\execute(), UpdateCollation\execute(), PopulateCategory\execute(), UpdateMediaWiki\execute(), RefreshImageMetadata\execute(), DeleteEqualMessages\execute(), ImportImages\execute(), FixDefaultJsonContentPages\handleRow(), moveToExternal(), RefreshLinks\refreshCategory(), resolveStubs(), RenameUserJob\run(), BackupReader\showReport(), UpdateLogging\sync(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), PopulateContentModel\updatePageRows(), and FixT22757\waitForSlaves().

◆ wfWarn()

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

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

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

Parameters
string$msgMessage to send
int$callerOffsetNumber of items to go back in the backtrace to find the correct caller (1 = function calling wfWarn, ...)
int$levelPHP error level; defaults to E_USER_NOTICE; only used when $wgDevelopmentWarnings is true

Definition at line 1142 of file GlobalFunctions.php.

Referenced by DatabaseTestHelper\__construct(), FakeDatabaseMysqlBase\__construct(), TextContent\__construct(), Exif\__construct(), Action\__construct(), MediaWiki\Tidy\RaggettExternal\cleanWrapped(), MediaWiki\Tidy\RaggettInternalPHP\cleanWrapped(), ApiEditPage\execute(), ForeignAPIRepo\fileExistsBatch(), Http\get(), SpecialPageFactory\getAliasList(), CacheHelper\getCachedValue(), WikiPage\getContentModel(), Action\getContext(), ParserCache\getKey(), SpecialPageFactory\getLocalNameFor(), Language\getMagic(), MediaWiki\initializeArticle(), Linker\link(), Linker\makeBrokenImageLinkObj(), BacklinkJobUtils\partitionBacklinkJob(), Autopromote\recCheckCondition(), EditPage\showEditForm(), and DifferenceEngine\textDiff().

◆ wfWikiID()

wfWikiID ( )

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

Returns
string

Definition at line 3011 of file GlobalFunctions.php.

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