MediaWiki  REL1_20
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_DB2
 DB2 format time. 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 the first array are replaced by the values in the second array with the corresponding keys.
 wfArrayMap ($function, $input)
 Wrapper around array_map() which also taints variables.
 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)
 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.
 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 sufficent 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.
 wfDl ($extension, $fileName=null)
 Wrapper function for PHP's dl().
 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 a XHTML string, this function checks for the nonexistance 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.
 wfLoadExtensionMessages ()
 Load an extension messages file.
 wfLocalFile ($title)
 Get an object referring to a locally registered file.
 wfLogDBError ($text)
 Log for database errors.
 wfLogProfilingData ()
 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 new 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 pesudo-random hex characters.
 wfReadOnly ()
 Check if the wiki read-only lock file is present.
 wfReadOnlyReason ()
 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.
 wfRestoreWarnings ()
 Restore error level to previous value.
 wfRunHooks ($event, $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())
 Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported.
 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)
 wfSpecialList ($page, $details, $oppositedm=true)
 Make a list item, used by various special pages.
 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 timetstamp 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)
 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 2359 of file GlobalFunctions.php.

enum TS_DB2

DB2 format time.

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

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

This is used by Special:Export

Definition at line 2371 of file GlobalFunctions.php.

ISO 8601 basic format with no timezone: 19860209T200000Z.

This is used by ResourceLoader

Definition at line 2400 of file GlobalFunctions.php.

enum TS_MW

MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)

Definition at line 2354 of file GlobalFunctions.php.

enum TS_ORACLE

Oracle format time.

Definition at line 2385 of file GlobalFunctions.php.

Postgres format time.

Definition at line 2390 of file GlobalFunctions.php.

enum TS_RFC2822

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

Definition at line 2364 of file GlobalFunctions.php.

enum TS_UNIX

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

Definition at line 2349 of file GlobalFunctions.php.


Function Documentation

in_string ( needle,
str,
insensitive = false 
)

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

Parameters:
$needleString
$strString
$insensitiveBoolean
Returns:
Boolean

Definition at line 2593 of file GlobalFunctions.php.

Referenced by GlobalTest\testInStringTest().

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

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

swap ( &$  x,
&$  y 
)

Swap two variables.

Parameters:
$xMixed
$yMixed

Definition at line 2475 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
$defString default
Returns:
Array

Definition at line 2213 of file GlobalFunctions.php.

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

References $url, and wfArrayToCgi().

Referenced by ImportSiteScripts\execute(), ForeignAPIRepo\fetchImageQuery(), ImportSiteScripts\fetchScriptList(), Title\getLocalURL(), Linker\getUploadUrl(), Linker\link(), ResourceLoader\makeLoaderURL(), and Linker\makeThumbLink2().

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

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

Parameters:
$keyString|Int
$valueMixed
$defaultMixed
$changedArray to alter

Definition at line 173 of file GlobalFunctions.php.

References $changed, 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 125 of file GlobalFunctions.php.

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

wfArrayDiff2_cmp ( a,
b 
)
Parameters:
$a
$b
Returns:
int

Definition at line 134 of file GlobalFunctions.php.

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

Insert array into another array after the specified *KEY*.

Parameters:
$arrayArray: The array.
$insertArray: The array to insert.
$afterMixed: The key to insert after
Returns:
Array

Definition at line 240 of file GlobalFunctions.php.

References $keys, and $output.

wfArrayLookup ( a,
b 
)

Array lookup Returns an array where the values in the first array are replaced by the values in the second array with the corresponding keys.

Parameters:
$aArray
$bArray
Returns:
array

Definition at line 161 of file GlobalFunctions.php.

wfArrayMap ( function,
input 
)

Wrapper around array_map() which also taints variables.

Parameters:
$functionCallback
$inputArray
Returns:
Array

Definition at line 286 of file GlobalFunctions.php.

References $input, and $value.

wfArrayMerge ( array1)

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

Parameters:
$array1Array
[$array2,[...]]Arrays
Returns:
Array

Definition at line 190 of file GlobalFunctions.php.

References $out.

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:
$array1Array ( String|Array )
$array2Array ( String|Array )
$prefixString
Returns:
String

Definition at line 387 of file GlobalFunctions.php.

References $value.

Referenced by Linker\link(), 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:
$urlPartsArray URL parts, as output from wfParseUrl
Returns:
string URL assembled from its component parts

Definition at line 582 of file GlobalFunctions.php.

References $result.

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

Get a debug backtrace as a string.

Returns:
string

Definition at line 1830 of file GlobalFunctions.php.

References $f, $file, $wgCommandLineMode, and wfDebugBacktrace().

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

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

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:
$inputString: of digits
$sourceBaseInteger: 2-36
$destBaseInteger: 2-36
$padInteger: 1 or greater
$lowercaseBoolean
Returns:
String or false on invalid input

Definition at line 3150 of file GlobalFunctions.php.

References $input, and $n.

Referenced by NewParserTest\addDBData(), Revision\base36Sha1(), SwiftFileBackend\doCreateInternal(), SwiftFileBackend\doStoreInternal(), FileBackendTest\doTestDoOperations(), FileBackendTest\doTestDoOperationsFailing(), FileBackendTest\doTestDoOperationsPipeline(), ApiQueryDeletedrevs\execute(), ApiQueryFilearchive\execute(), ApiQueryBlocks\execute(), ApiQueryRevisions\extractRowInfo(), ApiQueryImageInfo\getInfo(), ForeignAPIFile\getSha1(), FSFile\getSha1Base36(), FileJournal\getTimestampedUUID(), and ApiQueryAllImages\run().

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
$suffixString: to remove if present
Returns:
String

Definition at line 3067 of file GlobalFunctions.php.

References $matches, and $path.

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

wfBCP47 ( code)

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

Parameters:
$codeString: The language code.
Returns:
String: The language code which complying with BCP 47 standards.

Definition at line 3738 of file GlobalFunctions.php.

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

wfBoolToStr ( value)

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

Parameters:
$valueBoolean
Returns:
String

Definition at line 3558 of file GlobalFunctions.php.

References $value.

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

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 compa- tibility with legacy functions that accept raw query strings instead of nice arrays. Of course, keys and values are urldecode()d.

Parameters:
$queryString: query string
Returns:
array Array version of input

Definition at line 432 of file GlobalFunctions.php.

References $keys, and $value.

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

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

Returns:
bool true = there is sufficient entropy

Definition at line 3257 of file GlobalFunctions.php.

References wfIsWindows().

Referenced by wfFixSessionID().

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

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

Parameters:
$deflimitInt default limit if none supplied
$optionnameString Name of a user preference to check against
Returns:
array

Definition at line 2026 of file GlobalFunctions.php.

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

References $result, 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 3625 of file GlobalFunctions.php.

References $n, and echo.

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
$pArray: parameters
Returns:
object
Deprecated:
since 1.18, warnings in 1.18, removal in 1.20

Definition at line 3231 of file GlobalFunctions.php.

References 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
$logonlyBool: set true to avoid appearing in HTML when $wgDebugComments is set

Definition at line 937 of file GlobalFunctions.php.

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

Referenced by SearchUpdate\__construct(), UploadFromChunks\__construct(), DBABagOStuff\__construct(), MemcachedPeclBagOStuff\__construct(), UploadFromStash\__construct(), WikiXmlError\__construct(), MimeMagic\__construct(), ImportStreamSource\__construct(), StubObject\_unstub(), MediaHandler\addMeta(), LinkBatch\addObj(), Skin\afterContentHook(), AutoLoader\autoload(), SkinTemplate\buildContentActionUrls(), UploadBase\checkSvgScriptCallback(), UploadBase\checkXMLEncodingMissmatch(), LocalRepo\cleanupDeletedBatch(), UploadBase\cleanupTempFile(), SpecialEditWatchlist\cleanupWatchlist(), MessageBlobStore\clear(), Revision\compressRevisionText(), UploadFromChunks\concatenateChunks(), DjVuImage\convertDumpToXML(), EhcacheBagOStuff\createCache(), UploadBase\createFromRequest(), DatabaseIbm_db2\dataSeek(), WikiImporter\debug(), BaseDump\debug(), RecompressTracked\debug(), BagOStuff\debug(), SVGReader\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(), MimeMagic\doGuessMimeType(), DatabaseMssql\doQuery(), DatabaseOracle\doQuery(), EhcacheBagOStuff\doRequest(), Block\doRetroactiveAutoblock(), UserrightsPage\doSaveUserGroups(), BitmapHandler\doTransform(), DjVuHandler\doTransform(), HTMLCacheUpdate\doUpdate(), LoadBalancer\doWait(), MWCryptRand\driftHash(), DatabasePostgres\dumpError(), ZipDirectoryReader\error(), SpecialUserlogout\execute(), ChangesFeed\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), PoolWorkArticleView\fallback(), ExternalStoreDB\fetchBlob(), WikiDiff3\find_middle_snake(), FormatMetadata\flattenArray(), EhcacheBagOStuff\get(), DBABagOStuff\get(), ParserCache\get(), Interwiki\getAllPrefixesCached(), LoadBalancer\getConnection(), DoubleRedirectJob\getFinalDestination(), GenderCache\getGenderOf(), MediaHandler\getHandler(), DjVuImage\getInfo(), Interwiki\getInterwikiCacheEntry(), ParserCache\getKey(), DatabaseMysql\getLag(), BacklinkCache\getLinks(), 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(), SpecialEmailUser\getPermissionsError(), UserCache\getProp(), FSFile\getProps(), DisambiguationsPage\getQueryFromLinkBatch(), DBABagOStuff\getReader(), LoadBalancer\getReaderIndex(), Title\getRestrictionTypes(), ExternalStoreDB\getSlave(), ResourceLoaderFileModule\getStyles(), SpecialEmailUser\getTarget(), ForeignAPIRepo\getThumbUrl(), ForeignAPIRepo\getThumbUrlFromCache(), NewParserTest\getUploadDir(), DBABagOStuff\getWriter(), XCFHandler\getXCFMetaData(), MimeMagic\guessMimeType(), MWCryptRand\hashAlgo(), SquidUpdate\HTCPPurge(), ForeignAPIRepo\httpGet(), MimeMagic\improveTypeFromExtension(), DBABagOStuff\incr(), Block\insert(), MessageBlobStore\insertMessageBlob(), ExternalStore\insertToDefault(), DatabaseIbm_db2\installPrint(), Profiler\instance(), 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(), Revision\loadText(), DatabaseMysql\lock(), PostgresTransactionState\log_changed(), Linker\makeBrokenLink(), Linker\makeExternalImage(), Linker\makeExternalLink(), Linker\makeImageLink(), Skin\newFromKey(), SVGReader\notice(), RawAction\onView(), CdbReader\open(), DatabaseMysql\open(), DatabaseMssql\open(), CdbWriter\open(), DatabasePostgres\open(), DatabaseIbm_db2\open(), LoadBalancer\openConnection(), LoadBalancer\openForeignConnection(), UploadDumper\outputItem(), SkinTemplate\outputPage(), SearchMySQL\parseQuery(), BacklinkCache\partition(), DiffHistoryBlob\patch(), SavepointPostgres\query(), SvgHandler\rasterize(), TextPassDumper\readDump(), TestFileIterator\readNextTest(), MWCryptRand\realGenerate(), LoadBalancer\reallyOpenConnection(), DatabaseOracle\reportQueryError(), Http\request(), DjVuImage\retrieveMetaData(), LoadBalancer\reuseConnection(), DoubleRedirectJob\run(), DataUpdate\runUpdates(), RequestContext\sanitizeLangCode(), ParserCache\save(), FileCacheBase\saveText(), HTMLFileCache\saveToFileCache(), MessageCache\saveToScript(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), MWDebug\sendWarning(), UserMailer\sendWithPear(), EhcacheBagOStuff\set(), DBABagOStuff\set(), UploadFromUrlTestSuite\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(), Revision\userCanBitfield(), 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(), 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 talkin'.

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

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

Definition at line 1796 of file GlobalFunctions.php.

References $limit, 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.

Parameters:
$msgString: message shown when dying.

Definition at line 1723 of file GlobalFunctions.php.

Referenced by ApiBase\dieDebug().

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
$publicBool: whether to log the event in the public log if no private log file is specified, (default true)

Definition at line 1028 of file GlobalFunctions.php.

References wfDebug(), wfErrorLog(), wfHostname(), wfRunHooks(), wfTimestamp(), and wfWikiID().

Referenced by MWMemcached\_fwrite(), MemcachedPeclBagOStuff\checkResult(), UploadFromChunks\concatenateChunks(), IPTC\convIPTCHelper(), Exif\debug(), Exif\debugFile(), MemcachedBagOStuff\debugLog(), XMPReader\doAttribs(), DjVuHandler\doTransform(), DeferredUpdates\doUpdates(), XMPReader\endElement(), XMPReader\endElementModeLi(), XMPReader\endElementNested(), CheckUsernames\execute(), ExternalStoreDB\fetchBlob(), IPTC\getCharset(), RedisBagOStuff\getConnectionToServer(), LoadBalancer\getRandomNonLagged(), LoadBalancer\getReaderIndex(), RedisBagOStuff\handleException(), ExternalStore\insertToDefault(), SquidPurgeClient\log(), PoolCounterWork\logError(), RedisBagOStuff\logError(), BitmapHandler\logErrorForExternalProcess(), IPTC\parse(), XMPReader\parse(), XMPReader\parseExtended(), SvgHandler\rasterize(), MediaHandler\removeBadFile(), LocalFileMoveBatch\removeNonexistentFiles(), MWException\report(), SquidPurgeClientPool\run(), RunJobs\runJobsLog(), XMPReader\saveValue(), WebResponse\setcookie(), XMPReader\startElement(), XMPReader\startElementModeInitial(), XMPReader\startElementModeSeq(), XMPReader\startElementModeSimple(), IPTC\timeHelper(), 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:
$exactBool: print exact values instead of kilobytes (default: false)

Definition at line 1009 of file GlobalFunctions.php.

References wfDebug().

Referenced by GlobalTest\testDebugFunctionTest().

Get microsecond timestamps for debug logs.

Returns:
string

Definition at line 992 of file GlobalFunctions.php.

References $wgRequestTime.

Referenced by wfDebug().

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

Throws a warning that $function is deprecated.

Parameters:
$functionString
$versionString|bool: Version of MediaWiki that the function was deprecated in (Added in 1.19).
$componentString|bool: Added in 1.19.
$callerOffsetinteger: How far up the callstack is the original caller. 2 = function that called the function that called wfDeprecated (Added in 1.20)
Returns:
null

Definition at line 1087 of file GlobalFunctions.php.

References MWDebug\deprecated().

Referenced by WikiError\__construct(), WikiErrorMsg\__construct(), WikiXmlError\__construct(), StubContLang\__construct(), RawPage\__construct(), DeprecatedGlobal\_newObject(), Block\clear(), LoadBalancer\closeConnecton(), ApiBase\createContext(), Block\decodeExpiry(), Block\encodeExpiry(), Title\escapeCanonicalURL(), Title\escapeFullURL(), Title\escapeLocalURL(), WikiPage\estimateRevisionCount(), Article\fetchContent(), Title\fixUrlQueryArgs(), FormatExif\FormatExif(), Block\forUpdate(), ApiQueryUsers\getAutoGroups(), ProfilerSimple\getCpuTime(), Title\getEscapedText(), Linker\getExternalLinkAttributes(), Exif\getFormattedData(), DatabaseMysql\getLagFromProcesslist(), LegacyTemplate\getQuickbarCompensator(), ApiBase\getValidNamespaces(), Block\infinity(), WikiPage\isBigDeletion(), WikiError\isError(), MWNamespace\isMain(), ApiParse\languagesHtml(), Linker\link(), Block\load(), Preferences\loadOldSearchNs(), Linker\makeBrokenLink(), Linker\makeBrokenLinkObj(), Linker\makeColouredLinkObj(), Exif\makeFormattedData(), Skin\makeGlobalVariablesScript(), Linker\makeSizeLinkObj(), Xml\namespaceSelector(), Block\newFromDB(), Block\normaliseRange(), Block\parseExpiryInput(), Revision\revText(), ParserOptions\setInterfaceMessage(), DerivativeContext\setLang(), RequestContext\setLang(), Preferences\trySetUserEmail(), Title\updateTitleProtection(), Title\userCanEditCssSubpage(), Title\userCanEditJsSubpage(), Title\userCanRead(), wfCreateObject(), wfDoUpdates(), wfGenerateToken(), wfGetAgent(), wfGetForwardedFor(), wfGetIP(), wfLoadExtensionMessages(), wfOut(), wfSpecialList(), wfStreamFile(), wfUILang(), and wfViewPrevNext().

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

Returns unified plain-text diff of two texts.

Useful for machine processing of diffs.

Parameters:
$beforeString: the text before the changes.
$afterString: the text after the changes.
$paramsString: command-line options for the diff command.
Returns:
String: unified diff of $before and $after

Definition at line 2948 of file GlobalFunctions.php.

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

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

wfDl ( extension,
fileName = null 
)

Wrapper function for PHP's dl().

This doesn't work in most situations from PHP 5.3 onward, and is usually disabled in shared environments anyway.

Parameters:
$extensionString A PHP extension. The file suffix (.so or .dll) should be omitted
$fileNameString Name of the library, if not $extension.suffix
Returns:
Bool - Whether or not the extension is loaded

Definition at line 2641 of file GlobalFunctions.php.

References wfIniGetBool(), wfIsWindows(), wfRestoreWarnings(), and wfSuppressWarnings().

Referenced by MimeMagic\__construct(), Sqlite\isPresent(), DatabaseMysql\open(), DatabaseIbm_db2\open(), FormatMetadataTest\setUp(), ExifTest\setUp(), JpegTest\setUp(), XMPTest\setUp(), ExifBitmapTest\setUp(), ExifRotationTest\setUp(), TiffTest\testInvalidFile(), BitmapMetadataHandlerTest\testMultilingualCascade(), BitmapMetadataHandlerTest\testPNGXMP(), and TiffTest\testTiffMetadataExtraction().

wfDoUpdates ( commit = '')

Do any deferred updates and clear the list.

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

Definition at line 3131 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 a XHTML string, this function checks for the nonexistance 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 1713 of file GlobalFunctions.php.

References MessageCache\singleton().

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
$fileString filename

Definition at line 1114 of file GlobalFunctions.php.

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

Referenced by RecompressTracked\logToFile(), 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 2676 of file GlobalFunctions.php.

References wfInitShellLocale(), and wfIsWindows().

Referenced by CheckSyntax\checkFileWithCli(), MimeMagic\detectMimeType(), UploadBase\detectVirus(), PopulateImageSha1\doDBUpdates(), DjVuHandler\doTransform(), CheckSyntax\getGitModifiedFiles(), BitmapHandler\getMagickVersion(), SvgHandler\rasterize(), CheckStorage\restoreText(), DjVuImage\retrieveMetaData(), RecompressTracked\startSlaveProcs(), SevenZipStream\stream_open(), BitmapHandler\transformCustom(), BitmapHandler\transformImageMagick(), 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 835 of file GlobalFunctions.php.

References $url, and wfExpandUrl().

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

wfExpandIRI_callback ( matches)

Private callback for wfExpandIRI.

Parameters:
array$matches
Returns:
string

Definition at line 844 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:
$urlString: either 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 516 of file GlobalFunctions.php.

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

Referenced by ResourceLoaderFileModule\__construct(), ApiQuerySiteinfo\appendGeneralInfo(), ApiQuerySiteinfo\appendInterwikiMap(), ApiQuerySiteinfo\appendRightsInfo(), ApiQueryLangLinks\execute(), ApiQueryIWLinks\execute(), SquidUpdate\expand(), ApiQueryInfo\extractPageInfo(), CoreParserFunctions\filepath(), ApiParse\formatIWLinks(), ApiParse\formatLangLinks(), File\getCanonicalUrl(), Title\getCanonicalURL(), SpecialVersion\getEntryPointInfo(), RevertFileAction\getFormFields(), Title\getFullURL(), ApiQueryImageInfo\getInfo(), Title\getInternalURL(), ApiRsd\getRsdApiList(), File\getViewURL(), ForeignAPIRepo\httpGet(), ResourceLoader\makeLoaderURL(), RevertFileAction\onSuccess(), SpecialUploadStash\outputRemoteScaledThumb(), CSSMin\remap(), wfExpandUrl\testWfExpandUrl(), wfExpandIRI(), wfExtractThumbParams(), wfProxyCheck(), and wfStreamThumb().

wfFindFile ( title,
options = array() 
)

Find a file.

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

Parameters:
$titleString or Title object
$optionsarray Associative 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 3471 of file GlobalFunctions.php.

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

Referenced by UploadFromUrlTest\deleteFile(), ApiTestCaseUpload\deleteFileByTitle(), MovePageForm\doSubmit(), SpecialFilepath\execute(), ApiMove\execute(), DeleteBatch\execute(), FileDuplicateSearchPage\execute(), CoreParserFunctions\filepath(), Title\isAlwaysKnown(), Linker\makeBrokenImageLinkObj(), Linker\makeMediaLinkObj(), Linker\makeThumbLink2(), UploadDumper\outputItem(), LegacyTemplate\pageTitleLinks(), EditPage\showIntro(), LegacyTemplate\talkLink(), and Title\validateFileMoveOperation().

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

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

Referenced by UserRightsProxy\invalidateCache().

wfFormatStackFrame ( frame)

Return a string representation of frame.

Parameters:
$frameArray
Returns:
string

Definition at line 1917 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 pesudo-random strings
Warning:
This method is NOT secure. Additionally it has many callers that use it for pesudo-random purposes.

Definition at line 3648 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:
$limitint The maximum depth of the stack frame to return, or false for the entire stack.
Returns:
String

Definition at line 1902 of file GlobalFunctions.php.

References $limit, and wfDebugBacktrace().

Referenced by MWCryptRand\realGenerate().

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

References wfDebugBacktrace(), and wfFormatStackFrame().

Referenced by StubObject\_unstub(), wfGetCaller\callerOne(), wfGetCaller\intermediateFunction(), MWDebug\log(), and wfGetCaller\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.
$wikiString: the 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 3428 of file GlobalFunctions.php.

References wfGetLB().

Referenced by DeletedContribsPager\__construct(), SearchEngine\__construct(), SqlDataUpdate\__construct(), ImageListPager\__construct(), Block\__construct(), IndexPager\__construct(), MergeHistoryPager\__construct(), SiteStatsInit\__construct(), ContribsPager\__construct(), LinkCache\addLinkObj(), ApiQueryLogEvents\addLogParams(), ChangeTags\addTags(), WatchedItem\addWatch(), SpecialRecentChanges\buildMainQueryConds(), Linker\buildRollbackLink(), 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(), EditPage\commitWatch(), CompressOld\compressOldPages(), CompressOld\compressPage(), CompressOld\compressWithConcat(), Title\countAuthorsBetween(), SpecialWatchlist\countItems(), Title\countRevisionsBetween(), ConvertLinks\createTempTable(), Block\defaultRetroactiveAutoblock(), Block\delete(), RefreshLinks\deleteLinksFromNonexistent(), NukePage\deleteRevisions(), Title\deleteTitleProtection(), FixSlaveDesync\desyncFixPage(), SiteStatsInit\doAllAndCommit(), RecompressTracked\doAllOrphans(), RecompressTracked\doAllPages(), PopulateParentId\doDBUpdates(), FixExtLinksProtocolRelative\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(), MovePageForm\doSubmit(), ViewCountUpdate\doUpdate(), SiteStatsUpdate\doUpdate(), DeferredUpdates\doUpdates(), UpdateSearchIndex\doUpdateSearchIndex(), LinkHolderArray\doVariants(), Title\estimateRevisionCount(), StorageTypeStats\execute(), DumpRev\execute(), CleanupPreferences\execute(), SpecialTags\execute(), OrphanStats\execute(), SpecialWatchlist\execute(), CheckBadRedirects\execute(), GetSlaveServer\execute(), RebuildAll\execute(), MwSql\execute(), BenchmarkDeleteTruncate\execute(), CheckImages\execute(), ClearInterwikiCache\execute(), FixUserRegistration\execute(), FixBug20757\execute(), SpecialStatistics\execute(), DeleteRevision\execute(), DeleteSelfExternals\execute(), ResetUserTokens\execute(), BatchedQueryRunner\execute(), UpdateSpecialPages\execute(), UpdateLogging\execute(), CleanupAncientTables\execute(), DeleteDefaultMessages\execute(), MigrateUserGroup\execute(), RemoveUnusedAccounts\execute(), CleanupSpam\execute(), DeleteOrphanedRevisions\execute(), DumpSisterSites\execute(), GetTextMaint\execute(), InitEditCount\execute(), NukePage\execute(), AlterSharedConstraints\execute(), ShowJobs\execute(), UpdateArticleCount\execute(), UpdateRestrictions\execute(), CheckUsernames\execute(), CleanupRemovedModules\execute(), ConvertUserOptions\execute(), DeleteImageCache\execute(), PatchSql\execute(), AttachLatest\execute(), InitStats\execute(), RenameDbPrefix\execute(), ShowStats\execute(), FixDoubleRedirects\execute(), FixTimestamps\execute(), UpdateDoubleWidthSearch\execute(), DumpLinks\execute(), DeleteArchivedRevisions\execute(), FetchText\execute(), RebuildFileCache\execute(), DeleteBatch\execute(), RebuildTextIndex\execute(), SqliteMaintenance\execute(), NamespaceConflictChecker\execute(), RunJobs\execute(), ConvertLinks\execute(), NukeNS\execute(), MoveBatch\execute(), ImageBuilder\execute(), RefreshImageMetadata\execute(), UpdateMediaWiki\execute(), SpecialRevisionDelete\execute(), UploadDumper\fetchLocal(), Revision\fetchRevision(), HistoryAction\fetchRevisions(), UploadDumper\fetchUsed(), TitleCleanup\fileExists(), TrackBlobs\findOrphanBlobs(), FixSlaveDesync\findPageLatestCorruption(), RecompressTracked\finishIncompleteMoves(), RefreshLinks\fixLinksFromArticle(), RefreshLinks\fixRedirect(), DoubleRedirectJob\fixRedirects(), DoubleRedirectsPage\formatResult(), SpecialProtectedtitles\formatRow(), SpecialProtectedpages\formatRow(), LCStore_DB\get(), Interwiki\getAllPrefixesDB(), EditPage\getBaseRevision(), Title\getBrokenLinksFrom(), Title\getCascadeProtectionSources(), RevDel_RevisionList\getCurrent(), Block\getDatabaseArray(), ResourceLoaderWikiModule\getDB(), UserRightsProxy\getDB(), BacklinkCache\getDB(), ApiBase\getDB(), ProtectionForm\getExpiry(), ResourceLoaderModule\getFileDependencies(), DoubleRedirectJob\getFinalDestination(), Title\getFirstRevision(), MessageBlobStore\getFromDB(), DeleteImageCache\getImageCount(), WikiPage\getLastNAuthors(), SpecialExport\getLinks(), Title\getLinksFrom(), Title\getLinksTo(), ExternalUser\getLocalUser(), ForeignDBViaLBRepo\getMasterDB(), LocalRepo\getMasterDB(), SpecialStatistics\getMostViewedPages(), ResourceLoaderModule\getMsgBlobMtime(), User\getNewMessageLinks(), Title\getNextRevisionID(), Title\getNotificationTimestamp(), SpecialExport\getPagesFromCategory(), SpecialExport\getPagesFromNamespace(), Title\getParentCategories(), nextJobDB\getPendingDbs(), Title\getPreviousRevisionID(), DisambiguationsPage\getQueryFromLinkBatch(), NewFilesPager\getQueryInfo(), WithoutInterwikiPage\getQueryInfo(), UsersPager\getQueryInfo(), ImageListPager\getQueryInfo(), LinkSearchPage\getQueryInfo(), ProtectedPagesPager\getQueryInfo(), Block\getRangeCond(), Title\getRedirectsHere(), FixBug20757\getRevTextMap(), RollbackEdits\getRollbackTitles(), ForeignDBViaLBRepo\getSlaveDB(), LocalRepo\getSlaveDB(), ResourceLoaderFileModule\getStyles(), Title\getSubpages(), HistoryBlobStub\getText(), HistoryBlobCurStub\getText(), TrackBlobs\getTextClause(), Revision\getTimestampFromId(), Revision\getTitle(), 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(), Revision\isUnpatrolled(), SiteStats\jobs(), ImageCleanup\killRow(), ExternalUser\linkToLocal(), ChangeTags\listDefinedTags(), SiteStats\load(), WatchedItem\load(), Interwiki\load(), SiteStats\loadAndLazyInit(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), Revision\loadText(), Profiler\logData(), LinkFilter\makeLikeArray(), SpecialMergeHistory\merge(), SearchMySQL\minSearchLength(), TitleCleanup\moveIllegalPage(), TitleCleanup\moveInconsistentPage(), RecompressTracked\moveTextRow(), Title\moveTo(), moveToExternal(), Title\moveToInternal(), LinkSearchPage\mungeQuery(), Title\nameOf(), Revision\newFromConds(), Block\newFromID(), Title\newFromID(), UserArray\newFromIDs(), Title\newFromIDs(), SquidUpdate\newFromLinksTo(), ExternalUser\newFromUser(), Block\newLoad(), SiteStats\numberingroup(), SkinTemplate\outputPage(), InfoAction\pageCounts(), InfoAction\pageInfo(), SiteStats\pagesInNs(), SpecialBlock\parseExpiryInput(), ImageCleanup\pokeFile(), ResourceLoader\preloadModuleInfo(), Block\purgeExpired(), Title\purgeExpiredRestrictions(), PurgeList\purgeNamespace(), PurgeRedundantText(), 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(), RandomPage\selectRandomPageFromDB(), RevDel_RevisionItem\setBits(), RevDel_ArchiveItem\setBits(), RevDel_ArchivedRevisionItem\setBits(), RevDel_FileItem\setBits(), RevDel_ArchivedFileItem\setBits(), RevDel_LogItem\setBits(), DatabaseTest\setUp(), LinksUpdateTest\setUp(), TestORMRowTest\setUp(), setupTestResources(), RevisionDeleteUser\setUsernameBitfields(), RevDel_List\setVisibility(), SpecialBlockList\showList(), SpecialPrefixindex\showPrefixChunk(), SpecialVersion\softwareInformation(), RecompressTracked\syncDBs(), teardownTestResources(), WikiPageTest\testDoDeleteArticle(), WikiPageTest\testDoDeleteUpdates(), WikiPageTest\testDoEdit(), RevisionStorageTest\testNewNullRevision(), DatabaseTest\testStoredFunctions(), RevisionStorageTest\testUserWasLastToEdit(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), ResourceLoader\tryRespondFromFileCache(), SpecialEditWatchlist\unwatchTitles(), SearchIBM_DB2\update(), SearchOracle\update(), SearchMySQL\update(), Block\update(), SiteStatsInit\update(), MessageBlobStore\updateMessage(), MessageBlobStore\updateModule(), Block\updateTimestamp(), SearchIBM_DB2\updateTitle(), SearchOracle\updateTitle(), SearchMySQL\updateTitle(), userOptions\USAGER(), Revision\userWasLastToEdit(), SpecialEditWatchlist\watchTitles(), and SpecialRecentChanges\webOutput().

Get the cache object used by the language converter.

Returns:
BagOStuff

Definition at line 3810 of file GlobalFunctions.php.

References ObjectCache\getInstance().

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

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

Referenced by Skin\doEditSectionLink(), DateFormatter\getInstance(), Title\getPageLanguage(), Linker\tocList(), and wfMsgExt().

Get the main cache object.

Returns:
BagOStuff

Definition at line 3780 of file GlobalFunctions.php.

References ObjectCache\getInstance().

Referenced by UploadFromUrlTestSuite\setUp(), and NewParserTest\setUp().

Get the cache object used by the message cache.

Returns:
BagOStuff

Definition at line 3790 of file GlobalFunctions.php.

References ObjectCache\getInstance().

Referenced by UploadFromUrlTestSuite\setUp(), and NewParserTest\setUp().

wfGetNull ( )

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

/dev/null

Returns:
string

Definition at line 3577 of file GlobalFunctions.php.

References wfIsWindows().

Referenced by wfProxyCheck().

Get the cache object used by the parser cache.

Returns:
BagOStuff

Definition at line 3800 of file GlobalFunctions.php.

References ObjectCache\getInstance().

Referenced by PurgeParserCache\execute(), UploadFromUrlTestSuite\setUp(), and NewParserTest\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 3330 of file GlobalFunctions.php.

References $blob, $file, and $IP.

Referenced by IcuCollation\getFirstLetterData().

Get the script URL.

Returns:
string script URL

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

Referenced by DjVuHandler\doTransform(), MWCryptRand\initialRandomState(), Profiler\logData(), BitmapHandler\logErrorForExternalProcess(), RecompressTracked\logToFile(), DatabaseMysql\open(), 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 2122 of file GlobalFunctions.php.

References $wgOut, and print.

Referenced by MWException\report().

Returns:
bool

Definition at line 3239 of file GlobalFunctions.php.

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

wfIncrStats ( key,
count = 1 
)

Increment a statistics counter.

Parameters:
$keyString
$countInt

Definition at line 1228 of file GlobalFunctions.php.

References $count, $wgMemc, wfMemcKey(), wfRestoreWarnings(), and wfSuppressWarnings().

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

Referenced by UploadBase\isEnabled(), ObjectCache\newAccelerator(), UserMailer\send(), wfDl(), wfInitShellLocale(), and wfShellExec().

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

References 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:
$namestring the image name to check
$contextTitleTitle|bool the page on which the image occurs, if known
$blackliststring wikitext of a file blacklist
Returns:
bool

Definition at line 3876 of file GlobalFunctions.php.

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

Referenced by GlobalWithDBTest\testWfIsBadImage().

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

Returns:
bool

Definition at line 968 of file GlobalFunctions.php.

Referenced by wfDebug(), and wfLogProfilingData().

Check if we are running under HipHop.

Returns:
Bool

Definition at line 2465 of file GlobalFunctions.php.

Referenced by UploadBase\isEnabled().

Load an extension messages file.

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

Definition at line 3568 of file GlobalFunctions.php.

References wfDeprecated().

wfLogDBError ( text)

Log for database errors.

Parameters:
$textString: database error message.

Definition at line 1048 of file GlobalFunctions.php.

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

Referenced by DatabaseMysql\open(), and LoadBalancer\reportConnectionError().

wfMakeUrlIndexes ( url)

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

Parameters:
$urlString
Returns:
array

Definition at line 856 of file GlobalFunctions.php.

References $url, and wfParseUrl().

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

wfMatchesDomainList ( url,
domains 
)

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

Parameters:
$urlstring URL
$domainsarray Array of domains (strings)
Returns:
bool True if the host part of $url ends in one of the strings in $domains

Definition at line 910 of file GlobalFunctions.php.

References $url, 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 3679 of file GlobalFunctions.php.

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

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

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

References $out, and $params.

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

wfMessage ( key)

This is the new function for getting translated interface messages.

See the Message class for documentation how to use them. The intention is that this function replaces all old wfMsg* functions.

Parameters:
$key String : Message key. Varargs: normal message parameters.
Returns:
Message
Since:
1.17

Definition at line 1377 of file GlobalFunctions.php.

References $params.

Referenced by WikiErrorMsg\__construct(), ErrorPageError\__construct(), MediaTransformError\__construct(), TransformParameterError\__construct(), UserBlockedError\__construct(), HTMLFormField\__construct(), MediaHandler\addMeta(), Skin\addToSidebar(), SpecialVersion\arrayToString(), RdfMetaData\basics(), Linker\blockLink(), LegacyTemplate\bottomLinks(), ProtectionForm\buildCleanupScript(), ProtectionForm\buildForm(), Xml\buildForm(), ChangeTags\buildTagFilterSelector(), SpecialEditWatchlist\buildTools(), Title\checkSpecialsAndNSPermissions(), Title\checkUserBlock(), CleanupSpam\cleanupArticle(), FormatMetadata\collapseContactInfo(), Linker\commentBlock(), LegacyTemplate\commentLink(), MonoBookTemplate\customBox(), Xml\dateMenu(), CoreParserFunctions\defaultsort(), LegacyTemplate\deleteThisPage(), UploadBase\detectVirus(), CologneBlueTemplate\doAfterContent(), Block\doAutoblock(), CologneBlueTemplate\doBeforeContent(), Skin\doEditSectionLink(), ApiQueryTags\doTag(), SvgHandler\doTransform(), DjVuHandler\doTransform(), LegacyTemplate\editThisPage(), Linker\emailLink(), LegacyTemplate\emailUserLink(), WebInstallerPage\endForm(), ApiQueryAllMessages\execute(), DumpMessages\execute(), ApiEditPage\execute(), CleanupSpam\execute(), UsercreateTemplate\execute(), ApiFeedContributions\execute(), MoveBatch\execute(), ApiFeedWatchlist\execute(), WebInstaller_ExistingWiki\execute(), WebInstaller_Welcome\execute(), WebInstaller_DBConnect\execute(), WebInstaller_Upgrade\execute(), WebInstaller_Name\execute(), WebInstaller_Options\execute(), WebInstaller_Install\execute(), WebInstaller_Complete\execute(), WebInstaller_Restart\execute(), LegacyTemplate\extensionTabLinks(), ApiFeedContributions\feedItemDesc(), Linker\formatAutocommentsCallback(), FormatMetadata\formatCoords(), FeedUtils\formatDiff(), FeedUtils\formatDiffRow(), ResourceLoader\formatException(), Linker\formatHiddenCategories(), Linker\formatRevisionSize(), ChangeTags\formatSummaryRow(), Linker\formatTemplates(), ChangesFeed\generateFeed(), MessageBlobStore\generateMessageBlob(), EditPage\getCancelLink(), Skin\getCategoryLinks(), WebInstaller_Options\getCCDoneBox(), OracleInstaller\getConnectForm(), PostgresInstaller\getConnectForm(), Ibm_db2Installer\getConnectForm(), MysqlInstaller\getConnectForm(), Article\getContent(), SpecialVersion\getCopyrightAndAuthorList(), Title\getDefaultMessageText(), Interwiki\getDescription(), FeedUtils\getDiffLink(), ImageHandler\getDimensionsString(), SpecialVersion\getExtensionTypes(), WebInstaller_Document\getFileContents(), UploadBase\getFilenamePrefixBlacklist(), FormatMetadata\getFormattedData(), MediaHandler\getGeneralLongDesc(), SpecialPageFactory\getGroup(), WebInstallerOutput\getJQuery(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), ImageHandler\getLongDesc(), SvgHandler\getLongDesc(), MediaHandler\getLongDesc(), SpecialVersion\getMediaWikiCredits(), WikiXmlError\getMessage(), MakeLanguageSpec\getMessagesAndTests(), CliInstaller\getMessageText(), Interwiki\getName(), ProtectionForm\getOptionLabel(), Block\getRedactedName(), MysqlInstaller\getSettingsForm(), ImageHandler\getShortDesc(), SpecialBlock\getSuggestedDurations(), LegacyTemplate\getUploadLink(), DoubleRedirectJob\getUser(), SpecialVersion\getVersion(), SpecialVersion\getVersionLinkedSvn(), Status\getWikiText(), Status\getWikiTextForError(), Title\hasSourceText(), LegacyTemplate\historyLink(), Parser\interwikiTransclude(), CoreParserFunctions\intFunction(), Block\isWhitelistedFromAutoblocks(), WebInstaller\label(), FormatMetadata\langItem(), Xml\languageSelector(), ApiParse\languagesHtml(), Linker\linkAttribs(), Skin\makeI18nUrl(), Linker\makeThumbLink2(), CologneBlueTemplate\menuHead(), Xml\monthSelector(), LegacyTemplate\moveThisPage(), Title\moveTo(), Title\moveToInternal(), MWException\msg(), FormatMetadata\msg(), LegacyTemplate\nameAndLogin(), Html\namespaceSelector(), Title\newMainPage(), WikiImporter\notice(), LegacyTemplate\otherLanguages(), LegacyTemplate\pageSubtitle(), LegacyTemplate\pageTitleLinks(), RdfMetaData\person(), LegacyTemplate\printableLink(), LegacyTemplate\protectThisPage(), StandardTemplate\quickBar(), CologneBlueTemplate\quickBar(), TextPassDumper\readDump(), MessageBlobStore\reencodeBlob(), VectorTemplate\renderPortal(), Linker\revComment(), Linker\revDeleteLink(), Linker\revDeleteLinkDisabled(), Linker\revUserLink(), Linker\revUserTools(), DoubleRedirectJob\run(), ProtectionForm\save(), LegacyTemplate\searchForm(), CologneBlueTemplate\searchForm(), WikiImporter\setTargetRootPage(), RdfMetaData\setup(), ProtectionForm\show(), WebInstaller_Upgrade\showDoneMessage(), EditPage\showHeaderCopyrightWarning(), Article\showViewFooter(), SpecialVersion\softwareInformation(), CoreParserFunctions\special(), Linker\specialLink(), LegacyTemplate\specialPagesList(), WebInstaller_Install\startStage(), WebInstaller_Name\submit(), WebInstaller_Options\submit(), CologneBlueTemplate\sysLinks(), ChangeTags\tagDescription(), CoreParserFunctions\tagObj(), LegacyTemplate\talkLink(), MessageTest\testExists(), MessageTest\testInContentLanguage(), MessageTest\testInLanguage(), MessageTest\testInLanguageThrows(), MessageTest\testKey(), XmlTest\testLanguageSelector(), MessageTest\testMessageParams(), MessageTest\testMessageParamSubstitution(), ExtraParserTest\testTrackingCategory(), Linker\tocList(), NostalgiaTemplate\topLinks(), LegacyTemplate\topLinks(), BitmapHandler\transformGd(), MediaWiki_I18N\translate(), StripState\unstripCallback(), LegacyTemplate\userContribsLink(), Linker\userTalkLink(), Linker\userToolLinks(), MediaHandler\visibleMetadataFields(), LegacyTemplate\watchPageLinksLink(), LegacyTemplate\watchThisPage(), wfIsBadImage(), wfShowingResults(), wfStreamThumb(), and LegacyTemplate\whatLinksHere().

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

References MWFunction\callArray().

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:
$dirString: full path to directory to create
$modeInteger: chmod value to use, default is $wgDirectoryMode
$callerString: optional caller param for debugging.
Returns:
bool

Definition at line 2517 of file GlobalFunctions.php.

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

Referenced by FileCacheBase\checkCacheDirs(), TextPassDumperTest\checkpointHelper(), SvgHandler\doTransform(), BitmapHandler\doTransform(), DjVuHandler\doTransform(), ImageCleanup\pokeFile(), MessageCache\saveToScript(), and UploadFromUrlTestSuite\setupUploadDir().

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:
$keyString: lookup 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 1418 of file GlobalFunctions.php.

References wfMsgReal().

wfMsgExt ( key,
options 
)

Returns message in the requested format.

Deprecated:
since 1.18
Parameters:
$keyString: key of the message
$optionsArray: processing 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   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 (overriden by content). Behavior for conflicting options (e.g., parse+parseinline) is undefined.
Returns:
String

Definition at line 1633 of file GlobalFunctions.php.

References $options, Sanitizer\escapeHtmlAllowEntities(), MessageCache\singleton(), 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:
$keyString: lookup key for the message, usually defined in languages/Language.php
Returns:
String

Definition at line 1463 of file GlobalFunctions.php.

References wfMsgReal().

Same as above except doesn't transform the message.

Deprecated:
since 1.18
Parameters:
$keyString
Returns:
String

Definition at line 1484 of file GlobalFunctions.php.

References 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
$langCodeString: Code 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 1529 of file GlobalFunctions.php.

References MessageCache\singleton(), 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 1583 of file GlobalFunctions.php.

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

References wfMsgReal().

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

Really get a message.

Deprecated:
since 1.18
Parameters:
$keyString: key 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 1509 of file GlobalFunctions.php.

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

References $n.

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

References MessageCache\singleton(), 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:
$cprefsArray: client's acceptable type list
$sprefsArray: server'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 2277 of file GlobalFunctions.php.

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

References $value.

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

References $s, $wgCommandLineMode, echo, 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:
$urlString: a URL to parse
Returns:
Array: bits of the URL in an associative array, per PHP docs

Definition at line 771 of file GlobalFunctions.php.

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

Referenced by WikiReference\getDisplayName(), UploadFromUrl\isAllowedHost(), UserMailer\makeMsgId(), wfAssembleUrl\provideURLParts(), wfExpandUrl(), wfExtractThumbParams(), wfMakeUrlIndexes(), wfMatchesDomainList(), and wfThumbHandle404().

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

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

Should low-performance queries be disabled?

Returns:
Boolean

Definition at line 3501 of file GlobalFunctions.php.

References SiteStats\edits(), 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 304 of file GlobalFunctions.php.

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

wfRandomString ( length = 32)

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

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

Definition at line 323 of file GlobalFunctions.php.

Referenced by TempFSFile\factory(), MWException\getLogId(), and UploadSourceAdapter\registerSource().

Check if the wiki read-only lock file is present.

This can be used to lock off editing functions, but doesn't guarantee that the database will not be modified.

Returns:
bool

Definition at line 1280 of file GlobalFunctions.php.

Referenced by ProtectionForm\__construct(), ApiQuerySiteinfo\appendGeneralInfo(), Block\delete(), BackupReader\execute(), EmailInvalidation\execute(), Title\invalidateCache(), Profiler\logData(), User\saveSettings(), GlobalTest\testReadOnlyEmpty(), GlobalTest\testReadOnlySet(), and wfReadOnlyReason().

Remove a directory and all its content.

Does not hide error.

Definition at line 2555 of file GlobalFunctions.php.

References $dir, and wfDebug().

Referenced by TextPassDumperTest\checkpointHelper(), and teardownTestResources().

wfRelativePath ( path,
from 
)

Generate a relative path name to the given file.

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

Parameters:
$pathString: absolute destination path including target filename
$fromString: Absolute source path, directory only
Returns:
String

Definition at line 3088 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:
$urlPathString URL path, potentially containing dot-segments
Returns:
string URL path with all dot-segments removed

Definition at line 634 of file GlobalFunctions.php.

References $output.

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

Returns a HTML comment with the elapsed time since request.

This method has no side effects.

Returns:
string

Definition at line 1771 of file GlobalFunctions.php.

References $wgRequestTime, 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 2157 of file GlobalFunctions.php.

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

Restore error level to previous value.

Definition at line 2340 of file GlobalFunctions.php.

References wfSuppressWarnings().

Referenced by 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(), SwiftFileBackend\doStoreInternal(), SquidPurgeClient\doWrites(), CheckImages\execute(), JSParseHelper\execute(), RebuildFileCache\execute(), ModernTemplate\execute(), CommandLineInstaller\execute(), MonoBookTemplate\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), TempFSFile\factory(), DatabaseMysql\fetchObject(), DatabasePostgres\fetchObject(), DatabaseIbm_db2\fetchObject(), DatabaseMysql\fetchRow(), DatabasePostgres\fetchRow(), DatabaseIbm_db2\fetchRow(), DatabaseMysql\freeResult(), DatabasePostgres\freeResult(), DatabaseIbm_db2\freeResult(), ImageHandler\getImageSize(), DjVuImage\getInfo(), SquidPurgeClient\getIP(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), DjVuHandler\getMetaTree(), DatabaseLogEntry\getParameters(), IcuCollation\getPrimarySortKey(), ExifBitmapHandler\getRotationForExif(), SeleniumConfig\getSeleniumSettings(), FSFile\getSha1Base36(), SquidPurgeClient\getSocket(), IcuCollation\getSortKey(), SpecialVersion\getSvnInfo(), FSFile\getTimestamp(), MWCryptRand\initialRandomState(), DatabaseOracle\insertOneRow(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), Sqlite\isPresent(), DatabaseMysql\lastError(), DatabaseMysql\numRows(), DatabasePostgres\numRows(), SpecialUnlockdb\onSubmit(), SpecialLockdb\onSubmit(), DatabaseMysql\open(), DatabaseMssql\open(), DatabaseOracle\open(), DatabaseIbm_db2\openCataloged(), DatabaseIbm_db2\openUncataloged(), XMPReader\parse(), DiffHistoryBlob\patch(), TempFSFile\purge(), MWCryptRand\realGenerate(), Sanitizer\removeHTMLtags(), SquidPurgeClientPool\run(), MessageCache\saveToScript(), JpegMetadataExtractor\segmentSplitter(), DatabaseOracle\selectDB(), UserMailer\send(), PrefixSearch\specialSearch(), SeleniumServerManager\startServerOnUnix(), RecompressTracked\startSlaveProcs(), StreamFile\stream(), MWDebugTest\tearDown(), JavaScriptMinifierTest\testJavaScriptMinifierOutput(), MediaWiki_I18N\translate(), SvgHandler\unpackMetadata(), DatabaseOracle\update(), wfDiff(), wfDl(), wfErrorLog(), wfIncrStats(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfParseUrl(), wfSetupSession(), wfStreamThumb(), and wfUnpack().

wfRunHooks ( event,
args = array() 
)

Call hook functions defined in $wgHooks.

Parameters:
$eventString: event name
$argsArray: parameters passed to hook functions
Returns:
Boolean True if no handler aborted the hook

Definition at line 3822 of file GlobalFunctions.php.

References Hooks\run().

Referenced by ExtensionsTestSuite\__construct(), LinksUpdate\__construct(), ResourceLoader\__construct(), DatabaseOracle\__construct(), RedirectSpecialArticle\__construct(), Skin\afterContentHook(), ApiQuerySiteinfo\appendGeneralInfo(), SpecialChangePassword\attemptReset(), BenchmarkHooks\benchHooks(), Skin\bottomScripts(), SkinTemplate\buildContentNavigationUrls(), ProtectionForm\buildForm(), SkinTemplate\buildNavUrls(), SkinTemplate\buildPersonalUrls(), SpecialEditWatchlist\buildRemoveLine(), Skin\buildSidebar(), Autopromote\checkCondition(), Title\checkPermissionHooks(), Title\checkReadPermissions(), UploadBase\createFromRequest(), Block\doAutoblock(), Skin\doEditSectionLink(), WikiImporter\doImport(), SpecialRecentchangeslinked\doMainQuery(), SpecialRecentChanges\doMainQuery(), RevDel_RevisionList\doPostCommitUpdates(), RefreshLinks\doRefreshLinks(), Block\doRetroactiveAutoblock(), UserrightsPage\doSaveUserGroups(), MovePageForm\doSubmit(), BitmapHandler\doTransform(), WatchAction\doUnwatch(), SearchUpdate\doUpdate(), LinksUpdate\doUpdate(), LinkHolderArray\doVariants(), WatchAction\doWatch(), SpecialUserlogout\execute(), ApiUndelete\execute(), SpecialWatchlist\execute(), SpecialContributions\execute(), SpecialStatistics\execute(), ApiLogout\execute(), ApiEditPage\execute(), ApiLogin\execute(), SpecialEmailUser\execute(), SeleniumTester\execute(), LegacyTemplate\extensionTabLinks(), ApiQueryInfo\extractPageInfo(), Collation\factory(), WikiImporter\finishImportPage(), Parser_LinkHooks\firstCallInit(), Linker\formatAutocommentsCallback(), UsersPager\formatRow(), User\getAllRights(), Autopromote\getAutopromoteGroups(), MWNamespace\getCanonicalNamespaces(), Title\getCanonicalURL(), Title\getCategorySortkey(), BacklinkCache\getConditions(), ResourceLoaderStartUpModule\getConfig(), Skin\getCopyright(), SpecialRecentChanges\getCustomFilters(), UsersPager\getDefaultQuery(), User\getEmail(), User\getEmailAuthenticationTimestamp(), SpecialVersion\getExtensionCredits(), SpecialVersion\getExtensionTypes(), SpecialRecentChanges\getExtraOptions(), ApiBase\getFinalDescription(), ApiBase\getFinalParamDescription(), ApiBase\getFinalParams(), ApiBase\getFinalResultProperties(), Title\getFullURL(), User\getImplicitGroups(), Title\getInternalURL(), XMPInfo\getItems(), PreferencesForm\getLegend(), SpecialPageFactory\getList(), Title\getLocalURL(), MediaHandler\getMetadataVersion(), User\getNewMessageLinks(), UsersPager\getPageHeader(), Title\getPageLanguage(), NewParserTest\getParser(), SpecialEmailUser\getPermissionsError(), Skin\getPoweredBy(), Preferences\getPreferences(), BacklinkCache\getPrefix(), WantedPagesPage\getQueryInfo(), UsersPager\getQueryInfo(), HistoryPager\getQueryInfo(), ContribsPager\getQueryInfo(), RandomPage\getRandomTitle(), Title\getRestrictionTypes(), XMPReader\getResults(), User\getRights(), ApiRsd\getRsdApiList(), ResourceLoaderStartUpModule\getScript(), SpecialSearch\getSearchProfiles(), BaseTemplate\getSidebar(), Skin\getSiteNotice(), DeletedContributionsPage\getSubTitle(), ApiQueryUsers\getTokenFunctions(), ApiQueryRevisions\getTokenFunctions(), ApiQueryRecentChanges\getTokenFunctions(), ApiQueryInfo\getTokenFunctions(), ApiTokens\getTokenTypes(), BaseTemplate\getToolbox(), SpecialContributions\getUserLinks(), MagicWord\getVariableIDs(), GitInfo\getViewers(), WikiImporter\handleLogItem(), WikiImporter\handlePage(), WikiImporter\handleRevision(), WikiImporter\handleUpload(), ImageHistoryList\imageHistoryLine(), Revision\insertOn(), Title\isAlwaysKnown(), Title\isCssOrJsPage(), MWNamespace\isMovable(), Title\isMovable(), Title\isValidMoveOperation(), Title\isWikitextPage(), Linker\link(), ChangeTags\listDefinedTags(), Interwiki\load(), Linker\makeExternalImage(), Linker\makeExternalLink(), Parser\makeImage(), Linker\makeImageLink(), SpecialMergeHistory\merge(), Title\moveTo(), Title\moveToInternal(), UserArray\newFromResult(), TitleArray\newFromResult(), BitmapHandler\normaliseParams(), RawAction\onView(), InfoAction\onView(), HistoryAction\onView(), SkinTemplate\outputPage(), UploadBase\performUpload(), SpecialBlock\preText(), SpecialBlock\processForm(), ResourceLoader\registerTestModules(), VectorTemplate\renderPortal(), LinkHolderArray\replaceInternal(), ImportReporter\reportPage(), ProtectionForm\save(), User\saveSettings(), PrefixSearch\searchBackend(), UserMailer\send(), User\setEmail(), User\setEmailAuthenticationTimestamp(), SpecialNewpages\setup(), NewParserTest\setupGlobals(), EditAction\show(), SpecialSearch\showCreateLink(), SpecialChangePassword\showForm(), SpecialBlockList\showList(), SpecialBookSources\showList(), ProtectionForm\showLogExtract(), SpecialSearch\showResults(), SpecialVersion\softwareInformation(), SpecialEmailUser\submit(), Skin\subPageSubtitle(), SkinTemplate\tabAction(), HooksTest\testOldStyleHooks(), MonoBookTemplate\toolbox(), SpecialEditWatchlist\unwatchTitles(), Linker\userToolLinks(), UploadBase\verifyFile(), UploadBase\verifyUpload(), CategoryPage\view(), wfDebug(), wfDebugLog(), wfExtractThumbParams(), wfIsBadImage(), wfIsTrustedProxy(), wfMsgGetKey(), and wfShellWikiCmd().

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:
$scriptString: script filename, sans extension
Returns:
String

Definition at line 3517 of file GlobalFunctions.php.

Referenced by ResourceLoader\__construct(), SpecialContributions\execute(), SpecialVersion\getEntryPointInfo(), ApiRsd\getRsdApiList(), 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 2087 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 2070 of file GlobalFunctions.php.

References $source.

Referenced by ParserOptions\disableContentConversion(), ParserOptions\disableTitleConversion(), ParserOptions\enableLimitReport(), LinkCache\forUpdate(), Block\fromMaster(), Parser\getOutput(), Block\isAutoblocking(), Block\isHardblock(), LoadBalancer\parentInfo(), 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\setInterwikiMagic(), ParserOptions\setIsPrintable(), ParserOptions\setIsSectionPreview(), ParserOutput\setLanguageLinks(), ParserOptions\setMath(), ParserOptions\setMaxGeneratedPPNodeCount(), ParserOptions\setMaxIncludeSize(), ParserOptions\setMaxPPNodeCount(), ParserOptions\setMaxTemplateDepth(), WikiImporter\setNoticeCallback(), ParserOptions\setNumberHeadings(), Parser\setOutputType(), ParserOptions\setPreSaveTransform(), ParserOptions\setRemoveComments(), ParserOutput\setSections(), ParserOptions\setStubThreshold(), ParserOptions\setTargetLanguage(), ParserOptions\setTemplateCallback(), ParserOutput\setText(), ParserOptions\setTidy(), ParserOutput\setTimestamp(), ParserOptions\setTimestamp(), ParserOutput\setTitleText(), ParserOutput\setTOCHTML(), ParserOptions\setUserLang(), and LoadBalancer\waitTimeout().

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

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

Parameters:
$cmdString Command line, properly escaped for shell.
&$retvalnull|Mixed optional, will receive the program's exit code. (non-zero is usually failure)
$environArray optional environment variables which should be added to the executed command environment.
$limitsArray optional array with limits(filesize, memory, time) this overwrites the global wgShellMax* limits.
Returns:
string collected stdout as a string (trailing newlines stripped)

Definition at line 2741 of file GlobalFunctions.php.

References $IP, $output, wfDebug(), wfDebugLog(), wfIniGetBool(), wfInitShellLocale(), and wfIsWindows().

Referenced by UploadBase\detectVirus(), DjVuHandler\doTransform(), CheckSyntax\getGitModifiedFiles(), BitmapHandler\getMagickVersion(), SvgHandler\rasterize(), DjVuImage\retrieveMetaData(), BitmapHandler\transformCustom(), BitmapHandler\transformImageMagick(), RandomImageGenerator\writeImageWithApi(), and RandomImageGenerator\writeImageWithCommandLine().

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

Alias to wfShellWikiCmd()

See also:
wfShellWikiCmd()

Definition at line 2835 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:
$scriptstring MediaWiki cli script path
$parametersArray Arguments and options to the script
$optionsArray Associative 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 2850 of file GlobalFunctions.php.

References $options, and wfRunHooks().

Referenced by wfShellMaintenanceCmd().

wfShorthandToInteger ( string = '')

Converts shorthand byte notation to integer form.

Parameters:
$stringString
Returns:
Integer

Definition at line 3707 of file GlobalFunctions.php.

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

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

Definition at line 1934 of file GlobalFunctions.php.

References $limit, and wfMessage().

wfSpecialList ( page,
details,
oppositedm = true 
)

Make a list item, used by various special pages.

Parameters:
$pageString Page link
$detailsString Text between brackets
$oppositedmBoolean Add the direction mark opposite to your language, to display text properly
Returns:
String
Deprecated:
since 1.19; use Language::specialList() instead

Definition at line 1978 of file GlobalFunctions.php.

References $page, $wgLang, and wfDeprecated().

wfSplitWikiID ( wiki)

Split a wiki ID into DB name and table prefix.

Parameters:
$wikiString
Returns:
array

Definition at line 3398 of file GlobalFunctions.php.

Referenced by ForeignDBViaLBRepo\__construct(), LBFactory_Multi\getDBNameAndPrefix(), nextJobDB\getPendingDbs(), 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 3490 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 3662 of file GlobalFunctions.php.

References Title\legalChars(), and wfBaseName().

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

wfSuppressWarnings ( end = false)

Reference-counted warning suppression.

Parameters:
$endBool

Definition at line 2318 of file GlobalFunctions.php.

Referenced by 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(), SwiftFileBackend\doStoreInternal(), SquidPurgeClient\doWrites(), CheckImages\execute(), JSParseHelper\execute(), RebuildFileCache\execute(), ModernTemplate\execute(), CommandLineInstaller\execute(), MonoBookTemplate\execute(), CurlHttpRequest\execute(), PhpHttpRequest\execute(), TempFSFile\factory(), DatabaseMysql\fetchObject(), DatabasePostgres\fetchObject(), DatabaseIbm_db2\fetchObject(), DatabaseMysql\fetchRow(), DatabasePostgres\fetchRow(), DatabaseIbm_db2\fetchRow(), DatabaseMysql\freeResult(), DatabasePostgres\freeResult(), DatabaseIbm_db2\freeResult(), ImageHandler\getImageSize(), DjVuImage\getInfo(), SquidPurgeClient\getIP(), PNGHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGMetadataExtractor\getMetadata(), GIFMetadataExtractor\getMetadata(), DjVuHandler\getMetaTree(), DatabaseLogEntry\getParameters(), IcuCollation\getPrimarySortKey(), ExifBitmapHandler\getRotationForExif(), SeleniumConfig\getSeleniumSettings(), FSFile\getSha1Base36(), SquidPurgeClient\getSocket(), IcuCollation\getSortKey(), SpecialVersion\getSvnInfo(), FSFile\getTimestamp(), MWCryptRand\initialRandomState(), DatabaseOracle\insertOneRow(), ExifBitmapHandler\isMetadataValid(), PNGHandler\isMetadataValid(), GIFHandler\isMetadataValid(), Sqlite\isPresent(), DatabaseMysql\lastError(), DatabaseMysql\numRows(), DatabasePostgres\numRows(), SpecialUnlockdb\onSubmit(), SpecialLockdb\onSubmit(), DatabaseMysql\open(), DatabaseMssql\open(), DatabaseOracle\open(), DatabaseIbm_db2\openCataloged(), DatabaseIbm_db2\openUncataloged(), XMPReader\parse(), DiffHistoryBlob\patch(), TempFSFile\purge(), MWCryptRand\realGenerate(), Sanitizer\removeHTMLtags(), SquidPurgeClientPool\run(), MessageCache\saveToScript(), JpegMetadataExtractor\segmentSplitter(), DatabaseOracle\selectDB(), UserMailer\send(), MWDebugTest\setUp(), PrefixSearch\specialSearch(), SeleniumServerManager\startServerOnUnix(), RecompressTracked\startSlaveProcs(), StreamFile\stream(), JavaScriptMinifierTest\testJavaScriptMinifierOutput(), MediaWiki_I18N\translate(), SvgHandler\unpackMetadata(), DatabaseOracle\update(), wfDiff(), wfDl(), wfErrorLog(), wfIncrStats(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfParseUrl(), wfRestoreWarnings(), wfSetupSession(), wfStreamThumb(), and wfUnpack().

wfTime ( )

Get the current unix timetstamp with microseconds.

Useful for profiling

Returns:
Float

Definition at line 2056 of file GlobalFunctions.php.

Referenced by GlobalTest\testTime().

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: the timestamp to convert or 0 for the current timestamp
Returns:
Mixed: String / false The same date in the format specified in $outputtype or false

Definition at line 2411 of file GlobalFunctions.php.

References wfDebug().

Referenced by Block\__construct(), UserBlockedError\__construct(), BlockTest\addDBData(), ApiQueryLogEvents\addLogParams(), ApiQuerySiteinfo\appendGeneralInfo(), SpecialRecentChanges\buildMainQueryConds(), FileCacheBase\cacheTimestamp(), Title\checkUserBlock(), ApiQueryContributions\continueStr(), LanguageWa\date(), SwiftFileBackend\doGetFileStat(), MysqlUpdater\doSchemaRestructuring(), FileBackendTest\doTestGetFileStat(), ApiProtect\execute(), ApiUndelete\execute(), ApiSetNotificationTimestamp\execute(), ApiQueryDeletedrevs\execute(), ApiQueryFilearchive\execute(), ApiEditPage\execute(), SpecialExport\execute(), RemoveUnusedAccounts\execute(), ApiQueryBlocks\execute(), ApiQueryImageInfo\execute(), ApiQueryLogEvents\execute(), ApiQueryContributions\execute(), ApiBlock\execute(), FixTimestamps\execute(), PurgeParserCache\execute(), ApiQueryAllUsers\execute(), UpdateSearchIndex\execute(), ApiFeedWatchlist\execute(), CacheTime\expired(), ApiQueryInfo\extractPageInfo(), ApiQueryWatchlist\extractRowInfo(), ApiQueryLogEvents\extractRowInfo(), ApiQueryContributions\extractRowInfo(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryRevisions\extractRowInfo(), HistoryAction\feedEmpty(), FeedUtils\formatDiff(), SpecialMergeHistory\formatRevisionRow(), Block\getAutoblockExpiry(), ApiQueryUserInfo\getCurrentUserInfo(), ProtectionForm\getExpiry(), FormatMetadata\getFormattedData(), MessageBlobStore\getFromDB(), ApiQueryImageInfo\getInfo(), PNGMetadataExtractor\getMetadata(), ResourceLoaderUserCSSPrefsModule\getModifiedTime(), ResourceLoaderUserOptionsModule\getModifiedTime(), ResourceLoaderLanguageDataModule\getModifiedTime(), ResourceLoaderStartUpModule\getModifiedTime(), ResourceLoaderStartUpModule\getModuleRegistrations(), ResourceLoaderModule\getMsgBlobMtime(), RawAction\getRawText(), ResourceLoaderStartUpModule\getScript(), FSFile\getTimestamp(), ForeignAPIFile\getTimestamp(), DatabaseLogEntry\getTimestamp(), RCDatabaseLogEntry\getTimestamp(), ManualLogEntry\getTimestamp(), Revision\getTimestamp(), FileJournal\getTimestampedUUID(), Revision\getTimestampFromId(), ResourceLoaderWikiModule\getTitleMtimes(), ImageHistoryList\imageHistoryLine(), Block\initFromRow(), User\isEmailConfirmationPending(), ChangesFeed\loadFromCache(), MessageCache\logMessages(), SpecialBlock\maybeAlterFormDefaults(), SpecialMergeHistory\merge(), SpecialBlock\parseExpiryInput(), ResourceLoader\preloadModuleInfo(), StreamFile\prepareForStream(), TableCleanup\progress(), ImageBuilder\progress(), ResourceLoader\respond(), ApiQueryProtectedTitles\run(), ApiQuerySearch\run(), ApiQueryWatchlistRaw\run(), ApiQueryDuplicateFiles\run(), ApiQueryCategoryMembers\run(), ApiQueryCategories\run(), ApiQueryWatchlist\run(), ApiQueryQueryPage\run(), ApiQueryAllImages\run(), ApiQueryRecentChanges\run(), RunJobs\runJobsLog(), ChangesFeed\saveToCache(), ApiMain\sendCacheHeaders(), ResourceLoader\sendResponseHeaders(), WikiPage\setCachedLastEditTime(), wfTimestamp\testHttpDate(), wfTimestamp\testNormalTimestamps(), wfTimestamp\testOldTimestamps(), wfTimestamp\testTimestampParameter(), IPTC\timeHelper(), DatabaseMssql\timestamp(), DatabaseOracle\timestamp(), DatabaseIbm_db2\timestamp(), DatabasePostgres\timestamp(), ResourceLoader\tryRespondFromFileCache(), ResourceLoader\tryRespondLastModified(), 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 2429 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 1362 of file GlobalFunctions.php.

References $wgLang, and wfDeprecated().

wfUnpack ( format,
data,
length = false 
)

Wrapper around php's unpack.

Parameters:
$formatString: The format string (See php's docs)
$data,:A binary string of binary data
$lengthinteger or false: The minimun 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 3840 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 353 of file GlobalFunctions.php.

References $s.

Referenced by Title\getLocalURL(), 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:
$includeProtocolRelativebool If false, remove '//' from the returned protocol list. DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
Returns:
String

Definition at line 712 of file GlobalFunctions.php.

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

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

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

Returns:
String

Definition at line 757 of file GlobalFunctions.php.

References wfUrlProtocols().

Referenced by ApiFormatBase\formatHTML().

wfUseMW ( req_ver)

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

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

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

Definition at line 3047 of file GlobalFunctions.php.

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

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

References $s, $wgOut, 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
$queryString: optional URL query parameter string
$atendBool: optional param for specified if this is the last page
Returns:
String
Deprecated:
in 1.19; use Language::viewPrevNext() instead

Definition at line 1949 of file GlobalFunctions.php.

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

wfWaitForSlaves ( maxLag = false,
wiki = 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

Definition at line 3593 of file GlobalFunctions.php.

References $lb, and wfGetLB().

Referenced by CompressOld\compressWithConcat(), RefreshLinks\deleteLinksFromNonexistent(), PopulateRevisionLength\doDBUpdates(), PopulateParentId\doDBUpdates(), FixExtLinksProtocolRelative\doDBUpdates(), PopulateLogUsertext\doDBUpdates(), PopulateLogSearch\doDBUpdates(), PopulateImageSha1\doDBUpdates(), PopulateCategory\doPopulateCategory(), RefreshLinks\doRefreshLinks(), PopulateRevisionSha1\doSha1LegacyUpdates(), PopulateRevisionSha1\doSha1Updates(), MysqlUpdater\doTemplatelinksUpdate(), WaitForSlave\execute(), DeleteSelfExternals\execute(), UpdateSpecialPages\execute(), MigrateUserGroup\execute(), BatchedQueryRunner\execute(), DeleteDefaultMessages\execute(), InitEditCount\execute(), ConvertUserOptions\execute(), UpdateRestrictions\execute(), CleanupRemovedModules\execute(), DeleteBatch\execute(), RunJobs\execute(), MoveBatch\execute(), RefreshImageMetadata\execute(), UpdateCollation\execute(), UpdateMediaWiki\execute(), moveToExternal(), resolveStubs(), RefreshLinksJob2\run(), 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.

Parameters:
$msgString: message 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; only used when $wgDevelopmentWarnings is true

Definition at line 1101 of file GlobalFunctions.php.

References MWDebug\warning().

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