MediaWiki  REL1_24
GlobalFunctions.php File Reference

Global functions used everywhere. More...

Go to the source code of this file.

Enumerations

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

Functions

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

Detailed Description

Global functions used everywhere.

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

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

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

Definition in file GlobalFunctions.php.


Enumeration Type Documentation

enum TS_DB

MySQL DATETIME (YYYY-MM-DD HH:MM:SS)

Definition at line 2383 of file GlobalFunctions.php.

enum TS_EXIF

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

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

Definition at line 2404 of file GlobalFunctions.php.

ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.

This is used by Special:Export

Definition at line 2395 of file GlobalFunctions.php.

ISO 8601 basic format with no timezone: 19860209T200000Z.

This is used by ResourceLoader

Definition at line 2419 of file GlobalFunctions.php.

enum TS_MW

MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)

Definition at line 2378 of file GlobalFunctions.php.

enum TS_ORACLE

Oracle format time.

Definition at line 2409 of file GlobalFunctions.php.

Postgres format time.

Definition at line 2414 of file GlobalFunctions.php.

enum TS_RFC2822

RFC 2822 format, for E-mail and HTTP headers.

Definition at line 2388 of file GlobalFunctions.php.

enum TS_UNIX

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

Definition at line 2373 of file GlobalFunctions.php.


Function Documentation

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

References $type.

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

swap ( &$  x,
&$  y 
)

Swap two variables.

Deprecated:
since 1.24
Parameters:
mixed$x
mixed$y

Definition at line 2494 of file GlobalFunctions.php.

References wfDeprecated().

Referenced by GlobalTest\testSwapVarsTest().

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

References array(), and as.

wfAppendQuery ( url,
query 
)

Append a query string to an existing URL, which may or may not already have query string parameters already.

If so, they will be combined.

Parameters:
string$url
string|string[]$query String or associative array
Returns:
string

Definition at line 468 of file GlobalFunctions.php.

References $query, and wfArrayToCgi().

Referenced by RedirectSpecialPage\execute(), SpecialContributions\execute(), SpecialRecentChanges\execute(), ImportSiteScripts\execute(), ImportSiteScripts\fetchScriptList(), ImageHandler\getScriptedTransform(), ResourceLoaderStartUpModule\getStartupModulesUrl(), File\getUnscaledThumb(), Linker\getUploadUrl(), Linker\link(), Linker\makeThumbLink2(), and MediaWikiSite\normalizePageName().

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

References $changed, $key, and $value.

if (!defined( 'MEDIAWIKI')) 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 158 of file GlobalFunctions.php.

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

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

Definition at line 167 of file GlobalFunctions.php.

References list.

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

References $keys, and $output.

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

This function takes two arrays as input, and returns a CGI-style string, e.g.

"days=7&limit=100". Options in the first array override options in the second. Options set to null or false will not be output.

Parameters:
array$array1( String|Array )
array$array2( String|Array )
string$prefix
Returns:
string

Definition at line 376 of file GlobalFunctions.php.

References $key, $value, and as.

Referenced by PhpHttpRequest\execute(), getEscapedProfileUrl(), FormAction\getForm(), Title\getFullURL(), SpecialRunJobs\getQuerySignature(), UserNotLoggedIn\report(), PurgeAction\show(), GlobalTest\testArrayToCGI(), GlobalTest\testArrayToCGI2(), GlobalTest\testCgiRoundTrip(), and wfAppendQuery().

wfAssembleUrl ( urlParts)

This function will reassemble a URL parsed with wfParseURL.

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

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

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

Definition at line 582 of file GlobalFunctions.php.

References $result.

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

Get a debug backtrace as a string.

Returns:
string

Definition at line 1873 of file GlobalFunctions.php.

References $f, $file, $wgCommandLineMode, as, empty, global, and wfDebugBacktrace().

Referenced by MWDebug\deprecated().

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

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

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

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

Definition at line 3333 of file GlobalFunctions.php.

References $result, array(), and as.

Referenced by UIDGenerator\__construct(), Revision\base36Sha1(), ApiQueryDeletedrevs\execute(), ApiQueryFilearchive\execute(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryRevisions\extractRowInfo(), ApiQueryImageInfo\getInfo(), JobQueueRedis\getNewJobFields(), ForeignAPIFile\getSha1(), ApiQueryAllImages\run(), ExternalStoreMwstore\store(), WfBaseConvertTest\testDigitToBase10(), WfBaseConvertTest\testDigitToBase16(), WfBaseConvertTest\testDigitToBase2(), WfBaseConvertTest\testDigitToBase3(), WfBaseConvertTest\testDigitToBase36(), WfBaseConvertTest\testDigitToBase5(), WfBaseConvertTest\testDigitToBase8(), WfBaseConvertTest\testIdentity(), WfBaseConvertTest\testInvalid(), WfBaseConvertTest\testLargeNumber(), WfBaseConvertTest\testLeadingZero(), WfBaseConvertTest\testPadding(), and UIDGeneratorTest\testTimestampedUID().

wfBaseName ( path,
suffix = '' 
)

Return the final portion of a pathname.

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

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

Parameters:
string$path
string$suffixString to remove if present
Returns:
string

Definition at line 3258 of file GlobalFunctions.php.

References $matches, $path, and array().

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

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

References array(), and as.

Referenced by CoreParserFunctions\language(), Preferences\profilePreferences(), and WfBCP47Test\testBCP47().

wfBoolToStr ( value)

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

Parameters:
bool$value
Returns:
string

Definition at line 3741 of file GlobalFunctions.php.

References $value.

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

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

References array(), and wfRunHooks().

Referenced by Preferences\profilePreferences().

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

References $key, $keys, $query, $ret, $value, array(), as, and list.

Referenced by Linker\link(), Linker\makeBrokenImageLinkObj(), Linker\makeKnownLinkObj(), Linker\makeLinkObj(), GlobalTest\testCgiRoundTrip(), and GlobalTest\testCgiToArray().

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

Returns:
bool True = there is sufficient entropy

Definition at line 3434 of file GlobalFunctions.php.

References wfIsWindows().

Referenced by wfFixSessionID(), and wfResetSessionID().

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

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

Parameters:
int$deflimitDefault limit if none supplied
string$optionnameName of a user preference to check against
Returns:
array
Deprecated:
since 1.24, just call WebRequest::getLimitOffset() directly

Definition at line 2019 of file GlobalFunctions.php.

References global, and wfDeprecated().

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

References wfResetOutputBuffers().

wfClientAcceptsGzip ( force = false)
Todo:

document

FIXME: We may want to blacklist some broken browsers

Parameters:
bool$force
Returns:
bool Whereas client accept gzip compression

Definition at line 1985 of file GlobalFunctions.php.

References $result, array(), and wfDebug().

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

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

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

wfDebug ( text,
dest = 'all' 
)

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

In normal operation this is a NOP.

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

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

Definition at line 950 of file GlobalFunctions.php.

References MWDebug\debugMsg(), global, wfDebugTimer(), wfErrorLog(), and wfIsDebugRawPage().

Referenced by PageArchive\__construct(), UploadFromStash\__construct(), MemcachedPeclBagOStuff\__construct(), MimeMagic\__construct(), Parser\__construct(), MediaHandler\addMeta(), LinkBatch\addObj(), Skin\afterContentHook(), UploadBase\checkSvgScriptCallback(), UploadBase\checkXMLEncodingMissmatch(), UploadBase\cleanupTempFile(), SpecialEditWatchlist\cleanupWatchlist(), MessageBlobStore\clear(), DatabaseBase\clearFlag(), DjVuImage\convertDumpToXML(), UploadBase\createFromRequest(), WikiImporter\debug(), BaseDump\debug(), RecompressTracked\debug(), BagOStuff\debug(), UploadBase\detectScript(), UploadBase\detectVirus(), WikiDiff3\diff(), MockImageHandler\doFakeTransform(), DatabaseMssql\doQuery(), UserrightsPage\doSaveUserGroups(), TransformationalImageHandler\doTransform(), DjVuHandler\doTransform(), MWCryptRand\driftHash(), ZipDirectoryReader\error(), CLDRPluralRuleEvaluator\evaluateCompiled(), SpecialUserlogout\execute(), ApiUpload\execute(), ChangesFeed\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), LocalFileMoveBatch\execute(), DatabaseMssql\fieldExists(), DatabaseMssql\fieldInfo(), WikiDiff3\find_middle_snake(), Parser\findColonNoLinks(), CoreParserFunctions\getCachedRevisionObject(), SpecialVersion\getCreditsForExtension(), GenderCache\getGenderOf(), MediaHandler\getHandler(), DjVuImage\getInfo(), TransformationalImageHandler\getMagickVersion(), GIFHandler\getMetadata(), PNGHandler\getMetadata(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), TiffHandler\getMetadata(), JpegHandler\getMetadata(), SvgHandler\getMetadata(), DjVuHandler\getMetadata(), DjVuHandler\getMetaTree(), DjVuImage\getMultiPageInfo(), DjVuImage\getPageInfo(), Title\getPartialURL(), UserCache\getProp(), ExternalStoreDB\getSlave(), XCFHandler\getXCFMetaData(), OutputPage\getXVO(), MWCryptRand\hashAlgo(), WikiRevision\importUpload(), MessageBlobStore\insertMessageBlob(), ExternalStore\insertWithFallback(), FileCacheBase\isCacheGood(), DjVuHandler\isEnabled(), SvgHandler\isEnabled(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), SiteStats\loadAndLazyInit(), ChangesFeed\loadFromCache(), HTMLFileCache\loadFromFileCache(), User\loadFromId(), User\loadFromSession(), Linker\makeExternalImage(), Linker\makeExternalLink(), Linker\makeImageLink(), Linker\makeMediaLinkFile(), RawAction\onView(), DatabasePostgres\open(), OutputPage\output(), UploadDumper\outputItem(), SearchMySQL\parseQuery(), SearchSqlite\parseQuery(), SearchPostgres\parseQuery(), BacklinkCache\partition(), BacklinkCache\queryLinks(), SvgHandler\rasterize(), MWCryptRand\realGenerate(), DatabaseBase\reportQueryError(), Http\request(), DjVuImage\retrieveMetaData(), JpegHandler\rotate(), BitmapHandler\rotate(), DataUpdate\runUpdates(), FileCacheBase\saveText(), HTMLFileCache\saveToFileCache(), SearchPostgres\searchQuery(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), UserMailer\sendWithPear(), DatabaseBase\setFlag(), OutputPage\setLastModified(), DifferenceEngine\setReducedLineNumbers(), LanguageClassesTestCase\setUp(), TestFileIterator\setupCurrentTest(), UploadFromUrlTestSuite\setupUploadDir(), FileRepo\storeBatch(), DatabaseMssql\tableExists(), GlobalTest\testDebugFunctionTest(), ApiUploadTest\testUploadChunks(), WikiImporter\throwXmlError(), BitmapHandler\transformCustom(), BitmapHandler\transformGd(), BitmapHandler\transformImageMagick(), BitmapHandler\transformImageMagickExt(), SpecialUploadStash\tryClearStashedUploads(), MessageBlobStore\updateMessage(), MessageBlobStore\updateModule(), HTMLFileCache\useFileCache(), SvgHandler\validateParam(), ImageHandler\validateThumbParams(), UploadBase\verifyExtension(), UploadBase\verifyFile(), UploadBase\verifyMimeType(), WikiImporter\warn(), wfClientAcceptsGzip(), wfDebugBacktrace(), wfDebugLog(), wfDebugMem(), wfDiff(), wfFixSessionID(), wfGetLangObj(), wfGzipHandler(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfRecursiveRemoveDir(), wfShellExec(), wfShellExecDisabled(), and wfTimestamp().

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

References $limit, array(), and wfDebug().

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

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

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

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

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

Definition at line 1057 of file GlobalFunctions.php.

References $time, MWDebug\debugMsg(), global, wfDebug(), wfErrorLog(), wfHostname(), wfTimestamp(), and wfWikiID().

Referenced by GitInfo\__construct(), MWMemcached\_fwrite(), AutoLoader\autoload(), ExternalStoreDB\batchFetchBlobs(), MemcachedPeclBagOStuff\checkResult(), UploadBase\checkWarnings(), IPTC\convIPTCHelper(), MediaWikiParserTest\debug(), Exif\debugFile(), MemcachedBagOStuff\debugLog(), TransformationalImageHandler\doTransform(), DjVuHandler\doTransform(), SvgHandler\doTransform(), CheckUsernames\execute(), Message\extractParam(), ExternalStoreDB\fetchBlob(), IPTC\getCharset(), ResourceLoaderWikiModule\getContent(), ContentHandler\getContentText(), ContentHandler\getForModelID(), RequestContext\getLanguage(), ExternalStore\insertWithFallback(), User\loadFromSession(), MediaHandler\logErrorForExternalProcess(), MWExceptionHandler\logException(), MediaWikiSite\normalizePageName(), IPTC\parse(), GitInfo\precomputeValues(), MediaHandler\removeBadFile(), MWExceptionHandler\rollbackMasterChangesAndLog(), MWDebug\sendMessage(), WebResponse\setcookie(), XMPReader\startElement(), IPTC\timeHelper(), XMPValidate\validateBoolean(), XMPValidate\validateClosed(), XMPValidate\validateDate(), XMPValidate\validateFlash(), XMPValidate\validateGPS(), XMPValidate\validateInteger(), XMPValidate\validateLangCode(), XMPValidate\validateRating(), XMPValidate\validateRational(), wfLogProfilingData(), and wfShellExec().

wfDebugMem ( exact = false)

Send a line giving PHP memory usage.

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

Definition at line 1027 of file GlobalFunctions.php.

References wfDebug().

Referenced by GlobalTest\testDebugFunctionTest().

Get microsecond timestamps for debug logs.

Returns:
string

Definition at line 1010 of file GlobalFunctions.php.

References $wgRequestTime, and global.

Referenced by wfDebug().

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

Throws a warning that $function is deprecated.

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

Definition at line 1144 of file GlobalFunctions.php.

References MWDebug\deprecated().

Referenced by Skin\__call(), MailAddress\__construct(), DatabaseSqlite\__construct(), ImageGallery\__construct(), DeprecatedGlobal\_newObject(), MWFunction\call(), MWFunction\callArray(), ApiQueryBase\checkRowCount(), Skin\commonPrintStylesheet(), ApiQueryUsers\getAutoGroups(), Article\getAutosummary(), Skin\getCommonStylePath(), ArchivedFile\getDescription(), Linker\getExternalLinkAttributes(), SpecialPageFactory\getGroup(), LBFactory\getLBFactoryClass(), SpecialPageFactory\getList(), SpecialPageFactory\getPage(), Skin\getUsableSkins(), OutputPage\isTOCEnabled(), ApiQueryBase\keyPartToTitle(), ApiQueryBase\keyToTitle(), Linker\link(), UserrightsPage\makeGroupNameListForLog(), Linker\makeKnownLinkObj(), Linker\makeLinkObj(), Skin\newFromKey(), Hooks\run(), SpecialPageFactory\setGroup(), OutputPage\setStatusCode(), swap(), ApiQueryBase\titleToKey(), Preferences\trySetUserEmail(), wfCheckLimits(), wfEmptyMsg(), wfExtractThumbParams(), wfGetIP(), wfMsg(), wfMsgExt(), wfMsgForContent(), wfMsgForContentNoTrans(), wfMsgGetKey(), wfMsgHtml(), wfMsgNoTrans(), wfMsgReal(), and wfMsgWikiHtml().

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

Returns unified plain-text diff of two texts.

Useful for machine processing of diffs.

Parameters:
string$beforeThe text before the changes.
string$afterThe text after the changes.
string$paramsCommand-line options for the diff command.
Returns:
string Unified diff of $before and $after

Definition at line 3131 of file GlobalFunctions.php.

References $params, global, wfDebug(), wfEscapeShellArg(), wfRestoreWarnings(), wfSuppressWarnings(), and wfTempDir().

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

wfEmptyMsg ( key)

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

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

Definition at line 1774 of file GlobalFunctions.php.

References $key, MessageCache\singleton(), and wfDeprecated().

wfErrorLog ( text,
file 
)

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

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

Parameters:
string$text
string$fileFilename
Exceptions:
MWException

Definition at line 1185 of file GlobalFunctions.php.

References $file, $size, IP\isIPv4(), wfRestoreWarnings(), and wfSuppressWarnings().

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

Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell, but the escapeshellarg() function puts single quotes in regardless of OS.

Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to earlier distro releases of PHP)

Parameters:
string$args,...
Returns:
string

Definition at line 2654 of file GlobalFunctions.php.

References array(), as, wfInitShellLocale(), and wfIsWindows().

Referenced by DumpPipeOutput\__construct(), CheckSyntax\checkFileWithCli(), UploadBase\detectVirus(), PopulateImageSha1\doDBUpdates(), DjVuHandler\doTransform(), CheckSyntax\getGitModifiedFiles(), GitInfo\getHeadCommitDate(), TransformationalImageHandler\getMagickVersion(), SvgHandler\rasterize(), CheckStorage\restoreText(), DjVuImage\retrieveMetaData(), JpegHandler\rotate(), BitmapHandler\rotate(), RecompressTracked\startSlaveProcs(), SevenZipStream\stream_open(), BitmapHandler\transformCustom(), wfDiff(), wfMerge(), wfShellExec(), RandomImageGenerator\writeImageWithApi(), and RandomImageGenerator\writeImageWithCommandLine().

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

References wfExpandUrl().

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

wfExpandIRI_callback ( matches)

Private callback for wfExpandIRI.

Parameters:
array$matches
Returns:
string

Definition at line 855 of file GlobalFunctions.php.

References $matches.

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 Fully-qualified URL, current-path-relative URL or false if no valid URL can be constructed

Definition at line 506 of file GlobalFunctions.php.

References global, wfAssembleUrl(), wfParseUrl(), and wfRemoveDotSegments().

Referenced by ApiQuerySiteinfo\appendGeneralInfo(), ApiQuerySiteinfo\appendInterwikiMap(), ApiQuerySiteinfo\appendRightsInfo(), ApiQueryLangLinks\execute(), ApiQueryExternalLinks\execute(), ApiQueryIWLinks\execute(), ApiQueryInfo\extractPageInfo(), CoreParserFunctions\filepath(), SpecialVersion\getEntryPointInfo(), RevertAction\getFormFields(), ApiQueryImageInfo\getInfo(), ApiRsd\getRsdApiList(), RevertAction\onSuccess(), SpecialUploadStash\outputRemoteScaledThumb(), CSSMin\remapOne(), ApiQueryExtLinksUsage\run(), WfExpandUrlTest\testWfExpandUrl(), wfExpandIRI(), and wfStreamThumb().

wfFindFile ( title,
options = array() 
)

Find a file.

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

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

ignoreRedirect: If true, do not follow file redirects

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

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

Returns:
File|bool File, or false if the file does not exist

Definition at line 3663 of file GlobalFunctions.php.

References $options, $title, and RepoGroup\singleton().

Referenced by UploadFromUrlTest\deleteFile(), ApiTestCaseUpload\deleteFileByTitle(), ApiMove\execute(), DeleteBatch\execute(), ApiImageRotate\execute(), FileDuplicateSearchPage\execute(), WantedFilesPage\existenceCheck(), Parser\fetchFileNoRegister(), CoreParserFunctions\filepath(), Linker\makeBrokenImageLinkObj(), Linker\makeMediaLinkObj(), Linker\makeThumbLink2(), UploadDumper\outputItem(), and TraditionalImageGallery\toHTML().

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

Definition at line 3446 of file GlobalFunctions.php.

References MWCryptRand\generateHex(), wfCheckEntropy(), and wfDebug().

Referenced by wfSetupSession().

wfForeignMemcKey ( db,
prefix 
)

Get a cache key for a foreign DB.

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

Definition at line 3558 of file GlobalFunctions.php.

References $key.

Referenced by JobQueueFederated\getCacheKey(), and UserRightsProxy\invalidateCache().

wfFormatStackFrame ( frame)

Return a string representation of frame.

Parameters:
array$frame
Returns:
string

Definition at line 1959 of file GlobalFunctions.php.

Referenced by wfGetCaller().

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

References $limit, and wfDebugBacktrace().

Referenced by MWCryptRand\realGenerate().

wfGetCache ( inputType)

Get a cache object.

Parameters:
int$inputTypeCache type, one the the CACHE_* constants.
Returns:
BagOStuff

Definition at line 3930 of file GlobalFunctions.php.

References ObjectCache\getInstance().

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

wfGetCaller ( level = 2)

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

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

Parameters:
int$level
Returns:
string

Definition at line 1928 of file GlobalFunctions.php.

References wfDebugBacktrace(), and wfFormatStackFrame().

Referenced by WfGetCallerTest\callerOne(), MediaWikiParserTest\debug(), WfGetCallerTest\intermediateFunction(), MWDebug\log(), DatabaseBase\runOnTransactionIdleCallbacks(), and WfGetCallerTest\testZero().

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

Get a Database object.

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

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

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

Returns:
DatabaseBase

Definition at line 3620 of file GlobalFunctions.php.

References wfGetLB().

Referenced by DeletedContribsPager\__construct(), ImageListPager\__construct(), IndexPager\__construct(), SiteStatsInit\__construct(), LinkCache\addLinkObj(), ApiQueryLogEvents\addLogParams(), ChangeTags\addTags(), ImageListPager\buildQueryConds(), ImageBuilder\buildTable(), UserOptions\CHANGER(), CheckStorage\check(), TrackBlobs\checkIntegrity(), Orphans\checkOrphans(), RevisionDeleter\checkRevisionExistence(), Orphans\checkSeparation(), RecompressTracked\checkTrackingTable(), Orphans\checkWidows(), CleanupSpam\cleanupArticle(), SpecialEditWatchlist\cleanupWatchlist(), MessageBlobStore\clear(), SpecialEditWatchlist\clearWatchlist(), ViewCountUpdate\collect(), CgzCopyTransaction\commit(), CompressOld\compressOldPages(), CompressOld\compressPage(), CompressOld\compressWithConcat(), TestORMRowTest\constructorTestProvider(), Title\countRevisionsBetween(), ConvertLinks\createTempTable(), PrefixSearch\defaultSearchBackend(), SearchMySQL\delete(), RefreshLinks\deleteLinksFromNonexistent(), NukePage\deleteRevisions(), Title\deleteTitleProtection(), SiteStatsInit\doAllAndCommit(), RecompressTracked\doAllOrphans(), RecompressTracked\doAllPages(), PopulateFilearchiveSha1\doDBUpdates(), PopulateParentId\doDBUpdates(), FixExtLinksProtocolRelative\doDBUpdates(), PopulateImageSha1\doDBUpdates(), DeleteArchivedFilesImplementation\doDelete(), DeleteArchivedRevisionsImplementation\doDelete(), DeleteOldRevisions\doDelete(), SpecialExport\doExport(), SpecialRecentChangesLinked\doMainQuery(), RecompressTracked\doOrphanList(), RecompressTracked\doPage(), PopulateCategory\doPopulateCategory(), UserCache\doQuery(), GenderCache\doQuery(), LinkBatch\doQuery(), ReassignEdits\doReassignEdits(), RefreshLinks\doRefreshLinks(), DeferredUpdates\doUpdates(), UpdateSearchIndex\doUpdateSearchIndex(), Title\estimateRevisionCount(), TidyUpBug37714\execute(), StorageTypeStats\execute(), CleanupPreferences\execute(), ApiSetNotificationTimestamp\execute(), BenchmarkDeleteTruncate\execute(), CheckBadRedirects\execute(), ClearInterwikiCache\execute(), FixUserRegistration\execute(), GetSlaveServer\execute(), SpecialStatistics\execute(), DumpRev\execute(), CheckImages\execute(), DeleteRevision\execute(), DeleteSelfExternals\execute(), DeleteDefaultMessages\execute(), MigrateUserGroup\execute(), UpdateLogging\execute(), CleanupAncientTables\execute(), ConvertUserOptions\execute(), DeleteOrphanedRevisions\execute(), DumpSisterSites\execute(), InitEditCount\execute(), GetTextMaint\execute(), NukePage\execute(), RemoveUnusedAccounts\execute(), BatchedQueryRunner\execute(), DeleteImageCache\execute(), AlterSharedConstraints\execute(), RebuildAll\execute(), UpdateArticleCount\execute(), UpdateRestrictions\execute(), CheckUsernames\execute(), UpdateSpecialPages\execute(), EraseArchivedFile\execute(), FixDoubleRedirects\execute(), RefreshFileHeaders\execute(), RenameDbPrefix\execute(), FixBug20757\execute(), AttachLatest\execute(), CleanupSpam\execute(), FixTimestamps\execute(), ShowSiteStats\execute(), OrphanStats\execute(), DumpLinks\execute(), InitSiteStats\execute(), PatchSql\execute(), DeleteArchivedRevisions\execute(), FetchText\execute(), CleanupRemovedModules\execute(), ResetUserTokens\execute(), DeleteBatch\execute(), RebuildFileCache\execute(), NamespaceConflictChecker\execute(), RebuildTextIndex\execute(), UpdateDoubleWidthSearch\execute(), NukeNS\execute(), SqliteMaintenance\execute(), MoveBatch\execute(), ImageBuilder\execute(), ConvertLinks\execute(), RefreshImageMetadata\execute(), UpdateMediaWiki\execute(), DeleteEqualMessages\execute(), UploadDumper\fetchLocal(), UploadDumper\fetchUsed(), TitleCleanup\fileExists(), TrackBlobs\findOrphanBlobs(), RecompressTracked\finishIncompleteMoves(), RefreshLinks\fixLinksFromArticle(), RefreshLinks\fixRedirect(), EditPageTest\forceRevisionDate(), ApiEditPageTest\forceRevisionDate(), DoubleRedirectsPage\formatResult(), SpecialProtectedtitles\formatRow(), LCStoreDB\get(), WikiPage\getCategories(), RevDelRevisionList\getCurrent(), ResourceLoaderWikiModule\getDB(), BacklinkCache\getDB(), UserRightsProxy\getDB(), SpecialWatchlist\getDB(), User\getEditCount(), SpecialPagesWithProp\getExistingPropNames(), ProtectionForm\getExpiry(), MessageBlobStore\getFromDB(), DeleteImageCache\getImageCount(), SpecialExport\getLinks(), SpecialRandomInCategory\getMinAndMaxForCat(), SpecialStatistics\getMostViewedPages(), SpecialExport\getPagesFromCategory(), SpecialExport\getPagesFromNamespace(), BrokenRedirectsPage\getQueryInfo(), MediaStatisticsPage\getQueryInfo(), WithoutInterwikiPage\getQueryInfo(), NewFilesPager\getQueryInfo(), UsersPager\getQueryInfo(), SpecialRandomInCategory\getQueryInfo(), LinkSearchPage\getQueryInfo(), ImageListPager\getQueryInfoReal(), FixBug20757\getRevTextMap(), Linker\getRollbackEditCount(), RollbackEdits\getRollbackTitles(), HistoryBlobCurStub\getText(), TrackBlobs\getTextClause(), MessageBlobStore\getUpdatesForMessage(), SpecialEditWatchlist\getWatchlist(), SpecialEditWatchlist\getWatchlistInfo(), BackupReader\handleUpload(), User\idForName(), WikiImporter\importLogItem(), WikiImporter\importRevision(), CheckStorage\importRevision(), WikiImporter\importUpload(), User\incEditCount(), TrackBlobs\initTrackingTable(), MessageBlobStore\insertMessageBlob(), HTMLCacheUpdateJob\invalidateTitles(), WikiPage\isCountable(), RemoveUnusedAccounts\isInactiveAccount(), SiteStats\jobs(), ImageCleanup\killRow(), Title\legalChars(), ChangeTags\listDefinedTags(), SiteStats\load(), SiteStats\loadAndLazyInit(), ProfilerSimpleDB\logData(), LinkFilter\makeLikeArray(), BloomFilterTitleHasLogs\merge(), SearchMySQL\minSearchLength(), ChangeTags\modifyDisplayQuery(), TitleCleanup\moveIllegalPage(), TitleCleanup\moveInconsistentPage(), RecompressTracked\moveTextRow(), moveToExternal(), UserArray\newFromIDs(), SiteStats\numberingroup(), InfoAction\pageCounts(), InfoAction\pageInfo(), SiteStats\pagesInNs(), ImageCleanup\pokeFile(), PurgeList\purgeNamespace(), DoubleRedirectsPage\reallyGetQueryInfo(), RebuildRecentchanges\rebuildRecentChangesTablePass1(), RebuildRecentchanges\rebuildRecentChangesTablePass2(), RebuildRecentchanges\rebuildRecentChangesTablePass3(), RebuildRecentchanges\rebuildRecentChangesTablePass4(), SiteStatsInit\refresh(), RevDelList\reloadFromMaster(), WatchlistCleanup\removeWatch(), ImportReporter\reportPage(), resolveStub(), resolveStubs(), CheckStorage\restoreText(), TableCleanup\runTable(), User\saveSettings(), EraseArchivedFile\scrubAllVersions(), RandomPage\selectRandomPageFromDB(), SpecialRandomInCategory\selectRandomPageFromDB(), RevDelArchivedRevisionItem\setBits(), RevDelArchivedFileItem\setBits(), RevDelArchiveItem\setBits(), RevDelLogItem\setBits(), RevDelRevisionItem\setBits(), RevDelFileItem\setBits(), EditPage\setHeaders(), WikiPageTestContentHandlerUseDB\setUp(), RevisionTestContentHandlerUseDB\setUp(), DatabaseTest\setUp(), LinksUpdateTest\setUp(), TestORMRowTest\setUp(), RevisionDeleteUser\setUsernameBitfields(), RevDelList\setVisibility(), SpecialBlockList\showList(), SpecialPrefixindex\showPrefixChunk(), SpecialVersion\softwareInformation(), RevDelLogList\suggestTarget(), RecompressTracked\syncDBs(), ChangeTags\tagUsageStatistics(), TestORMRowTest\tearDown(), WikiPageTest\testDoDeleteArticle(), WikiPageTest\testDoDeleteUpdates(), WikiPageTest\testDoEdit(), WikiPageTest\testDoEditContent(), DatabaseTest\testStoredFunctions(), Title\touchLinks(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), SpecialEditWatchlist\unwatchTitles(), SearchOracle\update(), SearchSqlite\update(), SearchMySQL\update(), MessageBlobStore\updateMessage(), MessageBlobStore\updateModule(), SearchOracle\updateTitle(), SearchSqlite\updateTitle(), SearchMySQL\updateTitle(), UserOptions\USAGER(), and SpecialEditWatchlist\watchTitles().

wfGetIP ( )

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

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

Definition at line 4124 of file GlobalFunctions.php.

References global, and wfDeprecated().

Get the cache object used by the language converter.

Returns:
BagOStuff

Definition at line 3969 of file GlobalFunctions.php.

References ObjectCache\getInstance(), and global.

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

References $wgContLang, $wgLang, Language\factory(), Language\fetchLanguageNames(), global, and wfDebug().

Referenced by Skin\doEditSectionLink(), DateFormatter\getInstance(), CodeContentHandler\getPageLanguage(), CodeContentHandler\getPageViewLanguage(), ContentHandlerTest\testGetPageLanguage(), Linker\tocList(), and wfMsgExt().

Get the cache object used by the message cache.

Returns:
BagOStuff

Definition at line 3949 of file GlobalFunctions.php.

References ObjectCache\getInstance(), and global.

Referenced by UploadFromUrlTestSuite\setUp().

wfGetNull ( )

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

/dev/null

Returns:
string

Definition at line 3750 of file GlobalFunctions.php.

References wfIsWindows().

Get the cache object used by the parser cache.

Returns:
BagOStuff

Definition at line 3959 of file GlobalFunctions.php.

References ObjectCache\getInstance(), and global.

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

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

References $blob, $file, $IP, and global.

Get the script URL.

Returns:
string Script URL

Definition at line 3716 of file GlobalFunctions.php.

Fetch server name for use in error reporting etc.

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

Returns:
string

Definition at line 1787 of file GlobalFunctions.php.

References global.

Referenced by TransformationalImageHandler\doTransform(), DjVuHandler\doTransform(), SvgHandler\doTransform(), MWCryptRand\initialRandomState(), ProfilerSimpleDB\logData(), MediaHandler\logErrorForExternalProcess(), RecompressTracked\logToFile(), wfDebugLog(), wfLogDBError(), wfReportTime(), and wfThumbError().

wfHttpError ( code,
label,
desc 
)

Provide a simple HTTP error.

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

Definition at line 2138 of file GlobalFunctions.php.

References $wgOut, global, and print.

Referenced by MWException\report().

wfIncrStats ( key,
count = 1 
)

Increment a statistics counter.

Parameters:
string$key
int$count
Returns:
void

Definition at line 1321 of file GlobalFunctions.php.

References $count, $key, and StatCounter\singleton().

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

Referenced by Installer\envCheckMbstring(), MWHttpRequestTester\factory(), UploadBase\isEnabled(), ObjectCache\newAccelerator(), UserMailer\send(), wfInitShellLocale(), and wfShellExecDisabled().

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

Definition at line 2995 of file GlobalFunctions.php.

References global, and wfIniGetBool().

Referenced by wfEscapeShellArg(), and wfShellExec().

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

References $exceptions, $lines, $name, $title, array(), as, Title\makeTitle(), Title\newFromText(), RepoGroup\singleton(), wfMessage(), wfProfileIn(), wfProfileOut(), and wfRunHooks().

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

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

Deprecated:
Since 1.24, use IP::isConfiguredProxy()
Parameters:
string$ip
Returns:
bool
Since:
1.23 Supports CIDR ranges in $wgSquidServersNoPurge

Definition at line 4151 of file GlobalFunctions.php.

References IP\isConfiguredProxy().

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

Returns:
bool

Definition at line 986 of file GlobalFunctions.php.

References $cache.

Referenced by wfDebug(), and wfLogProfilingData().

wfIsHHVM ( )

Check if we are running under HHVM.

Returns:
bool

Definition at line 2483 of file GlobalFunctions.php.

Referenced by MWDebug\getDebugInfo(), UploadForm\getSourceSection(), UploadBase\isEnabled(), and SpecialVersion\softwareInformation().

wfIsTrustedProxy ( ip)

Checks if an IP is a trusted proxy provider.

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

Deprecated:
Since 1.24, use IP::isTrustedProxy()
Parameters:
string$ip
Returns:
bool

Definition at line 4139 of file GlobalFunctions.php.

References IP\isTrustedProxy().

wfLocalFile ( title)

Get an object referring to a locally registered file.

Returns a valid placeholder object if the file does not exist.

Parameters:
Title | string$title
Returns:
LocalFile|null A File, or null if passed an invalid Title

Definition at line 3674 of file GlobalFunctions.php.

References $title, and RepoGroup\singleton().

Referenced by ImageBuilder\addMissingImage(), PopulateImageSha1\doDBUpdates(), EraseArchivedFile\execute(), ApiQueryImageInfo\execute(), ImageListPager\formatValue(), UploadBase\getLocalFile(), UploadFromUrlTest\setUp(), UploadFromUrlTest\testAsyncUpload(), UploadFromUrlTest\testAsyncUploadWarning(), UploadFromUrlTest\testLeaveMessage(), LocalFileTest\testWfLocalFile(), wfStreamThumb(), and XmlDumpWriter\writeUploads().

wfLogDBError ( text)

Log for database errors.

Parameters:
string$textDatabase error message.

Definition at line 1104 of file GlobalFunctions.php.

References global, wfErrorLog(), wfHostname(), and wfWikiID().

Referenced by DatabaseBase\reportQueryError().

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

References MWDebug\warning().

Referenced by SpecialPageFactory\getPage(), and wfMkdirParents().

wfMakeUrlIndexes ( url)

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

Parameters:
string$url
Returns:
array

Definition at line 865 of file GlobalFunctions.php.

References array(), and wfParseUrl().

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

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

References array(), as, and wfParseUrl().

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

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

Returns:
int Value the memory limit was set to.

Definition at line 3843 of file GlobalFunctions.php.

References global, wfDebug(), wfRestoreWarnings(), wfShorthandToInteger(), and wfSuppressWarnings().

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

References $result, global, wfDebug(), wfEscapeShellArg(), wfRestoreWarnings(), wfSuppressWarnings(), and wfTempDir().

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

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

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

Parameters:
array$array1,...
Returns:
array

Definition at line 222 of file GlobalFunctions.php.

References $out, $params, array(), and as.

Referenced by SpecialImport\execute().

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[]$key Message key, or array of keys
mixed$params,...Normal message parameters
Returns:
Message
Since:
1.17
See also:
Message::__construct

Definition at line 1418 of file GlobalFunctions.php.

References $key, and $params.

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

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

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

Parameters:
string$dirFull path to directory to create
int$modeChmod value to use, default is $wgDirectoryMode
string$callerOptional caller param for debugging.
Exceptions:
MWException
Returns:
bool

Definition at line 2538 of file GlobalFunctions.php.

References $dir, $ok, array(), global, FileBackend\isStoragePath(), wfDebug(), wfLogWarning(), wfRestoreWarnings(), and wfSuppressWarnings().

Referenced by FileCacheBase\checkCacheDirs(), TextPassDumperTest\checkpointHelper(), TransformationalImageHandler\doTransform(), DjVuHandler\doTransform(), SvgHandler\doTransform(), ImageCleanup\pokeFile(), GitInfo\precomputeValues(), UploadFromUrlTestSuite\setupUploadDir(), and GlobalTest\testWfMkdirParents().

wfMsg ( key)

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

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

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

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

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

Definition at line 1463 of file GlobalFunctions.php.

References $key, wfDeprecated(), and wfMsgReal().

wfMsgExt ( key,
options 
)

Returns message in the requested format.

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

Definition at line 1695 of file GlobalFunctions.php.

References $key, $options, array(), as, Sanitizer\escapeHtmlAllowEntities(), MessageCache\singleton(), Parser\stripOuterParagraph(), wfDeprecated(), wfGetLangObj(), wfMsgGetKey(), wfMsgReplaceArgs(), and wfWarn().

wfMsgForContent ( key)

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

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

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

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

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

Definition at line 1512 of file GlobalFunctions.php.

References $key, global, wfDeprecated(), and wfMsgReal().

Same as above except doesn't transform the message.

Deprecated:
since 1.18
Parameters:
string$key
Returns:
string

Definition at line 1535 of file GlobalFunctions.php.

References $key, global, wfDeprecated(), and wfMsgReal().

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

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

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

Definition at line 1584 of file GlobalFunctions.php.

References $cache, $key, array(), MessageCache\singleton(), wfDeprecated(), and wfRunHooks().

Referenced by wfMsgExt(), wfMsgHtml(), wfMsgReal(), and wfMsgWikiHtml().

wfMsgHtml ( key)

Return an HTML-escaped version of a message.

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

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

Definition at line 1640 of file GlobalFunctions.php.

References $key, wfDeprecated(), wfMsgGetKey(), and wfMsgReplaceArgs().

wfMsgNoTrans ( key)

Same as above except doesn't transform the message.

Deprecated:
since 1.18
Parameters:
string$key
Returns:
string

Definition at line 1479 of file GlobalFunctions.php.

References $key, wfDeprecated(), and wfMsgReal().

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

Really get a message.

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

Definition at line 1562 of file GlobalFunctions.php.

References $key, wfDeprecated(), wfMsgGetKey(), wfMsgReplaceArgs(), wfProfileIn(), and wfProfileOut().

Referenced by wfMsg(), wfMsgForContent(), wfMsgForContentNoTrans(), and wfMsgNoTrans().

wfMsgReplaceArgs ( message,
args 
)

Replace message parameter keys on the given formatted output.

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

Definition at line 1607 of file GlobalFunctions.php.

References $n, array(), and as.

Referenced by MWException\msg(), wfMsgExt(), wfMsgHtml(), wfMsgReal(), and wfMsgWikiHtml().

wfMsgWikiHtml ( key)

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

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

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

Definition at line 1661 of file GlobalFunctions.php.

References $key, MessageCache\singleton(), wfDeprecated(), wfMsgGetKey(), and wfMsgReplaceArgs().

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

References $type, array(), as, and mimeTypeMatch().

Referenced by GlobalTest\testNegotiateType().

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

References $key, $value, array(), and as.

wfParseUrl ( url)

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

Differences:

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

Parameters:
string$urlA URL to parse
Returns:
string[] Bits of the URL in an associative array, per PHP docs

Definition at line 772 of file GlobalFunctions.php.

References global, wfRestoreWarnings(), and wfSuppressWarnings().

Referenced by LinkSearchPage\execute(), WikiReference\getDisplayName(), UploadFromUrl\isAllowedHost(), LinkFilter\makeLikeArray(), UserMailer\makeMsgId(), WfAssembleUrlTest\provideURLParts(), RedisPubSubFeedEngine\send(), WfParseUrlTest\testWfParseUrl(), wfExpandUrl(), wfMakeUrlIndexes(), and wfMatchesDomainList().

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

References $ret.

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

Should low-performance queries be disabled?

Returns:
bool

Definition at line 3684 of file GlobalFunctions.php.

References SiteStats\edits(), global, SiteStats\pages(), and SiteStats\users().

wfRandom ( )

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

Returns:
string

Definition at line 290 of file GlobalFunctions.php.

Referenced by CompareParserCache\execute(), RandomPage\getRandomTitle(), SpecialRandomInCategory\getRandomTitle(), ApiQueryRandom\run(), and GlobalTest\testRandom().

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

References $n.

Referenced by MockFileBackend\doGetLocalCopyMulti(), GenerateJsonI18n\doShim(), SvgHandler\doTransform(), MWExceptionHandler\getLogId(), JobQueueTest\setUp(), GlobalVarConfigTest\testConstructor(), GlobalVarConfigTest\testHas(), GlobalTest\testRandomString(), JobQueueTest\testRootDeduplication(), and GlobalVarConfigTest\testSet().

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

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

Definition at line 1339 of file GlobalFunctions.php.

References global.

Referenced by ReadOnlyError\__construct(), ApiQuerySiteinfo\appendGeneralInfo(), ReadOnlyErrorTest\testConstruction(), and wfReadOnly().

Remove a directory and all its content.

Does not hide error.

Parameters:
string$dir

Definition at line 2581 of file GlobalFunctions.php.

References $dir, as, and wfDebug().

Referenced by TextPassDumperTest\checkpointHelper().

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

References $from, $path, and wfBaseName().

Referenced by UploadDumper\outputItem().

wfRemoveDotSegments ( urlPath)

Remove all dot-segments in the provided URL path.

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

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

Definition at line 634 of file GlobalFunctions.php.

References $output.

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

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

References $wgRequestTime, array(), global, Skin\makeVariablesScript(), and wfHostname().

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

References global.

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

Reset the session_id.

Since:
1.22

Definition at line 3472 of file GlobalFunctions.php.

References array(), MWCryptRand\generateHex(), global, wfCheckEntropy(), wfRunHooks(), and wfSetupSession().

Restore error level to previous value.

Definition at line 2364 of file GlobalFunctions.php.

References wfSuppressWarnings().

Referenced by UIDGenerator\__construct(), CheckSyntax\buildFileList(), XCFHandler\canRender(), Exif\charCodeString(), UploadBase\checkXMLEncodingMissmatch(), FileCacheBase\clearCache(), MediaHandler\convertMetadataVersion(), IPTC\convIPTCHelper(), SpecialExport\doExport(), MemoryFileBackend\doStoreInternal(), SvgHandler\doTransform(), CheckImages\execute(), JSParseHelper\execute(), RebuildFileCache\execute(), CommandLineInstaller\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), StatsOutput\formatPercent(), WikiStatsOutput\formatPercent(), ImageHandler\getImageSize(), DjVuImage\getInfo(), ApiQueryImageInfo\getInfo(), MachineReadableRCFeedFormatter\getLine(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), DjVuHandler\getMetaTree(), GitInfo\getRemoteUrl(), ExifBitmapHandler\getRotationForExif(), SpecialVersion\getSvnInfo(), DatabaseOracle\getType(), DjVuHandler\getUnserializedMetadata(), MWCryptRand\initialRandomState(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), FixBug20757\isUnbrokenStub(), SpecialUnlockdb\onSubmit(), SpecialLockdb\onSubmit(), DatabaseMssql\open(), SearchMySQL\parseQuery(), SearchSqlite\parseQuery(), MWCryptRand\realGenerate(), Sanitizer\removeHTMLtags(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), RecompressTracked\startSlaveProcs(), FileRepo\storeBatch(), StreamFile\stream(), MWDebugTest\tearDown(), JavaScriptMinifierTest\testJavaScriptMinifierOutput(), ApiUploadTest\testUploadChunks(), GlobalTest\testWfMkdirParents(), BitmapHandler\transformImageMagick(), MediaWikiI18N\translate(), SvgHandler\unpackMetadata(), wfDiff(), wfErrorLog(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfParseUrl(), wfSetupSession(), wfStreamThumb(), and wfUnpack().

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

Call hook functions defined in $wgHooks.

Parameters:
string$eventEvent name
array$argsParameters passed to hook functions
string | null$deprecatedVersionOptionally mark hook as deprecated with version number
Returns:
bool True if no handler aborted the hook

Definition at line 3983 of file GlobalFunctions.php.

References Hooks\run().

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

As for wfSetVar except setting a bit.

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

Definition at line 2103 of file GlobalFunctions.php.

Referenced by DatabaseBase\trxLevel().

wfSetVar ( &$  dest,
source,
force = false 
)
wfShellExec ( cmd,
&$  retval = null,
environ = array(),
limits = array(),
options = array() 
)

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

Parameters:
string|string[]$cmd If 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
Returns:
string Collected stdout as a string

Definition at line 2751 of file GlobalFunctions.php.

References $error, $IP, $lines, $options, $retval, $time, array(), as, global, wfDebug(), wfDebugLog(), wfEscapeShellArg(), wfInitShellLocale(), wfIsWindows(), and wfShellExecDisabled().

Referenced by UIDGenerator\__construct(), DjVuHandler\doTransform(), CheckSyntax\getGitModifiedFiles(), GitInfo\getHeadCommitDate(), TransformationalImageHandler\getMagickVersion(), DjVuImage\retrieveMetaData(), WfShellExecTest\testBug67870(), wfShellExecWithStderr(), RandomImageGenerator\writeImageWithApi(), and RandomImageGenerator\writeImageWithCommandLine().

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

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

Definition at line 2715 of file GlobalFunctions.php.

References wfDebug(), and wfIniGetBool().

Referenced by wfShellExec().

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

Execute a shell command, returning both stdout and stderr.

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

Note:
This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
Parameters:
string$cmdCommand line, properly escaped for shell.
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 2987 of file GlobalFunctions.php.

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

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

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

Alias to wfShellWikiCmd()

See also:
wfShellWikiCmd()

Definition at line 3013 of file GlobalFunctions.php.

References $options, and wfShellWikiCmd().

Referenced by GlobalTest\testWfShellMaintenanceCmd().

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

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

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

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

Definition at line 3029 of file GlobalFunctions.php.

References $options, array(), global, and wfRunHooks().

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

wfShorthandToInteger ( string = '')

Converts shorthand byte notation to integer form.

Parameters:
string$string
Returns:
int

Definition at line 3871 of file GlobalFunctions.php.

References $last.

Referenced by UploadForm\getSourceSection(), WfShorthandToIntegerTest\testWfShorthandToInteger(), GlobalTest\testWfShorthandToInteger(), and wfMemoryLimit().

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

Definition at line 1974 of file GlobalFunctions.php.

References $limit, and wfMessage().

wfSplitWikiID ( wiki)

Split a wiki ID into DB name and table prefix.

Parameters:
string$wiki
Returns:
array

Definition at line 3590 of file GlobalFunctions.php.

Referenced by JobQueueFederated\getCacheKey().

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

Parameters:
string$nameFilename to process
Returns:
string

Definition at line 3826 of file GlobalFunctions.php.

References $name, global, Title\legalChars(), and wfBaseName().

Referenced by UploadBase\getTitle().

wfSuppressWarnings ( end = false)

Reference-counted warning suppression.

Parameters:
bool$end

Definition at line 2334 of file GlobalFunctions.php.

Referenced by UIDGenerator\__construct(), SqliteMaintenance\backup(), CheckSyntax\buildFileList(), XCFHandler\canRender(), Exif\charCodeString(), UploadBase\checkXMLEncodingMissmatch(), FileCacheBase\clearCache(), MediaHandler\convertMetadataVersion(), IPTC\convIPTCHelper(), SpecialExport\doExport(), MemoryFileBackend\doStoreInternal(), SvgHandler\doTransform(), CheckImages\execute(), JSParseHelper\execute(), RebuildFileCache\execute(), CommandLineInstaller\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), StatsOutput\formatPercent(), WikiStatsOutput\formatPercent(), ImageHandler\getImageSize(), DjVuImage\getInfo(), ApiQueryImageInfo\getInfo(), MachineReadableRCFeedFormatter\getLine(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), DjVuHandler\getMetaTree(), GitInfo\getRemoteUrl(), ExifBitmapHandler\getRotationForExif(), SpecialVersion\getSvnInfo(), DatabaseOracle\getType(), DjVuHandler\getUnserializedMetadata(), MWCryptRand\initialRandomState(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), FixBug20757\isUnbrokenStub(), SpecialUnlockdb\onSubmit(), SpecialLockdb\onSubmit(), DatabaseMssql\open(), SearchSqlite\parseQuery(), SearchMySQL\parseQuery(), MWCryptRand\realGenerate(), Sanitizer\removeHTMLtags(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), MWDebugTest\setUp(), RecompressTracked\startSlaveProcs(), FileRepo\storeBatch(), StreamFile\stream(), JavaScriptMinifierTest\testJavaScriptMinifierOutput(), ApiUploadTest\testUploadChunks(), GlobalTest\testWfMkdirParents(), BitmapHandler\transformImageMagick(), MediaWikiI18N\translate(), SvgHandler\unpackMetadata(), wfDiff(), wfErrorLog(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfParseUrl(), wfRestoreWarnings(), wfSetupSession(), wfStreamThumb(), and wfUnpack().

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, and if none are set try sys_get_temp_dir().

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

Returns:
string

Definition at line 2512 of file GlobalFunctions.php.

References array(), as, and global.

Referenced by UIDGenerator\__construct(), UploadBaseTest\createFileOfSize(), MockFileBackend\doGetLocalCopyMulti(), SvgHandler\doTransform(), WikiImporter\dumpTemp(), MWDocGen\execute(), ApiTestCaseUpload\fakeUploadChunk(), ApiTestCaseUpload\fakeUploadFile(), CheckStorage\restoreText(), GlobalTest\setUp(), StoreBatchTest\setUp(), UploadFromUrlTestSuite\setUp(), UploadFromUrlTestSuite\setupUploadDir(), CdbTest\testCdb(), GlobalTest\testDebugFunctionTest(), ApiUploadTest\testUpload(), ApiUploadTest\testUploadChunks(), ApiUploadTest\testUploadSameContent(), ApiUploadTest\testUploadSameFileName(), ApiUploadTest\testUploadStash(), ApiUploadTest\testUploadZeroLength(), wfDiff(), and wfMerge().

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

References $e, $timestamp, and wfDebug().

Referenced by BlockTest\addDBData(), LocalFileRestoreBatch\addIds(), ApiQueryLogEvents\addLogParams(), ApiQuerySiteinfo\appendExtensions(), ApiQuerySiteinfo\appendGeneralInfo(), SpecialRecentChanges\buildMainQueryConds(), FileCacheBase\cacheTimestamp(), LanguageWa\date(), MemoryFileBackend\doCopyInternal(), MemoryFileBackend\doCreateInternal(), MysqlUpdater\doSchemaRestructuring(), MemoryFileBackend\doStoreInternal(), ApiProtect\execute(), ApiUndelete\execute(), ApiEditPage\execute(), ApiSetNotificationTimestamp\execute(), ApiQueryDeletedrevs\execute(), SpecialExport\execute(), ApiQueryFilearchive\execute(), RemoveUnusedAccounts\execute(), ApiBlock\execute(), ApiQueryBlocks\execute(), UploadStashCleanup\execute(), FixTimestamps\execute(), ApiQueryImageInfo\execute(), PurgeParserCache\execute(), ApiQueryAllUsers\execute(), ApiFeedWatchlist\execute(), UpdateSearchIndex\execute(), ApiQueryUsers\execute(), ApiQueryInfo\extractPageInfo(), ApiQueryWatchlist\extractRowInfo(), ApiQueryContributions\extractRowInfo(), ApiQueryLogEvents\extractRowInfo(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryRevisions\extractRowInfo(), HistoryAction\feedEmpty(), FeedUtils\formatDiff(), RevDelArchivedFileItem\getApiData(), RevDelRevisionItem\getApiData(), RevDelFileItem\getApiData(), NewUsersLogFormatter\getComment(), ApiQueryUserInfo\getCurrentUserInfo(), MessageBlobStore\getFromDB(), ApiQueryImageInfo\getInfo(), MachineReadableRCFeedFormatter\getLine(), PNGMetadataExtractor\getMetadata(), SpecialRandomInCategory\getMinAndMaxForCat(), ResourceLoaderUserCSSPrefsModule\getModifiedTime(), ResourceLoaderUserOptionsModule\getModifiedTime(), ResourceLoaderStartUpModule\getModifiedTime(), ResourceLoaderStartUpModule\getModuleRegistrations(), ResourceLoaderStartUpModule\getStartupModulesUrl(), MockFSFile\getTimestamp(), ForeignAPIFile\getTimestamp(), ResourceLoaderWikiModule\getTitleInfo(), User\isEmailConfirmationPending(), ChangesFeed\loadFromCache(), BloomFilterTitleHasLogs\merge(), StreamFile\prepareForStream(), TableCleanup\progress(), ImageBuilder\progress(), Block\purgeExpired(), ApiQueryProtectedTitles\run(), ApiQueryWatchlistRaw\run(), ApiQueryCategories\run(), ApiQueryDuplicateFiles\run(), ApiQueryCategoryMembers\run(), ApiQuerySearch\run(), ApiQueryQueryPage\run(), RefreshLinksJob\runForTitle(), ChangesFeed\saveToCache(), ApiMain\sendCacheHeaders(), EditPageTest\testAutoMerge(), WfTimestampTest\testHttpDate(), WfTimestampTest\testNormalTimestamps(), WfTimestampTest\testOldTimestamps(), WfTimestampTest\testTimestampParameter(), IPTC\timeHelper(), DatabaseBase\timestamp(), XMPValidate\validateDate(), wfDebugLog(), wfStreamThumb(), wfTimestampNow(), and wfTimestampOrNull().

wfTimestampOrNull ( outputtype = TS_UNIX,
ts = null 
)

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

For dealing with nullable timestamp columns in the database.

Parameters:
int$outputtype
string$ts
Returns:
string

Definition at line 2447 of file GlobalFunctions.php.

References wfTimestamp().

Referenced by Autopromote\checkCondition(), ApiQueryUsers\execute(), and JobSpecification\getReleaseTimestamp().

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

References $result, wfRestoreWarnings(), and wfSuppressWarnings().

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

wfUrlencode ( s)

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

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

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

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

;:$!*(),/

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

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

Parameters:
string$s
Returns:
string

Definition at line 339 of file GlobalFunctions.php.

References $s, and array().

Referenced by MediaWikiSite\getPageUrl(), CoreParserFunctions\namespacee(), CoreParserFunctions\nse(), CoreParserFunctions\speciale(), CoreParserFunctions\subjectspacee(), CoreParserFunctions\talkspacee(), GlobalTest\testUrlencode(), and WfUrlencodeTest\verifyEncodingFor().

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

References $retval, array(), as, and global.

Referenced by Parser\__construct(), Skin\addToSidebarPlain(), ResourceLoaderStartUpModule\getConfigSettings(), Skin\makeInternalOrExternalUrl(), Sanitizer\safeEncodeAttribute(), Sanitizer\validateAttributes(), and 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 757 of file GlobalFunctions.php.

References wfUrlProtocols().

Referenced by ApiFormatBase\formatHTML().

wfUseMW ( req_ver)

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

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

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

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

Definition at line 3238 of file GlobalFunctions.php.

References global.

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

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

References $s, $wgOut, global, and print.

wfWaitForSlaves ( ifWritesSince = false,
wiki = false,
cluster = false 
)

Modern version of wfWaitForSlaves().

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

Parameters:
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.
Returns:
bool Success (able to connect and no timeouts reached)

Definition at line 3766 of file GlobalFunctions.php.

References $lb, array(), wfGetLB(), and wfGetLBFactory().

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

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

References MWDebug\warning().

Referenced by TextContent\__construct(), SpecialPageFactory\getLocalNameFor(), Linker\link(), Linker\linkText(), Linker\makeBrokenImageLinkObj(), BacklinkJobUtils\partitionBacklinkJob(), Autopromote\recCheckCondition(), and wfMsgExt().