MediaWiki  master
MessageCache.php
Go to the documentation of this file.
1 <?php
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(),
121  $wgUseLocalMessageCache
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  $po->setTidy( true );
202  return $po;
203  }
204 
205  $this->mParserOptions = new ParserOptions;
206  // Messages may take parameters that could come
207  // from malicious sources. As a precaution, disable
208  // the <html> parser tag when parsing messages.
209  $this->mParserOptions->setAllowUnsafeRawHtml( false );
210  // For the same reason, tidy the output!
211  $this->mParserOptions->setTidy( true );
212  }
213 
214  return $this->mParserOptions;
215  }
216 
223  protected function getLocalCache( $code ) {
224  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
225 
226  return $this->srvCache->get( $cacheKey );
227  }
228 
235  protected function saveToLocalCache( $code, $cache ) {
236  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
237  $this->srvCache->set( $cacheKey, $cache );
238  }
239 
261  protected function load( $code, $mode = null ) {
262  if ( !is_string( $code ) ) {
263  throw new InvalidArgumentException( "Missing language code" );
264  }
265 
266  # Don't do double loading...
267  if ( $this->cache->has( $code ) && $mode != self::FOR_UPDATE ) {
268  return true;
269  }
270 
271  $this->overridable = array_flip( Language::getMessageKeysFor( $code ) );
272 
273  // T208897 array_flip can fail and return null
274  if ( is_null( $this->overridable ) ) {
275  LoggerFactory::getInstance( 'MessageCache' )->error(
276  __METHOD__ . ': $this->overridable is null',
277  [
278  'message_keys' => Language::getMessageKeysFor( $code ),
279  'code' => $code
280  ]
281  );
282  }
283 
284  # 8 lines of code just to say (once) that message cache is disabled
285  if ( $this->mDisable ) {
286  static $shownDisabled = false;
287  if ( !$shownDisabled ) {
288  wfDebug( __METHOD__ . ": disabled\n" );
289  $shownDisabled = true;
290  }
291 
292  return true;
293  }
294 
295  # Loading code starts
296  $success = false; # Keep track of success
297  $staleCache = false; # a cache array with expired data, or false if none has been loaded
298  $where = []; # Debug info, delayed to avoid spamming debug log too much
299 
300  # Hash of the contents is stored in memcache, to detect if data-center cache
301  # or local cache goes out of date (e.g. due to replace() on some other server)
302  list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
303  $this->cacheVolatile[$code] = $hashVolatile;
304 
305  # Try the local cache and check against the cluster hash key...
306  $cache = $this->getLocalCache( $code );
307  if ( !$cache ) {
308  $where[] = 'local cache is empty';
309  } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
310  $where[] = 'local cache has the wrong hash';
311  $staleCache = $cache;
312  } elseif ( $this->isCacheExpired( $cache ) ) {
313  $where[] = 'local cache is expired';
314  $staleCache = $cache;
315  } elseif ( $hashVolatile ) {
316  $where[] = 'local cache validation key is expired/volatile';
317  $staleCache = $cache;
318  } else {
319  $where[] = 'got from local cache';
320  $this->cache->set( $code, $cache );
321  $success = true;
322  }
323 
324  if ( !$success ) {
325  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
326  # Try the global cache. If it is empty, try to acquire a lock. If
327  # the lock can't be acquired, wait for the other thread to finish
328  # and then try the global cache a second time.
329  for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
330  if ( $hashVolatile && $staleCache ) {
331  # Do not bother fetching the whole cache blob to avoid I/O.
332  # Instead, just try to get the non-blocking $statusKey lock
333  # below, and use the local stale value if it was not acquired.
334  $where[] = 'global cache is presumed expired';
335  } else {
336  $cache = $this->clusterCache->get( $cacheKey );
337  if ( !$cache ) {
338  $where[] = 'global cache is empty';
339  } elseif ( $this->isCacheExpired( $cache ) ) {
340  $where[] = 'global cache is expired';
341  $staleCache = $cache;
342  } elseif ( $hashVolatile ) {
343  # DB results are replica DB lag prone until the holdoff TTL passes.
344  # By then, updates should be reflected in loadFromDBWithLock().
345  # One thread renerates the cache while others use old values.
346  $where[] = 'global cache is expired/volatile';
347  $staleCache = $cache;
348  } else {
349  $where[] = 'got from global cache';
350  $this->cache->set( $code, $cache );
351  $this->saveToCaches( $cache, 'local-only', $code );
352  $success = true;
353  }
354  }
355 
356  if ( $success ) {
357  # Done, no need to retry
358  break;
359  }
360 
361  # We need to call loadFromDB. Limit the concurrency to one process.
362  # This prevents the site from going down when the cache expires.
363  # Note that the DB slam protection lock here is non-blocking.
364  $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
365  if ( $loadStatus === true ) {
366  $success = true;
367  break;
368  } elseif ( $staleCache ) {
369  # Use the stale cache while some other thread constructs the new one
370  $where[] = 'using stale cache';
371  $this->cache->set( $code, $staleCache );
372  $success = true;
373  break;
374  } elseif ( $failedAttempts > 0 ) {
375  # Already blocked once, so avoid another lock/unlock cycle.
376  # This case will typically be hit if memcached is down, or if
377  # loadFromDB() takes longer than LOCK_WAIT.
378  $where[] = "could not acquire status key.";
379  break;
380  } elseif ( $loadStatus === 'cantacquire' ) {
381  # Wait for the other thread to finish, then retry. Normally,
382  # the memcached get() will then yeild the other thread's result.
383  $where[] = 'waited for other thread to complete';
384  $this->getReentrantScopedLock( $cacheKey );
385  } else {
386  # Disable cache; $loadStatus is 'disabled'
387  break;
388  }
389  }
390  }
391 
392  if ( !$success ) {
393  $where[] = 'loading FAILED - cache is disabled';
394  $this->mDisable = true;
395  $this->cache->set( $code, [] );
396  wfDebugLog( 'MessageCacheError', __METHOD__ . ": Failed to load $code\n" );
397  # This used to throw an exception, but that led to nasty side effects like
398  # the whole wiki being instantly down if the memcached server died
399  }
400 
401  if ( !$this->cache->has( $code ) ) { // sanity
402  throw new LogicException( "Process cache for '$code' should be set by now." );
403  }
404 
405  $info = implode( ', ', $where );
406  wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
407 
408  return $success;
409  }
410 
417  protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
418  # If cache updates on all levels fail, give up on message overrides.
419  # This is to avoid easy site outages; see $saveSuccess comments below.
420  $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
421  $status = $this->clusterCache->get( $statusKey );
422  if ( $status === 'error' ) {
423  $where[] = "could not load; method is still globally disabled";
424  return 'disabled';
425  }
426 
427  # Now let's regenerate
428  $where[] = 'loading from database';
429 
430  # Lock the cache to prevent conflicting writes.
431  # This lock is non-blocking so stale cache can quickly be used.
432  # Note that load() will call a blocking getReentrantScopedLock()
433  # after this if it really need to wait for any current thread.
434  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
435  $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
436  if ( !$scopedLock ) {
437  $where[] = 'could not acquire main lock';
438  return 'cantacquire';
439  }
440 
441  $cache = $this->loadFromDB( $code, $mode );
442  $this->cache->set( $code, $cache );
443  $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
444 
445  if ( !$saveSuccess ) {
459  if ( $this->srvCache instanceof EmptyBagOStuff ) {
460  $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
461  $where[] = 'could not save cache, disabled globally for 5 minutes';
462  } else {
463  $where[] = "could not save global cache";
464  }
465  }
466 
467  return true;
468  }
469 
479  protected function loadFromDB( $code, $mode = null ) {
481 
482  // (T164666) The query here performs really poorly on WMF's
483  // contributions replicas. We don't have a way to say "any group except
484  // contributions", so for the moment let's specify 'api'.
485  // @todo: Get rid of this hack.
486  $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
487 
488  $cache = [];
489 
490  $mostused = []; // list of "<cased message key>/<code>"
491  if ( $wgAdaptiveMessageCache && $code !== $wgLanguageCode ) {
492  if ( !$this->cache->has( $wgLanguageCode ) ) {
493  $this->load( $wgLanguageCode );
494  }
495  $mostused = array_keys( $this->cache->get( $wgLanguageCode ) );
496  foreach ( $mostused as $key => $value ) {
497  $mostused[$key] = "$value/$code";
498  }
499  }
500 
501  // Get the list of software-defined messages in core/extensions
502  $overridable = array_flip( Language::getMessageKeysFor( $wgLanguageCode ) );
503 
504  // Common conditions
505  $conds = [
506  'page_is_redirect' => 0,
507  'page_namespace' => NS_MEDIAWIKI,
508  ];
509  if ( count( $mostused ) ) {
510  $conds['page_title'] = $mostused;
511  } elseif ( $code !== $wgLanguageCode ) {
512  $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
513  } else {
514  # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
515  # other than language code.
516  $conds[] = 'page_title NOT' .
517  $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
518  }
519 
520  // Set the stubs for oversized software-defined messages in the main cache map
521  $res = $dbr->select(
522  'page',
523  [ 'page_title', 'page_latest' ],
524  array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
525  __METHOD__ . "($code)-big"
526  );
527  foreach ( $res as $row ) {
528  $name = $this->contLang->lcfirst( $row->page_title );
529  // Include entries/stubs for all keys in $mostused in adaptive mode
530  if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $name, $overridable ) ) {
531  $cache[$row->page_title] = '!TOO BIG';
532  }
533  // At least include revision ID so page changes are reflected in the hash
534  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
535  }
536 
537  // Set the text for small software-defined messages in the main cache map
538  $res = $dbr->select(
539  [ 'page', 'revision', 'text' ],
540  [ 'page_title', 'page_latest', 'old_id', 'old_text', 'old_flags' ],
541  array_merge( $conds, [ 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
542  __METHOD__ . "($code)-small",
543  [],
544  [
545  'revision' => [ 'JOIN', 'page_latest=rev_id' ],
546  'text' => [ 'JOIN', 'rev_text_id=old_id' ],
547  ]
548  );
549  foreach ( $res as $row ) {
550  $name = $this->contLang->lcfirst( $row->page_title );
551  // Include entries/stubs for all keys in $mostused in adaptive mode
552  if ( $wgAdaptiveMessageCache || $this->isMainCacheable( $name, $overridable ) ) {
553  $text = Revision::getRevisionText( $row );
554  if ( $text === false ) {
555  // Failed to fetch data; possible ES errors?
556  // Store a marker to fetch on-demand as a workaround...
557  // TODO Use a differnt marker
558  $entry = '!TOO BIG';
559  wfDebugLog(
560  'MessageCache',
561  __METHOD__
562  . ": failed to load message page text for {$row->page_title} ($code)"
563  );
564  } else {
565  $entry = ' ' . $text;
566  }
567  $cache[$row->page_title] = $entry;
568  } else {
569  // T193271: cache object gets too big and slow to generate.
570  // At least include revision ID so page changes are reflected in the hash.
571  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
572  }
573  }
574 
575  $cache['VERSION'] = MSG_CACHE_VERSION;
576  ksort( $cache );
577 
578  # Hash for validating local cache (APC). No need to take into account
579  # messages larger than $wgMaxMsgCacheEntrySize, since those are only
580  # stored and fetched from memcache.
581  $cache['HASH'] = md5( serialize( $cache ) );
582  $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
583  unset( $cache['EXCESSIVE'] ); // only needed for hash
584 
585  return $cache;
586  }
587 
593  private function isMainCacheable( $name, array $overridable ) {
594  // Include common conversion table pages. This also avoids problems with
595  // Installer::parse() bailing out due to disallowed DB queries (T207979).
596  return ( isset( $overridable[$name] ) || strpos( $name, 'conversiontable/' ) === 0 );
597  }
598 
605  public function replace( $title, $text ) {
606  global $wgLanguageCode;
607 
608  if ( $this->mDisable ) {
609  return;
610  }
611 
612  list( $msg, $code ) = $this->figureMessage( $title );
613  if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
614  // Content language overrides do not use the /<code> suffix
615  return;
616  }
617 
618  // (a) Update the process cache with the new message text
619  if ( $text === false ) {
620  // Page deleted
621  $this->cache->setField( $code, $title, '!NONEXISTENT' );
622  } else {
623  // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
624  $this->cache->setField( $code, $title, ' ' . $text );
625  }
626 
627  // (b) Update the shared caches in a deferred update with a fresh DB snapshot
629  new MessageCacheUpdate( $code, $title, $msg ),
631  );
632  }
633 
639  public function refreshAndReplaceInternal( $code, array $replacements ) {
641 
642  // Allow one caller at a time to avoid race conditions
643  $scopedLock = $this->getReentrantScopedLock(
644  $this->clusterCache->makeKey( 'messages', $code )
645  );
646  if ( !$scopedLock ) {
647  foreach ( $replacements as list( $title ) ) {
648  LoggerFactory::getInstance( 'MessageCache' )->error(
649  __METHOD__ . ': could not acquire lock to update {title} ({code})',
650  [ 'title' => $title, 'code' => $code ] );
651  }
652 
653  return;
654  }
655 
656  // Load the existing cache to update it in the local DC cache.
657  // The other DCs will see a hash mismatch.
658  if ( $this->load( $code, self::FOR_UPDATE ) ) {
659  $cache = $this->cache->get( $code );
660  } else {
661  // Err? Fall back to loading from the database.
662  $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
663  }
664  // Check if individual cache keys should exist and update cache accordingly
665  $newTextByTitle = []; // map of (title => content)
666  $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
667  foreach ( $replacements as list( $title ) ) {
669  $page->loadPageData( $page::READ_LATEST );
670  $text = $this->getMessageTextFromContent( $page->getContent() );
671  // Remember the text for the blob store update later on
672  $newTextByTitle[$title] = $text;
673  // Note that if $text is false, then $cache should have a !NONEXISTANT entry
674  if ( !is_string( $text ) ) {
675  $cache[$title] = '!NONEXISTENT';
676  } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
677  $cache[$title] = '!TOO BIG';
678  $newBigTitles[$title] = $page->getLatest();
679  } else {
680  $cache[$title] = ' ' . $text;
681  }
682  }
683  // Update HASH for the new key. Incorporates various administrative keys,
684  // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
685  // and previous replace() calls), but that doesn't really matter since we
686  // only ever compare it for equality with a copy saved by saveToCaches().
687  $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
688  // Update the too-big WAN cache entries now that we have the new HASH
689  foreach ( $newBigTitles as $title => $id ) {
690  // Match logic of loadCachedMessagePageEntry()
691  $this->wanCache->set(
692  $this->bigMessageCacheKey( $cache['HASH'], $title ),
693  ' ' . $newTextByTitle[$title],
694  $this->mExpiry
695  );
696  }
697  // Mark this cache as definitely being "latest" (non-volatile) so
698  // load() calls do not try to refresh the cache with replica DB data
699  $cache['LATEST'] = time();
700  // Update the process cache
701  $this->cache->set( $code, $cache );
702  // Pre-emptively update the local datacenter cache so things like edit filter and
703  // blacklist changes are reflected immediately; these often use MediaWiki: pages.
704  // The datacenter handling replace() calls should be the same one handling edits
705  // as they require HTTP POST.
706  $this->saveToCaches( $cache, 'all', $code );
707  // Release the lock now that the cache is saved
708  ScopedCallback::consume( $scopedLock );
709 
710  // Relay the purge. Touching this check key expires cache contents
711  // and local cache (APC) validation hash across all datacenters.
712  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
713 
714  // Purge the messages in the message blob store and fire any hook handlers
715  $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
716  $blobStore = $resourceloader->getMessageBlobStore();
717  foreach ( $replacements as list( $title, $msg ) ) {
718  $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
719  Hooks::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
720  }
721  }
722 
729  protected function isCacheExpired( $cache ) {
730  if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
731  return true;
732  }
733  if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
734  return true;
735  }
736  if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
737  return true;
738  }
739 
740  return false;
741  }
742 
752  protected function saveToCaches( array $cache, $dest, $code = false ) {
753  if ( $dest === 'all' ) {
754  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
755  $success = $this->clusterCache->set( $cacheKey, $cache );
756  $this->setValidationHash( $code, $cache );
757  } else {
758  $success = true;
759  }
760 
761  $this->saveToLocalCache( $code, $cache );
762 
763  return $success;
764  }
765 
772  protected function getValidationHash( $code ) {
773  $curTTL = null;
774  $value = $this->wanCache->get(
775  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
776  $curTTL,
777  [ $this->getCheckKey( $code ) ]
778  );
779 
780  if ( $value ) {
781  $hash = $value['hash'];
782  if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
783  // Cache was recently updated via replace() and should be up-to-date.
784  // That method is only called in the primary datacenter and uses FOR_UPDATE.
785  // Also, it is unlikely that the current datacenter is *now* secondary one.
786  $expired = false;
787  } else {
788  // See if the "check" key was bumped after the hash was generated
789  $expired = ( $curTTL < 0 );
790  }
791  } else {
792  // No hash found at all; cache must regenerate to be safe
793  $hash = false;
794  $expired = true;
795  }
796 
797  return [ $hash, $expired ];
798  }
799 
810  protected function setValidationHash( $code, array $cache ) {
811  $this->wanCache->set(
812  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
813  [
814  'hash' => $cache['HASH'],
815  'latest' => $cache['LATEST'] ?? 0
816  ],
818  );
819  }
820 
826  protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
827  return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
828  }
829 
863  function get( $key, $useDB = true, $langcode = true ) {
864  if ( is_int( $key ) ) {
865  // Fix numerical strings that somehow become ints
866  // on their way here
867  $key = (string)$key;
868  } elseif ( !is_string( $key ) ) {
869  throw new MWException( 'Non-string key given' );
870  } elseif ( $key === '' ) {
871  // Shortcut: the empty key is always missing
872  return false;
873  }
874 
875  // Normalise title-case input (with some inlining)
876  $lckey = self::normalizeKey( $key );
877 
878  Hooks::run( 'MessageCache::get', [ &$lckey ] );
879 
880  // Loop through each language in the fallback list until we find something useful
881  $message = $this->getMessageFromFallbackChain(
882  wfGetLangObj( $langcode ),
883  $lckey,
884  !$this->mDisable && $useDB
885  );
886 
887  // If we still have no message, maybe the key was in fact a full key so try that
888  if ( $message === false ) {
889  $parts = explode( '/', $lckey );
890  // We may get calls for things that are http-urls from sidebar
891  // Let's not load nonexistent languages for those
892  // They usually have more than one slash.
893  if ( count( $parts ) == 2 && $parts[1] !== '' ) {
894  $message = Language::getMessageFor( $parts[0], $parts[1] );
895  if ( $message === null ) {
896  $message = false;
897  }
898  }
899  }
900 
901  // Post-processing if the message exists
902  if ( $message !== false ) {
903  // Fix whitespace
904  $message = str_replace(
905  [
906  # Fix for trailing whitespace, removed by textarea
907  '&#32;',
908  # Fix for NBSP, converted to space by firefox
909  '&nbsp;',
910  '&#160;',
911  '&shy;'
912  ],
913  [
914  ' ',
915  "\u{00A0}",
916  "\u{00A0}",
917  "\u{00AD}"
918  ],
919  $message
920  );
921  }
922 
923  return $message;
924  }
925 
938  protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
939  $alreadyTried = [];
940 
941  // First try the requested language.
942  $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
943  if ( $message !== false ) {
944  return $message;
945  }
946 
947  // Now try checking the site language.
948  $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
949  return $message;
950  }
951 
962  private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
963  $langcode = $lang->getCode();
964 
965  // Try checking the database for the requested language
966  if ( $useDB ) {
967  $uckey = $this->contLang->ucfirst( $lckey );
968 
969  if ( !isset( $alreadyTried[$langcode] ) ) {
970  $message = $this->getMsgFromNamespace(
971  $this->getMessagePageName( $langcode, $uckey ),
972  $langcode
973  );
974  if ( $message !== false ) {
975  return $message;
976  }
977  $alreadyTried[$langcode] = true;
978  }
979  } else {
980  $uckey = null;
981  }
982 
983  // Check the CDB cache
984  $message = $lang->getMessage( $lckey );
985  if ( $message !== null ) {
986  return $message;
987  }
988 
989  // Try checking the database for all of the fallback languages
990  if ( $useDB ) {
991  $fallbackChain = Language::getFallbacksFor( $langcode );
992 
993  foreach ( $fallbackChain as $code ) {
994  if ( isset( $alreadyTried[$code] ) ) {
995  continue;
996  }
997 
998  $message = $this->getMsgFromNamespace(
999  $this->getMessagePageName( $code, $uckey ), $code );
1000 
1001  if ( $message !== false ) {
1002  return $message;
1003  }
1004  $alreadyTried[$code] = true;
1005  }
1006  }
1007 
1008  return false;
1009  }
1010 
1018  private function getMessagePageName( $langcode, $uckey ) {
1019  global $wgLanguageCode;
1020 
1021  if ( $langcode === $wgLanguageCode ) {
1022  // Messages created in the content language will not have the /lang extension
1023  return $uckey;
1024  } else {
1025  return "$uckey/$langcode";
1026  }
1027  }
1028 
1041  public function getMsgFromNamespace( $title, $code ) {
1042  // Load all MediaWiki page definitions into cache. Note that individual keys
1043  // already loaded into cache during this request remain in the cache, which
1044  // includes the value of hook-defined messages.
1045  $this->load( $code );
1046 
1047  $entry = $this->cache->getField( $code, $title );
1048 
1049  if ( $entry !== null ) {
1050  // Message page exists as an override of a software messages
1051  if ( substr( $entry, 0, 1 ) === ' ' ) {
1052  // The message exists and is not '!TOO BIG'
1053  return (string)substr( $entry, 1 );
1054  } elseif ( $entry === '!NONEXISTENT' ) {
1055  // The text might be '-' or missing due to some data loss
1056  return false;
1057  }
1058  // Load the message page, utilizing the individual message cache.
1059  // If the page does not exist, there will be no hook handler fallbacks.
1060  $entry = $this->loadCachedMessagePageEntry(
1061  $title,
1062  $code,
1063  $this->cache->getField( $code, 'HASH' )
1064  );
1065  } else {
1066  // Message page either does not exist or does not override a software message
1067  $name = $this->contLang->lcfirst( $title );
1068  if ( !$this->isMainCacheable( $name, $this->overridable ) ) {
1069  // Message page does not override any software-defined message. A custom
1070  // message might be defined to have content or settings specific to the wiki.
1071  // Load the message page, utilizing the individual message cache as needed.
1072  $entry = $this->loadCachedMessagePageEntry(
1073  $title,
1074  $code,
1075  $this->cache->getField( $code, 'HASH' )
1076  );
1077  }
1078  if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1079  // Message does not have a MediaWiki page definition; try hook handlers
1080  $message = false;
1081  Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1082  if ( $message !== false ) {
1083  $this->cache->setField( $code, $title, ' ' . $message );
1084  } else {
1085  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1086  }
1087 
1088  return $message;
1089  }
1090  }
1091 
1092  if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1093  if ( $this->cacheVolatile[$code] ) {
1094  // Make sure that individual keys respect the WAN cache holdoff period too
1095  LoggerFactory::getInstance( 'MessageCache' )->debug(
1096  __METHOD__ . ': loading volatile key \'{titleKey}\'',
1097  [ 'titleKey' => $title, 'code' => $code ] );
1098  } else {
1099  $this->cache->setField( $code, $title, $entry );
1100  }
1101  // The message exists, so make sure a string is returned
1102  return (string)substr( $entry, 1 );
1103  }
1104 
1105  $this->cache->setField( $code, $title, '!NONEXISTENT' );
1106 
1107  return false;
1108  }
1109 
1116  private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1117  $fname = __METHOD__;
1118  return $this->srvCache->getWithSetCallback(
1119  $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1121  function () use ( $code, $dbKey, $hash, $fname ) {
1122  return $this->wanCache->getWithSetCallback(
1123  $this->bigMessageCacheKey( $hash, $dbKey ),
1124  $this->mExpiry,
1125  function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1126  // Try loading the message from the database
1127  $dbr = wfGetDB( DB_REPLICA );
1128  $setOpts += Database::getCacheSetOptions( $dbr );
1129  // Use newKnownCurrent() to avoid querying revision/user tables
1130  $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1131  $revision = Revision::newKnownCurrent( $dbr, $title );
1132  if ( !$revision ) {
1133  // The wiki doesn't have a local override page. Cache absence with normal TTL.
1134  // When overrides are created, self::replace() takes care of the cache.
1135  return '!NONEXISTENT';
1136  }
1137  $content = $revision->getContent();
1138  if ( $content ) {
1139  $message = $this->getMessageTextFromContent( $content );
1140  } else {
1141  LoggerFactory::getInstance( 'MessageCache' )->warning(
1142  $fname . ': failed to load page text for \'{titleKey}\'',
1143  [ 'titleKey' => $dbKey, 'code' => $code ]
1144  );
1145  $message = null;
1146  }
1147 
1148  if ( !is_string( $message ) ) {
1149  // Revision failed to load Content, or Content is incompatible with wikitext.
1150  // Possibly a temporary loading failure.
1151  $ttl = 5;
1152 
1153  return '!NONEXISTENT';
1154  }
1155 
1156  return ' ' . $message;
1157  }
1158  );
1159  }
1160  );
1161  }
1162 
1170  public function transform( $message, $interface = false, $language = null, $title = null ) {
1171  // Avoid creating parser if nothing to transform
1172  if ( strpos( $message, '{{' ) === false ) {
1173  return $message;
1174  }
1175 
1176  if ( $this->mInParser ) {
1177  return $message;
1178  }
1179 
1180  $parser = $this->getParser();
1181  if ( $parser ) {
1182  $popts = $this->getParserOptions();
1183  $popts->setInterfaceMessage( $interface );
1184  $popts->setTargetLanguage( $language );
1185 
1186  $userlang = $popts->setUserLang( $language );
1187  $this->mInParser = true;
1188  $message = $parser->transformMsg( $message, $popts, $title );
1189  $this->mInParser = false;
1190  $popts->setUserLang( $userlang );
1191  }
1192 
1193  return $message;
1194  }
1195 
1199  public function getParser() {
1200  global $wgParser, $wgParserConf;
1201 
1202  if ( !$this->mParser && isset( $wgParser ) ) {
1203  # Do some initialisation so that we don't have to do it twice
1204  $wgParser->firstCallInit();
1205  # Clone it and store it
1206  $class = $wgParserConf['class'];
1207  if ( $class == ParserDiffTest::class ) {
1208  # Uncloneable
1209  $this->mParser = new $class( $wgParserConf );
1210  } else {
1211  $this->mParser = clone $wgParser;
1212  }
1213  }
1214 
1215  return $this->mParser;
1216  }
1217 
1226  public function parse( $text, $title = null, $linestart = true,
1227  $interface = false, $language = null
1228  ) {
1229  global $wgTitle;
1230 
1231  if ( $this->mInParser ) {
1232  return htmlspecialchars( $text );
1233  }
1234 
1235  $parser = $this->getParser();
1236  $popts = $this->getParserOptions();
1237  $popts->setInterfaceMessage( $interface );
1238 
1239  if ( is_string( $language ) ) {
1240  $language = Language::factory( $language );
1241  }
1242  $popts->setTargetLanguage( $language );
1243 
1244  if ( !$title || !$title instanceof Title ) {
1245  wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1246  wfGetAllCallers( 6 ) . ' with no title set.' );
1247  $title = $wgTitle;
1248  }
1249  // Sometimes $wgTitle isn't set either...
1250  if ( !$title ) {
1251  # It's not uncommon having a null $wgTitle in scripts. See r80898
1252  # Create a ghost title in such case
1253  $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1254  }
1255 
1256  $this->mInParser = true;
1257  $res = $parser->parse( $text, $title, $popts, $linestart );
1258  $this->mInParser = false;
1259 
1260  return $res;
1261  }
1262 
1263  public function disable() {
1264  $this->mDisable = true;
1265  }
1266 
1267  public function enable() {
1268  $this->mDisable = false;
1269  }
1270 
1283  public function isDisabled() {
1284  return $this->mDisable;
1285  }
1286 
1292  public function clear() {
1293  $langs = Language::fetchLanguageNames( null, 'mw' );
1294  foreach ( array_keys( $langs ) as $code ) {
1295  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1296  }
1297  $this->cache->clear();
1298  }
1299 
1304  public function figureMessage( $key ) {
1305  global $wgLanguageCode;
1306 
1307  $pieces = explode( '/', $key );
1308  if ( count( $pieces ) < 2 ) {
1309  return [ $key, $wgLanguageCode ];
1310  }
1311 
1312  $lang = array_pop( $pieces );
1313  if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1314  return [ $key, $wgLanguageCode ];
1315  }
1316 
1317  $message = implode( '/', $pieces );
1318 
1319  return [ $message, $lang ];
1320  }
1321 
1330  public function getAllMessageKeys( $code ) {
1331  $this->load( $code );
1332  if ( !$this->cache->has( $code ) ) {
1333  // Apparently load() failed
1334  return null;
1335  }
1336  // Remove administrative keys
1337  $cache = $this->cache->get( $code );
1338  unset( $cache['VERSION'] );
1339  unset( $cache['EXPIRY'] );
1340  unset( $cache['EXCESSIVE'] );
1341  // Remove any !NONEXISTENT keys
1342  $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1343 
1344  // Keys may appear with a capital first letter. lcfirst them.
1345  return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1346  }
1347 
1355  public function updateMessageOverride( Title $title, Content $content = null ) {
1356  $msgText = $this->getMessageTextFromContent( $content );
1357  if ( $msgText === null ) {
1358  $msgText = false; // treat as not existing
1359  }
1360 
1361  $this->replace( $title->getDBkey(), $msgText );
1362 
1363  if ( $this->contLang->hasVariants() ) {
1364  $this->contLang->updateConversionTable( $title );
1365  }
1366  }
1367 
1372  public function getCheckKey( $code ) {
1373  return $this->wanCache->makeKey( 'messages', $code );
1374  }
1375 
1380  private function getMessageTextFromContent( Content $content = null ) {
1381  // @TODO: could skip pseudo-messages like js/css here, based on content model
1382  if ( $content ) {
1383  // Message page exists...
1384  // XXX: Is this the right way to turn a Content object into a message?
1385  // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1386  // CssContent. MessageContent is *not* used for storing messages, it's
1387  // only used for wrapping them when needed.
1388  $msgText = $content->getWikitextForTransclusion();
1389  if ( $msgText === false || $msgText === null ) {
1390  // This might be due to some kind of misconfiguration...
1391  $msgText = null;
1392  LoggerFactory::getInstance( 'MessageCache' )->warning(
1393  __METHOD__ . ": message content doesn't provide wikitext "
1394  . "(content model: " . $content->getModel() . ")" );
1395  }
1396  } else {
1397  // Message page does not exist...
1398  $msgText = false;
1399  }
1400 
1401  return $msgText;
1402  }
1403 
1409  private function bigMessageCacheKey( $hash, $title ) {
1410  return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1411  }
1412 }
load( $code, $mode=null)
Loads messages from caches or from database in this order: (1) local message cache (if $wgUseLocalMes...
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))
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:128
saveToCaches(array $cache, $dest, $code=false)
Shortcut to update caches.
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
loadFromDBWithLock( $code, array &$where, $mode=null)
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
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
static fetchLanguageNames( $inLanguage=self::AS_AUTONYMS, $include='mw')
Get an array of language names, indexed by code.
Definition: Language.php:843
figureMessage( $key)
$success
serialize()
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
transform( $message, $interface=false, $language=null, $title=null)
$wgParser
Definition: Setup.php:913
get( $key, $maxAge=0.0)
Get the value for a key.
setValidationHash( $code, array $cache)
Set the md5 used to validate the local disk cache.
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
database rows
Definition: globals.txt:10
if(!isset( $args[0])) $lang
static destroyInstance()
Destroy the singleton instance.
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:1277
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
bigMessageCacheKey( $hash, $title)
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
saveToLocalCache( $code, $cache)
Save the cache to APC.
$value
getMessageTextFromContent(Content $content=null)
const NS_SPECIAL
Definition: Defines.php:53
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
isMainCacheable( $name, array $overridable)
BagOStuff $clusterCache
Message cache purging and in-place update handler for specific message page changes.
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
Parser $mParser
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1813
wfGetMessageCacheStorage()
Get the cache object used by the message cache.
const DB_MASTER
Definition: defines.php:26
static normalizeKey( $key)
Normalize message key input.
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row.
Definition: Revision.php:1062
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
$wgUseLocalMessageCache
Set this to true to maintain a copy of the message cache on the local server.
getParserOptions()
ParserOptions is lazy initialised.
refreshAndReplaceInternal( $code, array $replacements)
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
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:1996
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
$wgLanguageCode
Site language code.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4627
MapCacheLRU $cache
Process cache of loaded messages that are defined in MediaWiki namespace.
$wgMaxMsgCacheEntrySize
Maximum entry size in the message cache, in bytes.
loadCachedMessagePageEntry( $dbKey, $code, $hash)
static getMain()
Get the RequestContext object associated with the main request.
replace( $title, $text)
Updates cache as necessary when message page is changed.
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:2221
static getMessageKeysFor( $code)
Get all message keys for a given language.
Definition: Language.php:4639
getDBkey()
Get the main part with underscores.
Definition: Title.php:951
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:1343
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
$wgAdaptiveMessageCache
Instead of caching everything, only cache those messages which have been customised in the site conte...
$res
Definition: database.txt:21
array $overridable
Map of (lowercase message key => index) for all software defined messages.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
$wgUseDatabaseMessages
Translation using MediaWiki: namespace.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
getLocalCache( $code)
Try to load the cache from APC.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:936
static $instance
Singleton instance.
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:214
bool [] $cacheVolatile
Map of (language code => boolean)
$wgParserConf
Parser configuration.
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
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:785
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
const NS_MEDIAWIKI
Definition: Defines.php:72
static newFromAnon()
Get a ParserOptions object for an anonymous user.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:121
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
const WAIT_SEC
How long to wait for memcached locks.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:545
static fetchLanguageName( $code, $inLanguage=self::AS_AUTONYMS, $include=self::ALL)
Definition: Language.php:940
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
const FOR_UPDATE
isDisabled()
Whether DB/cache usage is disabled for determining messages.
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
updateMessageOverride(Title $title, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
parse( $text, $title=null, $linestart=true, $interface=false, $language=null)
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
BagOStuff $srvCache
$mExpiry
Lifetime for cache, used by object caching.
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
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
$wgMsgCacheExpiry
Expiry time for the message cache key.
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
static getFallbacksFor( $code, $mode=self::MESSAGES_FALLBACKS)
Get the ordered list of fallback languages.
Definition: Language.php:4556
Language $contLang
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, $useDB, $expiry, Language $contLang=null)
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
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
clear()
Clear all stored messages in global and local cache.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:276
getCheckKey( $code)
const DB_REPLICA
Definition: defines.php:25
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
Definition: api.php:57
$mDisable
Should mean that database cannot be used, but check.
$content
Definition: pageupdater.txt:72
WANObjectCache $wanCache
const LOCK_TTL
How long memcached locks last.
static singleton()
Get the signleton instance of this class.
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200