BlueSpice MediaWiki REL1_27
 All Classes Namespaces Files Functions Variables Groups Pages
GlobalFunctions.php File Reference

Functions

 wfLoadExtension ($ext, $path=null)
 
 wfLoadExtensions (array $exts)
 
 wfLoadSkin ($skin, $path=null)
 
 wfLoadSkins (array $skins)
 
 wfArrayDiff2 ($a, $b)
 
 wfArrayDiff2_cmp ($a, $b)
 
 wfAppendToArrayIfNotDefault ($key, $value, $default, &$changed)
 
 wfMergeErrorArrays ()
 
 wfArrayInsertAfter (array $array, array $insert, $after)
 
 wfObjectToArray ($objOrArray, $recursive=true)
 
 wfRandom ()
 
 wfRandomString ($length=32)
 
 wfUrlencode ($s)
 
 wfArrayToCgi ($array1, $array2=null, $prefix= '')
 
 wfCgiToArray ($query)
 
 wfAppendQuery ($url, $query)
 
 wfExpandUrl ($url, $defaultProto=PROTO_CURRENT)
 
 wfAssembleUrl ($urlParts)
 
 wfRemoveDotSegments ($urlPath)
 
 wfUrlProtocols ($includeProtocolRelative=true)
 
 wfUrlProtocolsWithoutProtRel ()
 
 wfParseUrl ($url)
 
 wfExpandIRI ($url)
 
 wfExpandIRI_callback ($matches)
 
 wfMakeUrlIndexes ($url)
 
 wfMatchesDomainList ($url, $domains)
 
 wfDebug ($text, $dest= 'all', array $context=[])
 
 wfIsDebugRawPage ()
 
 wfDebugMem ($exact=false)
 
 wfDebugLog ($logGroup, $text, $dest= 'all', array $context=[])
 
 wfLogDBError ($text, array $context=[])
 
 wfDeprecated ($function, $version=false, $component=false, $callerOffset=2)
 
 wfWarn ($msg, $callerOffset=1, $level=E_USER_NOTICE)
 
 wfLogWarning ($msg, $callerOffset=1, $level=E_USER_WARNING)
 
 wfErrorLog ($text, $file, array $context=[])
 
 wfLogProfilingData ()
 
 wfIncrStats ($key, $count=1)
 
 wfReadOnly ()
 
 wfReadOnlyReason ()
 
 wfConfiguredReadOnlyReason ()
 
 wfGetLangObj ($langcode=false)
 
 wfMessage ($key)
 
 wfMessageFallback ()
 
 wfHostname ()
 
 wfReportTime ()
 
 wfDebugBacktrace ($limit=0)
 
 wfBacktrace ($raw=null)
 
 wfGetCaller ($level=2)
 
 wfGetAllCallers ($limit=3)
 
 wfFormatStackFrame ($frame)
 
 wfShowingResults ($offset, $limit)
 
 wfClientAcceptsGzip ($force=false)
 
 wfEscapeWikiText ($text)
 
 wfSetVar (&$dest, $source, $force=false)
 
 wfSetBit (&$dest, $bit, $state=true)
 
 wfVarDump ($var)
 
 wfHttpError ($code, $label, $desc)
 
 wfResetOutputBuffers ($resetGzipEncoding=true)
 
 wfClearOutputBuffers ()
 
 wfAcceptToPrefs ($accept, $def= '*/*')
 
 wfNegotiateType ($cprefs, $sprefs)
 
 wfSuppressWarnings ($end=false)
 
 wfRestoreWarnings ()
 
 wfTimestamp ($outputtype=TS_UNIX, $ts=0)
 
 wfTimestampOrNull ($outputtype=TS_UNIX, $ts=null)
 
 wfTimestampNow ()
 
 wfIsWindows ()
 
 wfIsHHVM ()
 
 wfTempDir ()
 
 wfMkdirParents ($dir, $mode=null, $caller=null)
 
 wfRecursiveRemoveDir ($dir)
 
 wfPercent ($nr, $acc=2, $round=true)
 
 wfIniGetBool ($setting)
 
 wfEscapeShellArg ()
 
 wfShellExecDisabled ()
 
 wfShellExec ($cmd, &$retval=null, $environ=[], $limits=[], $options=[])
 
 wfShellExecWithStderr ($cmd, &$retval=null, $environ=[], $limits=[])
 
 wfInitShellLocale ()
 
 wfShellWikiCmd ($script, array $parameters=[], array $options=[])
 
 wfMerge ($old, $mine, $yours, &$result)
 
 wfDiff ($before, $after, $params= '-u')
 
 wfUsePHP ($req_ver)
 
 wfUseMW ($req_ver)
 
 wfBaseName ($path, $suffix= '')
 
 wfRelativePath ($path, $from)
 
 wfBaseConvert ($input, $sourceBase, $destBase, $pad=1, $lowercase=true, $engine= 'auto')
 
 wfFixSessionID ()
 
 wfResetSessionID ()
 
 wfSetupSession ($sessionId=false)
 
 wfGetPrecompiledData ($name)
 
 wfMemcKey ()
 
 wfForeignMemcKey ($db, $prefix)
 
 wfGlobalCacheKey ()
 
 wfWikiID ()
 
 wfSplitWikiID ($wiki)
 
 wfGetDB ($db, $groups=[], $wiki=false)
 
 wfGetLB ($wiki=false)
 
 wfGetLBFactory ()
 
 wfFindFile ($title, $options=[])
 
 wfLocalFile ($title)
 
 wfQueriesMustScale ()
 
 wfScript ($script= 'index')
 
 wfGetScriptUrl ()
 
 wfBoolToStr ($value)
 
 wfGetNull ()
 
 wfWaitForSlaves ($ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
 
 wfCountDown ($seconds)
 
 wfStripIllegalFilenameChars ($name)
 
 wfMemoryLimit ()
 
 wfTransactionalTimeLimit ()
 
 wfShorthandToInteger ($string= '', $default=-1)
 
 wfBCP47 ($code)
 
 wfGetCache ($cacheType)
 
 wfGetMainCache ()
 
 wfGetMessageCacheStorage ()
 
 wfGetParserCacheStorage ()
 
 wfRunHooks ($event, array $args=[], $deprecatedVersion=null)
 
 wfUnpack ($format, $data, $length=false)
 
 wfIsBadImage ($name, $contextTitle=false, $blacklist=null)
 
 wfCanIPUseHTTPS ($ip)
 
 wfIsInfinity ($str)
 
 wfThumbIsStandard (File $file, array $params)
 
 wfArrayPlus2d (array $baseArray, array $newValues)
 

Variables

const TS_UNIX 0
 
const TS_MW 1
 
const TS_DB 2
 
const TS_RFC2822 3
 
const TS_ISO_8601 4
 
const TS_EXIF 5
 
const TS_ORACLE 6
 
const TS_POSTGRES 7
 
const TS_ISO_8601_BASIC 9
 

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

Function Documentation

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

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

Parameters
string$accept
string$defDefault
Returns
float[] Associative array of string => float pairs
wfAppendQuery (   $url,
  $query 
)

Append a query string to an existing URL, which may or may not already have query string parameters already. If so, they will be combined.

Parameters
string$url
string|string[]$query String or associative array
Returns
string
wfAppendToArrayIfNotDefault (   $key,
  $value,
  $default,
$changed 
)

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

Parameters
string | int$key
mixed$value
mixed$default
array$changedArray to alter
Exceptions
MWException
wfArrayDiff2 (   $a,
  $b 
)

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

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

Insert array into another array after the specified KEY

Parameters
array$arrayThe array.
array$insertThe array to insert.
mixed$afterThe key to insert after
Returns
array
wfArrayPlus2d ( array  $baseArray,
array  $newValues 
)

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

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

Parameters
array$baseArrayThe array where you want to add the values of $newValues to
array$newValuesAn array with new values
Returns
array The combined array
Since
1.26
wfArrayToCgi (   $array1,
  $array2 = null,
  $prefix = '' 
)

This function takes one or two arrays as input, and returns a CGI-style string, e.g. "days=7&limit=100". Options in the first array override options in the second. Options set to null or false will not be output.

Parameters
array$array1( String|Array )
array | null$array2( String|Array )
string$prefix
Returns
string
wfAssembleUrl (   $urlParts)

This function will reassemble a URL parsed with wfParseURL. This is useful if you need to edit part of a URL and put it back together.

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

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

Get a debug backtrace as a string

Parameters
bool | null$rawIf true, the return value is plain text. If false, HTML. Defaults to $wgCommandLineMode if unset.
Returns
string
Since
1.25 Supports $raw parameter.
wfBaseConvert (   $input,
  $sourceBase,
  $destBase,
  $pad = 1,
  $lowercase = true,
  $engine = 'auto' 
)

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

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

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

Return the final portion of a pathname. Reimplemented because PHP5's "basename()" is buggy with multibyte text. http://bugs.php.net/bug.php?id=33898

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

Parameters
string$path
string$suffixString to remove if present
Returns
string
wfBCP47 (   $code)

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

Parameters
string$codeThe language code.
Returns
string The language code which complying with BCP 47 standards.
wfBoolToStr (   $value)

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

Parameters
bool$value
Returns
string
wfCanIPUseHTTPS (   $ip)

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

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

This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns the same string in array form. This allows compatibility with legacy functions that accept raw query strings instead of nice arrays. Of course, keys and values are urldecode()d.

Parameters
string$queryQuery string
Returns
string[] Array version of input
wfClearOutputBuffers ( )

More legible than passing a 'false' parameter to wfResetOutputBuffers():

Clear away output buffers, but keep the Content-Encoding header produced by ob_gzhandler, if any.

This should be used for HTTP 304 responses, where you need to preserve the Content-Encoding header of the real result, but also need to suppress the output of ob_gzhandler to keep to spec and avoid breaking Firefox in rare cases where the headers and body are broken over two packets.

wfClientAcceptsGzip (   $force = false)
Todo:

document

FIXME: We may want to blacklist some broken browsers

Parameters
bool$force
Returns
bool Whereas client accept gzip compression
wfConfiguredReadOnlyReason ( )

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

Returns
string|bool String when in read-only mode; false otherwise
Since
1.27
wfCountDown (   $seconds)

Count down from $seconds to zero on the terminal, with a one-second pause between showing each number. For use in command-line scripts.

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

Sends a line to the debug log if enabled or, optionally, to a comment in output. In normal operation this is a NOP.

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

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

Safety wrapper for debug_backtrace().

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

Parameters
int$limitThis parameter can be used to limit the number of stack frames returned
Returns
array Array of backtrace information
wfDebugLog (   $logGroup,
  $text,
  $dest = 'all',
array  $context = [] 
)

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

To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to a string filename or an associative array mapping 'destination' to the desired filename. The associative array may also contain a 'sample' key with an integer value, specifying a sampling factor. Sampled log events will be emitted with a 1 in N random chance.

Since
1.23 support for sampling log messages via $wgDebugLogGroups.
1.25 support for additional context data
1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
Parameters
string$logGroup
string$text
string | bool$destDestination of the message:
  • 'all': both to the log and HTML (debug toolbar or HTML comments)
  • 'private': only to the specific log if set in $wgDebugLogGroups and discarded otherwise For backward compatibility, it can also take a boolean:
  • true: same as 'all'
  • false: same as 'private'
array$contextAdditional logging context data
wfDebugMem (   $exact = false)

Send a line giving PHP memory usage.

Parameters
bool$exactPrint exact byte values instead of kibibytes (default: false)
wfDeprecated (   $function,
  $version = false,
  $component = false,
  $callerOffset = 2 
)

Throws a warning that $function is deprecated

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

Returns unified plain-text diff of two texts. "Useful" for machine processing of diffs.

Deprecated:
since 1.25, use DiffEngine/UnifiedDiffFormatter directly
Parameters
string$beforeThe text before the changes.
string$afterThe text after the changes.
string$paramsCommand-line options for the diff command.
Returns
string Unified diff of $before and $after
wfErrorLog (   $text,
  $file,
array  $context = [] 
)

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

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

Since
1.25 support for additional context data
Parameters
string$text
string$fileFilename
array$contextAdditional logging context data
Exceptions
MWException
Deprecated:
since 1.25 Use ::emit or UDPTransport
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.

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

Parameters
string... strings to escape and glue together, or a single array of strings parameter
Returns
string
wfEscapeWikiText (   $text)

Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc. making its way through. This is achieved by substituting certain characters with HTML entities. As required by the callers, "<nowiki>" is not used.

Parameters
string$textText to be escaped
Returns
string
wfExpandIRI (   $url)

Take a URL, make sure it's expanded to fully qualified, and replace any encoded non-ASCII Unicode characters with their UTF-8 original forms for more compact display and legibility for local audiences.

Todo:
handle punycode domains too
Parameters
string$url
Returns
string
wfExpandIRI_callback (   $matches)

Private callback for wfExpandIRI

Parameters
array$matches
Returns
string
wfExpandUrl (   $url,
  $defaultProto = PROTO_CURRENT 
)

Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer is correct.

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

Todo:
this won't work with current-path-relative URLs like "subdir/foo.html", etc.
Parameters
string$urlEither fully-qualified or a local path + query
string$defaultProtoOne of the PROTO_* constants. Determines the protocol to use if $url or $wgServer is protocol-relative
Returns
string Fully-qualified URL, current-path-relative URL or false if no valid URL can be constructed
wfFindFile (   $title,
  $options = [] 
)

Find a file. Shortcut for RepoGroup::singleton()->findFile()

Parameters
string$titleString or Title object
array$optionsAssociative array of options (see RepoGroup::findFile)
Returns
File|bool File, or false if the file does not exist
wfFixSessionID ( )
Deprecated:
since 1.27, PHP's session generation isn't used with MediaWiki
wfForeignMemcKey (   $db,
  $prefix 
)

Make a cache key for a foreign DB.

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

Parameters
string$db
string$prefix
string$args,...
Returns
string
wfFormatStackFrame (   $frame)

Return a string representation of frame

Parameters
array$frame
Returns
string
wfGetAllCallers (   $limit = 3)

Return a string consisting of callers in the stack. Useful sometimes for profiling specific points.

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

Get a specific cache object.

Parameters
int | string$cacheTypeA CACHE_* constants, or other key in $wgObjectCaches
Returns
BagOStuff
wfGetCaller (   $level = 2)

Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. FUNCTION) wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller() wfGetCaller( 3 ) is the parent of that.

Parameters
int$level
Returns
string
wfGetDB (   $db,
  $groups = [],
  $wiki = false 
)

Get a Database object.

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

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

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

Returns
DatabaseBase
wfGetLangObj (   $langcode = false)

Return a Language object from $langcode

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

Get a load balancer object.

Parameters
string | bool$wikiWiki ID, or false for the current wiki
Returns
LoadBalancer
wfGetLBFactory ( )

Get the load balancer factory object

Returns
LBFactory
wfGetMainCache ( )

Get the main cache object

Returns
BagOStuff
wfGetMessageCacheStorage ( )

Get the cache object used by the message cache

Returns
BagOStuff
wfGetNull ( )

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

Returns
string
wfGetParserCacheStorage ( )

Get the cache object used by the parser cache

Returns
BagOStuff
wfGetPrecompiledData (   $name)

Get an object from the precompiled serialized directory

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

Get the script URL.

Returns
string Script URL
wfGlobalCacheKey ( )

Make a cache key with database-agnostic prefix.

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

Since
1.26
Parameters
string$args,...
Returns
string
wfHostname ( )

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
wfHttpError (   $code,
  $label,
  $desc 
)

Provide a simple HTTP error.

Parameters
int | string$code
string$label
string$desc
wfIncrStats (   $key,
  $count = 1 
)

Increment a statistics counter

Parameters
string$key
int$count
Returns
void
wfIniGetBool (   $setting)

Safety wrapper around ini_get() for boolean settings. The values returned from ini_get() are pre-normalized for settings set via php.ini or php_flag/php_admin_flag... but not for those set via php_value/php_admin_value.

It's fairly common for people to use php_value instead of php_flag, which can leave you with an 'off' setting giving a false positive for code that just takes the ini_get() return value as a boolean.

To make things extra interesting, setting via php_value accepts "true" and "yes" as true, but php.ini and php_flag consider them false. :) Unrecognized values go false... again opposite PHP's own coercion from string to bool.

Luckily, 'properly' set settings will always come back as '0' or '1', so we only have to worry about them and the 'improper' settings.

I frickin' hate PHP... :P

Parameters
string$setting
Returns
bool
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'.

The format of MediaWiki:Bad_image_list is as follows:

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

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

Returns
bool
wfIsHHVM ( )

Check if we are running under HHVM

Returns
bool
wfIsInfinity (   $str)

Determine input string is represents as infinity

Parameters
string$strThe string to determine
Returns
bool
Since
1.25
wfIsWindows ( )

Check if the operating system is Windows

Returns
bool True if it's Windows, false otherwise.
wfLoadExtension (   $ext,
  $path = null 
)

Load an extension

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

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

Load multiple extensions at once

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

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

See Also
wfLoadExtension
Parameters
string[]$exts Array of extension names to load
Since
1.25
wfLoadSkin (   $skin,
  $path = null 
)

Load a skin

See Also
wfLoadExtension
Parameters
string$skinName of the extension to load
string | null$pathAbsolute path of where to find the skin.json file
Since
1.25
wfLoadSkins ( array  $skins)

Load multiple skins at once

See Also
wfLoadExtensions
Parameters
string[]$skins Array of extension names to load
Since
1.25
wfLocalFile (   $title)

Get an object referring to a locally registered file. Returns a valid placeholder object if the file does not exist.

Parameters
Title | string$title
Returns
LocalFile|null A File, or null if passed an invalid Title
wfLogDBError (   $text,
array  $context = [] 
)

Log for database errors

Since
1.25 support for additional context data
Parameters
string$textDatabase error message.
array$contextAdditional logging context data
wfLogProfilingData ( )
Todo:
document
wfLogWarning (   $msg,
  $callerOffset = 1,
  $level = E_USER_WARNING 
)

Send a warning as a PHP error and the debug log. This is intended for logging warnings in production. For logging development warnings, use WfWarn instead.

Parameters
string$msgMessage to send
int$callerOffsetNumber of items to go back in the backtrace to find the correct caller (1 = function calling wfLogWarning, ...)
int$levelPHP error level; defaults to E_USER_WARNING
wfMakeUrlIndexes (   $url)

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

Parameters
string$url
Returns
array
wfMatchesDomainList (   $url,
  $domains 
)

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

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

Make a cache key for the local wiki.

Parameters
string$args,...
Returns
string
wfMemoryLimit ( )

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

Returns
int Resulting value of the memory limit.
wfMerge (   $old,
  $mine,
  $yours,
$result 
)

wfMerge attempts to merge differences between three texts. Returns true for a clean merge and false for failure or a conflict.

Parameters
string$old
string$mine
string$yours
string$result
Returns
bool
wfMergeErrorArrays ( )

Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g. wfMergeErrorArrays( array( array( 'x' ) ), array( array( 'x', '2' ) ), array( array( 'x' ) ), array( array( 'y' ) ) ); returns: array( array( 'x', '2' ), array( 'x' ), array( 'y' ) )

Parameters
array$array1,...
Returns
array
wfMessage (   $key)

This is the function for getting translated interface messages.

See Also
Message class for documentation how to use them.
https://www.mediawiki.org/wiki/Manual:Messages_API

This function replaces all old wfMsg* functions.

Parameters
string|string[]|MessageSpecifier$key Message key, or array of keys, or a MessageSpecifier
mixed$params,...Normal message parameters
Returns
Message
Since
1.17
See Also
Message::__construct
wfMessageFallback ( )

This function accepts multiple message keys and returns a message instance for the first message which is non-empty. If all messages are empty then an instance of the first message key is returned.

Parameters
string|string[]$keys,... Message keys
Returns
Message
Since
1.18
See Also
Message::newFallbackSequence
wfMkdirParents (   $dir,
  $mode = null,
  $caller = null 
)

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

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

Returns the 'best' match between a client's requested internet media types and the server's list of available types. Each list should be an associative array of type to preference (preference is a float between 0.0 and 1.0). Wildcards in the types are acceptable.

Parameters
array$cprefsClient's acceptable type list
array$sprefsServer's offered types
Returns
string
Todo:
FIXME: Doesn't handle params like 'text/plain; charset=UTF-8' XXX: generalize to negotiate other stuff
wfObjectToArray (   $objOrArray,
  $recursive = true 
)

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

Parameters
object | array$objOrArray
bool$recursive
Returns
array
wfParseUrl (   $url)

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

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

Parameters
string$urlA URL to parse
Returns
string[] Bits of the URL in an associative array, per PHP docs
wfPercent (   $nr,
  $acc = 2,
  $round = true 
)
Parameters
int$nrThe number to format
int$accThe number of digits after the decimal point, default 2
bool$roundWhether or not to round the value, default true
Returns
string
wfQueriesMustScale ( )

Should low-performance queries be disabled?

Returns
bool
wfRandom ( )

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

Note
This is designed for use in relation to Special:RandomPage and the page_random database field.
Returns
string
wfRandomString (   $length = 32)

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

Note
This is not secure, if you are trying to generate some sort of token please use MWCryptRand instead.
Parameters
int$lengthThe length of the string to generate
Returns
string
Since
1.20
wfReadOnly ( )

Check whether the wiki is in read-only mode.

Returns
bool
wfReadOnlyReason ( )

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

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

Returns
string|bool String when in read-only mode; false otherwise
wfRecursiveRemoveDir (   $dir)

Remove a directory and all its content. Does not hide error.

Parameters
string$dir
wfRelativePath (   $path,
  $from 
)

Generate a relative path name to the given file. May explode on non-matching case-insensitive paths, funky symlinks, etc.

Parameters
string$pathAbsolute destination path including target filename
string$fromAbsolute source path, directory only
Returns
string
wfRemoveDotSegments (   $urlPath)

Remove all dot-segments in the provided URL path. For example, '/a/./b/../c/' becomes '/a/c/'. For details on the algorithm, please see RFC3986 section 5.2.4.

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

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

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

Returns
string
wfResetOutputBuffers (   $resetGzipEncoding = true)

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

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

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

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

Parameters
bool$resetGzipEncoding
wfResetSessionID ( )

Reset the session id

Deprecated:
since 1.27, use MediaWiki instead
Since
1.22
wfRestoreWarnings ( )
Deprecated:
since 1.26, use MediaWiki() directly Restore error level to previous value
wfRunHooks (   $event,
array  $args = [],
  $deprecatedVersion = null 
)

Call hook functions defined in $wgHooks

Parameters
string$eventEvent name
array$argsParameters passed to hook functions
string | null$deprecatedVersionOptionally mark hook as deprecated with version number
Returns
bool True if no handler aborted the hook
Deprecated:
1.25 - use Hooks::run
wfScript (   $script = 'index')

Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScriptPath etc. except for 'index' and 'load' which use $wgScript/$wgLoadScript

Parameters
string$scriptScript filename, sans extension
Returns
string
wfSetBit ( $dest,
  $bit,
  $state = true 
)

As for wfSetVar except setting a bit

Parameters
int$dest
int$bit
bool$state
Returns
bool
wfSetupSession (   $sessionId = false)

Initialise php session

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

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

Parameters
mixed$dest
mixed$source
bool$force
Returns
mixed
wfShellExec (   $cmd,
$retval = null,
  $environ = [],
  $limits = [],
  $options = [] 
)

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

Parameters
string|string[]$cmd If string, a properly shell-escaped command line, or an array of unescaped arguments, in which case each value will be escaped Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
null | mixed&$retvalOptional, will receive the program's exit code. (non-zero is usually failure). If there is an error from read, select, or proc_open(), this will be set to -1.
array$environOptional environment variables which should be added to the executed command environment.
array$limitsOptional array with limits(filesize, memory, time, walltime) this overwrites the global wgMaxShell* limits.
array$optionsArray of options:
  • duplicateStderr: Set this to true to duplicate stderr to stdout, including errors from limit.sh
  • profileMethod: By default this function will profile based on the calling method. Set this to a string for an alternative method to profile from
Returns
string Collected stdout as a string
wfShellExecDisabled ( )

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

Returns
bool|string False or 'disabled'
Since
1.22
wfShellExecWithStderr (   $cmd,
$retval = null,
  $environ = [],
  $limits = [] 
)

Execute a shell command, returning both stdout and stderr. Convenience function, as all the arguments to wfShellExec can become unwieldy.

Note
This also includes errors from limit.sh, e.g. if $wgMaxShellFileSize is exceeded.
Parameters
string|string[]$cmd If string, a properly shell-escaped command line, or an array of unescaped arguments, in which case each value will be escaped Example: [ 'convert', '-font', 'font name' ] would produce "'convert' '-font' 'font name'"
null | mixed&$retvalOptional, will receive the program's exit code. (non-zero is usually failure)
array$environOptional environment variables which should be added to the executed command environment.
array$limitsOptional array with limits(filesize, memory, time, walltime) this overwrites the global wgMaxShell* limits.
Returns
string Collected stdout and stderr as a string
wfShellWikiCmd (   $script,
array  $parameters = [],
array  $options = [] 
)

Generate a shell-escaped command line string to run a MediaWiki cli script. Note that $parameters should be a flat array and an option with an argument should consist of two consecutive items in the array (do not use "--option value").

Parameters
string$scriptMediaWiki cli script path
array$parametersArguments and options to the script
array$optionsAssociative array of options: 'php': The path to the php executable 'wrapper': Path to a PHP wrapper to handle the maintenance script
Returns
string
wfShorthandToInteger (   $string = '',
  $default = -1 
)

Converts shorthand byte notation to integer form

Parameters
string$string
int$defaultReturned if $string is empty
Returns
int
wfShowingResults (   $offset,
  $limit 
)
Todo:
document
Parameters
int$offset
int$limit
Returns
string
wfSplitWikiID (   $wiki)

Split a wiki ID into DB name and table prefix

Parameters
string$wiki
Returns
array
wfStripIllegalFilenameChars (   $name)

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

Parameters
string$nameFilename to process
Returns
string
wfSuppressWarnings (   $end = false)

Reference-counted warning suppression

Deprecated:
since 1.26, use MediaWiki() directly
Parameters
bool$end
wfTempDir ( )

Tries to get the system directory for temporary files. First $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP environment variables are then checked in sequence, then sys_get_temp_dir(), then upload_tmp_dir from php.ini.

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

Returns
string

PHP on Windows will detect C: as not writable even though PHP can write to it so create a directory within that called 'mwtmp' with a suffix of the user running the current process. The user is included as if various scripts are run by different users they will likely not be able to access each others temporary files.

wfThumbIsStandard ( File  $file,
array  $params 
)

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

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

Parameters
File$file
array$params
Returns
bool
Since
1.24 Moved from thumb.php to GlobalFunctions in 1.25
wfTimestamp (   $outputtype = TS_UNIX,
  $ts = 0 
)

Get a timestamp string in one of various formats

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

Convenience function; returns MediaWiki timestamp for the present time.

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

Return a formatted timestamp, or null if input is null. For dealing with nullable timestamp columns in the database.

Parameters
int$outputtype
string$ts
Returns
string
wfTransactionalTimeLimit ( )

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

Returns
int Prior time limit
Since
1.26
wfUnpack (   $format,
  $data,
  $length = false 
)

Wrapper around php's unpack.

Parameters
string$formatThe format string (See php's docs)
string$dataA binary string of binary data
int | bool$lengthThe minimum length of $data or false. This is to prevent reading beyond the end of $data. false to disable the check.

Also be careful when using this function to read unsigned 32 bit integer because php might make it negative.

Exceptions
MWExceptionIf $data not long enough, or if unpack fails
Returns
array Associative array of the extracted data
wfUrlencode (   $s)

We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default. According to RFC 1738, all of the following should be safe:

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

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

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

;:$!*(),/~

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

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

Parameters
string$s
Returns
string
wfUrlProtocols (   $includeProtocolRelative = true)

Returns a regular expression of url protocols

Parameters
bool$includeProtocolRelativeIf false, remove '//' from the returned protocol list. DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
Returns
string
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
wfUseMW (   $req_ver)

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

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

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

See Also
perldoc -f use
Deprecated:
since 1.26, use the "requires' property of extension.json
Parameters
string | int | float$req_verThe version to check, can be a string, an integer, or a float
Exceptions
MWException
wfUsePHP (   $req_ver)

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

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

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

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

A wrapper around the PHP function var_export(). Either print it or add it to the regular output ($wgOut).

Parameters
mixed$varA PHP variable to dump.
wfWaitForSlaves (   $ifWritesSince = null,
  $wiki = false,
  $cluster = false,
  $timeout = null 
)

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.

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

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

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

Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.

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

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

Returns
string

Variable Documentation

const TS_DB 2

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

const TS_EXIF 5

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.
const TS_ISO_8601 4

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

This is used by Special:Export

const TS_ISO_8601_BASIC 9

ISO 8601 basic format with no timezone: 19860209T200000Z. This is used by ResourceLoader

const TS_MW 1

MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)

const TS_ORACLE 6

Oracle format time.

const TS_POSTGRES 7

Postgres format time.

const TS_RFC2822 3

RFC 2822 format, for E-mail and HTTP headers

const TS_UNIX 0

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