MediaWiki  1.32.0
MessageCache.php
Go to the documentation of this file.
1 <?php
24 use Wikimedia\ScopedCallback;
27 
32 define( 'MSG_CACHE_VERSION', 2 );
33 
40 class MessageCache {
41  const FOR_UPDATE = 1; // force message reload
42 
44  const WAIT_SEC = 15;
46  const LOCK_TTL = 30;
47 
53  protected $cache;
54 
60  protected $overridable;
61 
65  protected $cacheVolatile = [];
66 
71  protected $mDisable;
72 
77  protected $mExpiry;
78 
83  protected $mParserOptions;
85  protected $mParser;
86 
90  protected $mInParser = false;
91 
93  protected $wanCache;
95  protected $clusterCache;
97  protected $srvCache;
99  protected $contLang;
100 
106  private static $instance;
107 
114  public static function singleton() {
115  if ( self::$instance === null ) {
117  $services = MediaWikiServices::getInstance();
118  self::$instance = new self(
119  $services->getMainWANObjectCache(),
122  ? $services->getLocalServerObjectCache()
123  : new EmptyBagOStuff(),
126  $services->getContentLanguage()
127  );
128  }
129 
130  return self::$instance;
131  }
132 
138  public static function destroyInstance() {
139  self::$instance = null;
140  }
141 
148  public static function normalizeKey( $key ) {
149  $lckey = strtr( $key, ' ', '_' );
150  if ( ord( $lckey ) < 128 ) {
151  $lckey[0] = strtolower( $lckey[0] );
152  } else {
153  $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
154  }
155 
156  return $lckey;
157  }
158 
167  public function __construct(
170  BagOStuff $serverCache,
171  $useDB,
172  $expiry,
173  Language $contLang = null
174  ) {
175  $this->wanCache = $wanCache;
176  $this->clusterCache = $clusterCache;
177  $this->srvCache = $serverCache;
178 
179  $this->cache = new MapCacheLRU( 5 ); // limit size for sanity
180 
181  $this->mDisable = !$useDB;
182  $this->mExpiry = $expiry;
183  $this->contLang = $contLang ?? MediaWikiServices::getInstance()->getContentLanguage();
184  }
185 
191  function getParserOptions() {
192  global $wgUser;
193 
194  if ( !$this->mParserOptions ) {
195  if ( !$wgUser->isSafeToLoad() ) {
196  // $wgUser isn't unstubbable yet, so don't try to get a
197  // ParserOptions for it. And don't cache this ParserOptions
198  // either.
200  $po->setAllowUnsafeRawHtml( false );
201  return $po;
202  }
203 
204  $this->mParserOptions = new ParserOptions;
205  // Messages may take parameters that could come
206  // from malicious sources. As a precaution, disable
207  // the <html> parser tag when parsing messages.
208  $this->mParserOptions->setAllowUnsafeRawHtml( false );
209  }
210 
211  return $this->mParserOptions;
212  }
213 
220  protected function getLocalCache( $code ) {
221  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
222 
223  return $this->srvCache->get( $cacheKey );
224  }
225 
232  protected function saveToLocalCache( $code, $cache ) {
233  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
234  $this->srvCache->set( $cacheKey, $cache );
235  }
236 
258  protected function load( $code, $mode = null ) {
259  if ( !is_string( $code ) ) {
260  throw new InvalidArgumentException( "Missing language code" );
261  }
262 
263  # Don't do double loading...
264  if ( $this->cache->has( $code ) && $mode != self::FOR_UPDATE ) {
265  return true;
266  }
267 
268  $this->overridable = array_flip( Language::getMessageKeysFor( $code ) );
269 
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;
276  }
277 
278  return true;
279  }
280 
281  # Loading code starts
282  $success = false; # Keep track of success
283  $staleCache = false; # a cache array with expired data, or false if none has been loaded
284  $where = []; # Debug info, delayed to avoid spamming debug log too much
285 
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)
288  list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
289  $this->cacheVolatile[$code] = $hashVolatile;
290 
291  # Try the local cache and check against the cluster hash key...
292  $cache = $this->getLocalCache( $code );
293  if ( !$cache ) {
294  $where[] = 'local cache is empty';
295  } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
296  $where[] = 'local cache has the wrong hash';
297  $staleCache = $cache;
298  } elseif ( $this->isCacheExpired( $cache ) ) {
299  $where[] = 'local cache is expired';
300  $staleCache = $cache;
301  } elseif ( $hashVolatile ) {
302  $where[] = 'local cache validation key is expired/volatile';
303  $staleCache = $cache;
304  } else {
305  $where[] = 'got from local cache';
306  $this->cache->set( $code, $cache );
307  $success = true;
308  }
309 
310  if ( !$success ) {
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';
321  } else {
322  $cache = $this->clusterCache->get( $cacheKey );
323  if ( !$cache ) {
324  $where[] = 'global cache is empty';
325  } elseif ( $this->isCacheExpired( $cache ) ) {
326  $where[] = 'global cache is expired';
327  $staleCache = $cache;
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';
333  $staleCache = $cache;
334  } else {
335  $where[] = 'got from global cache';
336  $this->cache->set( $code, $cache );
337  $this->saveToCaches( $cache, 'local-only', $code );
338  $success = true;
339  }
340  }
341 
342  if ( $success ) {
343  # Done, no need to retry
344  break;
345  }
346 
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.
350  $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
351  if ( $loadStatus === true ) {
352  $success = true;
353  break;
354  } elseif ( $staleCache ) {
355  # Use the stale cache while some other thread constructs the new one
356  $where[] = 'using stale cache';
357  $this->cache->set( $code, $staleCache );
358  $success = true;
359  break;
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.";
365  break;
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';
370  $this->getReentrantScopedLock( $cacheKey );
371  } else {
372  # Disable cache; $loadStatus is 'disabled'
373  break;
374  }
375  }
376  }
377 
378  if ( !$success ) {
379  $where[] = 'loading FAILED - cache is disabled';
380  $this->mDisable = true;
381  $this->cache->set( $code, [] );
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
385  }
386 
387  if ( !$this->cache->has( $code ) ) { // sanity
388  throw new LogicException( "Process cache for '$code' should be set by now." );
389  }
390 
391  $info = implode( ', ', $where );
392  wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
393 
394  return $success;
395  }
396 
403  protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
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 );
408  if ( $status === 'error' ) {
409  $where[] = "could not load; method is still globally disabled";
410  return 'disabled';
411  }
412 
413  # Now let's regenerate
414  $where[] = 'loading from database';
415 
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 );
421  $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
422  if ( !$scopedLock ) {
423  $where[] = 'could not acquire main lock';
424  return 'cantacquire';
425  }
426 
427  $cache = $this->loadFromDB( $code, $mode );
428  $this->cache->set( $code, $cache );
429  $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
430 
431  if ( !$saveSuccess ) {
445  if ( $this->srvCache instanceof EmptyBagOStuff ) {
446  $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
447  $where[] = 'could not save cache, disabled globally for 5 minutes';
448  } else {
449  $where[] = "could not save global cache";
450  }
451  }
452 
453  return true;
454  }
455 
465  protected function loadFromDB( $code, $mode = null ) {
467 
468  // (T164666) The query here performs really poorly on WMF's
469  // contributions replicas. We don't have a way to say "any group except
470  // contributions", so for the moment let's specify 'api'.
471  // @todo: Get rid of this hack.
472  $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
473 
474  $cache = [];
475 
476  $mostused = []; // list of "<cased message key>/<code>"
478  if ( !$this->cache->has( $wgLanguageCode ) ) {
479  $this->load( $wgLanguageCode );
480  }
481  $mostused = array_keys( $this->cache->get( $wgLanguageCode ) );
482  foreach ( $mostused as $key => $value ) {
483  $mostused[$key] = "$value/$code";
484  }
485  }
486 
487  // Get the list of software-defined messages in core/extensions
489 
490  // Common conditions
491  $conds = [
492  'page_is_redirect' => 0,
493  'page_namespace' => NS_MEDIAWIKI,
494  ];
495  if ( count( $mostused ) ) {
496  $conds['page_title'] = $mostused;
497  } elseif ( $code !== $wgLanguageCode ) {
498  $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
499  } else {
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() );
504  }
505 
506  // Set the stubs for oversized software-defined messages in the main cache map
507  $res = $dbr->select(
508  'page',
509  [ 'page_title', 'page_latest' ],
510  array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
511  __METHOD__ . "($code)-big"
512  );
513  foreach ( $res as $row ) {
514  $name = $this->contLang->lcfirst( $row->page_title );
515  // Include entries/stubs for all keys in $mostused in adaptive mode
517  $cache[$row->page_title] = '!TOO BIG';
518  }
519  // At least include revision ID so page changes are reflected in the hash
520  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
521  }
522 
523  // Set the text for small software-defined messages in the main cache map
524  $res = $dbr->select(
525  [ 'page', 'revision', 'text' ],
526  [ 'page_title', 'page_latest', 'old_id', 'old_text', 'old_flags' ],
527  array_merge( $conds, [ 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
528  __METHOD__ . "($code)-small",
529  [],
530  [
531  'revision' => [ 'JOIN', 'page_latest=rev_id' ],
532  'text' => [ 'JOIN', 'rev_text_id=old_id' ],
533  ]
534  );
535  foreach ( $res as $row ) {
536  $name = $this->contLang->lcfirst( $row->page_title );
537  // Include entries/stubs for all keys in $mostused in adaptive mode
539  $text = Revision::getRevisionText( $row );
540  if ( $text === false ) {
541  // Failed to fetch data; possible ES errors?
542  // Store a marker to fetch on-demand as a workaround...
543  // TODO Use a differnt marker
544  $entry = '!TOO BIG';
545  wfDebugLog(
546  'MessageCache',
547  __METHOD__
548  . ": failed to load message page text for {$row->page_title} ($code)"
549  );
550  } else {
551  $entry = ' ' . $text;
552  }
553  $cache[$row->page_title] = $entry;
554  } else {
555  // T193271: cache object gets too big and slow to generate.
556  // At least include revision ID so page changes are reflected in the hash.
557  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
558  }
559  }
560 
561  $cache['VERSION'] = MSG_CACHE_VERSION;
562  ksort( $cache );
563 
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.
567  $cache['HASH'] = md5( serialize( $cache ) );
568  $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
569  unset( $cache['EXCESSIVE'] ); // only needed for hash
570 
571  return $cache;
572  }
573 
579  private function isMainCacheable( $name, array $overridable ) {
580  // Include common conversion table pages. This also avoids problems with
581  // Installer::parse() bailing out due to disallowed DB queries (T207979).
582  return ( isset( $overridable[$name] ) || strpos( $name, 'conversiontable/' ) === 0 );
583  }
584 
591  public function replace( $title, $text ) {
592  global $wgLanguageCode;
593 
594  if ( $this->mDisable ) {
595  return;
596  }
597 
598  list( $msg, $code ) = $this->figureMessage( $title );
599  if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
600  // Content language overrides do not use the /<code> suffix
601  return;
602  }
603 
604  // (a) Update the process cache with the new message text
605  if ( $text === false ) {
606  // Page deleted
607  $this->cache->setField( $code, $title, '!NONEXISTENT' );
608  } else {
609  // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
610  $this->cache->setField( $code, $title, ' ' . $text );
611  }
612 
613  // (b) Update the shared caches in a deferred update with a fresh DB snapshot
615  new MessageCacheUpdate( $code, $title, $msg ),
617  );
618  }
619 
625  public function refreshAndReplaceInternal( $code, array $replacements ) {
627 
628  // Allow one caller at a time to avoid race conditions
629  $scopedLock = $this->getReentrantScopedLock(
630  $this->clusterCache->makeKey( 'messages', $code )
631  );
632  if ( !$scopedLock ) {
633  foreach ( $replacements as list( $title ) ) {
634  LoggerFactory::getInstance( 'MessageCache' )->error(
635  __METHOD__ . ': could not acquire lock to update {title} ({code})',
636  [ 'title' => $title, 'code' => $code ] );
637  }
638 
639  return;
640  }
641 
642  // Load the existing cache to update it in the local DC cache.
643  // The other DCs will see a hash mismatch.
644  if ( $this->load( $code, self::FOR_UPDATE ) ) {
645  $cache = $this->cache->get( $code );
646  } else {
647  // Err? Fall back to loading from the database.
648  $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
649  }
650  // Check if individual cache keys should exist and update cache accordingly
651  $newTextByTitle = []; // map of (title => content)
652  $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
653  foreach ( $replacements as list( $title ) ) {
655  $page->loadPageData( $page::READ_LATEST );
656  $text = $this->getMessageTextFromContent( $page->getContent() );
657  // Remember the text for the blob store update later on
658  $newTextByTitle[$title] = $text;
659  // Note that if $text is false, then $cache should have a !NONEXISTANT entry
660  if ( !is_string( $text ) ) {
661  $cache[$title] = '!NONEXISTENT';
662  } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
663  $cache[$title] = '!TOO BIG';
664  $newBigTitles[$title] = $page->getLatest();
665  } else {
666  $cache[$title] = ' ' . $text;
667  }
668  }
669  // Update HASH for the new key. Incorporates various administrative keys,
670  // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
671  // and previous replace() calls), but that doesn't really matter since we
672  // only ever compare it for equality with a copy saved by saveToCaches().
673  $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
674  // Update the too-big WAN cache entries now that we have the new HASH
675  foreach ( $newBigTitles as $title => $id ) {
676  // Match logic of loadCachedMessagePageEntry()
677  $this->wanCache->set(
678  $this->bigMessageCacheKey( $cache['HASH'], $title ),
679  ' ' . $newTextByTitle[$title],
680  $this->mExpiry
681  );
682  }
683  // Mark this cache as definitely being "latest" (non-volatile) so
684  // load() calls do not try to refresh the cache with replica DB data
685  $cache['LATEST'] = time();
686  // Update the process cache
687  $this->cache->set( $code, $cache );
688  // Pre-emptively update the local datacenter cache so things like edit filter and
689  // blacklist changes are reflected immediately; these often use MediaWiki: pages.
690  // The datacenter handling replace() calls should be the same one handling edits
691  // as they require HTTP POST.
692  $this->saveToCaches( $cache, 'all', $code );
693  // Release the lock now that the cache is saved
694  ScopedCallback::consume( $scopedLock );
695 
696  // Relay the purge. Touching this check key expires cache contents
697  // and local cache (APC) validation hash across all datacenters.
698  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
699 
700  // Purge the messages in the message blob store and fire any hook handlers
701  $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
702  $blobStore = $resourceloader->getMessageBlobStore();
703  foreach ( $replacements as list( $title, $msg ) ) {
704  $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
705  Hooks::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
706  }
707  }
708 
715  protected function isCacheExpired( $cache ) {
716  if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
717  return true;
718  }
719  if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
720  return true;
721  }
722  if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
723  return true;
724  }
725 
726  return false;
727  }
728 
738  protected function saveToCaches( array $cache, $dest, $code = false ) {
739  if ( $dest === 'all' ) {
740  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
741  $success = $this->clusterCache->set( $cacheKey, $cache );
742  $this->setValidationHash( $code, $cache );
743  } else {
744  $success = true;
745  }
746 
747  $this->saveToLocalCache( $code, $cache );
748 
749  return $success;
750  }
751 
758  protected function getValidationHash( $code ) {
759  $curTTL = null;
760  $value = $this->wanCache->get(
761  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
762  $curTTL,
763  [ $this->getCheckKey( $code ) ]
764  );
765 
766  if ( $value ) {
767  $hash = $value['hash'];
768  if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
769  // Cache was recently updated via replace() and should be up-to-date.
770  // That method is only called in the primary datacenter and uses FOR_UPDATE.
771  // Also, it is unlikely that the current datacenter is *now* secondary one.
772  $expired = false;
773  } else {
774  // See if the "check" key was bumped after the hash was generated
775  $expired = ( $curTTL < 0 );
776  }
777  } else {
778  // No hash found at all; cache must regenerate to be safe
779  $hash = false;
780  $expired = true;
781  }
782 
783  return [ $hash, $expired ];
784  }
785 
796  protected function setValidationHash( $code, array $cache ) {
797  $this->wanCache->set(
798  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
799  [
800  'hash' => $cache['HASH'],
801  'latest' => $cache['LATEST'] ?? 0
802  ],
804  );
805  }
806 
812  protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
813  return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
814  }
815 
849  function get( $key, $useDB = true, $langcode = true ) {
850  if ( is_int( $key ) ) {
851  // Fix numerical strings that somehow become ints
852  // on their way here
853  $key = (string)$key;
854  } elseif ( !is_string( $key ) ) {
855  throw new MWException( 'Non-string key given' );
856  } elseif ( $key === '' ) {
857  // Shortcut: the empty key is always missing
858  return false;
859  }
860 
861  // Normalise title-case input (with some inlining)
862  $lckey = self::normalizeKey( $key );
863 
864  Hooks::run( 'MessageCache::get', [ &$lckey ] );
865 
866  // Loop through each language in the fallback list until we find something useful
867  $message = $this->getMessageFromFallbackChain(
868  wfGetLangObj( $langcode ),
869  $lckey,
870  !$this->mDisable && $useDB
871  );
872 
873  // If we still have no message, maybe the key was in fact a full key so try that
874  if ( $message === false ) {
875  $parts = explode( '/', $lckey );
876  // We may get calls for things that are http-urls from sidebar
877  // Let's not load nonexistent languages for those
878  // They usually have more than one slash.
879  if ( count( $parts ) == 2 && $parts[1] !== '' ) {
880  $message = Language::getMessageFor( $parts[0], $parts[1] );
881  if ( $message === null ) {
882  $message = false;
883  }
884  }
885  }
886 
887  // Post-processing if the message exists
888  if ( $message !== false ) {
889  // Fix whitespace
890  $message = str_replace(
891  [
892  # Fix for trailing whitespace, removed by textarea
893  '&#32;',
894  # Fix for NBSP, converted to space by firefox
895  '&nbsp;',
896  '&#160;',
897  '&shy;'
898  ],
899  [
900  ' ',
901  "\u{00A0}",
902  "\u{00A0}",
903  "\u{00AD}"
904  ],
905  $message
906  );
907  }
908 
909  return $message;
910  }
911 
924  protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
925  $alreadyTried = [];
926 
927  // First try the requested language.
928  $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
929  if ( $message !== false ) {
930  return $message;
931  }
932 
933  // Now try checking the site language.
934  $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
935  return $message;
936  }
937 
948  private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
949  $langcode = $lang->getCode();
950 
951  // Try checking the database for the requested language
952  if ( $useDB ) {
953  $uckey = $this->contLang->ucfirst( $lckey );
954 
955  if ( !isset( $alreadyTried[$langcode] ) ) {
956  $message = $this->getMsgFromNamespace(
957  $this->getMessagePageName( $langcode, $uckey ),
958  $langcode
959  );
960  if ( $message !== false ) {
961  return $message;
962  }
963  $alreadyTried[$langcode] = true;
964  }
965  } else {
966  $uckey = null;
967  }
968 
969  // Check the CDB cache
970  $message = $lang->getMessage( $lckey );
971  if ( $message !== null ) {
972  return $message;
973  }
974 
975  // Try checking the database for all of the fallback languages
976  if ( $useDB ) {
977  $fallbackChain = Language::getFallbacksFor( $langcode );
978 
979  foreach ( $fallbackChain as $code ) {
980  if ( isset( $alreadyTried[$code] ) ) {
981  continue;
982  }
983 
984  $message = $this->getMsgFromNamespace(
985  $this->getMessagePageName( $code, $uckey ), $code );
986 
987  if ( $message !== false ) {
988  return $message;
989  }
990  $alreadyTried[$code] = true;
991  }
992  }
993 
994  return false;
995  }
996 
1004  private function getMessagePageName( $langcode, $uckey ) {
1005  global $wgLanguageCode;
1006 
1007  if ( $langcode === $wgLanguageCode ) {
1008  // Messages created in the content language will not have the /lang extension
1009  return $uckey;
1010  } else {
1011  return "$uckey/$langcode";
1012  }
1013  }
1014 
1027  public function getMsgFromNamespace( $title, $code ) {
1028  // Load all MediaWiki page definitions into cache. Note that individual keys
1029  // already loaded into cache during this request remain in the cache, which
1030  // includes the value of hook-defined messages.
1031  $this->load( $code );
1032 
1033  $entry = $this->cache->getField( $code, $title );
1034 
1035  if ( $entry !== null ) {
1036  // Message page exists as an override of a software messages
1037  if ( substr( $entry, 0, 1 ) === ' ' ) {
1038  // The message exists and is not '!TOO BIG'
1039  return (string)substr( $entry, 1 );
1040  } elseif ( $entry === '!NONEXISTENT' ) {
1041  // The text might be '-' or missing due to some data loss
1042  return false;
1043  }
1044  // Load the message page, utilizing the individual message cache.
1045  // If the page does not exist, there will be no hook handler fallbacks.
1046  $entry = $this->loadCachedMessagePageEntry(
1047  $title,
1048  $code,
1049  $this->cache->getField( $code, 'HASH' )
1050  );
1051  } else {
1052  // Message page either does not exist or does not override a software message
1053  $name = $this->contLang->lcfirst( $title );
1054  if ( !$this->isMainCacheable( $name, $this->overridable ) ) {
1055  // Message page does not override any software-defined message. A custom
1056  // message might be defined to have content or settings specific to the wiki.
1057  // Load the message page, utilizing the individual message cache as needed.
1058  $entry = $this->loadCachedMessagePageEntry(
1059  $title,
1060  $code,
1061  $this->cache->getField( $code, 'HASH' )
1062  );
1063  }
1064  if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1065  // Message does not have a MediaWiki page definition; try hook handlers
1066  $message = false;
1067  Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1068  if ( $message !== false ) {
1069  $this->cache->setField( $code, $title, ' ' . $message );
1070  } else {
1071  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1072  }
1073 
1074  return $message;
1075  }
1076  }
1077 
1078  if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1079  if ( $this->cacheVolatile[$code] ) {
1080  // Make sure that individual keys respect the WAN cache holdoff period too
1081  LoggerFactory::getInstance( 'MessageCache' )->debug(
1082  __METHOD__ . ': loading volatile key \'{titleKey}\'',
1083  [ 'titleKey' => $title, 'code' => $code ] );
1084  } else {
1085  $this->cache->setField( $code, $title, $entry );
1086  }
1087  // The message exists, so make sure a string is returned
1088  return (string)substr( $entry, 1 );
1089  }
1090 
1091  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1092 
1093  return false;
1094  }
1095 
1102  private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1103  $fname = __METHOD__;
1104  return $this->srvCache->getWithSetCallback(
1105  $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1107  function () use ( $code, $dbKey, $hash, $fname ) {
1108  return $this->wanCache->getWithSetCallback(
1109  $this->bigMessageCacheKey( $hash, $dbKey ),
1110  $this->mExpiry,
1111  function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1112  // Try loading the message from the database
1113  $dbr = wfGetDB( DB_REPLICA );
1114  $setOpts += Database::getCacheSetOptions( $dbr );
1115  // Use newKnownCurrent() to avoid querying revision/user tables
1116  $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1117  $revision = Revision::newKnownCurrent( $dbr, $title );
1118  if ( !$revision ) {
1119  // The wiki doesn't have a local override page. Cache absence with normal TTL.
1120  // When overrides are created, self::replace() takes care of the cache.
1121  return '!NONEXISTENT';
1122  }
1123  $content = $revision->getContent();
1124  if ( $content ) {
1125  $message = $this->getMessageTextFromContent( $content );
1126  } else {
1127  LoggerFactory::getInstance( 'MessageCache' )->warning(
1128  $fname . ': failed to load page text for \'{titleKey}\'',
1129  [ 'titleKey' => $dbKey, 'code' => $code ]
1130  );
1131  $message = null;
1132  }
1133 
1134  if ( !is_string( $message ) ) {
1135  // Revision failed to load Content, or Content is incompatible with wikitext.
1136  // Possibly a temporary loading failure.
1137  $ttl = 5;
1138 
1139  return '!NONEXISTENT';
1140  }
1141 
1142  return ' ' . $message;
1143  }
1144  );
1145  }
1146  );
1147  }
1148 
1156  public function transform( $message, $interface = false, $language = null, $title = null ) {
1157  // Avoid creating parser if nothing to transform
1158  if ( strpos( $message, '{{' ) === false ) {
1159  return $message;
1160  }
1161 
1162  if ( $this->mInParser ) {
1163  return $message;
1164  }
1165 
1166  $parser = $this->getParser();
1167  if ( $parser ) {
1168  $popts = $this->getParserOptions();
1169  $popts->setInterfaceMessage( $interface );
1170  $popts->setTargetLanguage( $language );
1171 
1172  $userlang = $popts->setUserLang( $language );
1173  $this->mInParser = true;
1174  $message = $parser->transformMsg( $message, $popts, $title );
1175  $this->mInParser = false;
1176  $popts->setUserLang( $userlang );
1177  }
1178 
1179  return $message;
1180  }
1181 
1185  public function getParser() {
1186  global $wgParser, $wgParserConf;
1187 
1188  if ( !$this->mParser && isset( $wgParser ) ) {
1189  # Do some initialisation so that we don't have to do it twice
1190  $wgParser->firstCallInit();
1191  # Clone it and store it
1192  $class = $wgParserConf['class'];
1193  if ( $class == ParserDiffTest::class ) {
1194  # Uncloneable
1195  $this->mParser = new $class( $wgParserConf );
1196  } else {
1197  $this->mParser = clone $wgParser;
1198  }
1199  }
1200 
1201  return $this->mParser;
1202  }
1203 
1212  public function parse( $text, $title = null, $linestart = true,
1213  $interface = false, $language = null
1214  ) {
1215  global $wgTitle;
1216 
1217  if ( $this->mInParser ) {
1218  return htmlspecialchars( $text );
1219  }
1220 
1221  $parser = $this->getParser();
1222  $popts = $this->getParserOptions();
1223  $popts->setInterfaceMessage( $interface );
1224 
1225  if ( is_string( $language ) ) {
1226  $language = Language::factory( $language );
1227  }
1228  $popts->setTargetLanguage( $language );
1229 
1230  if ( !$title || !$title instanceof Title ) {
1231  wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1232  wfGetAllCallers( 6 ) . ' with no title set.' );
1233  $title = $wgTitle;
1234  }
1235  // Sometimes $wgTitle isn't set either...
1236  if ( !$title ) {
1237  # It's not uncommon having a null $wgTitle in scripts. See r80898
1238  # Create a ghost title in such case
1239  $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1240  }
1241 
1242  $this->mInParser = true;
1243  $res = $parser->parse( $text, $title, $popts, $linestart );
1244  $this->mInParser = false;
1245 
1246  return $res;
1247  }
1248 
1249  public function disable() {
1250  $this->mDisable = true;
1251  }
1252 
1253  public function enable() {
1254  $this->mDisable = false;
1255  }
1256 
1269  public function isDisabled() {
1270  return $this->mDisable;
1271  }
1272 
1278  public function clear() {
1279  $langs = Language::fetchLanguageNames( null, 'mw' );
1280  foreach ( array_keys( $langs ) as $code ) {
1281  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1282  }
1283  $this->cache->clear();
1284  }
1285 
1290  public function figureMessage( $key ) {
1291  global $wgLanguageCode;
1292 
1293  $pieces = explode( '/', $key );
1294  if ( count( $pieces ) < 2 ) {
1295  return [ $key, $wgLanguageCode ];
1296  }
1297 
1298  $lang = array_pop( $pieces );
1299  if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1300  return [ $key, $wgLanguageCode ];
1301  }
1302 
1303  $message = implode( '/', $pieces );
1304 
1305  return [ $message, $lang ];
1306  }
1307 
1316  public function getAllMessageKeys( $code ) {
1317  $this->load( $code );
1318  if ( !$this->cache->has( $code ) ) {
1319  // Apparently load() failed
1320  return null;
1321  }
1322  // Remove administrative keys
1323  $cache = $this->cache->get( $code );
1324  unset( $cache['VERSION'] );
1325  unset( $cache['EXPIRY'] );
1326  unset( $cache['EXCESSIVE'] );
1327  // Remove any !NONEXISTENT keys
1328  $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1329 
1330  // Keys may appear with a capital first letter. lcfirst them.
1331  return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1332  }
1333 
1341  public function updateMessageOverride( Title $title, Content $content = null ) {
1342  $msgText = $this->getMessageTextFromContent( $content );
1343  if ( $msgText === null ) {
1344  $msgText = false; // treat as not existing
1345  }
1346 
1347  $this->replace( $title->getDBkey(), $msgText );
1348 
1349  if ( $this->contLang->hasVariants() ) {
1350  $this->contLang->updateConversionTable( $title );
1351  }
1352  }
1353 
1358  public function getCheckKey( $code ) {
1359  return $this->wanCache->makeKey( 'messages', $code );
1360  }
1361 
1366  private function getMessageTextFromContent( Content $content = null ) {
1367  // @TODO: could skip pseudo-messages like js/css here, based on content model
1368  if ( $content ) {
1369  // Message page exists...
1370  // XXX: Is this the right way to turn a Content object into a message?
1371  // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1372  // CssContent. MessageContent is *not* used for storing messages, it's
1373  // only used for wrapping them when needed.
1374  $msgText = $content->getWikitextForTransclusion();
1375  if ( $msgText === false || $msgText === null ) {
1376  // This might be due to some kind of misconfiguration...
1377  $msgText = null;
1378  LoggerFactory::getInstance( 'MessageCache' )->warning(
1379  __METHOD__ . ": message content doesn't provide wikitext "
1380  . "(content model: " . $content->getModel() . ")" );
1381  }
1382  } else {
1383  // Message page does not exist...
1384  $msgText = false;
1385  }
1386 
1387  return $msgText;
1388  }
1389 
1395  private function bigMessageCacheKey( $hash, $title ) {
1396  return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1397  }
1398 }
MessageCache\transform
transform( $message, $interface=false, $language=null, $title=null)
Definition: MessageCache.php:1156
$status
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
Definition: hooks.txt:1305
Language\fetchLanguageName
static fetchLanguageName( $code, $inLanguage=self::AS_AUTONYMS, $include=self::ALL)
Definition: Language.php:940
MessageCache\$mParser
Parser $mParser
Definition: MessageCache.php:85
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:42
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
Revision\newKnownCurrent
static newKnownCurrent(IDatabase $db, $pageIdOrTitle, $revId=0)
Load a revision based on a known page ID and current revision ID from the DB.
Definition: Revision.php:1299
MessageCache\setValidationHash
setValidationHash( $code, array $cache)
Set the md5 used to validate the local disk cache.
Definition: MessageCache.php:796
MessageCache\$clusterCache
BagOStuff $clusterCache
Definition: MessageCache.php:95
$wgParser
$wgParser
Definition: Setup.php:913
MessageCache\normalizeKey
static normalizeKey( $key)
Normalize message key input.
Definition: MessageCache.php:148
MessageCache\parse
parse( $text, $title=null, $linestart=true, $interface=false, $language=null)
Definition: MessageCache.php:1212
ParserOptions\setAllowUnsafeRawHtml
setAllowUnsafeRawHtml( $x)
If the wiki is configured to allow raw html ($wgRawHtml = true) is it allowed in the specific case of...
Definition: ParserOptions.php:769
EmptyBagOStuff
A BagOStuff object with no objects in it.
Definition: EmptyBagOStuff.php:29
MessageCache\saveToCaches
saveToCaches(array $cache, $dest, $code=false)
Shortcut to update caches.
Definition: MessageCache.php:738
MessageCache\enable
enable()
Definition: MessageCache.php:1253
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
$wgParserConf
$wgParserConf
Parser configuration.
Definition: DefaultSettings.php:4158
captcha-old.count
count
Definition: captcha-old.py:249
MessageCache\$mParserOptions
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
Definition: MessageCache.php:83
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1954
MessageCache\$mInParser
$mInParser
Definition: MessageCache.php:90
MessageCache\loadCachedMessagePageEntry
loadCachedMessagePageEntry( $dbKey, $code, $hash)
Definition: MessageCache.php:1102
$wgMaxMsgCacheEntrySize
$wgMaxMsgCacheEntrySize
Maximum entry size in the message cache, in bytes.
Definition: DefaultSettings.php:3106
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
Definition: DeferredUpdates.php:79
ParserOptions\newFromAnon
static newFromAnon()
Get a ParserOptions object for an anonymous user.
Definition: ParserOptions.php:1001
MessageCache\LOCK_TTL
const LOCK_TTL
How long memcached locks last.
Definition: MessageCache.php:46
Revision\getRevisionText
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row.
Definition: Revision.php:1050
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:58
a
</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
Definition: parserTests.txt:89
MessageCache\saveToLocalCache
saveToLocalCache( $code, $cache)
Save the cache to APC.
Definition: MessageCache.php:232
$res
$res
Definition: database.txt:21
$wgTitle
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
Definition: api.php:57
IExpiringStore\TTL_MINUTE
const TTL_MINUTE
Definition: IExpiringStore.php:34
$success
$success
Definition: NoLocalSettings.php:42
data
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
Definition: hooks.txt:6
serialize
serialize()
Definition: ApiMessageTrait.php:131
cache
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
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.
Definition: GlobalFunctions.php:1082
php
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
Definition: injection.txt:35
MessageCache\getValidationHash
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
Definition: MessageCache.php:758
$dbr
$dbr
Definition: testCompression.php:50
none
</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
too
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
Definition: distributors.txt:9
MessageCache\getMessageTextFromContent
getMessageTextFromContent(Content $content=null)
Definition: MessageCache.php:1366
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:53
$wgAdaptiveMessageCache
$wgAdaptiveMessageCache
Instead of caching everything, only cache those messages which have been customised in the site conte...
Definition: DefaultSettings.php:2576
MessageCache\$instance
static $instance
Singleton instance.
Definition: MessageCache.php:106
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:951
MessageCache\loadFromDB
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
Definition: MessageCache.php:465
MWException
MediaWiki exception.
Definition: MWException.php:26
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:964
MessageCache\getCheckKey
getCheckKey( $code)
Definition: MessageCache.php:1358
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:127
MapCacheLRU\get
get( $key, $maxAge=0.0)
Get the value for a key.
Definition: MapCacheLRU.php:163
MessageCache\getMsgFromNamespace
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
Definition: MessageCache.php:1027
MessageCache\isMainCacheable
isMainCacheable( $name, array $overridable)
Definition: MessageCache.php:579
MessageCache\bigMessageCacheKey
bigMessageCacheKey( $hash, $title)
Definition: MessageCache.php:1395
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2693
Language\getMessageFor
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4675
$wgUseDatabaseMessages
$wgUseDatabaseMessages
Translation using MediaWiki: namespace.
Definition: DefaultSettings.php:3096
MessageCache\getMessagePageName
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
Definition: MessageCache.php:1004
IExpiringStore\TTL_INDEFINITE
const TTL_INDEFINITE
Definition: IExpiringStore.php:45
MSG_CACHE_VERSION
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
Definition: MessageCache.php:32
MapCacheLRU
Handles a simple LRU key/value map with a maximum number of entries.
Definition: MapCacheLRU.php:37
MessageCache\$cacheVolatile
bool[] $cacheVolatile
Map of (language code => boolean)
Definition: MessageCache.php:65
MessageCache\figureMessage
figureMessage( $key)
Definition: MessageCache.php:1290
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1281
use
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
Definition: MIT-LICENSE.txt:10
$code
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
Definition: hooks.txt:813
MessageCache\$srvCache
BagOStuff $srvCache
Definition: MessageCache.php:97
$parser
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1841
MessageCache\replace
replace( $title, $text)
Updates cache as necessary when message page is changed.
Definition: MessageCache.php:591
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:545
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1983
DB_MASTER
const DB_MASTER
Definition: defines.php:26
array
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))
by
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
Definition: APACHE-LICENSE-2.0.txt:49
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:988
string
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
Definition: hooks.txt:175
MessageCache\getMessageFromFallbackChain
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
Definition: MessageCache.php:924
MessageCacheUpdate
Message cache purging and in-place update handler for specific message page changes.
Definition: MessageCacheUpdate.php:31
MessageCache\FOR_UPDATE
const FOR_UPDATE
Definition: MessageCache.php:41
list
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
Definition: deferred.txt:11
MessageCache\singleton
static singleton()
Get the signleton instance of this class.
Definition: MessageCache.php:114
MessageCache\updateMessageOverride
updateMessageOverride(Title $title, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
Definition: MessageCache.php:1341
MessageCache\WAIT_SEC
const WAIT_SEC
How long to wait for memcached locks.
Definition: MessageCache.php:44
or
or
Definition: COPYING.txt:140
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:121
MessageCache\$overridable
array $overridable
Map of (lowercase message key => index) for all software defined messages.
Definition: MessageCache.php:60
MessageCache\$cache
MapCacheLRU $cache
Process cache of loaded messages that are defined in MediaWiki namespace.
Definition: MessageCache.php:53
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
$wgMsgCacheExpiry
$wgMsgCacheExpiry
Expiry time for the message cache key.
Definition: DefaultSettings.php:3101
$value
$value
Definition: styleTest.css.php:49
MessageCache\clear
clear()
Clear all stored messages in global and local cache.
Definition: MessageCache.php:1278
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:118
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:2942
MessageCache\getReentrantScopedLock
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
Definition: MessageCache.php:812
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:432
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1536
Content
Base interface for content objects.
Definition: Content.php:34
MessageCache\getParser
getParser()
Definition: MessageCache.php:1185
MessageCache\getLocalCache
getLocalCache( $code)
Try to load the cache from APC.
Definition: MessageCache.php:220
wfGetMessageCacheStorage
wfGetMessageCacheStorage()
Get the cache object used by the message cache.
Definition: GlobalFunctions.php:3038
MessageCache\refreshAndReplaceInternal
refreshAndReplaceInternal( $code, array $replacements)
Definition: MessageCache.php:625
Title
Represents a title within MediaWiki.
Definition: Title.php:39
MessageCache\loadFromDBWithLock
loadFromDBWithLock( $code, array &$where, $mode=null)
Definition: MessageCache.php:403
MessageCache\$mDisable
$mDisable
Should mean that database cannot be used, but check.
Definition: MessageCache.php:71
MessageCache\load
load( $code, $mode=null)
Loads messages from caches or from database in this order: (1) local message cache (if $wgUseLocalMes...
Definition: MessageCache.php:258
MessageCache\$wanCache
WANObjectCache $wanCache
Definition: MessageCache.php:93
DeferredUpdates\PRESEND
const PRESEND
Definition: DeferredUpdates.php:63
MessageCache\isDisabled
isDisabled()
Whether DB/cache usage is disabled for determining messages.
Definition: MessageCache.php:1269
as
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
Definition: distributors.txt:9
MessageCache\getParserOptions
getParserOptions()
ParserOptions is lazy initialised.
Definition: MessageCache.php:191
MessageCache\isCacheExpired
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
Definition: MessageCache.php:715
Language\getMessageKeysFor
static getMessageKeysFor( $code)
Get all message keys for a given language.
Definition: Language.php:4687
LoggerFactory
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
Definition: logger.txt:5
true
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
Definition: hooks.txt:2036
MessageCache\$mExpiry
$mExpiry
Lifetime for cache, used by object caching.
Definition: MessageCache.php:77
$content
$content
Definition: pageupdater.txt:72
of
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
Definition: globals.txt:10
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:214
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:72
class
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
Definition: maintenance.txt:52
$services
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
Definition: hooks.txt:2270
MediaWikiServices
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
Definition: injection.txt:23
MessageCache\__construct
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, $useDB, $expiry, Language $contLang=null)
Definition: MessageCache.php:167
Language\fetchLanguageNames
static fetchLanguageNames( $inLanguage=self::AS_AUTONYMS, $include='mw')
Get an array of language names, indexed by code.
Definition: Language.php:843
MessageCache\disable
disable()
Definition: MessageCache.php:1249
MessageCache
Cache of messages that are defined by MediaWiki namespace pages or by hooks.
Definition: MessageCache.php:40
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
MessageCache\getMessageForLang
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
Definition: MessageCache.php:948
Language
Internationalisation code.
Definition: Language.php:35
Language\getFallbacksFor
static getFallbacksFor( $code, $mode=self::MESSAGES_FALLBACKS)
Get the ordered list of fallback languages.
Definition: Language.php:4604
$wgUseLocalMessageCache
$wgUseLocalMessageCache
Set this to true to maintain a copy of the message cache on the local server.
Definition: DefaultSettings.php:2568
MessageCache\getAllMessageKeys
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
Definition: MessageCache.php:1316
MessageCache\destroyInstance
static destroyInstance()
Destroy the singleton instance.
Definition: MessageCache.php:138
MessageCache\$contLang
Language $contLang
Definition: MessageCache.php:99