MediaWiki  REL1_31
MessageCache.php
Go to the documentation of this file.
1 <?php
24 use Wikimedia\ScopedCallback;
27 
32 define( 'MSG_CACHE_VERSION', 2 );
33 
39 class MessageCache {
40  const FOR_UPDATE = 1; // force message reload
41 
43  const WAIT_SEC = 15;
45  const LOCK_TTL = 30;
46 
55  protected $mCache;
56 
60  protected $mCacheVolatile = [];
61 
66  protected $mDisable;
67 
72  protected $mExpiry;
73 
78  protected $mParserOptions;
80  protected $mParser;
81 
86  protected $mLoadedLanguages = [];
87 
91  protected $mInParser = false;
92 
94  protected $wanCache;
96  protected $clusterCache;
98  protected $srvCache;
99 
105  private static $instance;
106 
113  public static function singleton() {
114  if ( self::$instance === null ) {
116  self::$instance = new self(
117  MediaWikiServices::getInstance()->getMainWANObjectCache(),
120  ? MediaWikiServices::getInstance()->getLocalServerObjectCache()
121  : new EmptyBagOStuff(),
124  );
125  }
126 
127  return self::$instance;
128  }
129 
135  public static function destroyInstance() {
136  self::$instance = null;
137  }
138 
145  public static function normalizeKey( $key ) {
147 
148  $lckey = strtr( $key, ' ', '_' );
149  if ( ord( $lckey ) < 128 ) {
150  $lckey[0] = strtolower( $lckey[0] );
151  } else {
152  $lckey = $wgContLang->lcfirst( $lckey );
153  }
154 
155  return $lckey;
156  }
157 
165  public function __construct(
168  BagOStuff $serverCache,
169  $useDB,
170  $expiry
171  ) {
172  $this->wanCache = $wanCache;
173  $this->clusterCache = $clusterCache;
174  $this->srvCache = $serverCache;
175 
176  $this->mDisable = !$useDB;
177  $this->mExpiry = $expiry;
178  }
179 
185  function getParserOptions() {
186  global $wgUser;
187 
188  if ( !$this->mParserOptions ) {
189  if ( !$wgUser->isSafeToLoad() ) {
190  // $wgUser isn't unstubbable yet, so don't try to get a
191  // ParserOptions for it. And don't cache this ParserOptions
192  // either.
194  $po->setAllowUnsafeRawHtml( false );
195  return $po;
196  }
197 
198  $this->mParserOptions = new ParserOptions;
199  // Messages may take parameters that could come
200  // from malicious sources. As a precaution, disable
201  // the <html> parser tag when parsing messages.
202  $this->mParserOptions->setAllowUnsafeRawHtml( false );
203  }
204 
205  return $this->mParserOptions;
206  }
207 
214  protected function getLocalCache( $code ) {
215  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
216 
217  return $this->srvCache->get( $cacheKey );
218  }
219 
226  protected function saveToLocalCache( $code, $cache ) {
227  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
228  $this->srvCache->set( $cacheKey, $cache );
229  }
230 
252  protected function load( $code, $mode = null ) {
253  if ( !is_string( $code ) ) {
254  throw new InvalidArgumentException( "Missing language code" );
255  }
256 
257  # Don't do double loading...
258  if ( isset( $this->mLoadedLanguages[$code] ) && $mode != self::FOR_UPDATE ) {
259  return true;
260  }
261 
262  # 8 lines of code just to say (once) that message cache is disabled
263  if ( $this->mDisable ) {
264  static $shownDisabled = false;
265  if ( !$shownDisabled ) {
266  wfDebug( __METHOD__ . ": disabled\n" );
267  $shownDisabled = true;
268  }
269 
270  return true;
271  }
272 
273  # Loading code starts
274  $success = false; # Keep track of success
275  $staleCache = false; # a cache array with expired data, or false if none has been loaded
276  $where = []; # Debug info, delayed to avoid spamming debug log too much
277 
278  # Hash of the contents is stored in memcache, to detect if data-center cache
279  # or local cache goes out of date (e.g. due to replace() on some other server)
280  list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
281  $this->mCacheVolatile[$code] = $hashVolatile;
282 
283  # Try the local cache and check against the cluster hash key...
284  $cache = $this->getLocalCache( $code );
285  if ( !$cache ) {
286  $where[] = 'local cache is empty';
287  } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
288  $where[] = 'local cache has the wrong hash';
289  $staleCache = $cache;
290  } elseif ( $this->isCacheExpired( $cache ) ) {
291  $where[] = 'local cache is expired';
292  $staleCache = $cache;
293  } elseif ( $hashVolatile ) {
294  $where[] = 'local cache validation key is expired/volatile';
295  $staleCache = $cache;
296  } else {
297  $where[] = 'got from local cache';
298  $success = true;
299  $this->mCache[$code] = $cache;
300  }
301 
302  if ( !$success ) {
303  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
304  # Try the global cache. If it is empty, try to acquire a lock. If
305  # the lock can't be acquired, wait for the other thread to finish
306  # and then try the global cache a second time.
307  for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
308  if ( $hashVolatile && $staleCache ) {
309  # Do not bother fetching the whole cache blob to avoid I/O.
310  # Instead, just try to get the non-blocking $statusKey lock
311  # below, and use the local stale value if it was not acquired.
312  $where[] = 'global cache is presumed expired';
313  } else {
314  $cache = $this->clusterCache->get( $cacheKey );
315  if ( !$cache ) {
316  $where[] = 'global cache is empty';
317  } elseif ( $this->isCacheExpired( $cache ) ) {
318  $where[] = 'global cache is expired';
319  $staleCache = $cache;
320  } elseif ( $hashVolatile ) {
321  # DB results are replica DB lag prone until the holdoff TTL passes.
322  # By then, updates should be reflected in loadFromDBWithLock().
323  # One thread renerates the cache while others use old values.
324  $where[] = 'global cache is expired/volatile';
325  $staleCache = $cache;
326  } else {
327  $where[] = 'got from global cache';
328  $this->mCache[$code] = $cache;
329  $this->saveToCaches( $cache, 'local-only', $code );
330  $success = true;
331  }
332  }
333 
334  if ( $success ) {
335  # Done, no need to retry
336  break;
337  }
338 
339  # We need to call loadFromDB. Limit the concurrency to one process.
340  # This prevents the site from going down when the cache expires.
341  # Note that the DB slam protection lock here is non-blocking.
342  $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
343  if ( $loadStatus === true ) {
344  $success = true;
345  break;
346  } elseif ( $staleCache ) {
347  # Use the stale cache while some other thread constructs the new one
348  $where[] = 'using stale cache';
349  $this->mCache[$code] = $staleCache;
350  $success = true;
351  break;
352  } elseif ( $failedAttempts > 0 ) {
353  # Already blocked once, so avoid another lock/unlock cycle.
354  # This case will typically be hit if memcached is down, or if
355  # loadFromDB() takes longer than LOCK_WAIT.
356  $where[] = "could not acquire status key.";
357  break;
358  } elseif ( $loadStatus === 'cantacquire' ) {
359  # Wait for the other thread to finish, then retry. Normally,
360  # the memcached get() will then yeild the other thread's result.
361  $where[] = 'waited for other thread to complete';
362  $this->getReentrantScopedLock( $cacheKey );
363  } else {
364  # Disable cache; $loadStatus is 'disabled'
365  break;
366  }
367  }
368  }
369 
370  if ( !$success ) {
371  $where[] = 'loading FAILED - cache is disabled';
372  $this->mDisable = true;
373  $this->mCache = false;
374  wfDebugLog( 'MessageCacheError', __METHOD__ . ": Failed to load $code\n" );
375  # This used to throw an exception, but that led to nasty side effects like
376  # the whole wiki being instantly down if the memcached server died
377  } else {
378  # All good, just record the success
379  $this->mLoadedLanguages[$code] = true;
380  }
381 
382  $info = implode( ', ', $where );
383  wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
384 
385  return $success;
386  }
387 
394  protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
395  # If cache updates on all levels fail, give up on message overrides.
396  # This is to avoid easy site outages; see $saveSuccess comments below.
397  $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
398  $status = $this->clusterCache->get( $statusKey );
399  if ( $status === 'error' ) {
400  $where[] = "could not load; method is still globally disabled";
401  return 'disabled';
402  }
403 
404  # Now let's regenerate
405  $where[] = 'loading from database';
406 
407  # Lock the cache to prevent conflicting writes.
408  # This lock is non-blocking so stale cache can quickly be used.
409  # Note that load() will call a blocking getReentrantScopedLock()
410  # after this if it really need to wait for any current thread.
411  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
412  $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
413  if ( !$scopedLock ) {
414  $where[] = 'could not acquire main lock';
415  return 'cantacquire';
416  }
417 
418  $cache = $this->loadFromDB( $code, $mode );
419  $this->mCache[$code] = $cache;
420  $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
421 
422  if ( !$saveSuccess ) {
436  if ( $this->srvCache instanceof EmptyBagOStuff ) {
437  $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
438  $where[] = 'could not save cache, disabled globally for 5 minutes';
439  } else {
440  $where[] = "could not save global cache";
441  }
442  }
443 
444  return true;
445  }
446 
456  protected function loadFromDB( $code, $mode = null ) {
458 
459  // (T164666) The query here performs really poorly on WMF's
460  // contributions replicas. We don't have a way to say "any group except
461  // contributions", so for the moment let's specify 'api'.
462  // @todo: Get rid of this hack.
463  $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
464 
465  $cache = [];
466 
467  # Common conditions
468  $conds = [
469  'page_is_redirect' => 0,
470  'page_namespace' => NS_MEDIAWIKI,
471  ];
472 
473  $mostused = [];
475  if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
476  $this->load( $wgLanguageCode );
477  }
478  $mostused = array_keys( $this->mCache[$wgLanguageCode] );
479  foreach ( $mostused as $key => $value ) {
480  $mostused[$key] = "$value/$code";
481  }
482  }
483 
484  if ( count( $mostused ) ) {
485  $conds['page_title'] = $mostused;
486  } elseif ( $code !== $wgLanguageCode ) {
487  $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
488  } else {
489  # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
490  # other than language code.
491  $conds[] = 'page_title NOT' .
492  $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
493  }
494 
495  # Conditions to fetch oversized pages to ignore them
496  $bigConds = $conds;
497  $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
498 
499  # Load titles for all oversized pages in the MediaWiki namespace
500  $res = $dbr->select(
501  'page',
502  [ 'page_title', 'page_latest' ],
503  $bigConds,
504  __METHOD__ . "($code)-big"
505  );
506  foreach ( $res as $row ) {
507  $cache[$row->page_title] = '!TOO BIG';
508  // At least include revision ID so page changes are reflected in the hash
509  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
510  }
511 
512  # Conditions to load the remaining pages with their contents
513  $smallConds = $conds;
514  $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
515 
516  $res = $dbr->select(
517  [ 'page', 'revision', 'text' ],
518  [ 'page_title', 'old_id', 'old_text', 'old_flags' ],
519  $smallConds,
520  __METHOD__ . "($code)-small",
521  [],
522  [
523  'revision' => [ 'JOIN', 'page_latest=rev_id' ],
524  'text' => [ 'JOIN', 'rev_text_id=old_id' ],
525  ]
526  );
527 
528  foreach ( $res as $row ) {
529  $text = Revision::getRevisionText( $row );
530  if ( $text === false ) {
531  // Failed to fetch data; possible ES errors?
532  // Store a marker to fetch on-demand as a workaround...
533  // TODO Use a differnt marker
534  $entry = '!TOO BIG';
535  wfDebugLog(
536  'MessageCache',
537  __METHOD__
538  . ": failed to load message page text for {$row->page_title} ($code)"
539  );
540  } else {
541  $entry = ' ' . $text;
542  }
543  $cache[$row->page_title] = $entry;
544  }
545 
546  $cache['VERSION'] = MSG_CACHE_VERSION;
547  ksort( $cache );
548 
549  # Hash for validating local cache (APC). No need to take into account
550  # messages larger than $wgMaxMsgCacheEntrySize, since those are only
551  # stored and fetched from memcache.
552  $cache['HASH'] = md5( serialize( $cache ) );
553  $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
554 
555  return $cache;
556  }
557 
564  public function replace( $title, $text ) {
566 
567  if ( $this->mDisable ) {
568  return;
569  }
570 
571  list( $msg, $code ) = $this->figureMessage( $title );
572  if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
573  // Content language overrides do not use the /<code> suffix
574  return;
575  }
576 
577  // (a) Update the process cache with the new message text
578  if ( $text === false ) {
579  // Page deleted
580  $this->mCache[$code][$title] = '!NONEXISTENT';
581  } else {
582  // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
583  $this->mCache[$code][$title] = ' ' . $text;
584  }
585 
586  // (b) Update the shared caches in a deferred update with a fresh DB snapshot
588  function () use ( $title, $msg, $code ) {
590  // Allow one caller at a time to avoid race conditions
591  $scopedLock = $this->getReentrantScopedLock(
592  $this->clusterCache->makeKey( 'messages', $code )
593  );
594  if ( !$scopedLock ) {
595  LoggerFactory::getInstance( 'MessageCache' )->error(
596  __METHOD__ . ': could not acquire lock to update {title} ({code})',
597  [ 'title' => $title, 'code' => $code ] );
598  return;
599  }
600  // Load the messages from the master DB to avoid race conditions
601  $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
602  $this->mCache[$code] = $cache;
603  // Load the process cache values and set the per-title cache keys
605  $page->loadPageData( $page::READ_LATEST );
606  $text = $this->getMessageTextFromContent( $page->getContent() );
607  // Check if an individual cache key should exist and update cache accordingly
608  if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
609  $titleKey = $this->bigMessageCacheKey( $this->mCache[$code]['HASH'], $title );
610  $this->wanCache->set( $titleKey, ' ' . $text, $this->mExpiry );
611  }
612  // Mark this cache as definitely being "latest" (non-volatile) so
613  // load() calls do try to refresh the cache with replica DB data
614  $this->mCache[$code]['LATEST'] = time();
615  // Pre-emptively update the local datacenter cache so things like edit filter and
616  // blacklist changes are reflected immediately; these often use MediaWiki: pages.
617  // The datacenter handling replace() calls should be the same one handling edits
618  // as they require HTTP POST.
619  $this->saveToCaches( $this->mCache[$code], 'all', $code );
620  // Release the lock now that the cache is saved
621  ScopedCallback::consume( $scopedLock );
622 
623  // Relay the purge. Touching this check key expires cache contents
624  // and local cache (APC) validation hash across all datacenters.
625  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
626 
627  // Purge the message in the message blob store
628  $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
629  $blobStore = $resourceloader->getMessageBlobStore();
630  $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
631 
632  Hooks::run( 'MessageCacheReplace', [ $title, $text ] );
633  },
635  );
636  }
637 
644  protected function isCacheExpired( $cache ) {
645  if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
646  return true;
647  }
648  if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
649  return true;
650  }
651  if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
652  return true;
653  }
654 
655  return false;
656  }
657 
667  protected function saveToCaches( array $cache, $dest, $code = false ) {
668  if ( $dest === 'all' ) {
669  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
670  $success = $this->clusterCache->set( $cacheKey, $cache );
671  $this->setValidationHash( $code, $cache );
672  } else {
673  $success = true;
674  }
675 
676  $this->saveToLocalCache( $code, $cache );
677 
678  return $success;
679  }
680 
687  protected function getValidationHash( $code ) {
688  $curTTL = null;
689  $value = $this->wanCache->get(
690  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
691  $curTTL,
692  [ $this->getCheckKey( $code ) ]
693  );
694 
695  if ( $value ) {
696  $hash = $value['hash'];
697  if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
698  // Cache was recently updated via replace() and should be up-to-date.
699  // That method is only called in the primary datacenter and uses FOR_UPDATE.
700  // Also, it is unlikely that the current datacenter is *now* secondary one.
701  $expired = false;
702  } else {
703  // See if the "check" key was bumped after the hash was generated
704  $expired = ( $curTTL < 0 );
705  }
706  } else {
707  // No hash found at all; cache must regenerate to be safe
708  $hash = false;
709  $expired = true;
710  }
711 
712  return [ $hash, $expired ];
713  }
714 
725  protected function setValidationHash( $code, array $cache ) {
726  $this->wanCache->set(
727  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
728  [
729  'hash' => $cache['HASH'],
730  'latest' => isset( $cache['LATEST'] ) ? $cache['LATEST'] : 0
731  ],
733  );
734  }
735 
741  protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
742  return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
743  }
744 
779  function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
780  if ( is_int( $key ) ) {
781  // Fix numerical strings that somehow become ints
782  // on their way here
783  $key = (string)$key;
784  } elseif ( !is_string( $key ) ) {
785  throw new MWException( 'Non-string key given' );
786  } elseif ( $key === '' ) {
787  // Shortcut: the empty key is always missing
788  return false;
789  }
790 
791  // For full keys, get the language code from the key
792  $pos = strrpos( $key, '/' );
793  if ( $isFullKey && $pos !== false ) {
794  $langcode = substr( $key, $pos + 1 );
795  $key = substr( $key, 0, $pos );
796  }
797 
798  // Normalise title-case input (with some inlining)
799  $lckey = self::normalizeKey( $key );
800 
801  Hooks::run( 'MessageCache::get', [ &$lckey ] );
802 
803  // Loop through each language in the fallback list until we find something useful
804  $lang = wfGetLangObj( $langcode );
805  $message = $this->getMessageFromFallbackChain(
806  $lang,
807  $lckey,
808  !$this->mDisable && $useDB
809  );
810 
811  // If we still have no message, maybe the key was in fact a full key so try that
812  if ( $message === false ) {
813  $parts = explode( '/', $lckey );
814  // We may get calls for things that are http-urls from sidebar
815  // Let's not load nonexistent languages for those
816  // They usually have more than one slash.
817  if ( count( $parts ) == 2 && $parts[1] !== '' ) {
818  $message = Language::getMessageFor( $parts[0], $parts[1] );
819  if ( $message === null ) {
820  $message = false;
821  }
822  }
823  }
824 
825  // Post-processing if the message exists
826  if ( $message !== false ) {
827  // Fix whitespace
828  $message = str_replace(
829  [
830  # Fix for trailing whitespace, removed by textarea
831  '&#32;',
832  # Fix for NBSP, converted to space by firefox
833  '&nbsp;',
834  '&#160;',
835  '&shy;'
836  ],
837  [
838  ' ',
839  "\xc2\xa0",
840  "\xc2\xa0",
841  "\xc2\xad"
842  ],
843  $message
844  );
845  }
846 
847  return $message;
848  }
849 
862  protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
864 
865  $alreadyTried = [];
866 
867  // First try the requested language.
868  $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
869  if ( $message !== false ) {
870  return $message;
871  }
872 
873  // Now try checking the site language.
874  $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
875  return $message;
876  }
877 
888  private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
890 
891  $langcode = $lang->getCode();
892 
893  // Try checking the database for the requested language
894  if ( $useDB ) {
895  $uckey = $wgContLang->ucfirst( $lckey );
896 
897  if ( !isset( $alreadyTried[$langcode] ) ) {
898  $message = $this->getMsgFromNamespace(
899  $this->getMessagePageName( $langcode, $uckey ),
900  $langcode
901  );
902 
903  if ( $message !== false ) {
904  return $message;
905  }
906  $alreadyTried[$langcode] = true;
907  }
908  } else {
909  $uckey = null;
910  }
911 
912  // Check the CDB cache
913  $message = $lang->getMessage( $lckey );
914  if ( $message !== null ) {
915  return $message;
916  }
917 
918  // Try checking the database for all of the fallback languages
919  if ( $useDB ) {
920  $fallbackChain = Language::getFallbacksFor( $langcode );
921 
922  foreach ( $fallbackChain as $code ) {
923  if ( isset( $alreadyTried[$code] ) ) {
924  continue;
925  }
926 
927  $message = $this->getMsgFromNamespace(
928  $this->getMessagePageName( $code, $uckey ), $code );
929 
930  if ( $message !== false ) {
931  return $message;
932  }
933  $alreadyTried[$code] = true;
934  }
935  }
936 
937  return false;
938  }
939 
947  private function getMessagePageName( $langcode, $uckey ) {
949 
950  if ( $langcode === $wgLanguageCode ) {
951  // Messages created in the content language will not have the /lang extension
952  return $uckey;
953  } else {
954  return "$uckey/$langcode";
955  }
956  }
957 
970  public function getMsgFromNamespace( $title, $code ) {
971  $this->load( $code );
972 
973  if ( isset( $this->mCache[$code][$title] ) ) {
974  $entry = $this->mCache[$code][$title];
975  if ( substr( $entry, 0, 1 ) === ' ' ) {
976  // The message exists and is not '!TOO BIG'
977  return (string)substr( $entry, 1 );
978  } elseif ( $entry === '!NONEXISTENT' ) {
979  return false;
980  }
981  // Fall through and try invididual message cache below
982  } else {
983  // XXX: This is not cached in process cache, should it?
984  $message = false;
985  Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
986  if ( $message !== false ) {
987  return $message;
988  }
989 
990  return false;
991  }
992 
993  // Individual message cache key
994  $titleKey = $this->bigMessageCacheKey( $this->mCache[$code]['HASH'], $title );
995 
996  if ( $this->mCacheVolatile[$code] ) {
997  $entry = false;
998  // Make sure that individual keys respect the WAN cache holdoff period too
999  LoggerFactory::getInstance( 'MessageCache' )->debug(
1000  __METHOD__ . ': loading volatile key \'{titleKey}\'',
1001  [ 'titleKey' => $titleKey, 'code' => $code ] );
1002  } else {
1003  // Try the individual message cache
1004  $entry = $this->wanCache->get( $titleKey );
1005  }
1006 
1007  if ( $entry !== false ) {
1008  if ( substr( $entry, 0, 1 ) === ' ' ) {
1009  $this->mCache[$code][$title] = $entry;
1010  // The message exists, so make sure a string is returned
1011  return (string)substr( $entry, 1 );
1012  } elseif ( $entry === '!NONEXISTENT' ) {
1013  $this->mCache[$code][$title] = '!NONEXISTENT';
1014 
1015  return false;
1016  } else {
1017  // Corrupt/obsolete entry, delete it
1018  $this->wanCache->delete( $titleKey );
1019  }
1020  }
1021 
1022  // Try loading the message from the database
1023  $dbr = wfGetDB( DB_REPLICA );
1024  $cacheOpts = Database::getCacheSetOptions( $dbr );
1025  // Use newKnownCurrent() to avoid querying revision/user tables
1026  $titleObj = Title::makeTitle( NS_MEDIAWIKI, $title );
1027  if ( $titleObj->getLatestRevID() ) {
1028  $revision = Revision::newKnownCurrent(
1029  $dbr,
1030  $titleObj
1031  );
1032  } else {
1033  $revision = false;
1034  }
1035 
1036  if ( $revision ) {
1037  $content = $revision->getContent();
1038  if ( $content ) {
1039  $message = $this->getMessageTextFromContent( $content );
1040  if ( is_string( $message ) ) {
1041  $this->mCache[$code][$title] = ' ' . $message;
1042  $this->wanCache->set( $titleKey, ' ' . $message, $this->mExpiry, $cacheOpts );
1043  }
1044  } else {
1045  // A possibly temporary loading failure
1046  LoggerFactory::getInstance( 'MessageCache' )->warning(
1047  __METHOD__ . ': failed to load message page text for \'{titleKey}\'',
1048  [ 'titleKey' => $titleKey, 'code' => $code ] );
1049  $message = null; // no negative caching
1050  }
1051  } else {
1052  $message = false; // negative caching
1053  }
1054 
1055  if ( $message === false ) {
1056  // Negative caching in case a "too big" message is no longer available (deleted)
1057  $this->mCache[$code][$title] = '!NONEXISTENT';
1058  $this->wanCache->set( $titleKey, '!NONEXISTENT', $this->mExpiry, $cacheOpts );
1059  }
1060 
1061  return $message;
1062  }
1063 
1071  public function transform( $message, $interface = false, $language = null, $title = null ) {
1072  // Avoid creating parser if nothing to transform
1073  if ( strpos( $message, '{{' ) === false ) {
1074  return $message;
1075  }
1076 
1077  if ( $this->mInParser ) {
1078  return $message;
1079  }
1080 
1081  $parser = $this->getParser();
1082  if ( $parser ) {
1083  $popts = $this->getParserOptions();
1084  $popts->setInterfaceMessage( $interface );
1085  $popts->setTargetLanguage( $language );
1086 
1087  $userlang = $popts->setUserLang( $language );
1088  $this->mInParser = true;
1089  $message = $parser->transformMsg( $message, $popts, $title );
1090  $this->mInParser = false;
1091  $popts->setUserLang( $userlang );
1092  }
1093 
1094  return $message;
1095  }
1096 
1100  public function getParser() {
1102 
1103  if ( !$this->mParser && isset( $wgParser ) ) {
1104  # Do some initialisation so that we don't have to do it twice
1105  $wgParser->firstCallInit();
1106  # Clone it and store it
1107  $class = $wgParserConf['class'];
1108  if ( $class == ParserDiffTest::class ) {
1109  # Uncloneable
1110  $this->mParser = new $class( $wgParserConf );
1111  } else {
1112  $this->mParser = clone $wgParser;
1113  }
1114  }
1115 
1116  return $this->mParser;
1117  }
1118 
1127  public function parse( $text, $title = null, $linestart = true,
1128  $interface = false, $language = null
1129  ) {
1130  global $wgTitle;
1131 
1132  if ( $this->mInParser ) {
1133  return htmlspecialchars( $text );
1134  }
1135 
1136  $parser = $this->getParser();
1137  $popts = $this->getParserOptions();
1138  $popts->setInterfaceMessage( $interface );
1139 
1140  if ( is_string( $language ) ) {
1141  $language = Language::factory( $language );
1142  }
1143  $popts->setTargetLanguage( $language );
1144 
1145  if ( !$title || !$title instanceof Title ) {
1146  wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1147  wfGetAllCallers( 6 ) . ' with no title set.' );
1148  $title = $wgTitle;
1149  }
1150  // Sometimes $wgTitle isn't set either...
1151  if ( !$title ) {
1152  # It's not uncommon having a null $wgTitle in scripts. See r80898
1153  # Create a ghost title in such case
1154  $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1155  }
1156 
1157  $this->mInParser = true;
1158  $res = $parser->parse( $text, $title, $popts, $linestart );
1159  $this->mInParser = false;
1160 
1161  return $res;
1162  }
1163 
1164  public function disable() {
1165  $this->mDisable = true;
1166  }
1167 
1168  public function enable() {
1169  $this->mDisable = false;
1170  }
1171 
1184  public function isDisabled() {
1185  return $this->mDisable;
1186  }
1187 
1193  function clear() {
1194  $langs = Language::fetchLanguageNames( null, 'mw' );
1195  foreach ( array_keys( $langs ) as $code ) {
1196  $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1197  }
1198 
1199  $this->mLoadedLanguages = [];
1200  }
1201 
1206  public function figureMessage( $key ) {
1208 
1209  $pieces = explode( '/', $key );
1210  if ( count( $pieces ) < 2 ) {
1211  return [ $key, $wgLanguageCode ];
1212  }
1213 
1214  $lang = array_pop( $pieces );
1215  if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1216  return [ $key, $wgLanguageCode ];
1217  }
1218 
1219  $message = implode( '/', $pieces );
1220 
1221  return [ $message, $lang ];
1222  }
1223 
1232  public function getAllMessageKeys( $code ) {
1234 
1235  $this->load( $code );
1236  if ( !isset( $this->mCache[$code] ) ) {
1237  // Apparently load() failed
1238  return null;
1239  }
1240  // Remove administrative keys
1241  $cache = $this->mCache[$code];
1242  unset( $cache['VERSION'] );
1243  unset( $cache['EXPIRY'] );
1244  unset( $cache['EXCESSIVE'] );
1245  // Remove any !NONEXISTENT keys
1246  $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1247 
1248  // Keys may appear with a capital first letter. lcfirst them.
1249  return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1250  }
1251 
1259  public function updateMessageOverride( Title $title, Content $content = null ) {
1261 
1262  $msgText = $this->getMessageTextFromContent( $content );
1263  if ( $msgText === null ) {
1264  $msgText = false; // treat as not existing
1265  }
1266 
1267  $this->replace( $title->getDBkey(), $msgText );
1268 
1269  if ( $wgContLang->hasVariants() ) {
1270  $wgContLang->updateConversionTable( $title );
1271  }
1272  }
1273 
1278  public function getCheckKey( $code ) {
1279  return $this->wanCache->makeKey( 'messages', $code );
1280  }
1281 
1286  private function getMessageTextFromContent( Content $content = null ) {
1287  // @TODO: could skip pseudo-messages like js/css here, based on content model
1288  if ( $content ) {
1289  // Message page exists...
1290  // XXX: Is this the right way to turn a Content object into a message?
1291  // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1292  // CssContent. MessageContent is *not* used for storing messages, it's
1293  // only used for wrapping them when needed.
1294  $msgText = $content->getWikitextForTransclusion();
1295  if ( $msgText === false || $msgText === null ) {
1296  // This might be due to some kind of misconfiguration...
1297  $msgText = null;
1298  LoggerFactory::getInstance( 'MessageCache' )->warning(
1299  __METHOD__ . ": message content doesn't provide wikitext "
1300  . "(content model: " . $content->getModel() . ")" );
1301  }
1302  } else {
1303  // Message page does not exist...
1304  $msgText = false;
1305  }
1306 
1307  return $msgText;
1308  }
1309 
1315  private function bigMessageCacheKey( $hash, $title ) {
1316  return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1317  }
1318 }
Language\getFallbacksFor
static getFallbacksFor( $code)
Get the ordered list of fallback languages.
Definition: Language.php:4547
MessageCache\transform
transform( $message, $interface=false, $language=null, $title=null)
Definition: MessageCache.php:1071
MessageCache\$mParser
Parser $mParser
Definition: MessageCache.php:80
ParserOptions
Set options of the Parser.
Definition: ParserOptions.php:40
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
$wgUser
$wgUser
Definition: Setup.php:902
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:1288
MessageCache\$mLoadedLanguages
$mLoadedLanguages
Variable for tracking which variables are already loaded.
Definition: MessageCache.php:86
MessageCache\setValidationHash
setValidationHash( $code, array $cache)
Set the md5 used to validate the local disk cache.
Definition: MessageCache.php:725
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
MessageCache\$clusterCache
BagOStuff $clusterCache
Definition: MessageCache.php:96
$wgParser
$wgParser
Definition: Setup.php:917
MessageCache\normalizeKey
static normalizeKey( $key)
Normalize message key input.
Definition: MessageCache.php:145
MessageCache\parse
parse( $text, $title=null, $linestart=true, $interface=false, $language=null)
Definition: MessageCache.php:1127
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:759
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:667
array
the array() calling protocol came about after MediaWiki 1.4rc1.
MessageCache\enable
enable()
Definition: MessageCache.php:1168
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
$wgParserConf
$wgParserConf
Parser configuration.
Definition: DefaultSettings.php:4170
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:181
MessageCache\$mParserOptions
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
Definition: MessageCache.php:78
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1980
MessageCache\$mInParser
$mInParser
Definition: MessageCache.php:91
$wgMaxMsgCacheEntrySize
$wgMaxMsgCacheEntrySize
Maximum entry size in the message cache, in bytes.
Definition: DefaultSettings.php:3053
ParserOptions\newFromAnon
static newFromAnon()
Get a ParserOptions object for an anonymous user.
Definition: ParserOptions.php:963
MessageCache\LOCK_TTL
const LOCK_TTL
How long memcached locks last.
Definition: MessageCache.php:45
MessageCache\$mCacheVolatile
bool[] $mCacheVolatile
Map of (language code => boolean)
Definition: MessageCache.php:60
serialize
serialize()
Definition: ApiMessage.php:184
Revision\getRevisionText
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row.
Definition: Revision.php:1055
BagOStuff
interface is intended to be more or less compatible with the PHP memcached client.
Definition: BagOStuff.php:47
MessageCache\saveToLocalCache
saveToLocalCache( $code, $cache)
Save the cache to APC.
Definition: MessageCache.php:226
$res
$res
Definition: database.txt:21
$wgTitle
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') if(! $wgEnableAPI) $wgTitle
Definition: api.php:68
IExpiringStore\TTL_MINUTE
const TTL_MINUTE
Definition: IExpiringStore.php:34
$success
$success
Definition: NoLocalSettings.php:42
cache
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:55
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:1087
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:37
MessageCache\getValidationHash
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
Definition: MessageCache.php:687
$dbr
$dbr
Definition: testCompression.php:50
MessageCache\getMessageTextFromContent
getMessageTextFromContent(Content $content=null)
Definition: MessageCache.php:1286
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:63
$wgAdaptiveMessageCache
$wgAdaptiveMessageCache
Instead of caching everything, only cache those messages which have been customised in the site conte...
Definition: DefaultSettings.php:2511
MessageCache\$instance
static $instance
Singleton instance.
Definition: MessageCache.php:105
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:947
MessageCache\loadFromDB
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
Definition: MessageCache.php:456
MWException
MediaWiki exception.
Definition: MWException.php:26
MessageCache\getCheckKey
getCheckKey( $code)
Definition: MessageCache.php:1278
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:115
MessageCache\getMsgFromNamespace
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
Definition: MessageCache.php:970
MessageCache\bigMessageCacheKey
bigMessageCacheKey( $hash, $title)
Definition: MessageCache.php:1315
Language\fetchLanguageNames
static fetchLanguageNames( $inLanguage=null, $include='mw')
Get an array of language names, indexed by code.
Definition: Language.php:803
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2812
Language\getMessageFor
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4607
$parser
do that in ParserLimitReportFormat instead $parser
Definition: hooks.txt:2603
MessageCache\$mCache
$mCache
Process local cache of loaded messages that are defined in MediaWiki namespace.
Definition: MessageCache.php:55
$wgUseDatabaseMessages
$wgUseDatabaseMessages
Translation using MediaWiki: namespace.
Definition: DefaultSettings.php:3043
MessageCache\getMessagePageName
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
Definition: MessageCache.php:947
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
MessageCache\figureMessage
figureMessage( $key)
Definition: MessageCache.php:1206
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1306
MessageCache\$srvCache
BagOStuff $srvCache
Definition: MessageCache.php:98
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:964
MessageCache\replace
replace( $title, $text)
Updates cache as necessary when message page is changed.
Definition: MessageCache.php:564
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:534
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:95
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:2009
DB_MASTER
const DB_MASTER
Definition: defines.php:26
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:58
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:994
MessageCache\getMessageFromFallbackChain
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
Definition: MessageCache.php:862
MessageCache\FOR_UPDATE
const FOR_UPDATE
Definition: MessageCache.php:40
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:113
MessageCache\updateMessageOverride
updateMessageOverride(Title $title, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
Definition: MessageCache.php:1259
MessageCache\WAIT_SEC
const WAIT_SEC
How long to wait for memcached locks.
Definition: MessageCache.php:43
$wgMsgCacheExpiry
$wgMsgCacheExpiry
Expiry time for the message cache key.
Definition: DefaultSettings.php:3048
$value
$value
Definition: styleTest.css.php:45
MessageCache\__construct
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, $useDB, $expiry)
Definition: MessageCache.php:165
too
I won t presume to tell you how to I m just describing the methods I chose to use for myself If you do choose to follow these it will probably be easier for you to collaborate with others on the but if you want to contribute without by all means do which work well I also use K &R brace matching style I know that s a religious issue for so if you want to use a style that puts opening braces on the next that s OK too
Definition: design.txt:80
MessageCache\clear
clear()
Clear all stored messages in global and local cache.
Definition: MessageCache.php:1193
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:87
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:2887
MessageCache\getReentrantScopedLock
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
Definition: MessageCache.php:741
Language\fetchLanguageName
static fetchLanguageName( $code, $inLanguage=null, $include='all')
Definition: Language.php:896
$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. '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:1255
Parser
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition: Parser.php:70
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:434
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1563
Content
Base interface for content objects.
Definition: Content.php:34
MessageCache\getParser
getParser()
Definition: MessageCache.php:1100
MessageCache\getLocalCache
getLocalCache( $code)
Try to load the cache from APC.
Definition: MessageCache.php:214
wfGetMessageCacheStorage
wfGetMessageCacheStorage()
Get the cache object used by the message cache.
Definition: GlobalFunctions.php:3157
Title
Represents a title within MediaWiki.
Definition: Title.php:39
MessageCache\loadFromDBWithLock
loadFromDBWithLock( $code, array &$where, $mode=null)
Definition: MessageCache.php:394
MessageCache\$mDisable
$mDisable
Should mean that database cannot be used, but check.
Definition: MessageCache.php:66
$cache
$cache
Definition: mcc.php:33
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:252
$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:865
MessageCache\$wanCache
WANObjectCache $wanCache
Definition: MessageCache.php:94
DeferredUpdates\PRESEND
const PRESEND
Definition: DeferredUpdates.php:60
or
or
Definition: APACHE-LICENSE-2.0.txt:114
MessageCache\isDisabled
isDisabled()
Whether DB/cache usage is disabled for determining messages.
Definition: MessageCache.php:1184
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:22
MessageCache\getParserOptions
getParserOptions()
ParserOptions is lazy initialised.
Definition: MessageCache.php:185
MessageCache\isCacheExpired
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
Definition: MessageCache.php:644
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
MessageCache\$mExpiry
$mExpiry
Lifetime for cache, used by object caching.
Definition: MessageCache.php: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
database rows
Definition: globals.txt:10
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:183
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:82
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:56
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:25
MessageCache\disable
disable()
Definition: MessageCache.php:1164
MessageCache
Message cache Performs various MediaWiki namespace-related functions.
Definition: MessageCache.php:39
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add a callable update.
Definition: DeferredUpdates.php:111
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
MessageCache\getMessageForLang
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
Definition: MessageCache.php:888
$wgUseLocalMessageCache
$wgUseLocalMessageCache
Set this to true to maintain a copy of the message cache on the local server.
Definition: DefaultSettings.php:2503
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:18
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:57
MessageCache\getAllMessageKeys
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
Definition: MessageCache.php:1232
MessageCache\destroyInstance
static destroyInstance()
Destroy the singleton instance.
Definition: MessageCache.php:135