MediaWiki  REL1_22
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

 in_string ($needle, $str, $insensitive=false)
 Find out whether or not a mixed variable exists in a string.
 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*.
 wfArrayLookup ($a, $b)
 Array lookup Returns an array where the values in array $b are replaced by the values in array $a with the corresponding keys.
 wfArrayMerge ($array1)
 Backwards array plus for people who haven't bothered to read the PHP manual XXX: will not darn your socks for you.
 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 ($n)
 Count down from $n to zero on the terminal, with a one-second pause between showing each number.
 wfCreateObject ($name, $p)
 Create an object with a given name and an array of construct parameters.
 wfDebug ($text, $logonly=false)
 Sends a line to the debug log if enabled or, optionally, to a comment in output.
 wfDebugBacktrace ($limit=0)
 Safety wrapper for debug_backtrace().
 wfDebugDieBacktrace ($msg= '')
 Throw a debugging exception.
 wfDebugLog ($logGroup, $text, $public=true)
 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.
 wfDoUpdates ($commit= '')
 Do any deferred updates and clear the list.
 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.
 wfGenerateToken ($salt= '')
 Generate a random 32-character hexadecimal token.
 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.
 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.
 wfHttpOnlySafe ()
 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'.
 wfIsDebugRawPage ()
 Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
 wfIsHipHop ()
 Check if we are running under HipHop.
 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.
 wfOut ($s)
 Used to be used for outputting text in the installer/updater.
 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 HTML comment with the elapsed time since request.
 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())
 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.
 wfStreamFile ($fname, $headers=array())
 Stream a file to the browser.
 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.
 wfTime ()
 Get the current unix timestamp with microseconds.
 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.
 wfUILang ()
 Old function when $wgBetterDirectionality existed All usage removed, wfUILang can be removed in near future.
 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().
 wfViewPrevNext ($offset, $limit, $link, $query= '', $atend=false)
 Generate (prev x| next x) (20|50|100...) type links for paging.
 wfWaitForSlaves ($maxLag=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 2356 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 2377 of file GlobalFunctions.php.

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

This is used by Special:Export

Definition at line 2368 of file GlobalFunctions.php.

ISO 8601 basic format with no timezone: 19860209T200000Z.

This is used by ResourceLoader

Definition at line 2392 of file GlobalFunctions.php.

enum TS_MW

MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)

Definition at line 2351 of file GlobalFunctions.php.

enum TS_ORACLE

Oracle format time.

Definition at line 2382 of file GlobalFunctions.php.

Postgres format time.

Definition at line 2387 of file GlobalFunctions.php.

enum TS_RFC2822

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

Definition at line 2361 of file GlobalFunctions.php.

enum TS_UNIX

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

Definition at line 2346 of file GlobalFunctions.php.


Function Documentation

in_string ( needle,
str,
insensitive = false 
)

Find out whether or not a mixed variable exists in a string.

Deprecated:
Just use str(i)pos
Parameters:
$needleString
$strString
$insensitiveBoolean
Returns:
Boolean

Definition at line 2591 of file GlobalFunctions.php.

References wfDeprecated().

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:
$typeString
$availArray
Returns:
string

Definition at line 2246 of file GlobalFunctions.php.

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

swap ( &$  x,
&$  y 
)

Swap two variables.

Parameters:
$xMixed
$yMixed

Definition at line 2467 of file GlobalFunctions.php.

Referenced by GlobalTest\testSwapVarsTest().

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

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

Parameters:
$acceptString
string$defdefault
Returns:
Array

Definition at line 2210 of file GlobalFunctions.php.

References array(), and as.

Referenced by RdfMetaData\setup().

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:
$urlString
$queryMixed: string or associative array
Returns:
string

Definition at line 457 of file GlobalFunctions.php.

References $query, and wfArrayToCgi().

Referenced by SpecialContributions\execute(), ImportSiteScripts\execute(), LoginForm\execute(), ImportSiteScripts\fetchScriptList(), Title\getLocalURL(), ResourceLoaderStartUpModule\getScript(), ImageHandler\getScriptedTransform(), Linker\getUploadUrl(), ForeignAPIRepo\httpGetCached(), Linker\link(), Linker\makeThumbLink2(), MediaWikiSite\normalizePageName(), and SquidPurgeClient\queuePurge().

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

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

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

Definition at line 167 of file GlobalFunctions.php.

References $changed, $key, and $value.

Referenced by SpecialWatchlist\execute().

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

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

Parameters:
$aarray
$barray
Returns:
array

Definition at line 116 of file GlobalFunctions.php.

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

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

Definition at line 125 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.
$afterMixed: The key to insert after
Returns:
Array

Definition at line 236 of file GlobalFunctions.php.

References $keys, and $output.

wfArrayLookup ( a,
b 
)

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

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

Definition at line 153 of file GlobalFunctions.php.

References wfDeprecated().

wfArrayMerge ( array1)

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

Deprecated:
since 1.22; use array_replace()
Parameters:
$array1Array
[$array2,[...]]Arrays
Returns:
Array

Definition at line 185 of file GlobalFunctions.php.

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

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 )
$prefixString
Returns:
String

Definition at line 365 of file GlobalFunctions.php.

References $key, $value, and as.

Referenced by SkinTemplate\buildPersonalUrls(), PhpHttpRequest\execute(), WebInstaller_Options\execute(), Title\fixUrlQueryArgs(), getEscapedProfileUrl(), SpecialRecentChanges\getFeedQuery(), SkinTemplate\setupTemplateForOutput(), 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 560 of file GlobalFunctions.php.

References $result.

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

Get a debug backtrace as a string.

Returns:
string

Definition at line 1814 of file GlobalFunctions.php.

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

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

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

References $result, array(), and as.

Referenced by UIDGenerator\__construct(), NewParserTest\addDBData(), DatabasePostgres\bigintFromLockName(), ApiQueryDeletedrevs\execute(), ApiQueryFilearchive\execute(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryRevisions\extractRowInfo(), ApiQueryImageInfo\getInfo(), ForeignAPIFile\getSha1(), FSFile\getSha1Base36(), FileJournal\getTimestampedUUID(), 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\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:
$pathString
string$suffixto remove if present
Returns:
String

Definition at line 3094 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 3797 of file GlobalFunctions.php.

References array(), and as.

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

wfBoolToStr ( value)

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

Parameters:
$valueBoolean
Returns:
String

Definition at line 3620 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:
boolean

Definition at line 4004 of file GlobalFunctions.php.

References array(), and wfRunHooks().

Referenced by LoginForm\execute(), and 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:
array Array version of input

Definition at line 410 of file GlobalFunctions.php.

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

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

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

Returns:
bool true = there is sufficient entropy

Definition at line 3298 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

Definition at line 1991 of file GlobalFunctions.php.

References global.

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

References wfResetOutputBuffers().

wfClientAcceptsGzip ( force = false)
Todo:

document

FIXME: We may want to blacklist some broken browsers

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

Definition at line 1957 of file GlobalFunctions.php.

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

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

wfCountDown ( n)

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

For use in command-line scripts.

Parameters:
$nint

Definition at line 3684 of file GlobalFunctions.php.

References $n.

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

wfCreateObject ( name,
p 
)

Create an object with a given name and an array of construct parameters.

Parameters:
$nameString
array$pparameters
Returns:
object
Deprecated:
since 1.18, warnings in 1.18, removal in 1.20

Definition at line 3272 of file GlobalFunctions.php.

References $name, MWFunction\newObj(), and wfDeprecated().

wfDebug ( text,
logonly = false 
)

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 $wgProfileOnly - if set, normal debug messages will not be recorded. $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output. $wgDebugComments - if on, some debug items may appear in comments in the HTML output.

Parameters:
$textString
bool$logonlyset true to avoid appearing in HTML when $wgDebugComments is set

Definition at line 918 of file GlobalFunctions.php.

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

Referenced by UploadFromChunks\__construct(), DBABagOStuff\__construct(), UploadFromStash\__construct(), MemcachedPeclBagOStuff\__construct(), WikiXmlError\__construct(), MimeMagic\__construct(), ImportStreamSource\__construct(), StubObject\_unstub(), MediaHandler\addMeta(), LinkBatch\addObj(), Skin\afterContentHook(), AutoLoader\autoload(), SkinTemplate\buildContentActionUrls(), DBABagOStuff\cas(), UploadBase\checkSvgScriptCallback(), UploadBase\checkXMLEncodingMissmatch(), LocalRepo\cleanupDeletedBatch(), UploadBase\cleanupTempFile(), SpecialEditWatchlist\cleanupWatchlist(), MessageBlobStore\clear(), UploadFromChunks\concatenateChunks(), DjVuImage\convertDumpToXML(), EhcacheBagOStuff\createCache(), UploadBase\createFromRequest(), MockFileBackend\debug(), WikiImporter\debug(), BaseDump\debug(), RecompressTracked\debug(), SVGReader\debug(), BagOStuff\debug(), Profiler\debug(), Block\defaultRetroactiveAutoblock(), EhcacheBagOStuff\delete(), DBABagOStuff\delete(), Block\deleteIfExpired(), MimeMagic\detectMimeType(), UploadBase\detectScript(), UploadBase\detectVirus(), MimeMagic\detectZipType(), DatabasePostgres\determineCoreSchema(), WikiDiff3\diff(), BitmapMetadataHandler\doApp13(), Block\doAutoblock(), MockImageHandler\doFakeTransform(), MimeMagic\doGuessMimeType(), DatabaseMssql\doQuery(), DatabaseOracle\doQuery(), EhcacheBagOStuff\doRequest(), Block\doRetroactiveAutoblock(), UserrightsPage\doSaveUserGroups(), BitmapHandler\doTransform(), DjVuHandler\doTransform(), LoadBalancer\doWait(), MWCryptRand\driftHash(), DatabasePostgres\dumpError(), ZipDirectoryReader\error(), PoolWorkArticleView\error(), CLDRPluralRuleEvaluator\evaluateCompiled(), SpecialUserlogout\execute(), ApiUpload\execute(), ChangesFeed\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), Article\fetchContentObject(), WikiDiff3\find_middle_snake(), FormatMetadata\flattenArray(), EhcacheBagOStuff\get(), DBABagOStuff\get(), ParserCache\get(), Interwiki\getAllPrefixesCached(), LoadBalancer\getConnection(), File\getDescriptionText(), DoubleRedirectJob\getFinalDestination(), IcuCollation\getFirstLetterData(), GenderCache\getGenderOf(), MediaHandler\getHandler(), DjVuImage\getInfo(), Interwiki\getInterwikiCacheEntry(), ParserCache\getKey(), BitmapHandler\getMagickVersion(), LoadBalancer\getMasterPos(), GIFHandler\getMetadata(), JpegHandler\getMetadata(), PNGHandler\getMetadata(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), TiffHandler\getMetadata(), SvgHandler\getMetadata(), DjVuHandler\getMetadata(), DjVuHandler\getMetaTree(), DjVuImage\getMultiPageInfo(), SpecialPageFactory\getPage(), DjVuImage\getPageInfo(), UserCache\getProp(), FSFile\getProps(), DBABagOStuff\getReader(), LoadBalancer\getReaderIndex(), Title\getRestrictionTypes(), ExternalStoreDB\getSlave(), ForeignAPIRepo\getThumbError(), ForeignAPIRepo\getThumbUrl(), ForeignAPIRepo\getThumbUrlFromCache(), NewParserTest\getUploadDir(), DBABagOStuff\getWriter(), XCFHandler\getXCFMetaData(), MimeMagic\guessMimeType(), MWCryptRand\hashAlgo(), ForeignAPIRepo\httpGet(), EditPage\importFormData(), MimeMagic\improveTypeFromExtension(), DBABagOStuff\incr(), Block\insert(), MessageBlobStore\insertMessageBlob(), ExternalStore\insertWithFallback(), FileCacheBase\isCacheGood(), SvgHandler\isEnabled(), DjVuHandler\isEnabled(), FileDependency\isExpired(), Block\isExpired(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), Title\isValidMoveTarget(), Block\isWhitelistedFromAutoblocks(), SiteStats\loadAndLazyInit(), ChangesFeed\loadFromCache(), HTMLFileCache\loadFromFileCache(), User\loadFromId(), User\loadFromSession(), DatabasePostgres\lock(), PostgresTransactionState\log_changed(), Linker\makeBrokenLink(), Linker\makeExternalImage(), Linker\makeExternalLink(), Linker\makeImageLink(), Skin\newFromKey(), SVGReader\notice(), RawAction\onView(), CdbReader\open(), DatabaseMssql\open(), CdbWriter\open(), DatabasePostgres\open(), LoadBalancer\openConnection(), LoadBalancer\openForeignConnection(), UploadDumper\outputItem(), SkinTemplate\outputPage(), SearchMySQL\parseQuery(), BacklinkCache\partition(), DiffHistoryBlob\patch(), SavepointPostgres\query(), BacklinkCache\queryLinks(), SvgHandler\rasterize(), TextPassDumper\readDump(), TestFileIterator\readNextTest(), MWCryptRand\realGenerate(), EnhancedChangesList\recentChangesLine(), DatabaseOracle\reportQueryError(), Http\request(), DjVuImage\retrieveMetaData(), LoadBalancer\reuseConnection(), JpegHandler\rotate(), BitmapHandler\rotate(), DoubleRedirectJob\run(), DataUpdate\runUpdates(), RequestContext\sanitizeLangCode(), ParserCache\save(), FileCacheBase\saveText(), HTMLFileCache\saveToFileCache(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), MWDebug\sendWarning(), UserMailer\sendWithPear(), EhcacheBagOStuff\set(), DBABagOStuff\set(), LanguageClassesTestCase\setUp(), UploadFromUrlTestSuite\setupUploadDir(), ParserTest\setupUploadDir(), LoadBalancer\sleep(), GlobalTest\testDebugFunctionTest(), NewParserTest\testParserTest(), ApiUploadTest\testUploadChunks(), WikiImporter\throwXmlError(), SVGReader\throwXmlError(), BitmapHandler\transformCustom(), BitmapHandler\transformGd(), BitmapHandler\transformImageMagick(), BitmapHandler\transformImageMagickExt(), SpecialUploadStash\tryClearStashedUploads(), Block\update(), UploadFromChunks\updateChunkStatus(), MessageBlobStore\updateMessage(), MessageBlobStore\updateModule(), OldLocalFile\upgradeRow(), HTMLFileCache\useFileCache(), SvgHandler\validateParam(), ImageHandler\validateThumbParams(), UploadBase\verifyExtension(), UploadBase\verifyFile(), UploadBase\verifyMimeType(), WikiImporter\warn(), SVGReader\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().

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

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

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

Definition at line 1780 of file GlobalFunctions.php.

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

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

wfDebugDieBacktrace ( msg = '')

Throw a debugging exception.

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

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

Definition at line 1706 of file GlobalFunctions.php.

References wfDeprecated().

wfDebugLog ( logGroup,
text,
public = true 
)

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

$wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.

Parameters:
$logGroupString
$textString
bool$publicwhether to log the event in the public log if no private log file is specified, (default true)

Definition at line 1007 of file GlobalFunctions.php.

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

Referenced by MWMemcached\_fwrite(), ExternalStoreDB\batchFetchBlobs(), MemcachedPeclBagOStuff\checkResult(), UploadFromChunks\concatenateChunks(), IPTC\convIPTCHelper(), MediaWikiParserTest\debug(), Exif\debug(), Exif\debugFile(), MemcachedBagOStuff\debugLog(), XMPReader\doAttribs(), DjVuHandler\doTransform(), XMPReader\endElement(), XMPReader\endElementModeLi(), XMPReader\endElementNested(), PoolWorkArticleView\error(), CheckUsernames\execute(), ExternalStoreDB\fetchBlob(), IPTC\getCharset(), ResourceLoaderWikiModule\getContent(), ContentHandler\getContentText(), ContentHandler\getForModelID(), LoadBalancer\getRandomNonLagged(), LoadBalancer\getReaderIndex(), ResourceLoaderFileModule\getStyles(), ExternalStore\insertWithFallback(), User\loadFromSession(), SquidPurgeClient\log(), BitmapHandler\logErrorForExternalProcess(), MWExceptionHandler\logException(), MediaWiki\main(), MediaWikiSite\normalizePageName(), IPTC\parse(), XMPReader\parse(), XMPReader\parseExtended(), SvgHandler\rasterize(), ResourceLoaderFileModule\readStyleFile(), MediaHandler\removeBadFile(), LocalFileMoveBatch\removeNonexistentFiles(), SquidPurgeClientPool\run(), RunJobs\runJobsLog(), XMPReader\saveValue(), WebResponse\setcookie(), XMPReader\startElement(), XMPReader\startElementModeInitial(), XMPReader\startElementModeSeq(), XMPReader\startElementModeSimple(), IPTC\timeHelper(), Profiler\transactionWritingOut(), XMPValidate\validateBoolean(), XMPValidate\validateClosed(), XMPValidate\validateDate(), XMPValidate\validateFlash(), XMPValidate\validateGPS(), XMPValidate\validateInteger(), XMPValidate\validateLangCode(), XMPValidate\validateRating(), XMPValidate\validateRational(), wfSetupSession(), and wfShellExec().

wfDebugMem ( exact = false)

Send a line giving PHP memory usage.

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

Definition at line 988 of file GlobalFunctions.php.

References wfDebug().

Referenced by GlobalTest\testDebugFunctionTest().

Get microsecond timestamps for debug logs.

Returns:
string

Definition at line 971 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:
$functionString
string | bool$versionVersion of MediaWiki that the function was deprecated in (Added in 1.19).
string | bool$componentAdded in 1.19.
$callerOffsetinteger: How far up the call stack is the original caller. 2 = function that called the function that called wfDeprecated (Added in 1.20)
Returns:
null

Definition at line 1064 of file GlobalFunctions.php.

References MWDebug\deprecated().

Referenced by Skin\__call(), WikiError\__construct(), WikiErrorMsg\__construct(), WikiXmlError\__construct(), StubContLang\__construct(), RawPage\__construct(), ImageGallery\__construct(), DeprecatedGlobal\_newObject(), MWFunction\call(), MWFunction\callArray(), Block\clear(), LoadBalancer\closeConnecton(), Skin\commonPrintStylesheet(), ApiBase\createContext(), Block\decodeExpiry(), ContentHandler\deprecated(), Block\encodeExpiry(), Title\escapeCanonicalURL(), Title\escapeFullURL(), Title\escapeLocalURL(), Title\fixUrlQueryArgs(), FormatExif\FormatExif(), Block\forUpdate(), ApiQueryUsers\getAutoGroups(), ProfilerSimple\getCpuTime(), Title\getEscapedText(), Linker\getExternalLinkAttributes(), Exif\getFormattedData(), SpecialPageFactory\getGroup(), MWException\getLogId(), MWException\getLogMessage(), ApiBase\getValidNamespaces(), ApiBase\getVersion(), in_string(), Block\infinity(), WikiError\isError(), MWNamespace\isMain(), QuickTemplate\jstext(), Linker\link(), Block\load(), Preferences\loadOldSearchNs(), Linker\makeBrokenLink(), Linker\makeBrokenLinkObj(), Linker\makeColouredLinkObj(), Exif\makeFormattedData(), Skin\makeGlobalVariablesScript(), UserrightsPage\makeGroupNameListForLog(), Linker\makeKnownLinkObj(), Linker\makeLinkObj(), Linker\makeSizeLinkObj(), Xml\namespaceSelector(), Block\newFromDB(), Block\normaliseRange(), Block\parseExpiryInput(), SpecialPageFactory\setGroup(), ParserOptions\setInterfaceMessage(), DerivativeContext\setLang(), RequestContext\setLang(), Preferences\trySetUserEmail(), Title\updateTitleProtection(), Title\userCanRead(), wfArrayLookup(), wfArrayMerge(), wfCreateObject(), wfDebugDieBacktrace(), wfDoUpdates(), wfEmptyMsg(), wfExtractThumbParams(), wfGenerateToken(), wfGetAgent(), wfGetForwardedFor(), wfGetIP(), wfMsg(), wfMsgExt(), wfMsgForContent(), wfMsgForContentNoTrans(), wfMsgGetKey(), wfMsgHtml(), wfMsgNoTrans(), wfMsgReal(), wfMsgWikiHtml(), wfOut(), wfStreamFile(), wfTime(), wfUILang(), and wfViewPrevNext().

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

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

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

wfDoUpdates ( commit = '')

Do any deferred updates and clear the list.

Deprecated:
since 1.19
See also:
DeferredUpdates::doUpdate()
Parameters:
$commitstring

Definition at line 3158 of file GlobalFunctions.php.

References DeferredUpdates\doUpdates(), and wfDeprecated().

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:
$keyString: the message key looked up
Returns:
Boolean True if the message *doesn't* exist.

Definition at line 1692 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:
$textString
string$filefilename
Exceptions:
MWException

Definition at line 1105 of file GlobalFunctions.php.

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

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

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:
varargs
Returns:
String

Definition at line 2644 of file GlobalFunctions.php.

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

Referenced by CheckSyntax\checkFileWithCli(), MimeMagic\detectMimeType(), UploadBase\detectVirus(), PopulateImageSha1\doDBUpdates(), DjVuHandler\doTransform(), CheckSyntax\getGitModifiedFiles(), GitInfo\getHeadCommitDate(), BitmapHandler\getMagickVersion(), SvgHandler\rasterize(), CheckStorage\restoreText(), DjVuImage\retrieveMetaData(), JpegHandler\rotate(), BitmapHandler\rotate(), RecompressTracked\startSlaveProcs(), SevenZipStream\stream_open(), BitmapHandler\transformCustom(), wfDiff(), wfMerge(), 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:
$urlstring
Returns:
string

Definition at line 818 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 827 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
$defaultProtoMixed: one of the PROTO_* constants. Determines the protocol to use if $url or $wgServer is protocol-relative
Returns:
string Fully-qualified URL, current-path-relative URL or false if no valid URL can be constructed

Definition at line 494 of file GlobalFunctions.php.

References WebRequest\detectProtocol(), global, wfAssembleUrl(), wfParseUrl(), and wfRemoveDotSegments().

Referenced by ResourceLoaderFileModule\__construct(), ApiQuerySiteinfo\appendGeneralInfo(), ApiQuerySiteinfo\appendInterwikiMap(), ApiQuerySiteinfo\appendRightsInfo(), ApiQueryLangLinks\execute(), ApiQueryExternalLinks\execute(), ApiQueryIWLinks\execute(), ApiQueryInfo\extractPageInfo(), CoreParserFunctions\filepath(), File\getCanonicalUrl(), Title\getCanonicalURL(), SpecialVersion\getEntryPointInfo(), RevertFileAction\getFormFields(), Title\getFullURL(), ApiQueryImageInfo\getInfo(), Title\getInternalURL(), ApiRsd\getRsdApiList(), File\getViewURL(), ForeignAPIRepo\httpGet(), RevertFileAction\onSuccess(), OutputPage\output(), SpecialUploadStash\outputRemoteScaledThumb(), CSSMin\remap(), ApiQueryExtLinksUsage\run(), WfExpandUrlTest\testWfExpandUrl(), wfExpandIRI(), and wfStreamThumb().

wfFindFile ( title,
options = array() 
)

Find a file.

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

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

ignoreRedirect: If true, do not follow file redirects

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

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

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

Definition at line 3533 of file GlobalFunctions.php.

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

Referenced by UploadFromUrlTest\deleteFile(), ApiTestCaseUpload\deleteFileByTitle(), MovePageForm\doSubmit(), ApiMove\execute(), DeleteBatch\execute(), ApiImageRotate\execute(), FileDuplicateSearchPage\execute(), CoreParserFunctions\filepath(), Title\isAlwaysKnown(), Linker\makeBrokenImageLinkObj(), Linker\makeMediaLinkObj(), Linker\makeThumbLink2(), UploadDumper\outputItem(), TraditionalImageGallery\toHTML(), and Title\validateFileMoveOperation().

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

Definition at line 3310 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:
$dbString
$prefixString
varargsString
Returns:
String

Definition at line 3428 of file GlobalFunctions.php.

References $key.

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

wfFormatStackFrame ( frame)

Return a string representation of frame.

Parameters:
$frameArray
Returns:
string

Definition at line 1901 of file GlobalFunctions.php.

Referenced by wfGetCaller().

wfGenerateToken ( salt = '')

Generate a random 32-character hexadecimal token.

Parameters:
$saltMixed: some sort of salt, if necessary, to add to random characters before hashing.
Returns:
string
Deprecated:
since 1.20; Please use MWCryptRand for security purposes and wfRandomString for pseudo-random strings
Warning:
This method is NOT secure. Additionally it has many callers that use it for pseudo-random purposes.

Definition at line 3707 of file GlobalFunctions.php.

References wfDeprecated().

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

References $limit, and wfDebugBacktrace().

Referenced by MWCryptRand\realGenerate().

wfGetCache ( inputType)

Get a cache object.

Parameters:
$inputTypeinteger Cache type, one the the CACHE_* constants.
Returns:
BagOStuff

Definition at line 3825 of file GlobalFunctions.php.

References ObjectCache\getInstance().

Referenced by LCStore_Accel\__construct(), ResourceLoaderFileModule\compileLESSFile(), IcuCollation\getFirstLetterData(), ResourceLoaderModule\getHashMtime(), ForkController\initChild(), and ResourceLoaderModule\validateScriptFile().

wfGetCaller ( level = 2)

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

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

Parameters:
$levelInt
Returns:
string

Definition at line 1869 of file GlobalFunctions.php.

References wfDebugBacktrace(), and wfFormatStackFrame().

Referenced by StubObject\_unstub(), WfGetCallerTest\callerOne(), MockFileBackend\debug(), MediaWikiParserTest\debug(), WfGetCallerTest\intermediateFunction(), MWDebug\log(), and WfGetCallerTest\testZero().

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

Get a Database object.

Parameters:
$dbInteger: index 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.
$groupsMixed: 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$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 3490 of file GlobalFunctions.php.

References wfGetLB().

Referenced by DeletedContribsPager\__construct(), SearchEngine\__construct(), SqlDataUpdate\__construct(), Block\__construct(), ImageListPager\__construct(), IndexPager\__construct(), MergeHistoryPager\__construct(), SiteStatsInit\__construct(), LinkCache\addLinkObj(), ApiQueryLogEvents\addLogParams(), ChangeTags\addTags(), WatchedItem\addWatch(), SpecialRecentChanges\buildMainQueryConds(), ImageListPager\buildQueryConds(), ImageBuilder\buildTable(), SiteStatsUpdate\cacheUpdate(), TitleListDependency\calculateTimestamps(), userOptions\CHANGER(), CheckStorage\check(), TrackBlobs\checkIntegrity(), SpecialRecentChanges\checkLastModified(), 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\countAuthorsBetween(), Title\countRevisionsBetween(), ConvertLinks\createTempTable(), Block\defaultRetroactiveAutoblock(), SearchMySQL\delete(), Block\delete(), RefreshLinks\deleteLinksFromNonexistent(), NukePage\deleteRevisions(), Title\deleteTitleProtection(), FixSlaveDesync\desyncFixPage(), SiteStatsInit\doAllAndCommit(), RecompressTracked\doAllOrphans(), RecompressTracked\doAllPages(), PopulateFilearchiveSha1\doDBUpdates(), FixExtLinksProtocolRelative\doDBUpdates(), PopulateParentId\doDBUpdates(), PopulateImageSha1\doDBUpdates(), DeleteArchivedFilesImplementation\doDelete(), DeleteArchivedRevisionsImplementation\doDelete(), DeleteOldRevisions\doDelete(), WatchedItem\doDuplicateEntries(), SpecialExport\doExport(), SpecialRecentchangeslinked\doMainQuery(), SpecialRecentChanges\doMainQuery(), RecompressTracked\doOrphanList(), RecompressTracked\doPage(), PopulateCategory\doPopulateCategory(), UserCache\doQuery(), GenderCache\doQuery(), LinkBatch\doQuery(), ReassignEdits\doReassignEdits(), RefreshLinks\doRefreshLinks(), UpdateSpecialPages\doSpecialPageCacheUpdates(), MovePageForm\doSubmit(), ViewCountUpdate\doUpdate(), HTMLCacheUpdate\doUpdate(), SiteStatsUpdate\doUpdate(), DeferredUpdates\doUpdates(), UpdateSearchIndex\doUpdateSearchIndex(), LinkHolderArray\doVariants(), Title\estimateRevisionCount(), TidyUpBug37714\execute(), StorageTypeStats\execute(), CleanupPreferences\execute(), ApiSetNotificationTimestamp\execute(), SpecialWatchlist\execute(), CheckBadRedirects\execute(), GetSlaveServer\execute(), DumpRev\execute(), BenchmarkDeleteTruncate\execute(), CheckImages\execute(), ClearInterwikiCache\execute(), FixUserRegistration\execute(), SpecialStatistics\execute(), DeleteRevision\execute(), DeleteSelfExternals\execute(), BatchedQueryRunner\execute(), UpdateLogging\execute(), CleanupAncientTables\execute(), DeleteDefaultMessages\execute(), MigrateUserGroup\execute(), RemoveUnusedAccounts\execute(), CleanupSpam\execute(), DeleteOrphanedRevisions\execute(), DumpSisterSites\execute(), GetTextMaint\execute(), InitEditCount\execute(), NukePage\execute(), RebuildAll\execute(), UpdateArticleCount\execute(), UpdateRestrictions\execute(), UpdateSpecialPages\execute(), CheckUsernames\execute(), CleanupRemovedModules\execute(), ConvertUserOptions\execute(), DeleteImageCache\execute(), AlterSharedConstraints\execute(), SpecialPagesWithProp\execute(), ResetUserTokens\execute(), OrphanStats\execute(), AttachLatest\execute(), InitSiteStats\execute(), PatchSql\execute(), ShowSiteStats\execute(), RefreshFileHeaders\execute(), RenameDbPrefix\execute(), FixBug20757\execute(), EraseArchivedFile\execute(), FixDoubleRedirects\execute(), FixTimestamps\execute(), UpdateDoubleWidthSearch\execute(), DumpLinks\execute(), DeleteArchivedRevisions\execute(), FetchText\execute(), RebuildFileCache\execute(), DeleteBatch\execute(), RebuildTextIndex\execute(), SqliteMaintenance\execute(), NamespaceConflictChecker\execute(), ConvertLinks\execute(), NukeNS\execute(), MoveBatch\execute(), ImageBuilder\execute(), RefreshImageMetadata\execute(), DeleteEqualMessages\execute(), UpdateMediaWiki\execute(), UploadDumper\fetchLocal(), HistoryAction\fetchRevisions(), UploadDumper\fetchUsed(), TitleCleanup\fileExists(), TrackBlobs\findOrphanBlobs(), FixSlaveDesync\findPageLatestCorruption(), RecompressTracked\finishIncompleteMoves(), RefreshLinks\fixLinksFromArticle(), RefreshLinks\fixRedirect(), DoubleRedirectJob\fixRedirects(), EditPageTest\forceRevisionDate(), ApiEditPageTest\forceRevisionDate(), DoubleRedirectsPage\formatResult(), SpecialProtectedtitles\formatRow(), SpecialProtectedpages\formatRow(), LCStore_DB\get(), Interwiki\getAllPrefixesDB(), ContentHandler\getAutoDeleteReason(), Block\getBlocksForIPList(), Title\getBrokenLinksFrom(), Title\getCascadeProtectionSources(), RevDel_RevisionList\getCurrent(), Block\getDatabaseArray(), ResourceLoaderWikiModule\getDB(), UserRightsProxy\getDB(), BacklinkCache\getDB(), ApiBase\getDB(), User\getEditCount(), ProtectionForm\getExpiry(), ResourceLoaderModule\getFileDependencies(), DoubleRedirectJob\getFinalDestination(), Title\getFirstRevision(), MessageBlobStore\getFromDB(), DeleteImageCache\getImageCount(), SpecialExport\getLinks(), Title\getLinksFrom(), Title\getLinksTo(), ForeignDBViaLBRepo\getMasterDB(), LocalRepo\getMasterDB(), SpecialRandomInCategory\getMinAndMaxForCat(), SpecialStatistics\getMostViewedPages(), ResourceLoaderModule\getMsgBlobMtime(), Title\getNextRevisionID(), Title\getNotificationTimestamp(), SpecialExport\getPagesFromCategory(), SpecialExport\getPagesFromNamespace(), Title\getParentCategories(), Title\getPreviousRevisionID(), BrokenRedirectsPage\getQueryInfo(), NewFilesPager\getQueryInfo(), WithoutInterwikiPage\getQueryInfo(), UsersPager\getQueryInfo(), LinkSearchPage\getQueryInfo(), SpecialRandomInCategory\getQueryInfo(), ImageListPager\getQueryInfoReal(), Block\getRangeCond(), Title\getRedirectsHere(), WikiPage\getRedirectTarget(), FixBug20757\getRevTextMap(), Linker\getRollbackEditCount(), RollbackEdits\getRollbackTitles(), ForeignDBViaLBRepo\getSlaveDB(), LocalRepo\getSlaveDB(), ResourceLoaderFileModule\getStyles(), Title\getSubpages(), HistoryBlobStub\getText(), HistoryBlobCurStub\getText(), TrackBlobs\getTextClause(), Title\getTitleProtection(), Title\getTouched(), MessageBlobStore\getUpdatesForMessage(), SpecialEditWatchlist\getWatchlist(), SpecialEditWatchlist\getWatchlistInfo(), BackupReader\handleUpload(), User\idForName(), WikiImporter\importLogItem(), WikiImporter\importRevision(), CheckStorage\importRevision(), WikiImporter\importUpload(), User\incEditCount(), Block\infinity(), Block\initFromRow(), TrackBlobs\initTrackingTable(), ManualLogEntry\insert(), Block\insert(), MessageBlobStore\insertMessageBlob(), Title\invalidateCache(), Title\isDeleted(), Title\isDeletedQuick(), RemoveUnusedAccounts\isInactiveAccount(), Title\isNewPage(), Title\isSingleRevRedirect(), SiteStats\jobs(), ImageCleanup\killRow(), ChangeTags\listDefinedTags(), SiteStats\load(), WatchedItem\load(), Interwiki\load(), SiteStats\loadAndLazyInit(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), Profiler\logData(), LinkFilter\makeLikeArray(), SpecialMergeHistory\merge(), SearchMySQL\minSearchLength(), TitleCleanup\moveIllegalPage(), TitleCleanup\moveInconsistentPage(), RecompressTracked\moveTextRow(), Title\moveTo(), moveToExternal(), Title\moveToInternal(), LinkSearchPage\mungeQuery(), Title\nameOf(), Block\newFromID(), Title\newFromID(), UserArray\newFromIDs(), Title\newFromIDs(), Block\newLoad(), SiteStats\numberingroup(), SkinTemplate\outputPage(), InfoAction\pageCounts(), InfoAction\pageInfo(), SiteStats\pagesInNs(), SpecialBlock\parseExpiryInput(), ImageCleanup\pokeFile(), Block\purgeExpired(), Title\purgeExpiredRestrictions(), PurgeList\purgeNamespace(), PurgeRedundantText(), DoubleRedirectsPage\reallyGetQueryInfo(), RebuildRecentchanges\rebuildRecentChangesTablePass1(), RebuildRecentchanges\rebuildRecentChangesTablePass2(), RebuildRecentchanges\rebuildRecentChangesTablePass3(), RebuildRecentchanges\rebuildRecentChangesTablePass4(), SiteStatsInit\refresh(), RevDel_List\reloadFromMaster(), WatchlistCleanup\removeWatch(), WatchedItem\removeWatch(), LinkHolderArray\replaceInternal(), ImportReporter\reportPage(), WatchedItem\resetNotificationTimestamp(), resolveStub(), resolveStubs(), CheckStorage\restoreText(), TableCleanup\runTable(), User\saveSettings(), EraseArchivedFile\scrubAllVersions(), RandomPage\selectRandomPageFromDB(), SpecialRandomInCategory\selectRandomPageFromDB(), RevDel_RevisionItem\setBits(), RevDel_ArchiveItem\setBits(), RevDel_ArchivedRevisionItem\setBits(), RevDel_FileItem\setBits(), RevDel_ArchivedFileItem\setBits(), RevDel_LogItem\setBits(), RevisionTest_ContentHandlerUseDB\setUp(), WikiPageTest_ContentHandlerUseDB\setUp(), DatabaseTest\setUp(), LinksUpdateTest\setUp(), TestORMRowTest\setUp(), RevisionDeleteUser\setUsernameBitfields(), RevDel_List\setVisibility(), SpecialBlockList\showList(), SpecialPrefixindex\showPrefixChunk(), SpecialVersion\softwareInformation(), RevDel_LogList\suggestTarget(), RecompressTracked\syncDBs(), ChangeTags\tagUsageStatistics(), TestORMRowTest\tearDown(), WikiPageTest\testDoDeleteArticle(), WikiPageTest\testDoDeleteUpdates(), WikiPageTest\testDoEdit(), WikiPageTest\testDoEditContent(), WikiPageTest\testIsCountable(), DatabaseTest\testStoredFunctions(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), SiteStatsUpdate\tryDBUpdateInternal(), SpecialEditWatchlist\unwatchTitles(), SearchOracle\update(), SearchMySQL\update(), Block\update(), SiteStatsInit\update(), WikiPage\updateCategoryCounts(), MessageBlobStore\updateMessage(), MessageBlobStore\updateModule(), Block\updateTimestamp(), SearchOracle\updateTitle(), SearchMySQL\updateTitle(), userOptions\USAGER(), SpecialEditWatchlist\watchTitles(), and SpecialRecentChanges\webOutput().

Get the cache object used by the language converter.

Returns:
BagOStuff

Definition at line 3864 of file GlobalFunctions.php.

References ObjectCache\getInstance(), and global.

wfGetLangObj ( langcode = false)

Return a Language object from $langcode.

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

Definition at line 1279 of file GlobalFunctions.php.

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

Referenced by Skin\doEditSectionLink(), DateFormatter\getInstance(), CssContentHandler\getPageLanguage(), JavaScriptContentHandler\getPageLanguage(), ContentHandler\getPageLanguage(), Title\getPageLanguage(), JavaScriptContentHandler\getPageViewLanguage(), CssContentHandler\getPageViewLanguage(), ContentHandlerTest\testGetPageLanguage(), Linker\tocList(), and wfMsgExt().

Get the main cache object.

Returns:
BagOStuff

Definition at line 3834 of file GlobalFunctions.php.

References $wgMainCacheType, ObjectCache\getInstance(), and global.

Referenced by UploadFromUrlTestSuite\setUp().

Get the cache object used by the message cache.

Returns:
BagOStuff

Definition at line 3844 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 3629 of file GlobalFunctions.php.

References wfIsWindows().

Get the cache object used by the parser cache.

Returns:
BagOStuff

Definition at line 3854 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:
$nameString
Returns:
Mixed: the variable on success, false on failure

Definition at line 3392 of file GlobalFunctions.php.

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

Referenced by IcuCollation\getFirstLetterData().

Get the script URL.

Returns:
string script URL

Definition at line 3595 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 1718 of file GlobalFunctions.php.

References global.

Referenced by DjVuHandler\doTransform(), MWCryptRand\initialRandomState(), Profiler\logData(), BitmapHandler\logErrorForExternalProcess(), RecompressTracked\logToFile(), LoadBalancer\openForeignConnection(), SvgHandler\rasterize(), wfDebugLog(), wfLogDBError(), wfReportTime(), and wfThumbError().

wfHttpError ( code,
label,
desc 
)

Provide a simple HTTP error.

Parameters:
$codeInt|String
$labelString
$descString

Definition at line 2119 of file GlobalFunctions.php.

References $wgOut, global, and print.

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

Returns:
bool

Definition at line 3280 of file GlobalFunctions.php.

References as, and global.

Referenced by WebResponse\setcookie(), and wfSetupSession().

wfIncrStats ( key,
count = 1 
)

Increment a statistics counter.

Parameters:
$keyString
$countInt
Returns:
void

Definition at line 1231 of file GlobalFunctions.php.

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

Referenced by ParserCache\get(), and ParserCache\getKey().

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:
$settingString
Returns:
Bool

Definition at line 2624 of file GlobalFunctions.php.

Referenced by Installer\envCheckBrokenXML(), Installer\envCheckMagicSybase(), Installer\envCheckMbstring(), Installer\envCheckSafeMode(), Installer\envCheckZE1(), 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 2839 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
$contextTitleTitle|bool the page on which the image occurs, if known
string$blacklistwikitext of a file blacklist
Returns:
bool

Definition at line 3930 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().

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

Returns:
bool

Definition at line 947 of file GlobalFunctions.php.

References $cache.

Referenced by wfDebug(), and wfLogProfilingData().

Check if we are running under HipHop.

Returns:
Bool

Definition at line 2457 of file GlobalFunctions.php.

Referenced by UploadBase\isEnabled().

wfLogDBError ( text)

Log for database errors.

Parameters:
string$textdatabase error message.

Definition at line 1025 of file GlobalFunctions.php.

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

Referenced by LoadBalancer\reportConnectionError().

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

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

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

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

Definition at line 1091 of file GlobalFunctions.php.

References MWDebug\warning().

Referenced by wfMkdirParents().

wfMakeUrlIndexes ( url)

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

Parameters:
$urlString
Returns:
array

Definition at line 837 of file GlobalFunctions.php.

References array(), and wfParseUrl().

Referenced by 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 891 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:
Integer value memory was set to.

Definition at line 3738 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:
$oldString
$mineString
$yoursString
$resultString
Returns:
Bool

Definition at line 2895 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:
varargs
Returns:
Array

Definition at line 214 of file GlobalFunctions.php.

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

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

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:
$key String : Message key. Varargs: normal message parameters.
Returns:
Message
Since:
1.17

Definition at line 1338 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:
varargs,:message keys
Returns:
Message
Since:
1.18

Definition at line 1355 of file GlobalFunctions.php.

Referenced by SkinTemplate\buildContentNavigationUrls(), and SkinTemplate\tabAction().

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
$modeInteger: chmod value to use, default is $wgDirectoryMode
string$calleroptional caller param for debugging.
Exceptions:
MWException
Returns:
bool

Definition at line 2510 of file GlobalFunctions.php.

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

Referenced by FileCacheBase\checkCacheDirs(), TextPassDumperTest\checkpointHelper(), BitmapHandler\doTransform(), SvgHandler\doTransform(), DjVuHandler\doTransform(), ImageCleanup\pokeFile(), UploadFromUrlTestSuite\setupUploadDir(), ParserTest\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 1379 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 1610 of file GlobalFunctions.php.

References $key, $options, array(), as, Sanitizer\escapeHtmlAllowEntities(), MessageCache\singleton(), 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 1428 of file GlobalFunctions.php.

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

Same as above except doesn't transform the message.

Deprecated:
since 1.18
Parameters:
$keyString
Returns:
String

Definition at line 1451 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:
$keyString
$useDBBool
string$langCodeCode of the language to get the message for, or behaves as a content language switch if it is a boolean.
$transformBoolean: whether to parse magic words, etc.
Returns:
string

Definition at line 1500 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:
$keyString
string... parameters
Returns:
string

Definition at line 1556 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:
$keyString
Returns:
String

Definition at line 1395 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.
$args
$useDBBoolean
$forContentMixed: Language code, or false for user lang, true for content lang.
$transformBoolean: Whether or not to transform the message.
Returns:
String: the requested message.

Definition at line 1478 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:
$messageString
$argsArray
Returns:
string
Access:
private

Definition at line 1523 of file GlobalFunctions.php.

References $n, array(), and as.

Referenced by MWException\msg(), ApiBase\parseMsg(), 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:
$keyString
string... parameters
Returns:
string

Definition at line 1577 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 2274 of file GlobalFunctions.php.

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

Referenced by RdfMetaData\setup(), and GlobalTest\testNegotiateType().

wfObjectToArray ( objOrArray,
recursive = true 
)

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

Parameters:
$objOrArrayObject|Array
$recursiveBool
Returns:
Array

Definition at line 259 of file GlobalFunctions.php.

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

wfOut ( s)

Used to be used for outputting text in the installer/updater.

Deprecated:
since 1.18, warnings in 1.18, remove in 1.20

Definition at line 3667 of file GlobalFunctions.php.

References $s, $wgCommandLineMode, global, and wfDeprecated().

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:
Array: bits of the URL in an associative array, per PHP docs

Definition at line 749 of file GlobalFunctions.php.

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

Referenced by WikiReference\getDisplayName(), UploadFromUrl\isAllowedHost(), UserMailer\makeMsgId(), WfAssembleUrlTest\provideURLParts(), SquidPurgeClient\queuePurge(), WfParseUrlTest\testWfParseUrl(), wfExpandUrl(), wfMakeUrlIndexes(), and wfMatchesDomainList().

wfPercent ( nr,
acc = 2,
round = true 
)
Parameters:
$nrMixed: the number to format
$accInteger: the number of digits after the decimal point, default 2
$roundBoolean: whether or not to round the value, default true
Returns:
float

Definition at line 2577 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:
Boolean

Definition at line 3563 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 282 of file GlobalFunctions.php.

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

References $n.

Referenced by MockFileBackend\doGetLocalCopyMulti(), TempFSFile\factory(), MWExceptionHandler\getLogId(), UploadSourceAdapter\registerSource(), JobQueueTest\setUp(), Parser\setUser(), and JobQueueTest\testRootDeduplication().

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

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

Definition at line 1249 of file GlobalFunctions.php.

References global.

Referenced by ProtectionForm\__construct(), ReadOnlyError\__construct(), ApiQuerySiteinfo\appendGeneralInfo(), ApiBase\dieReadOnly(), and wfReadOnly().

Remove a directory and all its content.

Does not hide error.

Definition at line 2552 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 3115 of file GlobalFunctions.php.

References $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 612 of file GlobalFunctions.php.

References $output.

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

Returns a HTML comment with the elapsed time since request.

This method has no side effects.

Returns:
string

Definition at line 1755 of file GlobalFunctions.php.

References $wgRequestTime, global, and wfHostname().

Referenced by SkinTemplate\outputPage().

wfResetOutputBuffers ( resetGzipEncoding = true)

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

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

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

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

Parameters:
$resetGzipEncodingBool

Definition at line 2154 of file GlobalFunctions.php.

References global.

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

Reset the session_id.

Since:
1.22

Definition at line 3333 of file GlobalFunctions.php.

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

Restore error level to previous value.

Definition at line 2337 of file GlobalFunctions.php.

References wfSuppressWarnings().

Referenced by UIDGenerator\__construct(), SVGReader\__construct(), ImportStreamSource\__construct(), TempFSFile\__destruct(), DatabaseOracle\__destruct(), CheckSyntax\buildFileList(), Exif\charCodeString(), UploadBase\checkXMLEncodingMissmatch(), FileCacheBase\clearCache(), SquidPurgeClient\close(), ZhClient\connect(), MediaHandler\convertMetadataVersion(), IPTC\convIPTCHelper(), DiffHistoryBlob\diff(), SpecialExport\doExport(), MimeMagic\doGuessMimeType(), SquidPurgeClient\doReads(), SquidPurgeClient\doWrites(), CheckImages\execute(), JSParseHelper\execute(), RebuildFileCache\execute(), CologneBlueTemplate\execute(), ModernTemplate\execute(), MonoBookTemplate\execute(), CommandLineInstaller\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), TempFSFile\factory(), DatabasePostgres\fetchObject(), DatabasePostgres\fetchRow(), DatabasePostgres\freeResult(), ImageHandler\getImageSize(), DjVuImage\getInfo(), ApiQueryImageInfo\getInfo(), SquidPurgeClient\getIP(), JSONRCFeedFormatter\getLine(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), DjVuHandler\getMetaTree(), DatabaseLogEntry\getParameters(), IcuCollation\getPrimarySortKey(), ExifBitmapHandler\getRotationForExif(), FSFile\getSha1Base36(), SquidPurgeClient\getSocket(), IcuCollation\getSortKey(), SpecialVersion\getSvnInfo(), FSFile\getTimestamp(), MWCryptRand\initialRandomState(), DatabaseOracle\insertOneRow(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), DatabasePostgres\numRows(), SpecialUnlockdb\onSubmit(), SpecialLockdb\onSubmit(), DatabaseMssql\open(), DatabaseOracle\open(), XMPReader\parse(), DiffHistoryBlob\patch(), TempFSFile\purge(), MWCryptRand\realGenerate(), Sanitizer\removeHTMLtags(), SquidPurgeClientPool\run(), ContentHandler\runLegacyHooks(), JpegMetadataExtractor\segmentSplitter(), DatabaseOracle\selectDB(), UserMailer\send(), PrefixSearch\specialSearch(), RecompressTracked\startSlaveProcs(), StreamFile\stream(), MWDebugTest\tearDown(), JavaScriptMinifierTest\testJavaScriptMinifierOutput(), GlobalTest\testWfMkdirParents(), MediaWiki_I18N\translate(), SvgHandler\unpackMetadata(), DatabaseOracle\update(), wfDiff(), wfErrorLog(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfParseUrl(), wfSetupSession(), wfStreamThumb(), and wfUnpack().

wfRunHooks ( event,
array args = array() 
)

Call hook functions defined in $wgHooks.

Parameters:
string$eventevent name
array$argsparameters passed to hook functions
Returns:
Boolean True if no handler aborted the hook

Definition at line 3876 of file GlobalFunctions.php.

References Hooks\run().

wfScript ( script = 'index')

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

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

Parameters:
string$scriptscript filename, sans extension
Returns:
String

Definition at line 3579 of file GlobalFunctions.php.

References global.

Referenced by SpecialContributions\execute(), SpecialVersion\getEntryPointInfo(), ApiRsd\getRsdApiList(), ResourceLoaderStartUpModule\getScript(), ApiFormatBase\initPrinter(), and ApiTestCase\setUp().

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

As for wfSetVar except setting a bit.

Parameters:
$destInt
$bitInt
$stateBool
Returns:
bool

Definition at line 2084 of file GlobalFunctions.php.

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

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

Parameters:
$destMixed
$sourceMixed
$forceBool
Returns:
Mixed

Definition at line 2067 of file GlobalFunctions.php.

References $source.

Referenced by ParserOptions\disableContentConversion(), ParserOptions\disableTitleConversion(), ParserOptions\enableLimitReport(), LinkCache\forUpdate(), Block\fromMaster(), Block\isAutoblocking(), Block\isHardblock(), LoadBalancer\parentInfo(), ParserOutput\preventClickjacking(), Block\prevents(), ParserOptions\setAllowExternalImages(), ParserOptions\setAllowExternalImagesFrom(), ParserOptions\setAllowSpecialInclusion(), CacheTime\setCacheTime(), ParserOutput\setCategoryLinks(), ParserOptions\setCleanSignatures(), CacheTime\setContainsOldMagic(), ParserOptions\setDateFormat(), ParserOptions\setEditSection(), ParserOutput\setEditSectionTokens(), ParserOptions\setEnableImageWhitelist(), ParserOptions\setExternalLinkTarget(), ParserOutput\setIndexPolicy(), ParserOptions\setIsPrintable(), ParserOptions\setIsSectionPreview(), ParserOutput\setLanguageLinks(), ParserOptions\setMaxGeneratedPPNodeCount(), ParserOptions\setMaxIncludeSize(), ParserOptions\setMaxPPNodeCount(), ParserOptions\setMaxTemplateDepth(), WikiImporter\setNoticeCallback(), ParserOptions\setNumberHeadings(), ParserOptions\setPreSaveTransform(), ParserOptions\setRemoveComments(), ParserOutput\setSections(), ParserOptions\setStubThreshold(), ParserOptions\setTargetLanguage(), ParserOptions\setTemplateCallback(), ParserOutput\setText(), ParserOptions\setTidy(), ParserOutput\setTimestamp(), ParserOptions\setTimestamp(), ParserOutput\setTitleText(), ParserOutput\setTOCEnabled(), ParserOutput\setTOCHTML(), ParserOptions\setUserLang(), and LoadBalancer\waitTimeout().

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

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

Parameters:
string$cmdCommand line, properly escaped for shell.
&$retvalnull|Mixed optional, will receive the program's exit code. (non-zero is usually failure)
array$environoptional environment variables which should be added to the executed command environment.
array$limitsoptional array with limits(filesize, memory, time, walltime) this overwrites the global wgShellMax* limits.
array$optionsArray of options. Only one is "duplicateStderr" => true, which Which duplicates stderr to stdout, including errors from limit.sh
Returns:
string collected stdout as a string

Definition at line 2736 of file GlobalFunctions.php.

References $IP, $options, $output, $retval, $time, as, global, wfDebug(), wfDebugLog(), wfInitShellLocale(), wfIsWindows(), and wfShellExecDisabled().

Referenced by UIDGenerator\__construct(), MimeMagic\detectMimeType(), DjVuHandler\doTransform(), CheckSyntax\getGitModifiedFiles(), GitInfo\getHeadCommitDate(), BitmapHandler\getMagickVersion(), DjVuImage\retrieveMetaData(), 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 2702 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.
&$retvalnull|Mixed optional, will receive the program's exit code. (non-zero is usually failure)
array$environoptional environment variables which should be added to the executed command environment.
array$limitsoptional array with limits(filesize, memory, time, walltime) this overwrites the global wgShellMax* limits.
Returns:
string collected stdout and stderr as a string

Definition at line 2831 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 2856 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:
Array

Definition at line 2871 of file GlobalFunctions.php.

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

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

wfShorthandToInteger ( string = '')

Converts shorthand byte notation to integer form.

Parameters:
$stringString
Returns:
Integer

Definition at line 3766 of file GlobalFunctions.php.

References $last.

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

wfShowingResults ( offset,
limit 
)
Todo:
document
Parameters:
$offsetInt
$limitInt
Returns:
String

Definition at line 1916 of file GlobalFunctions.php.

References $limit, and wfMessage().

wfSplitWikiID ( wiki)

Split a wiki ID into DB name and table prefix.

Parameters:
$wikiString
Returns:
array

Definition at line 3460 of file GlobalFunctions.php.

Referenced by ForeignDBViaLBRepo\__construct(), JobQueueFederated\getCacheKey(), LBFactory_Multi\getDBNameAndPrefix(), and LoadBalancer\openForeignConnection().

wfStreamFile ( fname,
headers = array() 
)

Stream a file to the browser.

Back-compat alias for StreamFile::stream()

Deprecated:
since 1.19

Definition at line 3552 of file GlobalFunctions.php.

References $fname, StreamFile\stream(), and wfDeprecated().

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

Parameters:
$nameMixed: filename to process
Returns:
String

Definition at line 3721 of file GlobalFunctions.php.

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

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

wfSuppressWarnings ( end = false)

Reference-counted warning suppression.

Parameters:
$endBool

Definition at line 2315 of file GlobalFunctions.php.

Referenced by UIDGenerator\__construct(), SVGReader\__construct(), ImportStreamSource\__construct(), TempFSFile\__destruct(), DatabaseOracle\__destruct(), SqliteMaintenance\backup(), CheckSyntax\buildFileList(), Exif\charCodeString(), UploadBase\checkXMLEncodingMissmatch(), FileCacheBase\clearCache(), SquidPurgeClient\close(), ZhClient\connect(), MediaHandler\convertMetadataVersion(), IPTC\convIPTCHelper(), DiffHistoryBlob\diff(), SpecialExport\doExport(), MimeMagic\doGuessMimeType(), SquidPurgeClient\doReads(), SquidPurgeClient\doWrites(), CheckImages\execute(), JSParseHelper\execute(), RebuildFileCache\execute(), CologneBlueTemplate\execute(), ModernTemplate\execute(), MonoBookTemplate\execute(), CommandLineInstaller\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), TempFSFile\factory(), DatabasePostgres\fetchObject(), DatabasePostgres\fetchRow(), DatabasePostgres\freeResult(), ImageHandler\getImageSize(), DjVuImage\getInfo(), ApiQueryImageInfo\getInfo(), SquidPurgeClient\getIP(), JSONRCFeedFormatter\getLine(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), DjVuHandler\getMetaTree(), DatabaseLogEntry\getParameters(), IcuCollation\getPrimarySortKey(), ExifBitmapHandler\getRotationForExif(), FSFile\getSha1Base36(), SquidPurgeClient\getSocket(), IcuCollation\getSortKey(), SpecialVersion\getSvnInfo(), FSFile\getTimestamp(), MWCryptRand\initialRandomState(), DatabaseOracle\insertOneRow(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), DatabasePostgres\numRows(), SpecialUnlockdb\onSubmit(), SpecialLockdb\onSubmit(), DatabaseMssql\open(), DatabaseOracle\open(), XMPReader\parse(), DiffHistoryBlob\patch(), TempFSFile\purge(), MWCryptRand\realGenerate(), Sanitizer\removeHTMLtags(), SquidPurgeClientPool\run(), ContentHandler\runLegacyHooks(), JpegMetadataExtractor\segmentSplitter(), DatabaseOracle\selectDB(), UserMailer\send(), MWDebugTest\setUp(), PrefixSearch\specialSearch(), RecompressTracked\startSlaveProcs(), StreamFile\stream(), JavaScriptMinifierTest\testJavaScriptMinifierOutput(), GlobalTest\testWfMkdirParents(), MediaWiki_I18N\translate(), SvgHandler\unpackMetadata(), DatabaseOracle\update(), wfDiff(), wfErrorLog(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfParseUrl(), wfRestoreWarnings(), wfSetupSession(), wfStreamThumb(), and wfUnpack().

wfTime ( )

Get the current unix timestamp with microseconds.

Useful for profiling

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

Definition at line 2052 of file GlobalFunctions.php.

References wfDeprecated().

wfTimestamp ( outputtype = TS_UNIX,
ts = 0 
)

Get a timestamp string in one of various formats.

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

Definition at line 2403 of file GlobalFunctions.php.

References $timestamp, and wfDebug().

Referenced by Block\__construct(), BlockTest\addDBData(), ApiQueryLogEvents\addLogParams(), ApiQuerySiteinfo\appendGeneralInfo(), SpecialRecentChanges\buildMainQueryConds(), FileCacheBase\cacheTimestamp(), SiteStatsUpdate\cacheUpdate(), ApiQueryContributions\continueStr(), LanguageWa\date(), MockFileBackend\doGetFileStat(), MysqlUpdater\doSchemaRestructuring(), ApiProtect\execute(), ApiUndelete\execute(), ApiSetNotificationTimestamp\execute(), ApiEditPage\execute(), ApiQueryDeletedrevs\execute(), SpecialExport\execute(), ApiQueryFilearchive\execute(), ApiBlock\execute(), RemoveUnusedAccounts\execute(), ApiQueryBlocks\execute(), ApiQueryLogEvents\execute(), UploadStashCleanup\execute(), ApiQueryContributions\execute(), ApiQueryImageInfo\execute(), FixTimestamps\execute(), PurgeParserCache\execute(), ApiQueryAllUsers\execute(), UpdateSearchIndex\execute(), ApiFeedWatchlist\execute(), CacheTime\expired(), ApiQueryInfo\extractPageInfo(), ApiQueryWatchlist\extractRowInfo(), ApiQueryContributions\extractRowInfo(), ApiQueryLogEvents\extractRowInfo(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryRevisions\extractRowInfo(), HistoryAction\feedEmpty(), FeedUtils\formatDiff(), SpecialMergeHistory\formatRevisionRow(), Block\getAutoblockExpiry(), NewUsersLogFormatter\getComment(), ApiQueryUserInfo\getCurrentUserInfo(), ProtectionForm\getExpiry(), FormatMetadata\getFormattedData(), MessageBlobStore\getFromDB(), ResourceLoaderModule\getHashMtime(), ApiQueryImageInfo\getInfo(), JSONRCFeedFormatter\getLine(), PNGMetadataExtractor\getMetadata(), SpecialRandomInCategory\getMinAndMaxForCat(), ResourceLoaderUserCSSPrefsModule\getModifiedTime(), ResourceLoaderUserOptionsModule\getModifiedTime(), ResourceLoaderStartUpModule\getModifiedTime(), ResourceLoaderStartUpModule\getModuleRegistrations(), ResourceLoaderModule\getMsgBlobMtime(), Block\getPermissionsError(), RawAction\getRawText(), ResourceLoaderStartUpModule\getScript(), MockFSFile\getTimestamp(), FSFile\getTimestamp(), ForeignAPIFile\getTimestamp(), DatabaseLogEntry\getTimestamp(), RCDatabaseLogEntry\getTimestamp(), ManualLogEntry\getTimestamp(), FileJournal\getTimestampedUUID(), ResourceLoaderWikiModule\getTitleMtimes(), ImageHistoryList\imageHistoryLine(), Block\initFromRow(), User\isEmailConfirmationPending(), ChangesFeed\loadFromCache(), SpecialBlock\maybeAlterFormDefaults(), SpecialMergeHistory\merge(), OutputPage\output(), SpecialBlock\parseExpiryInput(), StreamFile\prepareForStream(), TableCleanup\progress(), ImageBuilder\progress(), ApiQueryProtectedTitles\run(), ApiQueryWatchlistRaw\run(), ApiQueryDuplicateFiles\run(), ApiQueryCategories\run(), ApiQueryCategoryMembers\run(), ApiQueryWatchlist\run(), ApiQuerySearch\run(), ApiQueryQueryPage\run(), ApiQueryAllImages\run(), ApiQueryRecentChanges\run(), RunJobs\runJobsLog(), ChangesFeed\saveToCache(), ApiMain\sendCacheHeaders(), EditPageTest\testAutoMerge(), WfTimestampTest\testHttpDate(), WfTimestampTest\testNormalTimestamps(), WfTimestampTest\testOldTimestamps(), WfTimestampTest\testTimestampParameter(), IPTC\timeHelper(), DatabaseMssql\timestamp(), DatabaseOracle\timestamp(), DatabasePostgres\timestamp(), Block\updateTimestamp(), XMPValidate\validateDate(), ApiBase\validateTimestamp(), 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:
$outputtypeInteger
$tsString
Returns:
String

Definition at line 2421 of file GlobalFunctions.php.

References wfTimestamp().

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

wfUILang ( )

Old function when $wgBetterDirectionality existed All usage removed, wfUILang can be removed in near future.

Deprecated:
since 1.18
Returns:
Language

Definition at line 1319 of file GlobalFunctions.php.

References $wgLang, global, and wfDeprecated().

wfUnpack ( format,
data,
length = false 
)

Wrapper around php's unpack.

Parameters:
string$formatThe format string (See php's docs)
$data,:A binary string of binary data
$lengthinteger or false: The minimum length of $data. 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 3894 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:
$sString:
Returns:
string

Definition at line 331 of file GlobalFunctions.php.

References $s, and array().

Referenced by Title\getLocalURL(), MediaWikiSite\getPageUrl(), Title\getPrefixedURL(), Title\getSubpageUrlForm(), Interwiki\getURL(), Title\makeTitle(), CoreParserFunctions\namespacee(), CoreParserFunctions\nse(), Title\secureAndSplit(), 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 690 of file GlobalFunctions.php.

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

Referenced by Skin\addToSidebarPlain(), ResourceLoaderStartUpModule\getConfig(), 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 735 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

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

Definition at line 3074 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:
$req_verMixed: the version to check, can be a string, an integer, or a float
Exceptions:
MWException

Definition at line 3052 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:
$varmixed A PHP variable to dump.

Definition at line 2102 of file GlobalFunctions.php.

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

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

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

Parameters:
$offsetString
$limitInteger
$linkString
string$queryoptional URL query parameter string
bool$atendoptional param for specified if this is the last page
Returns:
String
Deprecated:
in 1.19; use Language::viewPrevNext() instead

Definition at line 1931 of file GlobalFunctions.php.

References $limit, $link, $query, $title, $wgLang, global, Title\newFromText(), wfCgiToArray(), and wfDeprecated().

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

Modern version of wfWaitForSlaves().

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

Parameters:
$maxLagInteger (deprecated)
$wikimixed Wiki identifier accepted by wfGetLB
$clusterstring cluster name accepted by LBFactory

Definition at line 3646 of file GlobalFunctions.php.

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

Referenced by CompressOld\compressWithConcat(), RefreshLinks\deleteLinksFromNonexistent(), PopulateFilearchiveSha1\doDBUpdates(), PopulateRevisionLength\doDBUpdates(), PopulateParentId\doDBUpdates(), FixExtLinksProtocolRelative\doDBUpdates(), PopulateLogSearch\doDBUpdates(), PopulateLogUsertext\doDBUpdates(), PopulateImageSha1\doDBUpdates(), 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(), UpdateRestrictions\execute(), UpdateSpecialPages\execute(), CleanupRemovedModules\execute(), ConvertUserOptions\execute(), ResetUserTokens\execute(), DeleteBatch\execute(), RunJobs\execute(), MoveBatch\execute(), RefreshImageMetadata\execute(), UpdateCollation\execute(), DeleteEqualMessages\execute(), UpdateMediaWiki\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
$callerOffsetInteger: number of items to go back in the backtrace to find the correct caller (1 = function calling wfWarn, ...)
$levelInteger: PHP error level; defaults to E_USER_NOTICE; only used when $wgDevelopmentWarnings is true

Definition at line 1078 of file GlobalFunctions.php.

References MWDebug\warning().

Referenced by TextContent\__construct(), Exif\__construct(), ForeignAPIRepo\fileExistsBatch(), ParserCache\getKey(), SpecialPageFactory\getLocalNameFor(), Autopromote\recCheckCondition(), ContentHandler\runLegacyHooks(), and wfMsgExt().