Go to the documentation of this file.
24 use Wikimedia\ScopedCallback;
32 define(
'MSG_CACHE_VERSION', 2 );
115 if ( self::$instance ===
null ) {
117 $services = MediaWikiServices::getInstance();
118 self::$instance =
new self(
139 self::$instance =
null;
149 $lckey = strtr( $key,
' ',
'_' );
150 if ( ord( $lckey ) < 128 ) {
151 $lckey[0] = strtolower( $lckey[0] );
153 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
177 $this->srvCache = $serverCache;
181 $this->mDisable = !$useDB;
182 $this->mExpiry = $expiry;
183 $this->contLang =
$contLang ?? MediaWikiServices::getInstance()->getContentLanguage();
194 if ( !$this->mParserOptions ) {
195 if ( !$wgUser->isSafeToLoad() ) {
200 $po->setAllowUnsafeRawHtml(
false );
221 $cacheKey = $this->srvCache->makeKey( __CLASS__,
$code );
223 return $this->srvCache->get( $cacheKey );
233 $cacheKey = $this->srvCache->makeKey( __CLASS__,
$code );
234 $this->srvCache->set( $cacheKey,
$cache );
259 if ( !is_string(
$code ) ) {
260 throw new InvalidArgumentException(
"Missing language code" );
263 # Don't do double loading...
270 # 8 lines of code just to say (once) that message cache is disabled
271 if ( $this->mDisable ) {
272 static $shownDisabled =
false;
273 if ( !$shownDisabled ) {
274 wfDebug( __METHOD__ .
": disabled\n" );
275 $shownDisabled =
true;
281 # Loading code starts
284 $where = []; # Debug info, delayed to avoid spamming debug log
too much
286 # Hash of the contents is stored in memcache, to detect if data-center cache
287 # or local cache goes out of date (e.g. due to replace() on some other server)
289 $this->cacheVolatile[
$code] = $hashVolatile;
291 # Try the local cache and check against the cluster hash key...
294 $where[] =
'local cache is empty';
295 } elseif ( !isset(
$cache[
'HASH'] ) ||
$cache[
'HASH'] !== $hash ) {
296 $where[] =
'local cache has the wrong hash';
299 $where[] =
'local cache is expired';
301 } elseif ( $hashVolatile ) {
302 $where[] =
'local cache validation key is expired/volatile';
305 $where[] =
'got from local cache';
311 $cacheKey = $this->clusterCache->makeKey(
'messages',
$code );
312 # Try the global cache. If it is empty, try to acquire a lock. If
313 # the lock can't be acquired, wait for the other thread to finish
314 # and then try the global cache a second time.
315 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
316 if ( $hashVolatile && $staleCache ) {
317 # Do not bother fetching the whole cache blob to avoid I/O.
318 # Instead, just try to get the non-blocking $statusKey lock
319 # below, and use the local stale value if it was not acquired.
320 $where[] =
'global cache is presumed expired';
322 $cache = $this->clusterCache->
get( $cacheKey );
324 $where[] =
'global cache is empty';
326 $where[] =
'global cache is expired';
328 } elseif ( $hashVolatile ) {
329 # DB results are replica DB lag prone until the holdoff TTL passes.
330 # By then, updates should be reflected in loadFromDBWithLock().
331 # One thread renerates the cache while others use old values.
332 $where[] =
'global cache is expired/volatile';
335 $where[] =
'got from global cache';
343 # Done, no need to retry
347 # We need to call loadFromDB. Limit the concurrency to one process.
348 # This prevents the site from going down when the cache expires.
349 # Note that the DB slam protection lock here is non-blocking.
351 if ( $loadStatus ===
true ) {
354 } elseif ( $staleCache ) {
355 # Use the stale cache while some other thread constructs the new one
356 $where[] =
'using stale cache';
360 } elseif ( $failedAttempts > 0 ) {
361 # Already blocked once, so avoid another lock/unlock cycle.
362 # This case will typically be hit if memcached is down, or if
363 # loadFromDB() takes longer than LOCK_WAIT.
364 $where[] =
"could not acquire status key.";
366 } elseif ( $loadStatus ===
'cantacquire' ) {
367 # Wait for the other thread to finish, then retry. Normally,
368 # the memcached get() will then yeild the other thread's result.
369 $where[] =
'waited for other thread to complete';
372 # Disable cache; $loadStatus is 'disabled'
379 $where[] =
'loading FAILED - cache is disabled';
380 $this->mDisable =
true;
382 wfDebugLog(
'MessageCacheError', __METHOD__ .
": Failed to load $code\n" );
383 # This used to throw an exception, but that led to nasty side effects like
384 # the whole wiki being instantly down if the memcached server died
388 throw new LogicException(
"Process cache for '$code' should be set by now." );
391 $info = implode(
', ', $where );
392 wfDebugLog(
'MessageCache', __METHOD__ .
": Loading $code... $info\n" );
404 # If cache updates on all levels fail, give up on message overrides.
405 # This is to avoid easy site outages; see $saveSuccess comments below.
406 $statusKey = $this->clusterCache->makeKey(
'messages',
$code,
'status' );
407 $status = $this->clusterCache->get( $statusKey );
409 $where[] =
"could not load; method is still globally disabled";
413 # Now let's regenerate
414 $where[] =
'loading from database';
416 # Lock the cache to prevent conflicting writes.
417 # This lock is non-blocking so stale cache can quickly be used.
418 # Note that load() will call a blocking getReentrantScopedLock()
419 # after this if it really need to wait for any current thread.
420 $cacheKey = $this->clusterCache->makeKey(
'messages',
$code );
422 if ( !$scopedLock ) {
423 $where[] =
'could not acquire main lock';
424 return 'cantacquire';
431 if ( !$saveSuccess ) {
446 $this->clusterCache->set( $statusKey,
'error', 60 * 5 );
447 $where[] =
'could not save cache, disabled globally for 5 minutes';
449 $where[] =
"could not save global cache";
478 if ( !$this->
cache->has( $wgLanguageCode ) ) {
479 $this->
load( $wgLanguageCode );
481 $mostused = array_keys( $this->
cache->get( $wgLanguageCode ) );
482 foreach ( $mostused
as $key =>
$value ) {
483 $mostused[$key] =
"$value/$code";
492 'page_is_redirect' => 0,
495 if (
count( $mostused ) ) {
496 $conds[
'page_title'] = $mostused;
498 $conds[] =
'page_title' .
$dbr->buildLike(
$dbr->anyString(),
'/',
$code );
500 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
501 # other than language code.
502 $conds[] =
'page_title NOT' .
503 $dbr->buildLike(
$dbr->anyString(),
'/',
$dbr->anyString() );
509 [
'page_title',
'page_latest' ],
511 __METHOD__ .
"($code)-big"
513 foreach (
$res as $row ) {
514 $name = $this->contLang->lcfirst( $row->page_title );
517 $cache[$row->page_title] =
'!TOO BIG';
520 $cache[
'EXCESSIVE'][$row->page_title] = $row->page_latest;
525 [
'page',
'revision',
'text' ],
526 [
'page_title',
'page_latest',
'old_id',
'old_text',
'old_flags' ],
528 __METHOD__ .
"($code)-small",
531 'revision' => [
'JOIN',
'page_latest=rev_id' ],
532 'text' => [
'JOIN',
'rev_text_id=old_id' ],
535 foreach (
$res as $row ) {
536 $name = $this->contLang->lcfirst( $row->page_title );
540 if ( $text ===
false ) {
548 .
": failed to load message page text for {$row->page_title} ($code)"
551 $entry =
' ' . $text;
553 $cache[$row->page_title] = $entry;
557 $cache[
'EXCESSIVE'][$row->page_title] = $row->page_latest;
564 # Hash for validating local cache (APC). No need to take into account
565 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
566 # stored and fetched from memcache.
569 unset(
$cache[
'EXCESSIVE'] );
594 if ( $this->mDisable ) {
605 if ( $text ===
false ) {
630 $this->clusterCache->makeKey(
'messages',
$code )
632 if ( !$scopedLock ) {
634 LoggerFactory::getInstance(
'MessageCache' )->error(
635 __METHOD__ .
': could not acquire lock to update {title} ({code})',
644 if ( $this->
load(
$code, self::FOR_UPDATE ) ) {
651 $newTextByTitle = [];
655 $page->loadPageData( $page::READ_LATEST );
658 $newTextByTitle[
$title] = $text;
660 if ( !is_string( $text ) ) {
664 $newBigTitles[
$title] = $page->getLatest();
675 foreach ( $newBigTitles
as $title => $id ) {
677 $this->wanCache->set(
679 ' ' . $newTextByTitle[
$title],
685 $cache[
'LATEST'] = time();
694 ScopedCallback::consume( $scopedLock );
702 $blobStore = $resourceloader->getMessageBlobStore();
704 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
716 if ( !isset(
$cache[
'VERSION'] ) || !isset(
$cache[
'EXPIRY'] ) ) {
739 if ( $dest ===
'all' ) {
740 $cacheKey = $this->clusterCache->makeKey(
'messages',
$code );
760 $value = $this->wanCache->get(
761 $this->wanCache->makeKey(
'messages',
$code,
'hash',
'v1' ),
775 $expired = ( $curTTL < 0 );
783 return [ $hash, $expired ];
797 $this->wanCache->set(
798 $this->wanCache->makeKey(
'messages',
$code,
'hash',
'v1' ),
801 'latest' =>
$cache[
'LATEST'] ?? 0
813 return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
849 function get( $key, $useDB =
true, $langcode =
true ) {
850 if ( is_int( $key ) ) {
854 } elseif ( !is_string( $key ) ) {
856 } elseif ( $key ===
'' ) {
864 Hooks::run(
'MessageCache::get', [ &$lckey ] );
870 !$this->mDisable && $useDB
874 if ( $message ===
false ) {
875 $parts = explode(
'/', $lckey );
879 if (
count( $parts ) == 2 && $parts[1] !==
'' ) {
881 if ( $message ===
null ) {
888 if ( $message !==
false ) {
890 $message = str_replace(
892 # Fix
for trailing whitespace, removed
by textarea
894 # Fix
for NBSP, converted to space
by firefox
929 if ( $message !==
false ) {
934 $message = $this->
getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
949 $langcode =
$lang->getCode();
953 $uckey = $this->contLang->ucfirst( $lckey );
955 if ( !isset( $alreadyTried[$langcode] ) ) {
960 if ( $message !==
false ) {
963 $alreadyTried[$langcode] =
true;
970 $message =
$lang->getMessage( $lckey );
971 if ( $message !==
null ) {
979 foreach ( $fallbackChain
as $code ) {
980 if ( isset( $alreadyTried[
$code] ) ) {
987 if ( $message !==
false ) {
990 $alreadyTried[
$code] =
true;
1011 return "$uckey/$langcode";
1035 if ( $entry !==
null ) {
1037 if ( substr( $entry, 0, 1 ) ===
' ' ) {
1039 return (
string)substr( $entry, 1 );
1040 } elseif ( $entry ===
'!NONEXISTENT' ) {
1064 if ( $entry ===
null || substr( $entry, 0, 1 ) !==
' ' ) {
1068 if ( $message !==
false ) {
1078 if ( $entry !==
false && substr( $entry, 0, 1 ) ===
' ' ) {
1079 if ( $this->cacheVolatile[
$code] ) {
1081 LoggerFactory::getInstance(
'MessageCache' )->debug(
1082 __METHOD__ .
': loading volatile key \'{titleKey}\'',
1088 return (
string)substr( $entry, 1 );
1104 return $this->srvCache->getWithSetCallback(
1105 $this->srvCache->makeKey(
'messages-big', $hash, $dbKey ),
1108 return $this->wanCache->getWithSetCallback(
1111 function ( $oldValue, &$ttl, &$setOpts )
use ( $dbKey,
$code,
$fname ) {
1114 $setOpts += Database::getCacheSetOptions(
$dbr );
1121 return '!NONEXISTENT';
1123 $content = $revision->getContent();
1127 LoggerFactory::getInstance(
'MessageCache' )->warning(
1128 $fname .
': failed to load page text for \'{titleKey}\'',
1129 [
'titleKey' => $dbKey,
'code' =>
$code ]
1134 if ( !is_string( $message ) ) {
1139 return '!NONEXISTENT';
1142 return ' ' . $message;
1156 public function transform( $message, $interface =
false, $language =
null,
$title =
null ) {
1158 if ( strpos( $message,
'{{' ) ===
false ) {
1162 if ( $this->mInParser ) {
1169 $popts->setInterfaceMessage( $interface );
1170 $popts->setTargetLanguage( $language );
1172 $userlang = $popts->setUserLang( $language );
1173 $this->mInParser =
true;
1174 $message =
$parser->transformMsg( $message, $popts,
$title );
1175 $this->mInParser =
false;
1176 $popts->setUserLang( $userlang );
1188 if ( !$this->mParser && isset(
$wgParser ) ) {
1189 # Do some initialisation so that we don't have to do it twice
1191 # Clone it and store it
1213 $interface =
false, $language =
null
1217 if ( $this->mInParser ) {
1218 return htmlspecialchars( $text );
1223 $popts->setInterfaceMessage( $interface );
1225 if ( is_string( $language ) ) {
1228 $popts->setTargetLanguage( $language );
1231 wfDebugLog(
'GlobalTitleFail', __METHOD__ .
' called by ' .
1237 # It's not uncommon having a null $wgTitle in scripts. See r80898
1238 # Create a ghost title in such case
1242 $this->mInParser =
true;
1244 $this->mInParser =
false;
1250 $this->mDisable =
true;
1254 $this->mDisable =
false;
1280 foreach ( array_keys( $langs )
as $code ) {
1281 $this->wanCache->touchCheckKey( $this->
getCheckKey( $code ) );
1283 $this->
cache->clear();
1293 $pieces = explode(
'/', $key );
1294 if (
count( $pieces ) < 2 ) {
1298 $lang = array_pop( $pieces );
1303 $message = implode(
'/', $pieces );
1305 return [ $message,
$lang ];
1324 unset(
$cache[
'VERSION'] );
1325 unset(
$cache[
'EXPIRY'] );
1326 unset(
$cache[
'EXCESSIVE'] );
1331 return array_map( [ $this->contLang,
'lcfirst' ], array_keys(
$cache ) );
1343 if ( $msgText ===
null ) {
1349 if ( $this->contLang->hasVariants() ) {
1350 $this->contLang->updateConversionTable(
$title );
1359 return $this->wanCache->makeKey(
'messages',
$code );
1374 $msgText =
$content->getWikitextForTransclusion();
1375 if ( $msgText ===
false || $msgText ===
null ) {
1378 LoggerFactory::getInstance(
'MessageCache' )->warning(
1379 __METHOD__ .
": message content doesn't provide wikitext "
1380 .
"(content model: " .
$content->getModel() .
")" );
1396 return $this->wanCache->makeKey(
'messages-big', $hash,
$title );
transform( $message, $interface=false, $language=null, $title=null)
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
static fetchLanguageName( $code, $inLanguage=self::AS_AUTONYMS, $include=self::ALL)
Set options of the Parser.
static newKnownCurrent(IDatabase $db, $pageIdOrTitle, $revId=0)
Load a revision based on a known page ID and current revision ID from the DB.
setValidationHash( $code, array $cache)
Set the md5 used to validate the local disk cache.
static normalizeKey( $key)
Normalize message key input.
parse( $text, $title=null, $linestart=true, $interface=false, $language=null)
setAllowUnsafeRawHtml( $x)
If the wiki is configured to allow raw html ($wgRawHtml = true) is it allowed in the specific case of...
A BagOStuff object with no objects in it.
saveToCaches(array $cache, $dest, $code=false)
Shortcut to update caches.
if(!isset( $args[0])) $lang
$wgParserConf
Parser configuration.
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
loadCachedMessagePageEntry( $dbKey, $code, $hash)
$wgMaxMsgCacheEntrySize
Maximum entry size in the message cache, in bytes.
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
static newFromAnon()
Get a ParserOptions object for an anonymous user.
const LOCK_TTL
How long memcached locks last.
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row.
Class representing a cache/ephemeral data store.
</source > ! result< div class="mw-highlight mw-content-ltr" dir="ltr">< pre >< span ></span >< span class="kd"> var</span >< span class="nx"> a</span >< span class="p"></span ></pre ></div > ! end ! test Multiline< source/> in lists !input *< source > a b</source > *foo< source > a b</source > ! html< ul >< li >< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul >< ul >< li > foo< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul > ! html tidy< ul >< li >< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul >< ul >< li > foo< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul > ! end ! test Custom attributes !input< source lang="javascript" id="foo" class="bar" dir="rtl" style="font-size: larger;"> var a
saveToLocalCache( $code, $cache)
Save the cache to APC.
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of data
you have access to all of the normal MediaWiki so you can get a DB use the cache
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
</source > ! result< p > Text< code class="mw-highlight" dir="ltr">< span class="kd"> var</span >< span class="nx"> a</span >< span class="p"></span ></code ></p > ! end ! test Enclose none(inline code) !!input Text< source lang
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access too
getMessageTextFromContent(Content $content=null)
$wgAdaptiveMessageCache
Instead of caching everything, only cache those messages which have been customised in the site conte...
static $instance
Singleton instance.
getDBkey()
Get the main part with underscores.
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
namespace and then decline to actually register it file or subcat img or subcat $title
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
get( $key, $maxAge=0.0)
Get the value for a key.
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
isMainCacheable( $name, array $overridable)
bigMessageCacheKey( $hash, $title)
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
static getMessageFor( $key, $code)
Get a message for a given language.
$wgUseDatabaseMessages
Translation using MediaWiki: namespace.
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
Handles a simple LRU key/value map with a maximum number of entries.
bool[] $cacheVolatile
Map of (language code => boolean)
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
replace( $title, $text)
Updates cache as necessary when message page is changed.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this submitted means any form of or written communication sent to the Licensor or its including but not limited to communication on electronic mailing source code control and issue tracking systems that are managed by
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
Message cache purging and in-place update handler for specific message page changes.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
static singleton()
Get the signleton instance of this class.
updateMessageOverride(Title $title, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
const WAIT_SEC
How long to wait for memcached locks.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
array $overridable
Map of (lowercase message key => index) for all software defined messages.
MapCacheLRU $cache
Process cache of loaded messages that are defined in MediaWiki namespace.
Allows to change the fields on the form that will be generated $name
$wgMsgCacheExpiry
Expiry time for the message cache key.
clear()
Clear all stored messages in global and local cache.
Multi-datacenter aware caching interface.
$wgLanguageCode
Site language code.
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
static getMain()
Get the RequestContext object associated with the main request.
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Base interface for content objects.
getLocalCache( $code)
Try to load the cache from APC.
wfGetMessageCacheStorage()
Get the cache object used by the message cache.
refreshAndReplaceInternal( $code, array $replacements)
Represents a title within MediaWiki.
loadFromDBWithLock( $code, array &$where, $mode=null)
$mDisable
Should mean that database cannot be used, but check.
load( $code, $mode=null)
Loads messages from caches or from database in this order: (1) local message cache (if $wgUseLocalMes...
isDisabled()
Whether DB/cache usage is disabled for determining messages.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
getParserOptions()
ParserOptions is lazy initialised.
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
static getMessageKeysFor( $code)
Get all message keys for a given language.
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
$mExpiry
Lifetime for cache, used by object caching.
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
static factory( $code)
Get a cached or new language object for a given language code.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, $useDB, $expiry, Language $contLang=null)
static fetchLanguageNames( $inLanguage=self::AS_AUTONYMS, $include='mw')
Get an array of language names, indexed by code.
Cache of messages that are defined by MediaWiki namespace pages or by hooks.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
Internationalisation code.
static getFallbacksFor( $code, $mode=self::MESSAGES_FALLBACKS)
Get the ordered list of fallback languages.
$wgUseLocalMessageCache
Set this to true to maintain a copy of the message cache on the local server.
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
static destroyInstance()
Destroy the singleton instance.