MediaWiki REL1_35
GlobalFunctions.php File Reference

Global functions used everywhere. More...

Go to the source code of this file.

Functions

 mimeTypeMatch ( $type, $avail)
 Checks if a given MIME type matches any of the keys in the given array.
 
 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.
 
 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
 
 wfArrayPlus2d (array $baseArray, array $newValues)
 Merges two (possibly) 2 dimensional arrays into the target array ($baseArray).
 
 wfArrayToCgi ( $array1, $array2=null, $prefix='')
 This function takes one or two arrays as input, and returns a CGI-style string, e.g.
 
 wfAssembleUrl ( $urlParts)
 This function will reassemble a URL parsed with wfParseURL.
 
 wfBacktrace ( $raw=null)
 Get a debug backtrace as a string.
 
 wfBaseName ( $path, $suffix='')
 Return the final portion of a pathname.
 
 wfBoolToStr ( $value)
 Convenience function converts boolean values into "true" or "false" (string) values.
 
 wfCanIPUseHTTPS ( $ip)
 Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
 
 wfCgiToArray ( $query)
 This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns the same string in array form.
 
 wfClearOutputBuffers ()
 More legible than passing a 'false' parameter to wfResetOutputBuffers():
 
 wfClientAcceptsGzip ( $force=false)
 Whether the client accept gzip encoding.
 
 wfConfiguredReadOnlyReason ()
 Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
 
 wfDebug ( $text, $dest='all', array $context=[])
 Sends a line to the debug log if enabled or, optionally, to a comment in output.
 
 wfDebugBacktrace ( $limit=0)
 Safety wrapper for debug_backtrace().
 
 wfDebugLog ( $logGroup, $text, $dest='all', array $context=[])
 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.
 
 wfDeprecated ( $function, $version=false, $component=false, $callerOffset=2)
 Logs a warning that $function is deprecated.
 
 wfDeprecatedMsg ( $msg, $version=false, $component=false, $callerOffset=2)
 Log a deprecation warning with arbitrary message text.
 
 wfDiff ( $before, $after, $params='-u')
 Returns unified plain-text diff of two texts.
 
 wfEscapeShellArg (... $args)
 Version of escapeshellarg() that works better on Windows.
 
 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.
 
 wfExpandUrl ( $url, $defaultProto=PROTO_CURRENT)
 Expand a potentially local URL to a fully-qualified URL.
 
 wfFindFile ( $title, $options=[])
 Find a file.
 
 wfForeignMemcKey ( $db, $prefix,... $args)
 Make a cache key for a foreign DB.
 
 wfFormatStackFrame ( $frame)
 Return a string representation of frame.
 
 wfGetAllCallers ( $limit=3)
 Return a string consisting of callers in the stack.
 
 wfGetCache ( $cacheType)
 Get a specific 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=[], $wiki=false)
 Get a Database object.
 
 wfGetLangObj ( $langcode=false)
 Return a Language object from $langcode.
 
 wfGetLB ( $wiki=false)
 Get a load balancer object.
 
 wfGetMainCache ()
 Get the main cache object.
 
 wfGetNull ()
 Get a platform-independent path to the null file, e.g.
 
 wfGetPrecompiledData ( $name)
 Get an object from the precompiled serialized directory.
 
 wfGetRusage ()
 Get system resource usage of current request context.
 
 wfGetScriptUrl ()
 Get the script URL.
 
 wfGetServerUrl ( $proto)
 Get the wiki's "server", i.e.
 
 wfHostname ()
 Get host name of the current machine, for use in error reporting.
 
 wfHttpError ( $code, $label, $desc)
 Provide a simple HTTP error.
 
 wfIncrStats ( $key, $count=1)
 Increment a statistics counter.
 
 wfIniGetBool ( $setting)
 Safety wrapper around ini_get() for boolean settings.
 
 wfIsBadImage ( $name, $contextTitle=false)
 Determine if an image exists on the 'bad image list'.
 
 wfIsCLI ()
 Check if we are running from the commandline.
 
 wfIsDebugRawPage ()
 Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
 
 wfIsInfinity ( $str)
 Determine input string is represents as infinity.
 
 wfIsWindows ()
 Check if the operating system is Windows.
 
 wfLoadExtension ( $ext, $path=null)
 Load an extension.
 
 wfLoadExtensions (array $exts)
 Load multiple extensions at once.
 
 wfLoadSkin ( $skin, $path=null)
 Load a skin.
 
 wfLoadSkins (array $skins)
 Load multiple skins at once.
 
 wfLocalFile ( $title)
 Get an object referring to a locally registered file.
 
 wfLogDBError ( $text, array $context=[])
 Log for database errors.
 
 wfLogProfilingData ()
 
 wfLogWarning ( $msg, $callerOffset=1, $level=E_USER_WARNING)
 Send a warning as a PHP error and the debug log.
 
 wfMatchesDomainList ( $url, $domains)
 Check whether a given URL has a domain that occurs in a given set of domains.
 
 wfMemcKey (... $args)
 Make a cache key for the local wiki.
 
 wfMemoryLimit ( $newLimit)
 Raise PHP's memory limit (if needed).
 
 wfMerge ( $old, $mine, $yours, &$result, &$mergeAttemptResult=null)
 wfMerge attempts to merge differences between three texts.
 
 wfMergeErrorArrays (... $args)
 Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e.g.
 
 wfMessage ( $key,... $params)
 This is the function for getting translated interface messages.
 
 wfMessageFallback (... $keys)
 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.
 
 wfMsgReplaceArgs ( $message, $args)
 Replace message parameter keys on the given formatted output.
 
 wfNegotiateType ( $cprefs, $sprefs)
 Returns the 'best' match between a client's requested internet media types and the server's list of available types.
 
 wfObjectToArray ( $objOrArray, $recursive=true)
 Recursively converts the parameter (an object) to an array with the same data.
 
 wfParseUrl ( $url)
 parse_url() work-alike, but non-broken.
 
 wfPercent ( $nr, int $acc=2, bool $round=true)
 
 wfQueriesMustScale ()
 Should low-performance queries be disabled?
 
 wfRandom ()
 Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for any realistic number of articles.
 
 wfRandomString ( $length=32)
 Get a random string containing a number of pseudo-random hex characters.
 
 wfReadOnly ()
 Check whether the wiki is in read-only mode.
 
 wfReadOnlyReason ()
 Check if the site is in read-only mode and return the message if so.
 
 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 ( $nonce=null)
 Returns a script tag that stores the amount of time it took MediaWiki to handle the request in milliseconds as 'wgBackendResponseTime'.
 
 wfResetOutputBuffers ( $resetGzipEncoding=true)
 Clear away any user-level output buffers, discarding contents.
 
 wfScript ( $script='index')
 Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScriptPath etc.
 
 wfSetBit (&$dest, $bit, $state=true)
 As for wfSetVar except setting a bit.
 
 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=[], $limits=[], $options=[])
 Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported.
 
 wfShellExecWithStderr ( $cmd, &$retval=null, $environ=[], $limits=[])
 Execute a shell command, returning both stdout and stderr.
 
 wfShellWikiCmd ( $script, array $parameters=[], array $options=[])
 Generate a shell-escaped command line string to run a MediaWiki cli script.
 
 wfShorthandToInteger (?string $string='', int $default=-1)
 Converts shorthand byte notation to integer form.
 
 wfShowingResults ( $offset, $limit)
 
 wfStringToBool ( $val)
 Convert string value to boolean, when the following are interpreted as true:
 
 wfStripIllegalFilenameChars ( $name)
 Replace all invalid characters with '-'.
 
 wfTempDir ()
 Tries to get the system directory for 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.
 
 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.
 
 wfTransactionalTimeLimit ()
 Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit.
 
 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.
 
 wfVarDump ( $var)
 A wrapper around the PHP function var_export().
 
 wfWaitForSlaves ( $ifWritesSince=null, $wiki=false, $cluster=false, $timeout=null)
 Waits for the replica DBs to catch up to the master position.
 
 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.

Function Documentation

◆ mimeTypeMatch()

mimeTypeMatch (   $type,
  $avail 
)

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

Basic wildcards are accepted in the array keys.

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

Parameters
string$type
array$avail
Returns
string

Definition at line 1730 of file GlobalFunctions.php.

References $type.

Referenced by wfNegotiateType().

◆ wfAcceptToPrefs()

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

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

Parameters
string$accept
string$defDefault
Returns
float[] Associative array of string => float pairs

Definition at line 1694 of file GlobalFunctions.php.

◆ wfAppendQuery()

◆ wfAppendToArrayIfNotDefault()

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

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

Parameters
string | int$key
mixed$value
mixed$default
array&$changedArray to alter
Exceptions
MWException

Definition at line 152 of file GlobalFunctions.php.

◆ wfArrayDiff2()

wfArrayDiff2 (   $a,
  $b 
)

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

Parameters
array$a
array$b
Returns
array

Definition at line 112 of file GlobalFunctions.php.

Referenced by WikiPage\doRollback(), EditPage\getEditPermissionErrors(), and UploadBase\verifyTitlePermissions().

◆ wfArrayDiff2_cmp()

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

Definition at line 121 of file GlobalFunctions.php.

◆ wfArrayInsertAfter()

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

Insert array into another array after the specified KEY

Parameters
array$arrayThe array.
array$insertThe array to insert.
mixed$afterThe key to insert after. Callers need to make sure the key is set.
Returns
array

Definition at line 206 of file GlobalFunctions.php.

References $keys.

Referenced by ApiComparePages\getAllowedParams(), SpecialDeletedContributions\getSubTitle(), and UpdateExtensionJsonSchema\updateTo2().

◆ wfArrayPlus2d()

wfArrayPlus2d ( array  $baseArray,
array  $newValues 
)

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

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

Parameters
array$baseArrayThe array where you want to add the values of $newValues to
array$newValuesAn array with new values
Returns
array The combined array
Since
1.26

Definition at line 2935 of file GlobalFunctions.php.

Referenced by HTMLUserTextField\__construct(), and ExtensionRegistry\exportExtractedData().

◆ wfArrayToCgi()

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

◆ wfAssembleUrl()

wfAssembleUrl (   $urlParts)

This function will reassemble a URL parsed with wfParseURL.

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

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

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

Definition at line 586 of file GlobalFunctions.php.

Referenced by ApiCSPReport\matchUrlPattern(), ApiCSPReport\originFromUrl(), and wfExpandUrl().

◆ wfBacktrace()

wfBacktrace (   $raw = null)

Get a debug backtrace as a string.

Parameters
bool | null$rawIf true, the return value is plain text. If false, HTML. Defaults to $wgCommandLineMode if unset.
Returns
string
Since
1.25 Supports $raw parameter.

Definition at line 1354 of file GlobalFunctions.php.

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

Referenced by MediaWiki\Revision\RevisionStore\constructSlotRecords(), MediaWiki\Revision\RevisionStore\ensureRevisionRowMatchesTitle(), MediaWiki\Revision\RevisionStore\getTitle(), MediaWiki\Revision\RevisionStore\loadSlotRecords(), and MWDebug\sendRawDeprecated().

◆ wfBaseName()

wfBaseName (   $path,
  $suffix = '' 
)

Return the final portion of a pathname.

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

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

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

Definition at line 2308 of file GlobalFunctions.php.

References $matches, and $path.

Referenced by Exif\__construct(), ImageBuilder\checkMissingImage(), FileOpPerfTest\doPerfTest(), ImportImages\execute(), wfImageAuthMain(), wfRelativePath(), and wfStripIllegalFilenameChars().

◆ wfBoolToStr()

wfBoolToStr (   $value)

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

Parameters
bool$value
Returns
string

Definition at line 2572 of file GlobalFunctions.php.

Referenced by ApiRsd\formatRsdApiList().

◆ wfCanIPUseHTTPS()

wfCanIPUseHTTPS (   $ip)

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

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

Definition at line 2817 of file GlobalFunctions.php.

Referenced by LoginSignupSpecialPage\execute(), MediaWiki\Preferences\DefaultPreferencesFactory\getFormDescriptor(), and User\requiresHTTPS().

◆ wfCgiToArray()

wfCgiToArray (   $query)

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

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

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

Definition at line 391 of file GlobalFunctions.php.

References $keys.

Referenced by SkinTemplate\buildPersonalUrls(), Linker\makeBrokenImageLinkObj(), SpecialChangeEmail\onSuccess(), OutputPage\returnToMain(), LoginHelper\showReturnToPage(), MediaWiki\Storage\SqlBlobStore\splitBlobAddress(), and SpecialCreateAccount\successfulAction().

◆ wfClearOutputBuffers()

wfClearOutputBuffers ( )

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

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

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

Definition at line 1682 of file GlobalFunctions.php.

References wfResetOutputBuffers().

Referenced by ApiMain\checkConditionalRequestHeaders(), and OutputPage\checkLastModified().

◆ wfClientAcceptsGzip()

wfClientAcceptsGzip (   $force = false)

Whether the client accept gzip encoding.

Uses the Accept-Encoding header to check if the client supports gzip encoding. Use this when considering to send a gzip-encoded response to the client.

Parameters
bool$forceForces another check even if we already have a cached result.
Returns
bool

Definition at line 1453 of file GlobalFunctions.php.

References wfDebug().

Referenced by MediaWiki\OutputHandler\handleGzip(), HTMLFileCache\loadFromFileCache(), and HTMLFileCache\saveToFileCache().

◆ wfConfiguredReadOnlyReason()

wfConfiguredReadOnlyReason ( )

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

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

Definition at line 1150 of file GlobalFunctions.php.

Referenced by JobQueueGroup\singleton().

◆ wfDebug()

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

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

In normal operation this is a NOP.

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

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

Definition at line 910 of file GlobalFunctions.php.

References $wgDebugLogPrefix, $wgDebugRawPage, and wfIsDebugRawPage().

Referenced by ApiMain\__construct(), DifferenceEngine\__construct(), UploadStashFile\__construct(), PageArchive\__construct(), UploadFromStash\__construct(), QuickTemplate\__construct(), ParserFactory\__construct(), UploadFromChunks\__construct(), StubObject\_unstub(), LogPage\actionText(), ImageGalleryBase\add(), MediaHandler\addMeta(), LinkBatch\addObj(), LocalFileMoveBatch\addOlds(), ParserOutput\addTrackingCategory(), Skin\afterContentHook(), Linker\blockLink(), SkinTemplate\buildContentActionUrls(), EmailNotification\canSendUserTalkEmail(), OutputPage\checkLastModified(), UploadBase\checkSvgScriptCallback(), UploadBase\checkXMLEncodingMissmatch(), JobQueueDB\claimOldest(), LocalRepo\cleanupDeletedBatch(), UploadBase\cleanupTempFile(), SpecialEditWatchlist\cleanupWatchlist(), UploadStash\clear(), CloneDatabase\cloneTableStructure(), MediaWiki\Storage\SqlBlobStore\compressData(), UploadFromChunks\concatenateChunks(), Article\confirmDelete(), DjVuImage\convertDumpToXML(), UploadBase\createFromRequest(), WikiImporter\debug(), SVGReader\debug(), RecompressTracked\debug(), SectionProfiler\debug(), BaseDump\debug(), MediaWiki\Block\DatabaseBlock\defaultRetroactiveAutoblock(), Article\delete(), MediaWiki\Block\DatabaseBlock\deleteIfExpired(), ChangeTags\deleteTagEverywhere(), UploadBase\detectScript(), UploadBase\detectVirus(), DiffEngine\diffInternal(), BitmapMetadataHandler\doApp13(), MediaWiki\Block\DatabaseBlock\doAutoblock(), JobQueueDB\doBatchPushInternal(), WikiPage\doDeleteArticleBatched(), WikiPage\doDeleteArticleReal(), WikiFilePage\doPurge(), MediaWiki\Block\DatabaseBlock\doRetroactiveAutoblock(), UserrightsPage\doSaveUserGroups(), DjVuHandler\doTransform(), TransformationalImageHandler\doTransform(), MediaWiki\Storage\DerivedPageDataUpdater\doUpdates(), EditPage\edit(), ZipDirectoryReader\error(), SpecialUpload\execute(), LocalFileRestoreBatch\execute(), DjVuHandler\extractTreesFromMetadata(), MediaWiki\Storage\SqlBlobStore\fetchBlobs(), IcuCollation\fetchFirstLetterData(), Article\fetchRevisionRecord(), DiffEngine\find_middle_snake(), BlockLevelPass\findColonNoLinks(), WikiImporter\finishImportPage(), FormatMetadata\flattenArrayReal(), ContribsPager\formatRow(), DeletedContribsPager\formatRow(), FileRepo\freeTemp(), LCStoreCDB\get(), ParserCache\get(), MediaWiki\Interwiki\ClassicInterwikiLookup\getAllPrefixesCached(), User\getBlockedStatus(), PreferencesFormOOUI\getBody(), CoreParserFunctions\getCachedRevisionObject(), PoolWorkArticleView\getCachedWork(), Action\getContext(), ContextSource\getContext(), Article\getContext(), Profiler\getContext(), SpecialPage\getContext(), SpecialVersion\getCreditsForExtension(), WikiPage\getDeletionUpdates(), File\getDescriptionText(), ForeignDBFile\getDescriptionText(), DifferenceEngine\getEngine(), UploadStash\getFile(), DoubleRedirectJob\getFinalDestination(), WikiFilePage\getForeignCategories(), GenderCache\getGenderOf(), MediaHandlerFactory\getHandler(), DjVuImage\getInfo(), SpecialUpload\getInitialPageText(), MediaWiki\Interwiki\ClassicInterwikiLookup\getInterwikiCacheEntry(), ParserCache\getKey(), TransformationalImageHandler\getMagickVersion(), RequestContext\getMainAndWarn(), SvgHandler\getMetadata(), GIFMetadataExtractor\getMetadata(), PNGMetadataExtractor\getMetadata(), GIFHandler\getMetadata(), JpegHandler\getMetadata(), PNGHandler\getMetadata(), TiffHandler\getMetadata(), DjVuHandler\getMetadata(), DjVuHandler\getMetaTree(), DjVuImage\getMultiPageInfo(), WebRequestUpload\getName(), Title\getNsText(), DjVuImage\getPageInfo(), WikiPage\getParserOutput(), SpecialEmailUser\getPermissionsError(), EditPage\getPreloadedContent(), UserCache\getProp(), Title\getRestrictionTypes(), SpecialEmailUser\getTarget(), ForeignAPIRepo\getThumbError(), ForeignAPIRepo\getThumbUrl(), UploadStashFile\getThumbUrl(), ForeignAPIRepo\getThumbUrlFromCache(), Title\getTitleValue(), File\getViewURL(), XCFHandler\getXCFMetaData(), MediaWiki\OutputHandler\handleGzip(), OutputPage\haveCacheVaryCookies(), ThumbnailRenderJob\hitThumbUrl(), ForeignAPIRepo\httpGet(), EditPage\importFormData(), WikiRevision\importLogItem(), MediaWiki\Block\DatabaseBlock\insert(), EditPage\internalAttemptSave(), FileCacheBase\isCacheGood(), MediaWiki\Shell\Shell\isDisabled(), DjVuHandler\isEnabled(), SvgHandler\isEnabled(), MediaWiki\Block\DatabaseBlock\isExpired(), FileDependency\isExpired(), ExifBitmapHandler\isMetadataValid(), GIFHandler\isMetadataValid(), PNGHandler\isMetadataValid(), WebPHandler\isMetadataValid(), MovePage\isValidMoveTarget(), MediaWiki\Block\DatabaseBlock\isWhitelistedFromAutoblocks(), SiteStats\loadAndLazyInit(), User\loadFromCache(), HTMLFileCache\loadFromFileCache(), PopulateArchiveRevId\makeDummyRevisionRow(), Linker\makeExternalImage(), Linker\makeExternalLink(), Linker\makeImageLink(), Linker\makeMediaLinkFile(), ImportStreamSource\newFromURL(), WikiImporter\notice(), RawAction\onView(), DumpUploads\outputItem(), SearchMySQL\parseQuery(), SearchSqlite\parseQuery(), SearchPostgres\parseQuery(), BacklinkCache\partition(), DiffHistoryBlob\patch(), AjaxDispatcher\performAction(), ApiUpload\performStash(), MediaWiki\preOutputCommit(), SkinTemplate\prepareQuickTemplate(), SpecialUpload\processUpload(), LocalFile\purgeThumbList(), BacklinkCache\queryLinks(), SvgHandler\rasterize(), TextPassDumper\readDump(), UploadStash\removeFileNoAuth(), WikiPage\replaceSectionAtRev(), MediaWiki\restInPeace(), DjVuImage\retrieveMetaData(), BitmapHandler\rotate(), DoubleRedirectJob\run(), ParserCache\save(), FileCacheBase\saveText(), HTMLFileCache\saveToFileCache(), SearchPostgres\searchQuery(), JpegMetadataExtractor\segmentSplitter(), UserMailer\send(), OutputPage\sendCacheControl(), UserMailer\sendInternal(), UserMailer\sendWithPear(), ApiMain\setCacheMode(), ManualLogEntry\setTags(), ViewAction\show(), LocalRepo\skipWriteOperationIfSha1(), User\spreadBlock(), UploadStash\stashFile(), FileRepo\storeBatch(), WikiImporter\throwXmlError(), MediaWiki\Tidy\RemexDriver\tidy(), MediaWiki\Tidy\RemexCompatMunger\trace(), File\transform(), BitmapHandler\transformCustom(), BitmapHandler\transformGd(), BitmapHandler\transformImageMagick(), BitmapHandler\transformImageMagickExt(), LocalisationCacheBulkLoad\trimCache(), SpecialUploadStash\tryClearStashedUploads(), Article\tryFileCache(), PageArchive\undeleteAsUser(), PageArchive\undeleteRevisions(), MediaWiki\Block\DatabaseBlock\update(), UploadFromChunks\updateChunkStatus(), LocalFile\upgradeRow(), OldLocalFile\upgradeRow(), MediaWiki\Revision\RevisionRecord\userCanBitfield(), LogEventsList\userCanBitfield(), Linker\userLink(), Linker\userTalkLink(), Linker\userToolLinks(), SpecialEmailUser\validateTarget(), ImageHandler\validateThumbParams(), UploadBase\verifyExtension(), UploadBase\verifyFile(), UploadBase\verifyMimeType(), ApiUpload\verifyUpload(), Article\view(), WikiImporter\warn(), wfApiMain(), wfClientAcceptsGzip(), wfDebugBacktrace(), wfDebugMem(), wfDiff(), wfGetLangObj(), wfMemoryLimit(), wfMerge(), wfMkdirParents(), wfRecursiveRemoveDir(), and wfTimestamp().

◆ wfDebugBacktrace()

wfDebugBacktrace (   $limit = 0)

Safety wrapper for debug_backtrace().

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

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

Definition at line 1326 of file GlobalFunctions.php.

References wfDebug().

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

◆ wfDebugLog()

wfDebugLog (   $logGroup,
  $text,
  $dest = 'all',
array  $context = [] 
)

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

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

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

Definition at line 989 of file GlobalFunctions.php.

Referenced by GitInfo\__construct(), AutoLoader\autoload(), RCCacheEntryFactory\buildCLink(), RCCacheEntryFactory\buildDiffLink(), ApiMain\checkBotReadOnly(), UploadFromChunks\concatenateChunks(), IPTC\convIPTCHelper(), Exif\debug(), Exif\debugFile(), SectionProfiler\debugGroup(), WebPHandler\decodeLosslessChunkHeader(), WebPHandler\decodeLossyChunkHeader(), JobQueueRedis\doAck(), JobQueueRedis\doBatchPush(), JobQueueRedis\doPop(), DjVuHandler\doTransform(), SvgHandler\doTransform(), TransformationalImageHandler\doTransform(), LocalFileMoveBatch\execute(), CheckUsernames\execute(), WebPHandler\extractMetadata(), WebPHandler\extractMetadataFromChunks(), PoolWorkArticleView\fallback(), FormatMetadata\formatCoords(), Message\formatListParam(), ParserCache\get(), IPTC\getCharset(), ContentHandler\getContentText(), ResourceLoaderImage\getImageData(), ParserCache\getKey(), RequestContext\getLanguage(), LocalFileMoveBatch\getMoveTriplets(), WebResponse\header(), CdnCacheUpdate\HTCPPurge(), User\inDnsBlacklist(), EditPage\internalAttemptSave(), SquidPurgeClient\log(), PoolCounterWork\logError(), MediaHandler\logErrorForExternalProcess(), JobQueueFederated\logException(), ApiBase\logFeatureUsage(), ApiMain\logRequest(), MediaWiki\maybeDoHttpsRedirect(), LocalFile\move(), MediaWiki\Site\MediaWikiPageNameNormalizer\normalizePageName(), IPTC\parse(), GitInfo\precomputeValues(), MediaWiki\preOutputCommit(), CdnCacheUpdate\purge(), UploadFromUrl\reallyFetchFile(), MediaHandler\removeBadFile(), LocalFileMoveBatch\removeNonexistentFiles(), SquidPurgeClientPool\run(), UploadFromUrl\saveTempFileChunk(), MWDebug\sendMessage(), WebResponse\setCookie(), WebResponse\statusHeader(), IPTC\timeHelper(), wfForbidden(), and wfImageAuthMain().

◆ wfDebugMem()

wfDebugMem (   $exact = false)

Send a line giving PHP memory usage.

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

Definition at line 954 of file GlobalFunctions.php.

References wfDebug().

◆ wfDeprecated()

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

Logs a warning that $function is deprecated.

Parameters
string$functionFunction that is deprecated.
string | false$versionVersion of MediaWiki that the function was deprecated in (Added in 1.19).
string | bool$componentComponent to which the function belongs. If false, it is assumed the function is in MediaWiki core (Added 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).
Exceptions
ExceptionIf the MediaWiki version number specified by $version is neither a string nor false, an exception is thrown to indicate invalid arguments.

Definition at line 1027 of file GlobalFunctions.php.

Referenced by SearchResultSet\__construct(), SearchUpdate\__construct(), ConfiguredReadOnlyMode\__construct(), Revision\__construct(), Parser\__construct(), TemplateParser\__construct(), MWHttpRequest\__construct(), CategoryFinder\__construct(), SearchResult\__construct(), SpecialChangeContentModel\__construct(), ResourceLoader\__construct(), MediaWikiTitleCodec\__construct(), LinkHolderArray\__construct(), MediaWiki\Preferences\DefaultPreferencesFactory\__construct(), MediaWiki\Search\SearchWidgets\SimpleSearchResultWidget\__construct(), MediaWiki\Search\SearchWidgets\SimpleSearchResultSetWidget\__construct(), MediaWiki\EditPage\TextConflictHelper\__construct(), LinkCache\__construct(), __get(), User\__get(), __set(), User\__set(), DeprecatedGlobal\_newObject(), LogPage\addEntry(), ApiModuleManager\addModule(), Wikimedia\Rdbms\Database\assertConditionIsNotEmpty(), Parser\attributeStripCallback(), Revision\base36Sha1(), BaseSearchResultSet\bcIterator(), Linker\buildRollbackLink(), MediaWiki\HookContainer\HookContainer\callLegacyHook(), SpecialPageFactory\capturePath(), MediaWiki\Debug\DeprecatablePropertyArray\checkDeprecatedAccess(), ActorMigration\checkDeprecation(), Article\checkFlags(), ChangesListSpecialPage\checkStructuredFilterUiEnabled(), SpecialWatchlist\checkStructuredFilterUiEnabled(), Article\checkTouched(), WebRequest\checkUrlExtension(), MediaWiki\Block\DatabaseBlock\chooseBlock(), Language\classFromCode(), Hooks\clear(), User\clearAllNotifications(), Language\clearCaches(), MediaWiki\Block\DatabaseBlock\clearCookie(), Article\clearPreparedEdit(), Article\commitRollback(), ResourceLoaderFileModule\compileLessFile(), Revision\compressRevisionText(), Title\countAuthorsBetween(), Revision\countByPageId(), Revision\countByTitle(), Title\countRevisionsBetween(), Http\createMultiClient(), User\createNew(), Revision\decompressRevisionText(), File\delete(), ForeignDBFile\delete(), LocalFile\delete(), UserGroupMembership\delete(), MediaWiki\Block\DatabaseBlock\deleteIfExpired(), LocalFile\deleteOld(), ObjectCache\detectLocalServerCache(), Parser\doBlockLevels(), FileDeleteForm\doDelete(), Article\doDeleteArticle(), WikiPage\doDeleteArticle(), Article\doDeleteArticleReal(), WikiPage\doDeleteArticleReal(), Article\doDeleteUpdates(), WikiPage\doDeleteUpdates(), WikiPage\doEditUpdates(), Article\doEditUpdates(), Article\doPurge(), Article\doRollback(), Article\doUpdateRestrictions(), Article\doViewUpdates(), Parser\enableOOUI(), Maintenance\error(), Sanitizer\escapeId(), SpecialPageFactory\executePath(), SpecialPageFactory\exists(), Article\exists(), ApiBase\explodeMultiValue(), Action\factory(), FileJournal\factory(), JobQueue\factory(), Parser\fetchCurrentRevisionOfTitle(), Parser\fetchTemplate(), Article\followRedirect(), MediaWiki\Block\DatabaseBlock\fromMaster(), Skin\generateDebugHTML(), Article\generateReason(), Linker\generateRollback(), ParserCache\get(), User\getAllRights(), LockManagerGroup\getAny(), PageArchive\getArchivedRevision(), Revision\getArchiveQueryInfo(), Maintenance\getArg(), Title\getAuthorsBetween(), Article\getAutoDeleteReason(), EditPage\getBaseRevision(), MediaWiki\Block\AbstractBlock\getBlocker(), MediaWiki\Block\AbstractBlock\getBlockErrorParams(), Article\getCategories(), CategoryPage\getCategoryViewerClass(), Article\getComment(), WikiPage\getComment(), Revision\getComment(), ResourceLoaderContext\getConfig(), Revision\getContent(), Revision\getContentFormat(), Article\getContentHandler(), Revision\getContentHandler(), Article\getContentModel(), Revision\getContentModel(), EditPage\getContextTitle(), Article\getContributors(), MediaWiki\Block\DatabaseBlock\getCookieValue(), Article\getCreator(), WikiPage\getCreator(), ParserOptions\getCurrentRevisionCallback(), LockManagerGroup\getDefault(), WikiPage\getDeletionUpdates(), Article\getDeletionUpdates(), Skin\getDynamicStylesheetQuery(), LogEventsList\getExcludeClause(), SpecialVersion\getExtAuthorsFileName(), SpecialVersion\getExtLicenseFileName(), Title\getFirstRevision(), SpecialContributions\getForm(), Message\getFormat(), Article\getHiddenCategories(), TextContent\getHtml(), Article\getId(), Revision\getId(), MediaWiki\Block\DatabaseBlock\getIdFromCookieValue(), ActorMigration\getInsertValuesWithTempTable(), Article\getLatest(), MediaWiki\Storage\SqlBlobStore\getLegacyEncodingConversionLang(), WebRequest\getLimitOffset(), Article\getLinksTimestamp(), SpecialPageFactory\getLocalNameFor(), UserGroupMembership\getMembership(), UserGroupMembership\getMembershipsForUser(), SVGMetadataExtractor\getMetadata(), Article\getMinorEdit(), User\getNewMessageLinks(), User\getNewMessageRevisionId(), User\getNewtalk(), Revision\getNext(), MediaWiki\Revision\RevisionStore\getNextRevision(), Title\getNotificationTimestamp(), Article\getOldestRevision(), WikiPage\getOldestRevision(), SpecialPageFactory\getPage(), Revision\getPage(), Revision\getParentId(), Revision\getParentLengths(), Revision\getPrevious(), PageArchive\getPreviousRevision(), MediaWiki\Revision\RevisionStore\getPreviousRevision(), Http\getProxy(), Revision\getQueryInfo(), Revision\getRecentChange(), Article\getRedirectTarget(), Article\getRedirectURL(), Linker\getRevDeleteLink(), PageArchive\getRevision(), LinksUpdate\getRevision(), Article\getRevision(), WikiPage\getRevision(), Article\getRevisionFetched(), DifferenceEngine\getRevisionHeader(), Parser\getRevisionObject(), Revision\getRevisionRecord(), Revision\getRevisionText(), Linker\getRollbackEditCount(), ApiQueryRevisions\getRollbackToken(), Revision\getSerializedData(), Revision\getSha1(), Revision\getSize(), ExternalStoreDB\getSlave(), Profiler\getTemplated(), Revision\getTextId(), ParserOptions\getTidy(), Article\getTimestamp(), Revision\getTimestamp(), Revision\getTimestampFromId(), Revision\getTitle(), SpecialPageFactory\getTitleForAlias(), Article\getTouched(), ContentHandler\getUndoContent(), WikiPage\getUndoContent(), Article\getUndoContent(), Article\getUser(), WikiPage\getUser(), Revision\getUser(), Title\getUserPermissionsErrors(), Article\getUserText(), WikiPage\getUserText(), Revision\getUserText(), Revision\getVisibility(), EditPage\handleStatus(), Maintenance\hasArg(), WikiPage\hasDifferencesOutsideMainSlot(), Article\hasViewableContent(), OutputPage\headElement(), DatabaseUpdater\ifNoActorTable(), User\inDnsBlacklist(), UserGroupMembership\initFromRow(), UserGroupMembership\insert(), Revision\insertOn(), Article\insertOn(), Article\insertProtectNullRevision(), WikiPage\insertProtectNullRevision(), Article\insertRedirect(), Article\insertRedirectEntry(), CommentStore\insertWithTempTable(), Article\isCountable(), Revision\isCurrent(), Revision\isDeleted(), User\isDnsBlacklisted(), User\isEveryoneAllowed(), User\isLocallyBlockedProxy(), Revision\isMinor(), Article\isRedirect(), Revision\isUnpatrolled(), SpecialPage\listed(), MediaWiki\Revision\RevisionStore\listRevisionSizes(), Revision\loadFromPageId(), Article\loadFromRow(), Revision\loadFromTimestamp(), Revision\loadFromTitle(), Article\loadPageData(), MediaWiki\Revision\RevisionStore\loadRevisionFromPageId(), MediaWiki\Revision\RevisionStore\loadRevisionFromTimestamp(), MediaWiki\Revision\RevisionStore\loadRevisionFromTitle(), Article\lockAndGetLatest(), SkinTemplate\makeArticleUrlDetails(), Skin\makeI18nUrl(), Skin\makeNSUrl(), Article\makeParserOptions(), ResourceLoader\makeVersionQuery(), RecentChange\markPatrolled(), EditPage\matchSpamRegex(), EditPage\matchSummarySpamRegex(), ParserOptions\newCanonical(), Revision\newFromArchiveRow(), Revision\newFromId(), Revision\newFromPageId(), Revision\newFromRow(), UserGroupMembership\newFromRow(), Revision\newFromTitle(), Revision\newKnownCurrent(), Revision\newNullRevision(), BaseSearchResultSet\next(), Linker\normaliseSpecialPage(), WikiPage\onArticleEdit(), Parser\Options(), Parser\OutputType(), Article\pageDataFromId(), Article\pageDataFromTitle(), ApiBase\parseMultiValue(), StreamFile\parseRange(), ApiQueryBase\prefixedTitlePartToKey(), Article\prepareContentForEdit(), WikiPage\prepareContentForEdit(), MediaWiki\Storage\DerivedPageDataUpdater\prepareUpdate(), MediaWiki\Block\AbstractBlock\prevents(), Profiler\profileIn(), Profiler\profileOut(), Article\protectDescription(), Article\protectDescriptionLog(), UserGroupMembership\purgeExpired(), SquidPurgeClient\queuePurge(), Title\quickUserCan(), PatrolLog\record(), File\recordUpload(), ForeignDBFile\recordUpload(), LocalFile\recordUpload(), MediaWiki\HookContainer\HookContainer\register(), Article\replaceSectionAtRev(), Article\replaceSectionContent(), SpecialPageFactory\resetList(), Linker\revComment(), Linker\revUserLink(), Linker\revUserTools(), BaseSearchResultSet\rewind(), UserGroupMembership\selectFields(), StreamFile\send404Message(), ParserOptions\setAllowExternalImages(), ParserOptions\setAllowExternalImagesFrom(), MediaWiki\Block\AbstractBlock\setBlocker(), CategoryPage\setCategoryViewerClass(), MediaWiki\Block\DatabaseBlock\setCookie(), ParserOptions\setCurrentRevisionCallback(), ParserOptions\setEnableImageWhitelist(), setExtensionData(), Parser\setFunctionTagHook(), Revision\setId(), SpecialPage\setListed(), JobRunner\setLogger(), User\setNewtalk(), LinksUpdate\setRevision(), Profiler\setTemplated(), Article\setTimestamp(), Revision\setTitle(), Revision\setUserIdAndName(), ParserOptions\setWrapOutputClass(), Article\shouldCheckParserCache(), MediaWiki\Block\AbstractBlock\shouldTrackWithCookie(), MediaWiki\Block\DatabaseBlock\shouldTrackWithCookie(), ApiQueryBase\showHiddenUsersAddBlockInfo(), LogEventsList\showOptions(), GenderCache\singleton(), ParserCache\singleton(), UploadBase\stashFile(), UploadFromChunks\stashFile(), Parser\statelessFetchRevision(), Article\supportsSections(), User\trackBlockWithCookie(), Language\transformUsingPairFile(), Article\triggerOpportunisticLinksUpdate(), ChangeTags\truncateTagDescription(), ContribsPager\tryToCreateValidRevision(), LogEventsList\typeAction(), PageArchive\undelete(), Article\updateCategoryCounts(), Article\updateIfNewerOn(), WikiPage\updateIfNewerOn(), Article\updateRedirectOn(), Article\updateRestrictions(), Article\updateRevisionOn(), WikiPage\updateRevisionOn(), Title\userCan(), ArchivedFile\userCan(), File\userCan(), OldLocalFile\userCan(), Revision\userCan(), LogEventsList\userCan(), LogEventsList\userCanBitfield(), Revision\userCanBitfield(), LogEventsList\userCanViewLogType(), Revision\userWasLastToEdit(), Sanitizer\validateAttributes(), ApiBase\validateLimit(), ApiBase\validateTimestamp(), Language\viewPrevNext(), wfGetRusage(), wfGetScriptUrl(), wfIsBadImage(), wfWaitForSlaves(), and MediaWiki\Session\PHPSessionHandler\write().

◆ wfDeprecatedMsg()

wfDeprecatedMsg (   $msg,
  $version = false,
  $component = false,
  $callerOffset = 2 
)

Log a deprecation warning with arbitrary message text.

A caller description will be appended. If the message has already been sent for this caller, it won't be sent again.

Although there are component and version parameters, they are not automatically appended to the message. The message text should include information about when the thing was deprecated. The component and version are just used to implement $wgDeprecationReleaseLimit.

Since
1.35
Parameters
string$msgThe message
string | false$versionVersion of MediaWiki that the function was deprecated in.
string | bool$componentComponent to which the function belongs. If false, it is assumed the function is in MediaWiki core.
int | false$callerOffsetHow far up the call stack is the original caller. 2 = function that called the function that called us. If false, the caller description will not be appended.

Definition at line 1059 of file GlobalFunctions.php.

Referenced by PasswordReset\__construct(), FileDeleteForm\__construct(), ParsoidVirtualRESTService\__construct(), LocalFileDeleteBatch\__construct(), CategoryMembershipChange\__construct(), MergeHistory\__construct(), Article\__get(), Language\__get(), Article\__set(), OutputPage\addVaryHeader(), Parser\expandMagicVariable(), Title\fixUrlQueryArgs(), HTMLInfoField\getOOUI(), MediaWiki\SpecialPage\SpecialPageFactory\getPage(), Sanitizer\getRecognizedTagData(), NamespaceInfo\isMovable(), ExtensionRegistry\readFromQueue(), Hooks\register(), MediaWiki\Search\SearchWidgets\DidYouMeanWidget\rewrittenHtml(), ApiQuerySearch\run(), ParserOptions\setTidy(), SpecialSearch\showResults(), SpecialEmailUser\submit(), and MediaWiki\Search\SearchWidgets\DidYouMeanWidget\suggestionHtml().

◆ wfDiff()

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

Returns unified plain-text diff of two texts.

"Useful" for machine processing of diffs.

Deprecated:
since 1.25, use DiffEngine/UnifiedDiffFormatter directly
Parameters
string$beforeThe text before the changes.
string$afterThe text after the changes.
string$paramsCommand-line options for the diff command.
Returns
string Unified diff of $before and $after

Definition at line 2228 of file GlobalFunctions.php.

References $wgDiff, wfDebug(), and wfTempDir().

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

◆ wfEscapeShellArg()

wfEscapeShellArg (   $args)

Version of escapeshellarg() that works better on Windows.

Originally, this fixed the incorrect use of single quotes on Windows (https://bugs.php.net/bug.php?id=26285) and the locale problems on Linux in PHP 5.2.6+ (bug backported to earlier distro releases of PHP).

Parameters
string|string[]...$args strings to escape and glue together, or a single array of strings parameter
Returns
string
Deprecated:
since 1.30 use MediaWiki\Shell\Shell::escape()

Definition at line 2019 of file GlobalFunctions.php.

References $args.

◆ wfEscapeWikiText()

wfEscapeWikiText (   $text)

Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.

making its way through. This is achieved by substituting certain characters with HTML entities. As required by the callers, "<nowiki>" is not used.

Parameters
string$textText to be escaped
-taint$textescapes_html
Returns
string

Definition at line 1488 of file GlobalFunctions.php.

References $wgEnableMagicLinks, and $wgUrlProtocols.

Referenced by MalformedTitleException\__construct(), MediaHandler\addMeta(), CoreParserFunctions\basepagename(), CoreParserFunctions\basepagenamee(), Parser\braceSubstitution(), SpecialPageLanguage\changePageLanguage(), ApiMain\checkAsserts(), ApiQueryImageInfo\checkParameterNormalise(), SpecialContributions\contributionsSub(), ApiMain\createPrinterByName(), CoreParserFunctions\defaultsort(), Article\delete(), CoreParserFunctions\displaytitle(), Article\doDelete(), FileDeleteForm\doDelete(), WikiPage\doDeleteArticleBatched(), ApiCSPReport\error(), ApiMain\errorMessagesFromException(), SpecialFileDuplicateSearch\execute(), SpecialMergeHistory\execute(), SpecialUnblock\execute(), ApiAMCreateAccount\execute(), ApiClientLogin\execute(), ApiComparePages\execute(), ApiEditPage\execute(), ApiExpandTemplates\execute(), ApiLinkAccount\execute(), ApiMergeHistory\execute(), ApiMove\execute(), ApiOptions\execute(), ApiParse\execute(), ApiProtect\execute(), ApiQueryAllMessages\execute(), ApiQueryLogEvents\execute(), ApiQueryUserContribs\execute(), ApiUndelete\execute(), ApiUserrights\execute(), ApiValidatePassword\execute(), CoreMagicVariables\expand(), ApiQueryRevisionsBase\extractAllSlotInfo(), ApiQueryRevisionsBase\extractDeprecatedContent(), ApiBase\extractRequestParams(), CoreParserFunctions\fullpagename(), CoreParserFunctions\fullpagenamee(), ApiComparePages\getDiffRevision(), Status\getErrorMessage(), ApiFeedRecentChanges\getFeedObject(), ApiErrorFormatter\getMessageFromException(), ApiBase\getModuleFromPath(), ApiRollback\getRbTitle(), TextSlotDiffRenderer\getTextDiffInternal(), ApiBase\getTitleFromTitleOrPageId(), ApiBase\getTitleOrPageId(), Parser\getUserSig(), ApiBase\getWatchlistUser(), RollbackAction\handleRollbackRequest(), EditPage\importFormData(), SpecialBlock\maybeAlterFormDefaults(), ApiQueryImageInfo\mergeThumbParams(), PPFrame_Hash\newChild(), SpecialRandomInCategory\onSubmit(), SpecialBlock\onSuccess(), SpecialPasswordReset\onSuccess(), ImagePage\openShowImage(), ImageListPager\outputUserDoesNotExist(), CoreParserFunctions\pagename(), CoreParserFunctions\pagenamee(), ApiBase\parseMultiValue(), ApiQueryBase\parsePrefixedTitlePart(), SpecialBlock\postText(), FileDeleteForm\prepareMessage(), ApiQueryBlocks\prepareUsername(), CoreParserFunctions\rootpagename(), CoreParserFunctions\rootpagenamee(), ApiQueryCategories\run(), ApiQueryImages\run(), ApiQueryLinks\run(), ApiQueryRecentChanges\run(), ApiQueryRevisions\run(), ApiMain\setupModule(), ProtectionForm\show(), SpecialSearch\showCreateLink(), UserrightsPage\showEditUserGroupsForm(), SpecialUndelete\showHistory(), EditPage\showIntro(), Article\showMissingArticle(), SpecialSearch\showResults(), LoginSignupSpecialPage\showSuccessPage(), EditPage\spamPageWithContent(), CoreParserFunctions\subjectpagename(), CoreParserFunctions\subjectpagenamee(), CoreParserFunctions\subpagename(), CoreParserFunctions\subpagenamee(), CoreParserFunctions\talkpagename(), CoreParserFunctions\talkpagenamee(), ApiQueryBase\titlePartToKey(), ApiFileRevert\validateParameters(), MediaWiki\Preferences\SignatureValidator\validateSignature(), and SpecialBlock\validateTarget().

◆ wfExpandIRI()

wfExpandIRI (   $url)

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

Todo:
handle punycode domains too
Parameters
string$url
Returns
string

Definition at line 860 of file GlobalFunctions.php.

References $matches, and wfExpandUrl().

Referenced by Skin\printSource().

◆ wfExpandUrl()

wfExpandUrl (   $url,
  $defaultProto = PROTO_CURRENT 
)

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

Assumes $wgServer is correct.

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

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

Definition at line 490 of file GlobalFunctions.php.

References $wgCanonicalServer, $wgHttpsPort, $wgInternalServer, $wgRequest, $wgServer, PROTO_CANONICAL, PROTO_CURRENT, PROTO_HTTP, PROTO_HTTPS, PROTO_INTERNAL, wfAssembleUrl(), wfParseUrl(), and wfRemoveDotSegments().

Referenced by MWHttpRequest\__construct(), ParsoidVirtualRESTService\__construct(), DumpCategoriesAsRdf\addDumpHeader(), ApiQuerySiteinfo\appendGeneralInfo(), ApiQuerySiteinfo\appendInterwikiMap(), ApiQuerySiteinfo\appendRightsInfo(), EmailNotification\composeCommonMailtext(), SpecialApiHelp\execute(), ApiQueryExternalLinks\execute(), ApiQueryIWLinks\execute(), ApiQueryLangLinks\execute(), WebInstallerWelcome\execute(), CdnCacheUpdate\expand(), ApiQueryInfo\extractPageInfo(), CoreParserFunctions\filepath(), MediaWiki\Search\SearchWidgets\InterwikiSearchResultSetWidget\footerHtml(), ApiParse\formatIWLinks(), ApiParse\formatLangLinks(), Title\getCanonicalURL(), File\getCanonicalUrl(), SpecialVersion\getEntryPointInfo(), RevertAction\getFormFields(), Title\getFullURL(), File\getFullUrl(), OutputPage\getHeadLinksArray(), ApiQueryImageInfo\getInfo(), LocalRepo\getInfo(), Title\getInternalURL(), ApiRsd\getRsdApiList(), FeedItem\getUniqueIdUnescaped(), MediaWiki\Search\SearchWidgets\SimpleSearchResultSetWidget\headerHtml(), ForeignAPIRepo\httpGet(), MediaWiki\Search\SearchWidgets\InterwikiSearchResultSetWidget\iwIcon(), RevertAction\onSuccess(), AtomFeed\outHeader(), RSSFeed\outHeader(), AtomFeed\outItem(), RSSFeed\outItem(), OutputPage\output(), SpecialUploadStash\outputRemoteScaledThumb(), MediaWiki\performAction(), FileDeleteForm\prepareMessage(), CSSMin\remapOne(), ApiQueryExtLinksUsage\run(), VirtualRESTServiceClient\runMulti(), ApiOpenSearch\search(), SearchSuggestion\setSuggestedTitle(), MediaWiki\shouldDoHttpRedirect(), EditPage\showIntro(), ApiMain\substituteResultWithError(), File\transform(), MediaWiki\tryNormaliseRedirect(), wfApiMain(), wfExpandIRI(), wfGetServerUrl(), wfOpenSearchDescMain(), and wfStreamThumb().

◆ wfFindFile()

wfFindFile (   $title,
  $options = [] 
)

Find a file.

Deprecated:
since 1.34, use MediaWikiServices
Parameters
string | LinkTarget$titleString or LinkTarget object
array$optionsAssociative array of options (see RepoGroup::findFile)
Returns
File|bool File, or false if the file does not exist

Definition at line 2491 of file GlobalFunctions.php.

References $title.

◆ wfForeignMemcKey()

wfForeignMemcKey (   $db,
  $prefix,
  $args 
)

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|int...$args
Returns
string
Deprecated:
Since 1.35 Call makeGlobalKey on a BagOStuff instance

Definition at line 2409 of file GlobalFunctions.php.

References $args.

◆ wfFormatStackFrame()

wfFormatStackFrame (   $frame)

Return a string representation of frame.

Parameters
array$frame
Returns
string

Definition at line 1422 of file GlobalFunctions.php.

Referenced by wfGetCaller().

◆ wfGetAllCallers()

wfGetAllCallers (   $limit = 3)

Return a string consisting of callers in the stack.

Useful sometimes for profiling specific points.

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

Definition at line 1407 of file GlobalFunctions.php.

References wfDebugBacktrace().

Referenced by MediaWiki\Session\SessionBackend\addData(), MediaWiki\Session\SessionBackend\dirty(), and MediaWiki\Session\SessionBackend\renew().

◆ wfGetCache()

wfGetCache (   $cacheType)

Get a specific cache object.

Deprecated:
since 1.32, use ObjectCache::getInstance() instead
Parameters
int | string$cacheTypeA CACHE_* constants, or other key in $wgObjectCaches
Returns
BagOStuff

Definition at line 2739 of file GlobalFunctions.php.

Referenced by SpecialVersion\getCreditsForExtension(), CacheHelper\initCaching(), and CacheHelper\saveCache().

◆ wfGetCaller()

wfGetCaller (   $level = 2)

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

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

Parameters
int$level
Returns
string

Definition at line 1391 of file GlobalFunctions.php.

References wfDebugBacktrace(), and wfFormatStackFrame().

Referenced by StubObject\_unstub(), DeferredUpdates\addCallableUpdate(), MWDebug\log(), MWLBFactory\logDeprecation(), MediaWiki\HeaderCallback\warnIfHeadersSent(), wfShellExec(), and wfShellExecWithStderr().

◆ wfGetDB()

wfGetDB (   $db,
  $groups = [],
  $wiki = false 
)

Get a Database object.

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

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

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

Note 3: When replacing calls to this with calls to methods on an injected LoadBalancer, LoadBalancer::getConnectionRef is more commonly needed than LoadBalancer::getMaintenanceConnectionRef, which is needed for more advanced administrative tasks. See the IMaintainableDatabase and IDatabase interfaces for details.

Todo:
Replace calls to wfGetDB with calls to LoadBalancer::getConnection() on an injected instance of LoadBalancer.
Returns
\Wikimedia\Rdbms\DBConnRef

Definition at line 2462 of file GlobalFunctions.php.

References wfGetLB().

Referenced by LogPager\__construct(), SpecialRandomrootpage\__construct(), MediaWiki\Block\DatabaseBlock\__construct(), DeletedContribsPager\__construct(), ImageListPager\__construct(), ContribsPager\__construct(), IndexPager\__construct(), MergeHistoryPager\__construct(), Pingback\acquireLock(), OutputPage\addCategoryLinksToLBAndGetResult(), LinkCache\addLinkObj(), LogPage\addRelations(), User\addToDatabase(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\beginPrimaryAuthentication(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\beginPrimaryAuthentication(), MediaWiki\Auth\EmailNotificationSecondaryAuthenticationProvider\beginSecondaryAccountCreation(), ImageListPager\buildQueryConds(), SpecialPageLanguage\changePageLanguage(), CheckStorage\check(), User\checkAndSetTouched(), Pingback\checkIfSent(), TrackBlobs\checkIntegrity(), RevisionDeleter\checkRevisionExistence(), RecompressTracked\checkTrackingTable(), CgzCopyTransaction\commit(), WikiPage\commitRollback(), User\createNew(), MediaWiki\Block\DatabaseBlock\defaultRetroactiveAutoblock(), PrefixSearch\defaultSearchBackend(), ChangeTags\defineTag(), MediaWiki\Block\DatabaseBlock\delete(), Article\delete(), QueryPage\delete(), DifferenceEngine\deletedLink(), ChangeTags\deleteTagEverywhere(), Title\deleteTitleProtection(), SpecialUndelete\diffHeader(), RecompressTracked\doAllOrphans(), RecompressTracked\doAllPages(), UsersPager\doBatchLookups(), CategoryViewer\doCategoryQuery(), FileDeleteForm\doDelete(), WikiPage\doDeleteArticleBatched(), SpecialExport\doExport(), SpecialRecentChangesLinked\doMainQuery(), RecompressTracked\doOrphanList(), RecompressTracked\doPage(), PopulateInterwiki\doPopulate(), UserCache\doQuery(), MovePageForm\doSubmit(), WikiPage\doUpdateRestrictions(), LinkHolderArray\doVariants(), Title\estimateRevisionCount(), ApiSetNotificationTimestamp\execute(), UpdateLogging\execute(), RenameRestrictions\execute(), QueryPage\fetchFromCache(), HistoryAction\fetchRevisions(), TrackBlobs\findOrphanBlobs(), User\findUsersByGroup(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\finishAccountCreation(), RecompressTracked\finishIncompleteMoves(), DoubleRedirectJob\fixRedirects(), Language\formatExpiry(), ApiResult\formatExpiry(), SpecialDoubleRedirects\formatResult(), LCStoreDB\get(), MediaWiki\Interwiki\ClassicInterwikiLookup\getAllPrefixesDB(), PageProps\getAllProperties(), ContentHandler\getAutoDeleteReason(), MediaWiki\Block\DatabaseBlock\getBlocksForIPList(), Title\getBrokenLinksFrom(), QueryPage\getCachedTimestamp(), Title\getCascadeProtectionSources(), WikiPage\getCategories(), RCDatabaseLogEntry\getComment(), WikiPage\getContributors(), RevDelRevisionList\getCurrent(), AllMessagesTablePager\getCustomisedStatuses(), UserRightsProxy\getDB(), ApiBase\getDB(), BacklinkCache\getDB(), LinksUpdate\getDB(), ResourceLoaderWikiModule\getDB(), ChangesListSpecialPage\getDB(), SpecialBlockList\getDB(), SpecialRecentChanges\getDB(), SpecialWatchlist\getDB(), LocalRepo\getDBFactory(), DoubleRedirectJob\getFinalDestination(), WikiPage\getHiddenCategories(), SpecialActiveUsers\getIntroText(), EditPage\getLastDelete(), PageArchive\getLastRevisionId(), SpecialExport\getLinks(), Title\getLinksFrom(), Title\getLinksTo(), LocalRepo\getMasterDB(), SpecialRandomInCategory\getMinAndMaxForCat(), ApiQuery\getNamedDB(), Pingback\getOrCreatePingbackId(), SpecialExport\getPagesFromCategory(), SpecialExport\getPagesFromNamespace(), Title\getParentCategories(), PageArchive\getPreviousRevisionRecord(), PageProps\getProperties(), LinkFilter\getQueryConditions(), SpecialRandomInCategory\getQueryInfo(), DeletedContribsPager\getQueryInfo(), NewFilesPager\getQueryInfo(), UsersPager\getQueryInfo(), SpecialBrokenRedirects\getQueryInfo(), SpecialLinkSearch\getQueryInfo(), SpecialMediaStatistics\getQueryInfo(), SpecialUncategorizedCategories\getQueryInfo(), SpecialUnwatchedPages\getQueryInfo(), WantedPagesPage\getQueryInfo(), SpecialWithoutInterwiki\getQueryInfo(), ImageListPager\getQueryInfoReal(), MediaWiki\Block\DatabaseBlock\getRangeCond(), QueryPage\getRecacheDB(), Title\getRedirectsHere(), WikiPage\getRedirectTarget(), LocalRepo\getReplicaDB(), PageArchive\getRevisionByConditions(), PageArchive\getRevisionRecordByTimestamp(), OutputPage\getRlClient(), Linker\getRollbackEditCount(), SpecialVersion\getSoftwareInformation(), Title\getSubpages(), SpecialMIMESearch\getSuggestionsForTypes(), HistoryBlobCurStub\getText(), HistoryBlobStub\getText(), TrackBlobs\getTextClause(), Title\getTitleProtectionInternal(), Title\getTouched(), SpecialUpload\getUploadForm(), LCStoreDB\getWriteConnection(), User\idForName(), User\idFromName(), WikiRevision\importLogItem(), CheckStorage\importRevision(), MediaWiki\Block\DatabaseBlock\initFromRow(), TrackBlobs\initTrackingTable(), MediaWiki\Block\DatabaseBlock\insert(), ManualLogEntry\insert(), WikiPage\insertRedirect(), WikiPage\insertRedirectEntry(), EditPage\internalAttemptSave(), Title\invalidateCache(), WikiPage\isBatchedDelete(), Title\isBigDeletion(), WikiPage\isCountable(), PageArchive\isDeleted(), Title\isDeleted(), Title\isDeletedQuick(), Title\isNewPage(), Title\isSingleRevRedirect(), MediaWiki\Block\DatabaseBlock\isWhitelistedFromAutoblocks(), LogPager\limitPerformer(), ChangeTags\listExplicitlyDefinedTags(), PageArchive\listFiles(), PageArchive\listPagesByPrefix(), PageArchive\listPagesBySearch(), PageArchive\listRevisions(), ChangeTags\listSoftwareActivatedTags(), ChangeTags\listSoftwareDefinedTags(), User\load(), MediaWiki\Interwiki\ClassicInterwikiLookup\load(), ArchivedFile\load(), MessageCache\loadCachedMessagePageEntry(), Title\loadFieldFromDB(), User\loadFromCache(), User\loadFromDatabase(), MessageCache\loadFromDB(), RecentChange\loadFromRow(), ArchivedFile\loadFromRow(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), DifferenceEngine\loadRevisionData(), WikiPage\lockAndGetLatest(), ChangeTags\logTagManagementAction(), LocalIdLookup\lookupCentralIds(), LocalIdLookup\lookupUserNames(), LinkFilter\makeLikeArray(), ChangeTags\makeTagSummarySubquery(), Pingback\markSent(), ChangeTags\modifyDisplayQuery(), RecompressTracked\moveTextRow(), moveToExternal(), Title\nameOf(), RecentChange\newFromConds(), User\newFromConfirmationCode(), MediaWiki\Block\DatabaseBlock\newFromID(), Title\newFromID(), WikiPage\newFromID(), Title\newFromIDs(), UserArray\newFromIDs(), UserArray\newFromNames(), MediaWiki\Block\DatabaseBlock\newLoad(), User\newSystemUser(), RecentChange\notifyEdit(), RecentChange\notifyNew(), HistoryAction\onView(), ImagePage\openShowImage(), InfoAction\pageCounts(), ResourceLoader\preloadModuleInfo(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerChangeAuthenticationData(), ManualLogEntry\publish(), MediaWiki\Block\DatabaseBlock\purgeExpired(), Title\purgeExpiredRestrictions(), RecentChangesUpdateJob\purgeExpiredRows(), SpecialPagesWithProp\queryExistingProps(), ImagePage\queryImageLinks(), SpecialDoubleRedirects\reallyGetQueryInfo(), RecentChange\reallyMarkPatrolled(), RebuildRecentchanges\rebuildRecentChangesTablePass5(), QueryPage\recache(), MessageBlobStore\recacheMessageBlob(), ChangeTagsList\reloadFromMaster(), RevDelList\reloadFromMaster(), LinkHolderArray\replaceInternal(), ImportReporter\reportPage(), RevisionListBase\reset(), resolveStub(), resolveStubs(), CheckStorage\restoreText(), CategoryFinder\run(), DeleteLinksJob\run(), RecentChange\save(), LogPage\saveContent(), User\saveSettings(), UserNamePrefixSearch\search(), SpecialRandomInCategory\selectRandomPageFromDB(), RandomPage\selectRandomPageFromDB(), RevDelArchivedFileItem\setBits(), RevDelArchivedRevisionItem\setBits(), RevDelArchiveItem\setBits(), RevDelFileItem\setBits(), RevDelLogItem\setBits(), RevDelRevisionItem\setBits(), RevisionDeleteUser\setUsernameBitfields(), RevDelList\setVisibility(), SpecialAllPages\showChunk(), MovePageForm\showForm(), SpecialWhatLinksHere\showIndirectLinks(), EditPage\showIntro(), LogEventsList\showLogExtract(), Article\showMissingArticle(), Article\showPatrolFooter(), SpecialPrefixindex\showPrefixChunk(), UserOptionsMaintenance\showUsageStats(), RevDelLogList\suggestTarget(), RecompressTracked\syncDBs(), ChangeTags\tagUsageStatistics(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\testUserCanAuthenticate(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\testUserExists(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\testUserExists(), TrackBlobs\trackOrphanText(), TrackBlobs\trackRevisions(), ResourceLoader\tryRespondFromFileCache(), ChangeTags\undefineTag(), PageArchive\undeleteRevisions(), MediaWiki\Block\DatabaseBlock\update(), RecentChangesUpdateJob\updateActiveUsers(), WikiPage\updateCategoryCounts(), UserOptionsMaintenance\updateOptions(), ChangeTags\updateTags(), ChangeTags\updateTagsWithChecks(), MediaWiki\Block\DatabaseBlock\updateTimestamp(), ActivityUpdateJob\updateWatchlistNotification(), Revision\userWasLastToEdit(), and ApiTag\validateLogId().

◆ wfGetLangObj()

wfGetLangObj (   $langcode = false)

Return a Language object from $langcode.

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

Definition at line 1170 of file GlobalFunctions.php.

References $wgLang, $wgLanguageCode, and wfDebug().

Referenced by AllMessagesTablePager\__construct(), MessageCache\get(), Title\getPageLanguage(), ContentHandler\getPageLanguage(), and Title\getPageViewLanguage().

◆ wfGetLB()

wfGetLB (   $wiki = false)

Get a load balancer object.

Deprecated:
since 1.27, use MediaWikiServices::getInstance()->getDBLoadBalancer() or MediaWikiServices::getInstance()->getDBLoadBalancerFactory() instead.
Parameters
string | bool$wikiWiki ID, or false for the current wiki
Returns
\Wikimedia\Rdbms\LoadBalancer

Definition at line 2475 of file GlobalFunctions.php.

Referenced by wfGetDB().

◆ wfGetMainCache()

wfGetMainCache ( )

Get the main cache object.

Deprecated:
since 1.32, use ObjectCache::getLocalClusterInstance() instead
Returns
BagOStuff

Definition at line 2749 of file GlobalFunctions.php.

◆ wfGetNull()

wfGetNull ( )

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

/dev/null

Returns
string

Definition at line 2581 of file GlobalFunctions.php.

References wfIsWindows().

Referenced by Dump7ZipOutput\setup7zCommand().

◆ wfGetPrecompiledData()

wfGetPrecompiledData (   $name)

Get an object from the precompiled serialized directory.

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

Definition at line 2374 of file GlobalFunctions.php.

References $blob, $file, $IP, and unserialize().

Referenced by IcuCollation\fetchFirstLetterData().

◆ wfGetRusage()

wfGetRusage ( )

Get system resource usage of current request context.

Invokes the getrusage(2) system call, requesting RUSAGE_SELF. Returns false if getrusage is not available.

Deprecated:
since 1.35
Since
1.24
Returns
array|bool Resource usage data or false if no data available.

Definition at line 2957 of file GlobalFunctions.php.

References wfDeprecated().

◆ wfGetScriptUrl()

wfGetScriptUrl ( )

Get the script URL.

Deprecated:
since 1.35. Use wfScript() to obtain an entry point URL.
Returns
string Script URL

Definition at line 2546 of file GlobalFunctions.php.

References wfDeprecated().

◆ wfGetServerUrl()

wfGetServerUrl (   $proto)

Get the wiki's "server", i.e.

the protocol and host part of the URL, with a protocol specified using a PROTO_* constant as in wfExpandUrl()

Since
1.32
Parameters
string | int | null$protoOne of the PROTO_* constants.
Returns
string The URL

Definition at line 568 of file GlobalFunctions.php.

References wfExpandUrl().

Referenced by WebRequest\getFullRequestURL(), and GenerateSitemap\indexEntry().

◆ wfHostname()

◆ wfHttpError()

wfHttpError (   $code,
  $label,
  $desc 
)

Provide a simple HTTP error.

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

Definition at line 1596 of file GlobalFunctions.php.

References $wgOut, and print.

Referenced by SpecialJavaScriptTest\execute(), SpecialRunJobs\execute(), RawAction\getRawText(), and AjaxDispatcher\performAction().

◆ wfIncrStats()

wfIncrStats (   $key,
  $count = 1 
)

Increment a statistics counter.

Parameters
string$key
int$count
Returns
void

Definition at line 1116 of file GlobalFunctions.php.

◆ wfIniGetBool()

wfIniGetBool (   $setting)

Safety wrapper around ini_get() for boolean settings.

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

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

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

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

I frickin' hate PHP... :P

Parameters
string$setting
Returns
bool

Definition at line 1982 of file GlobalFunctions.php.

References wfStringToBool().

Referenced by PhpHttpRequest\__construct(), MediaWiki\Http\HttpRequestFactory\canMakeRequests(), MWHttpRequest\canMakeRequests(), UploadBase\isEnabled(), and WebInstaller\startSession().

◆ wfIsBadImage()

wfIsBadImage (   $name,
  $contextTitle = false 
)

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.
Deprecated:
since 1.34, use the BadFileLookup service directly instead
Parameters
string$nameThe image name to check
Title | bool$contextTitleThe page on which the image occurs, if known
Returns
bool

Definition at line 2804 of file GlobalFunctions.php.

References wfDeprecated().

◆ wfIsCLI()

wfIsCLI ( )

Check if we are running from the commandline.

Since
1.31
Returns
bool

Definition at line 1851 of file GlobalFunctions.php.

Referenced by ForkController\__construct(), MediaWiki\Logger\Monolog\WikiProcessor\__invoke(), MWExceptionHandler\handleUncaughtException(), and ProfilerOutputText\log().

◆ wfIsDebugRawPage()

wfIsDebugRawPage ( )

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

Returns
bool

Definition at line 932 of file GlobalFunctions.php.

References $cache, and MW_ENTRY_POINT.

Referenced by wfDebug().

◆ wfIsInfinity()

wfIsInfinity (   $str)

◆ wfIsWindows()

◆ wfLoadExtension()

wfLoadExtension (   $ext,
  $path = null 
)

Load an extension.

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

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

Definition at line 46 of file GlobalFunctions.php.

References $path, and $wgExtensionDirectory.

◆ wfLoadExtensions()

wfLoadExtensions ( array  $exts)

Load multiple extensions at once.

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

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

See also
wfLoadExtension
Parameters
string[]$extsArray of extension names to load
Since
1.25

Definition at line 67 of file GlobalFunctions.php.

References $ext, and $wgExtensionDirectory.

◆ wfLoadSkin()

wfLoadSkin (   $skin,
  $path = null 
)

Load a skin.

See also
wfLoadExtension
Parameters
string$skinName of the extension to load
string | null$pathAbsolute path of where to find the skin.json file
Since
1.25

Definition at line 83 of file GlobalFunctions.php.

References $path, and $wgStyleDirectory.

◆ wfLoadSkins()

wfLoadSkins ( array  $skins)

Load multiple skins at once.

See also
wfLoadExtensions
Parameters
string[]$skinsArray of extension names to load
Since
1.25

Definition at line 98 of file GlobalFunctions.php.

References $wgStyleDirectory.

◆ wfLocalFile()

wfLocalFile (   $title)

Get an object referring to a locally registered file.

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

Deprecated:
since 1.34, use MediaWikiServices
Parameters
Title | string$title
Returns
LocalFile|null A File, or null if passed an invalid Title

Definition at line 2503 of file GlobalFunctions.php.

References $title.

◆ wfLogDBError()

wfLogDBError (   $text,
array  $context = [] 
)

Log for database errors.

Since
1.25 support for additional context data
Parameters
string$textDatabase error message.
array$contextAdditional logging context data

Definition at line 1007 of file GlobalFunctions.php.

◆ wfLogProfilingData()

wfLogProfilingData ( )
Todo:

document

Move logic to MediaWiki.php

Definition at line 1095 of file GlobalFunctions.php.

Referenced by MediaWiki\restInPeace().

◆ wfLogWarning()

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

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

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

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

Definition at line 1087 of file GlobalFunctions.php.

Referenced by User\__get(), User\__set(), LinkBatch\addResultToCache(), ChangesListSpecialPage\areFiltersInConflict(), MediaWiki\Storage\SqlBlobStore\compressData(), Language\convertGrammar(), WikiPage\doDeleteArticleBatched(), Linker\emailLink(), Revision\ensureTitle(), LogFormatter\formatParametersForApi(), CommentStore\getCommentInternal(), MediaWiki\SpecialPage\SpecialPageFactory\getPage(), SiteImporter\handleException(), Html\inlineScript(), ParserOutput\mergeInternalMetaDataFrom(), OutputPage\transformFilePath(), Title\warnIfPageCannotExist(), and wfMkdirParents().

◆ wfMatchesDomainList()

wfMatchesDomainList (   $url,
  $domains 
)

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

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

Definition at line 876 of file GlobalFunctions.php.

References wfParseUrl().

Referenced by Skin\addToSidebarPlain(), and Parser\getExternalLinkRel().

◆ wfMemcKey()

wfMemcKey (   $args)

Make a cache key for the local wiki.

Deprecated:
since 1.30 Call makeKey on a BagOStuff instance
Parameters
string|int...$args
Returns
string

Definition at line 2394 of file GlobalFunctions.php.

References $args.

◆ wfMemoryLimit()

wfMemoryLimit (   $newLimit)

Raise PHP's memory limit (if needed).

Definition at line 2662 of file GlobalFunctions.php.

References wfDebug(), and wfShorthandToInteger().

◆ wfMerge()

wfMerge (   $old,
  $mine,
  $yours,
$result,
$mergeAttemptResult = null 
)

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
string | null&$mergeAttemptResult
Returns
bool

Definition at line 2145 of file GlobalFunctions.php.

References $wgDiff3, wfDebug(), and wfTempDir().

Referenced by TextContentHandler\merge3().

◆ wfMergeErrorArrays()

wfMergeErrorArrays (   $args)

Merge arrays in the style of PermissionManager::getPermissionErrors, with duplicate removal e.g.

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

Parameters
array[]...$args
Returns
array

Definition at line 180 of file GlobalFunctions.php.

References $args.

Referenced by ContentModelChange\checkPermissions(), MergeHistory\checkPermissions(), MovePage\checkPermissions(), SpecialImport\execute(), and DifferenceEngine\getPermissionErrors().

◆ wfMessage()

wfMessage (   $key,
  $params 
)

This is the function for getting translated interface messages.

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

This function replaces all old wfMsg* functions.

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

Definition at line 1220 of file GlobalFunctions.php.

Referenced by MalformedTitleException\__construct(), MessageContent\__construct(), MediaTransformError\__construct(), HTMLAutoCompleteSelectField\__construct(), HTMLSelectOrOtherField\__construct(), TransformParameterError\__construct(), TransformTooBigImageAreaError\__construct(), UploadStashFile\__construct(), CollapsibleFieldsetLayout\__construct(), MediaWiki\Widget\DateInputWidget\__construct(), MediaWiki\Widget\SizeFilterWidget\__construct(), UploadChunkVerificationException\__construct(), Linker\accesskey(), LogPage\actionText(), Action\addHelpLink(), Article\addHelpLink(), MediaHandler\addMeta(), WikitextContent\addSectionHeader(), ParserOutput\addTrackingCategory(), ApiQuerySiteinfo\appendInterwikiMap(), JsonContent\arrayTable(), SpecialVersion\arrayToString(), MediaWiki\Auth\AuthManager\autoCreateUser(), MediaWiki\Auth\AuthManager\beginAccountCreation(), MediaWiki\Auth\AuthManager\beginAccountLink(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProvider\beginLinkAttempt(), Linker\blockLink(), Parser\braceSubstitution(), OutputPage\buildBacklinkSubtitle(), Xml\buildForm(), ProtectionForm\buildForm(), ChangesFeed\buildItems(), SpecialEditWatchlist\buildTools(), MediaWiki\Auth\AuthManager\checkAccountCreatePermissions(), MediaWiki\Permissions\PermissionManager\checkActionPermissions(), SpecialPage\checkLoginSecurityLevel(), MediaWiki\Permissions\PermissionManager\checkSiteConfigPermissions(), MediaWiki\Permissions\PermissionManager\checkSpecialsAndNSPermissions(), CleanupSpam\cleanupArticle(), UploadStash\clear(), Language\commaList(), Linker\commentBlock(), WikiPage\commitRollback(), EmailNotification\composeCommonMailtext(), Article\confirmDelete(), MediaWiki\Auth\AuthManager\continueAccountCreation(), MediaWiki\Auth\AuthManager\continueAccountLink(), MediaWiki\Auth\AuthManager\continueAuthentication(), MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProvider\continueLinkAttempt(), LanguageConverter\convertNamespace(), Installer\createMainpage(), Xml\dateMenu(), CoreParserFunctions\defaultsort(), Article\delete(), MediaWiki\Session\SessionProvider\describe(), MediaWiki\Auth\PasswordAuthenticationRequest\describeCredentials(), MediaWiki\Auth\PasswordDomainAuthenticationRequest\describeCredentials(), MediaWiki\Auth\TemporaryPasswordAuthenticationRequest\describeCredentials(), MediaWiki\Session\SessionProvider\describeMessage(), UploadBase\detectVirus(), CoreParserFunctions\displaytitle(), MediaWiki\Block\DatabaseBlock\doAutoblock(), ContentModelChange\doContentModelChange(), Article\doDelete(), FileDeleteForm\doDelete(), DjVuHandler\doTransform(), SvgHandler\doTransform(), TransformationalImageHandler\doTransform(), WikiPage\doUpdateRestrictions(), Linker\emailLink(), WebInstallerPage\endForm(), WebInstallerInstall\endStage(), Installer\envCheckDB(), ApiEditPage\execute(), ApiFeedContributions\execute(), ApiFeedWatchlist\execute(), ApiImageRotate\execute(), ApiQueryAllMessages\execute(), FileDeleteForm\execute(), WebInstallerComplete\execute(), WebInstallerDBConnect\execute(), WebInstallerExistingWiki\execute(), WebInstallerInstall\execute(), WebInstallerName\execute(), WebInstallerOptions\execute(), WebInstallerRestart\execute(), WebInstallerUpgrade\execute(), WebInstallerWelcome\execute(), CleanupSpam\execute(), DumpIterator\execute(), DumpMessages\execute(), DumpRenderer\execute(), MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\failResponse(), ApiFeedContributions\feedItemDesc(), MessageBlobStore\fetchMessage(), DeleteEqualMessages\fetchMessageInfo(), UnknownContent\fillParserOutput(), ChangesList\flag(), Linker\formatAutocomments(), BlockLogFormatter\formatBlockFlag(), BlockLogFormatter\formatBlockFlags(), FeedUtils\formatDiff(), FeedUtils\formatDiffRow(), LanguageZh_hans\formatDuration(), Language\formatDuration(), WikiPage\formatExpiry(), Linker\formatHiddenCategories(), Linker\formatRevisionSize(), ApiParse\formatSummary(), Language\formatTimePeriod(), ContentHandler\getAutoDeleteReason(), ContentHandler\getAutosummary(), WebInstallerOptions\getCCDoneBox(), CategoryMembershipChange\getChangeMessageText(), WebInstaller\getCheckBox(), MysqlInstaller\getConnectForm(), PostgresInstaller\getConnectForm(), SpecialVersion\getCopyrightAndAuthorList(), EditPage\getCopyrightWarning(), Title\getDefaultMessageText(), Interwiki\getDescription(), LogPage\getDescription(), MediaWiki\Config\ConfigRepository\getDescriptionOf(), FeedUtils\getDiffLink(), ImageHandler\getDimensionsString(), Title\getEditNotices(), SpecialUpload\getExistsWarning(), SpecialVersion\getExtensionTypes(), MediaWiki\Auth\ConfirmLinkAuthenticationRequest\getFieldInfo(), MediaWiki\Auth\CreationReasonAuthenticationRequest\getFieldInfo(), MediaWiki\Auth\PasswordAuthenticationRequest\getFieldInfo(), MediaWiki\Auth\PasswordDomainAuthenticationRequest\getFieldInfo(), MediaWiki\Auth\RememberMeAuthenticationRequest\getFieldInfo(), MediaWiki\Auth\TemporaryPasswordAuthenticationRequest\getFieldInfo(), MediaWiki\Auth\UserDataAuthenticationRequest\getFieldInfo(), MediaWiki\Auth\UsernameAuthenticationRequest\getFieldInfo(), WebInstallerPage\getFieldsetStart(), UploadStash\getFile(), WebInstallerDocument\getFileContents(), UploadBase\getFilenamePrefixBlacklist(), IcuCollation\getFirstLetter(), NumericUppercaseCollation\getFirstLetter(), MediaHandler\getGeneralLongDesc(), User\getGrantName(), MWGrants\getGrantsWikiText(), UserGroupMembership\getGroupMemberName(), UserGroupMembership\getGroupName(), UserGroupMembership\getGroupPage(), WebInstaller\getHelpBox(), Language\getHumanTimestampInternal(), WikiTextStructure\getIgnoredHeadings(), WebInstaller\getInfoBox(), SpecialUpload\getInitialPageText(), DatabaseInstaller\getInstallUserBox(), LogFormatter\getIRCActionComment(), LogFormatter\getIRCActionText(), ContentHandler\getLocalizedName(), ImageHandler\getLongDesc(), SvgHandler\getLongDesc(), GIFHandler\getLongDesc(), PNGHandler\getLongDesc(), SpecialVersion\getMediaWikiCredits(), Licenses\getMessageFromParams(), ErrorPageError\getMessageObject(), MalformedTitleException\getMessageObject(), CliInstaller\getMessageText(), Interwiki\getName(), LogPage\getName(), WebInstaller\getPageListItem(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\getPasswordResetData(), EditPage\getPreviewLimitReport(), WebInstaller\getRadioElements(), LogPage\getRcComment(), LogPage\getRcCommentIRC(), DatabaseInstaller\getReadableName(), MediaWiki\Block\DatabaseBlock\getRedactedName(), Article\getRedirectHeaderHtml(), MWTimestamp\getRelativeTimestamp(), User\getRightDescription(), ImageHandler\getShortDesc(), SpecialBlock\getSuggestedDurations(), MediaWiki\Preferences\DefaultPreferencesFactory\getTimeZoneList(), MWTimestamp\getTimezoneMessage(), TrackingCategories\getTrackingCategories(), CategoryMembershipChange\getUser(), DoubleRedirectJob\getUser(), Parser\getUserSig(), Language\getVariantname(), SpecialVersion\getVersion(), FormatMetadata\getVisibleFields(), StripState\getWarning(), DatabaseInstaller\getWebUserBox(), MWGrants\grantName(), PageDataRequestHandler\handleRequest(), Title\hasSourceText(), QuickTemplate\haveMsg(), CoreTagHooks\html(), PageDataRequestHandler\httpContentNegotiation(), BackupReader\importFromHandle(), CoreTagHooks\indicator(), UploadStash\initFile(), WikiPage\insertNullProtectionRevision(), DifferenceEngine\intermediateEditsMsg(), Parser\interwikiTransclude(), CoreParserFunctions\intFunction(), MovePage\isValidMove(), MediaWiki\Block\DatabaseBlock\isWhitelistedFromAutoblocks(), WebInstaller\label(), Xml\languageSelector(), Parser\limitationWarn(), UploadStash\listFiles(), BotPassword\login(), Parser\magicLinkCallback(), MediaWiki\Linker\LinkRenderer\makeBrokenLink(), ContentSecurityPolicy\makeCSPDirectives(), WebInstaller\makeDownloadLinkHtml(), Skin\makeI18nUrl(), Parser\makeLimitReport(), ApiBase\makeMessage(), WebInstallerOptions\makeScreenshotsLink(), Linker\makeThumbLink2(), Parser\maybeMakeExternalImage(), MergeHistory\merge(), Xml\monthSelector(), MovePage\moveToInternal(), MovePage\moveUnsafe(), MWException\msg(), MWExceptionRenderer\msg(), DerivativeContext\msg(), RequestContext\msg(), HTMLFormField\msg(), QuickTemplate\msg(), SearchEngineConfig\namespacesAsText(), Html\namespaceSelectorOptions(), PPFrame_Hash\newChild(), Title\newMainPage(), WikiImporter\notice(), Language\numLink(), JsonContent\objectTable(), RawAction\onView(), WebInstallerOutput\outputFooter(), WebInstallerOutput\outputTitle(), FormatJson\parse(), ConverterRule\parse(), SearchEngine\parseNamespacePrefixes(), Language\pipeList(), FileDeleteForm\prepareMessage(), WikiPage\protectDescription(), TextPassDumper\readDump(), LanguageConverter\recursiveConvertRule(), UploadStash\removeFile(), WikitextContent\replaceSection(), CheckStorage\restoreText(), Linker\revComment(), Linker\revDeleteLink(), Linker\revDeleteLinkDisabled(), Linker\revUserLink(), Linker\revUserTools(), DoubleRedirectJob\run(), MediaWiki\Storage\PageUpdater\saveRevision(), Language\semicolonList(), User\sendConfirmationMail(), EmailNotification\sendImpersonal(), User\sendMail(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\sendNewAccountEmail(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\sendPasswordResetEmail(), User\setEmailWithConfirmation(), FileDeleteForm\setHeaders(), WikiImporter\setTargetRootPage(), Article\showDiffPage(), WebInstallerUpgrade\showDoneMessage(), WebInstaller\showError(), WebInstallerExistingWiki\showKeyForm(), WebInstaller\showMessage(), Article\showMissingArticle(), Article\showNamespaceHeader(), Article\showPatrolFooter(), SpecialVersion\softwareInformation(), Linker\specialLink(), WebInstaller\startPageWrapper(), WebInstallerInstall\startStage(), UploadStash\stashFile(), Parser\statelessFetchTemplate(), WebInstallerName\submit(), WebInstallerOptions\submit(), Installer\subscribeToMediaWikiAnnounce(), MediaWiki\Auth\ThrottlePreAuthenticationProvider\testForAccountCreation(), MediaWiki\Auth\ThrottlePreAuthenticationProvider\testForAuthentication(), Linker\titleAttrib(), Linker\tocList(), File\transformErrorOutput(), BitmapHandler\transformGd(), Language\truncateHtml(), Language\truncateInternal(), MediaWiki\Auth\ResetPasswordSecondaryAuthenticationProvider\tryReset(), PageArchive\undeleteRevisions(), Linker\userLink(), Linker\userTalkLink(), Linker\userToolLinks(), Article\view(), Language\viewPrevNext(), Article\viewRedirect(), wfForbidden(), wfGenerateThumbnail(), wfOpenSearchDescMain(), wfShowingResults(), wfStreamThumb(), MediaWiki\Session\CookieSessionProvider\whyNoSession(), and MediaWiki\Session\ImmutableSessionProviderWithCookie\whyNoSession().

◆ wfMessageFallback()

wfMessageFallback (   $keys)

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...$keys Message keys
Returns
Message
Since
1.18
See also
Message::newFallbackSequence

Definition at line 1243 of file GlobalFunctions.php.

References $keys, and Message\newFallbackSequence().

Referenced by SkinTemplate\buildContentNavigationUrls(), FileRepo\getDisplayName(), ImagePage\openShowImage(), and SkinTemplate\tabAction().

◆ wfMkdirParents()

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

◆ wfMsgReplaceArgs()

wfMsgReplaceArgs (   $message,
  $args 
)

Replace message parameter keys on the given formatted output.

Parameters
string$message
array$args
Returns
string

Definition at line 1255 of file GlobalFunctions.php.

References $args.

Referenced by WikiPage\commitRollback(), MWException\msg(), and MWExceptionRenderer\msg().

◆ wfNegotiateType()

wfNegotiateType (   $cprefs,
  $sprefs 
)

Returns the 'best' match between a client's requested internet media types and the server's list of available types.

Each list should be an associative array of type to preference (preference is a float between 0.0 and 1.0). Wildcards in the types are acceptable.

Parameters
array$cprefsClient's acceptable type list
array$sprefsServer's offered types
Returns
string|null
Todo:

FIXME: Doesn't handle params like 'text/plain; charset=UTF-8' XXX: generalize to negotiate other stuff

The function appears unused. Is it worth to keep?

Definition at line 1759 of file GlobalFunctions.php.

References $type, and mimeTypeMatch().

◆ wfObjectToArray()

wfObjectToArray (   $objOrArray,
  $recursive = true 
)

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

Parameters
object | array$objOrArray
bool$recursive
Returns
array

Definition at line 229 of file GlobalFunctions.php.

References wfObjectToArray().

Referenced by wfObjectToArray().

◆ wfParseUrl()

wfParseUrl (   $url)

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

Differences:

1) Handles protocols that don't use :// (e.g., mailto: and news:, as well as protocol-relative URLs) correctly. 2) Adds a "delimiter" element to the array (see (2)). 3) Verifies that the protocol is on the $wgUrlProtocols whitelist. 4) Rejects some invalid URLs that parse_url doesn't, e.g. the empty string or URLs starting with a line feed character.

Parameters
string$urlA URL to parse
Returns
string[]|bool Bits of the URL in an associative array, or false on failure. Possible fields:
  • scheme: URI scheme (protocol), e.g. 'http', 'mailto'. Lowercase, always present, but can be an empty string for protocol-relative URLs.
  • delimiter: either '://', ':' or '//'. Always present.
  • host: domain name / IP. Always present, but could be an empty string, e.g. for file: URLs.
  • port: port number. Will be missing when port is not explicitly specified.
  • user: user name, e.g. for HTTP Basic auth URLs such as http://user:pass@example.com/ Missing when there is no username.
  • pass: password, same as above.
  • path: path including the leading /. Will be missing when empty (e.g. 'http://example.com')
  • query: query string (as a string; see wfCgiToArray() for parsing it), can be missing.
  • fragment: the part after #, can be missing.

Definition at line 792 of file GlobalFunctions.php.

References $wgUrlProtocols.

Referenced by MWHttpRequest\__construct(), ParsoidVirtualRESTService\__construct(), SpecialLinkSearch\execute(), ApiAMCreateAccount\execute(), ApiClientLogin\execute(), ApiLinkAccount\execute(), DeleteSelfExternals\execute(), MediaWiki\Search\SearchWidgets\InterwikiSearchResultSetWidget\footerHtml(), WikiMap\getCanonicalServerInfoForAllWikis(), WikiReference\getDisplayName(), WikiMap\getWikiFromUrl(), WikiMap\getWikiWikiReferenceFromSites(), MediaWiki\Search\SearchWidgets\SimpleSearchResultSetWidget\headerHtml(), ThumbnailRenderJob\hitThumbUrl(), UploadFromUrl\isAllowedHost(), MediaWiki\Search\SearchWidgets\InterwikiSearchResultSetWidget\iwIcon(), LinkFilter\makeIndexes(), LinkFilter\makeLikeArray(), UserMailer\makeMsgId(), ApiCSPReport\matchUrlPattern(), CdnCacheUpdate\naivePurge(), ApiCSPReport\originFromUrl(), ContentSecurityPolicy\prepareUrlForCSP(), SquidPurgeClient\queuePurge(), RedisPubSubFeedEngine\send(), MediaWiki\triggerAsyncJobs(), wfExpandUrl(), and wfMatchesDomainList().

◆ wfPercent()

wfPercent (   $nr,
int  $acc = 2,
bool  $round = true 
)
Parameters
float | int$nrThe number to format
int$accThe number of digits after the decimal point, default 2
bool$roundWhether or not to round the value, default true
Returns
string

Definition at line 1953 of file GlobalFunctions.php.

◆ wfQueriesMustScale()

wfQueriesMustScale ( )

Should low-performance queries be disabled?

Returns
bool

Definition at line 2513 of file GlobalFunctions.php.

References $wgMiserMode, SiteStats\edits(), SiteStats\pages(), and SiteStats\users().

◆ wfRandom()

wfRandom ( )

Get a random decimal value in the domain of [0, 1), in a way not likely to give duplicate values for any realistic number of articles.

Note
This is designed for use in relation to Special:RandomPage and the page_random database field.
Returns
string

Definition at line 255 of file GlobalFunctions.php.

Referenced by CompareParserCache\execute(), ResetPageRandom\execute(), SpecialRandomInCategory\getRandomTitle(), RandomPage\getRandomTitle(), WikiPage\insertOn(), and ApiQueryRandom\run().

◆ wfRandomString()

wfRandomString (   $length = 32)

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

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

Definition at line 273 of file GlobalFunctions.php.

Referenced by JobQueueDB\doPop(), SvgHandler\doTransform(), BenchmarkLruHash\execute(), BenchmarkSanitizer\execute(), MakeTestEdits\execute(), WebRequest\getRequestId(), BenchmarkTitleValue\randomize(), and UploadSourceAdapter\registerSource().

◆ wfReadOnly()

◆ wfReadOnlyReason()

wfReadOnlyReason ( )

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

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

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

Definition at line 1139 of file GlobalFunctions.php.

Referenced by ReadOnlyError\__construct(), ProtectionForm\__construct(), ApiQuerySiteinfo\appendGeneralInfo(), MediaWiki\Auth\AuthManager\autoCreateUser(), MediaWiki\Auth\AuthManager\checkAccountCreatePermissions(), ApiBase\dieReadOnly(), WikiPage\doUpdateRestrictions(), McrUndoAction\show(), and EditPage\showHeader().

◆ wfRecursiveRemoveDir()

wfRecursiveRemoveDir (   $dir)

Remove a directory and all its content.

Does not hide error.

Parameters
string$dir

Definition at line 1928 of file GlobalFunctions.php.

References wfDebug(), and wfRecursiveRemoveDir().

Referenced by ForeignResourceManager\cleanUp(), ForeignResourceManager\run(), and wfRecursiveRemoveDir().

◆ wfRelativePath()

wfRelativePath (   $path,
  $from 
)

Generate a relative path name to the given file.

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

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

Definition at line 2332 of file GlobalFunctions.php.

References $path, and wfBaseName().

Referenced by DumpUploads\outputItem().

◆ wfRemoveDotSegments()

wfRemoveDotSegments (   $urlPath)

Remove all dot-segments in the provided URL path.

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

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

Definition at line 640 of file GlobalFunctions.php.

Referenced by PathRouter\parse(), CSSMin\remapOne(), and wfExpandUrl().

◆ wfReportTime()

wfReportTime (   $nonce = null)

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.

Parameters
string | null$nonceValue from OutputPage->getCSP()->getNonce()
Returns
string|WrappedString HTML

Definition at line 1303 of file GlobalFunctions.php.

References $wgShowHostnames, and wfHostname().

Referenced by SkinTemplate\prepareQuickTemplate(), and SkinMustache\tailElement().

◆ wfResetOutputBuffers()

wfResetOutputBuffers (   $resetGzipEncoding = true)

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

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

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

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

Parameters
bool$resetGzipEncoding

Definition at line 1636 of file GlobalFunctions.php.

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

◆ wfScript()

◆ wfSetBit()

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

As for wfSetVar except setting a bit.

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

Definition at line 1561 of file GlobalFunctions.php.

◆ wfSetVar()

◆ wfShellExec()

wfShellExec (   $cmd,
$retval = null,
  $environ = [],
  $limits = [],
  $options = [] 
)

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

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

Definition at line 2047 of file GlobalFunctions.php.

References wfGetCaller().

Referenced by DjVuHandler\doTransform(), DjVuImage\retrieveMetaData(), and wfShellExecWithStderr().

◆ wfShellExecWithStderr()

wfShellExecWithStderr (   $cmd,
$retval = null,
  $environ = [],
  $limits = [] 
)

Execute a shell command, returning both stdout and stderr.

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

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

Definition at line 2100 of file GlobalFunctions.php.

References wfGetCaller(), and wfShellExec().

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

◆ wfShellWikiCmd()

wfShellWikiCmd (   $script,
array  $parameters = [],
array  $options = [] 
)

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

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

Deprecated:
since 1.31, use Shell::makeScriptCommand()
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 -param array{php?:string,wrapper?:string} $options
Returns
string

Definition at line 2120 of file GlobalFunctions.php.

References $wgPhpCli.

Referenced by CleanupSpam\execute().

◆ wfShorthandToInteger()

wfShorthandToInteger ( ?string  $string = '',
int  $default = -1 
)

Converts shorthand byte notation to integer form.

Parameters
null | string$string
int$defaultReturned if $string is empty
Returns
int

Definition at line 2708 of file GlobalFunctions.php.

Referenced by Installer\envCheckMemory(), UploadBase\getMaxPhpUploadSize(), ApiUpload\getMinUploadChunkSize(), WebRequestUpload\isIniSizeOverflow(), and wfMemoryLimit().

◆ wfShowingResults()

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

Definition at line 1440 of file GlobalFunctions.php.

References wfMessage().

◆ wfStringToBool()

wfStringToBool (   $val)

Convert string value to boolean, when the following are interpreted as true:

  • on
  • true
  • yes
  • Any number, except 0 All other strings are interpreted as false.
Parameters
string$val
Returns
bool
Since
1.31

Definition at line 1998 of file GlobalFunctions.php.

Referenced by wfIniGetBool().

◆ wfStripIllegalFilenameChars()

wfStripIllegalFilenameChars (   $name)

Replace all invalid characters with '-'.

Additional characters can be defined in $wgIllegalFileChars (see T22489). By default, $wgIllegalFileChars includes ':', '/', '\'.

Parameters
string$nameFilename to process
Returns
string

Definition at line 2643 of file GlobalFunctions.php.

References $wgIllegalFileChars, and wfBaseName().

Referenced by UploadBase\getTitle(), and MovePage\isValidFileMove().

◆ wfTempDir()

wfTempDir ( )

Tries to get the system directory for temporary files.

First $wgTmpDirectory is checked, and then the TMPDIR, TMP, and TEMP environment variables are then checked in sequence, then sys_get_temp_dir(), then upload_tmp_dir from php.ini.

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

Returns
string

Definition at line 1866 of file GlobalFunctions.php.

References $wgTmpDirectory.

Referenced by SvgHandler\doTransform(), ImportableUploadRevisionImporter\downloadSource(), WikiImporter\dumpTemp(), MWDocGen\execute(), MediaWikiShell\execute(), TextSlotDiffRenderer\getTextDiffInternal(), JobRunner\loadBackoffs(), ResourceLoaderImage\rasterize(), CheckStorage\restoreText(), JobRunner\syncBackoffDeltas(), wfDiff(), and wfMerge().

◆ wfThumbIsStandard()

wfThumbIsStandard ( File  $file,
array  $params 
)

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

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

Parameters
File$file
array$params
Returns
bool
Since
1.24 Moved from thumb.php to GlobalFunctions in 1.25

Definition at line 2849 of file GlobalFunctions.php.

References $file, $wgImageLimits, $wgResponsiveImages, and $wgThumbLimits.

Referenced by wfStreamThumb().

◆ wfTimestamp()

wfTimestamp (   $outputtype = TS_UNIX,
  $ts = 0 
)

Get a timestamp string in one of various formats.

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

Definition at line 1803 of file GlobalFunctions.php.

References wfDebug().

Referenced by MediaWiki\Block\AbstractBlock\__construct(), OutputPage\adaptCdnTTL(), DumpCategoriesAsRdf\addDumpHeader(), LinkCache\addLinkObj(), ApiMain\addRequestedFields(), ApiQuerySiteinfo\appendExtensions(), ApiQuerySiteinfo\appendGeneralInfo(), ChangesListSpecialPage\buildQuery(), FileCacheBase\cacheTimestamp(), MediaWiki\Storage\PageEditStash\checkCache(), ApiMain\checkConditionalRequestHeaders(), OutputPage\checkLastModified(), User\confirmationToken(), LanguageWa\date(), Language\date(), DifferenceEngine\debug(), JobRunner\debugCallback(), LocalFile\decodeRow(), SpecialUndelete\diffHeader(), JobRunner\doExecuteJob(), MysqlUpdater\doSchemaRestructuring(), SpecialExport\execute(), ApiEditPage\execute(), ApiFeedWatchlist\execute(), ApiMergeHistory\execute(), ApiProtect\execute(), ApiQueryAllUsers\execute(), ApiQueryBlocks\execute(), ApiQueryDeletedrevs\execute(), ApiQueryFilearchive\execute(), ApiQueryImageInfo\execute(), ApiSetNotificationTimestamp\execute(), ApiUndelete\execute(), LocalFileRestoreBatch\execute(), BenchmarkParse\execute(), CleanupUploadStash\execute(), FixTimestamps\execute(), GenerateSitemap\execute(), ImportTextFiles\execute(), PurgeParserCache\execute(), RemoveUnusedAccounts\execute(), UpdateSearchIndex\execute(), CoreMagicVariables\expand(), Parser\expandMagicVariable(), UserrightsPage\expiryToTimestamp(), ApiQueryWatchlist\extractOutputData(), ApiQueryInfo\extractPageInfo(), ApiQueryRevisionsBase\extractRevisionInfo(), ApiQueryLogEvents\extractRowInfo(), ApiQueryRecentChanges\extractRowInfo(), ApiQueryUserContribs\extractRowInfo(), HistoryAction\feedEmpty(), MediaWiki\Logger\LegacyLogger\formatAsWfDebugLog(), FeedUtils\formatDiff(), Language\formatExpiry(), ApiResult\formatExpiry(), SpecialUndelete\formatFileRow(), LogFormatter\formatParameterValueForApi(), SpecialMergeHistory\formatRevisionRow(), SpecialUndelete\formatRevisionRow(), AtomFeed\formatTime(), RSSFeed\formatTime(), ImageListPager\formatValue(), GenerateSitemap\generateLimit(), RevDelArchivedFileItem\getApiData(), RevDelFileItem\getApiData(), RevDelRevisionItem\getApiData(), MediaWiki\Block\DatabaseBlock\getAutoblockExpiry(), NewUsersLogFormatter\getComment(), ApiQueryUserInfo\getCurrentUserInfo(), LocalFile\getDescriptionTouched(), User\getExperienceLevel(), ProtectionForm\getExpiry(), FormatMetadata\getExtendedMetadataFromFile(), ApiQueryImageInfo\getInfo(), SpecialActiveUsers\getIntroText(), LogFormatter\getIRCActionText(), OutputPage\getJSVars(), ApiQueryUserInfo\getLatestContributionTime(), MachineReadableRCFeedFormatter\getLine(), BlockLogFormatter\getMessageParameters(), PNGMetadataExtractor\getMetadata(), SpecialRandomInCategory\getMinAndMaxForCat(), MediaWiki\Auth\AbstractPasswordPrimaryAuthenticationProvider\getNewPasswordExpiry(), BlockLogFormatter\getParametersForApi(), RefreshLinksJob\getParserOutputFromCache(), MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider\getPasswordResetData(), PageArchive\getPreviousRevisionRecord(), ActiveUsersPager\getQueryInfo(), RawAction\getRawText(), MediaWiki\Rest\Handler\UserContributionsHandler\getRevisionsList(), CoreMagicVariables\getRevisionTimestampSubstring(), ApiQuerySearch\getSearchResultData(), FindBadBlobs\getStartTimestamp(), ImageHistoryList\getThumbForLine(), ArchivedFile\getTimestamp(), ForeignAPIFile\getTimestamp(), DatabaseLogEntry\getTimestamp(), ManualLogEntry\getTimestamp(), RCDatabaseLogEntry\getTimestamp(), RevisionItemBase\getTimestamp(), WANCacheReapUpdate\getTitleChangeEvents(), User\getTouched(), ApiQueryInfo\getVisitingWatcherInfo(), ForeignAPIRepo\httpGet(), ImageHistoryList\imageHistoryLine(), MediaWiki\Block\DatabaseBlock\initFromRow(), UserGroupMembership\initFromRow(), Language\internalUserTimeAndDate(), RefreshLinksJob\isAlreadyRefreshed(), User\isEmailConfirmationPending(), RecentChange\isInRCLifespan(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\isTimestampValid(), User\loadDefaults(), LocalFile\loadFromCache(), User\loadFromCache(), MessageCache\loadFromDB(), RecentChange\loadFromRow(), User\loadFromRow(), SpecialUndelete\loadRequest(), MediaWiki\Rest\Handler\PageHistoryCountHandler\loggingTableTime(), ApiMain\logRequest(), GenerateSitemap\main(), FormatMetadata\makeFormattedData(), MediaWiki\Session\Token\match(), SpecialBlock\maybeAlterFormDefaults(), UserGroupMembership\newFromRow(), User\newTouchedTimestamp(), OutputPage\output(), SpecialRecentChanges\outputChangesList(), InfoAction\pageCounts(), MediaWiki\Storage\PageEditStash\parseAndCache(), SpecialBlock\parseExpiryInput(), MediaWiki\Rest\Handler\PageHistoryHandler\processDbResults(), TableCleanup\progress(), ImageBuilder\progress(), MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider\providerAllowsAuthenticationDataChange(), LocalFile\publishTo(), RebuildRecentchanges\rebuildRecentChangesTablePass1(), QueryPage\recache(), ManageJobs\repushAbandoned(), WatchedItemStore\resetNotificationTimestamp(), MediaWiki\Rest\Handler\RevisionHandler\run(), ApiQueryCategories\run(), ApiQueryCategoryMembers\run(), ApiQueryDuplicateFiles\run(), ApiQueryProtectedTitles\run(), ApiQueryQueryPage\run(), ApiQueryWatchlistRaw\run(), CategoryMembershipChangeJob\run(), ApiMain\sendCacheHeaders(), MediaWiki\Block\BlockManager\setBlockCookie(), OutputPage\setLastModified(), WikiRevision\setTimestamp(), ApiComparePages\setVals(), BackupDumper\showReport(), TextPassDumper\showReport(), MediaWiki\Storage\PageEditStash\storeStashValue(), UpdateLogging\sync(), Language\time(), Language\timeanddate(), IPTC\timeHelper(), MediaWiki\Session\Token\toString(), ApiUpload\transformWarnings(), RecentChangesUpdateJob\updateActiveUsers(), MediaWiki\Block\DatabaseBlock\updateTimestamp(), CategoryChangesAsRdf\updateTS(), EditPage\wasDeletedSinceLastEdit(), wfApiMain(), wfStreamThumb(), wfTimestampOrNull(), and XmlDumpWriter\writeTimestamp().

◆ wfTimestampNow()

wfTimestampNow ( )

Convenience function; returns MediaWiki timestamp for the present time.

Returns
string TS_MW timestamp

Definition at line 1832 of file GlobalFunctions.php.

Referenced by UserGroupMembership\__construct(), CategoryMembershipChange\__construct(), LinksDeletionUpdate\__construct(), User\confirmEmail(), MediaWiki\Preferences\DefaultPreferencesFactory\datetimePreferences(), MediaWiki\Block\DatabaseBlock\doAutoblock(), SpecialWatchlist\doHeader(), PoolWorkArticleView\doWork(), SpecialExport\execute(), ApiEditPage\execute(), ApiProtect\execute(), ApiUserrights\execute(), GenerateSitemap\execute(), ImportTextFiles\execute(), MigrateFileRepoLayout\execute(), PPFuzzTest\execute(), ResetUserEmail\execute(), UpdateSearchIndex\execute(), FormatMetadata\fetchExtendedMetadata(), Title\getCascadeProtectionSources(), MediaWiki\Preferences\DefaultPreferencesFactory\getDateOptions(), RefreshLinksJob\getParserOutput(), ManualLogEntry\getTimestamp(), ParserOptions\getTimestamp(), EditPage\importFormData(), ManualLogEntry\insert(), MessageCache\isCacheExpired(), MediaWiki\Block\DatabaseBlock\isExpired(), Title\loadRestrictions(), Title\loadRestrictionsFromRows(), MergeHistory\merge(), Job\newRootJobParams(), SpecialLockdb\onSubmit(), SpecialRecentChanges\optionsPanel(), AtomFeed\outHeader(), RSSFeed\outHeader(), SpecialBlock\processForm(), WikiImporter\processRevision(), ManageJobs\repushAbandoned(), ProtectionForm\save(), ParserCache\save(), LogPage\saveContent(), HTMLFileCache\saveToFileCache(), and UserrightsPage\saveUserGroups().

◆ wfTimestampOrNull()

◆ wfTransactionalTimeLimit()

wfTransactionalTimeLimit ( )

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

Returns
int Prior time limit
Since
1.26

Definition at line 2687 of file GlobalFunctions.php.

References $wgTransactionalTimeLimit.

Referenced by RollbackAction\enableTransactionalTimelimit(), Action\useTransactionalTimeLimit(), ApiBase\useTransactionalTimeLimit(), and SpecialPage\useTransactionalTimeLimit().

◆ wfUnpack()

wfUnpack (   $format,
  $data,
  $length = false 
)

Wrapper around php's unpack.

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

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

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

Definition at line 2767 of file GlobalFunctions.php.

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

◆ wfUrlencode()

wfUrlencode (   $s)

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

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

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

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

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

;:$!*(),/~

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

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

Parameters
string$s
Returns
string

Definition at line 308 of file GlobalFunctions.php.

References $s.

Referenced by Title\__wakeup(), OutputPage\addHelpLink(), CoreParserFunctions\basepagenamee(), CoreMagicVariables\expand(), FileRepo\getDescriptionRenderUrl(), FileRepo\getDescriptionUrl(), WikiReference\getLocalUrl(), Title\getLocalURL(), MediaWikiSite\getPageUrl(), Title\getPrefixedURL(), LoginSignupSpecialPage\getReturnToQueryStringFragment(), Title\getSubpageUrlForm(), ParserOutput\getText(), Interwiki\getURL(), ApiBase\logFeatureUsage(), ApiMain\logRequest(), Title\makeTitle(), CoreParserFunctions\namespacee(), CoreParserFunctions\nse(), CoreParserFunctions\rootpagenamee(), Title\secureAndSplit(), CoreParserFunctions\speciale(), CoreParserFunctions\subjectspacee(), and CoreParserFunctions\talkspacee().

◆ wfUrlProtocols()

wfUrlProtocols (   $includeProtocolRelative = true)

Returns a regular expression of url protocols.

Parameters
bool$includeProtocolRelativeIf false, remove '//' from the returned protocol list. DO NOT USE this directly, use wfUrlProtocolsWithoutProtRel() instead
Returns
string

Definition at line 718 of file GlobalFunctions.php.

References $wgUrlProtocols.

Referenced by Parser\__construct(), Skin\addToSidebarPlain(), Skin\makeInternalOrExternalUrl(), Sanitizer\safeEncodeAttribute(), Sanitizer\validateAttributes(), and wfUrlProtocolsWithoutProtRel().

◆ wfUrlProtocolsWithoutProtRel()

wfUrlProtocolsWithoutProtRel ( )

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

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

Returns
string

Definition at line 763 of file GlobalFunctions.php.

References wfUrlProtocols().

Referenced by Parser\handleExternalLinks(), and Parser\handleMagicLinks().

◆ wfVarDump()

wfVarDump (   $var)

A wrapper around the PHP function var_export().

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

Parameters
mixed$varA PHP variable to dump.

Definition at line 1579 of file GlobalFunctions.php.

References $s, $wgOut, and print.

◆ wfWaitForSlaves()

wfWaitForSlaves (   $ifWritesSince = null,
  $wiki = false,
  $cluster = false,
  $timeout = null 
)

Waits for the replica DBs to catch up to the master position.

Use this when updating very large numbers of rows, as in maintenance scripts, to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.

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

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

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

Definition at line 2607 of file GlobalFunctions.php.

References wfDeprecated().

◆ wfWarn()

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

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

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

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

Definition at line 1074 of file GlobalFunctions.php.

Referenced by Exif\__construct(), TextContent\__construct(), Action\__construct(), MediaWiki\Storage\SqlBlobStore\decompressData(), ApiEditPage\execute(), TextPassDumper\exportTransform(), ForeignAPIRepo\fileExistsBatch(), Http\get(), MediaWiki\SpecialPage\SpecialPageFactory\getAliasList(), CacheHelper\getCachedValue(), WikiPage\getContentModel(), DifferenceEngine\getEngine(), ContribsPager\getExtraSortFields(), ContribsPager\getIndexField(), ParserCache\getKey(), MediaWiki\Revision\RevisionStore\getKnownCurrentRevision(), MediaWiki\SpecialPage\SpecialPageFactory\getLocalNameFor(), Language\getMagic(), MediaWiki\Revision\SlotRoleRegistry\getRoleHandler(), ChangeTags\getSoftwareTags(), MediaWiki\initializeArticle(), Html\inlineScript(), Linker\link(), Html\linkedScript(), MediaWiki\Revision\RevisionStoreCacheRecord\loadFreshRow(), Linker\makeBrokenImageLinkObj(), MediaWiki\Storage\PageUpdater\makeNewRevision(), MediaWiki\Revision\RevisionStore\newRevisionFromArchiveRowAndSlots(), MediaWiki\Revision\RevisionStore\newRevisionFromRowAndSlots(), Html\openElement(), BacklinkJobUtils\partitionBacklinkJob(), and EditPage\showEditForm().

◆ wfWikiID()

wfWikiID ( )

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

Deprecated:
since 1.35 Use WikiMap::getCurrentWikiId()
Returns
string

Definition at line 2421 of file GlobalFunctions.php.

References $wgDBname, and $wgDBprefix.