MediaWiki  1.30.0
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(
169  $useDB,
170  $expiry
171  ) {
172  $this->wanCache = $wanCache;
173  $this->clusterCache = $clusterCache;
174  $this->srvCache = $srvCache;
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->setEditSection( false );
195  $po->setAllowUnsafeRawHtml( false );
196  $po->setWrapOutputClass( false );
197  return $po;
198  }
199 
200  $this->mParserOptions = new ParserOptions;
201  $this->mParserOptions->setEditSection( false );
202  // Messages may take parameters that could come
203  // from malicious sources. As a precaution, disable
204  // the <html> parser tag when parsing messages.
205  $this->mParserOptions->setAllowUnsafeRawHtml( false );
206  // Wrapping messages in an extra <div> is probably not expected. If
207  // they're outside the content area they probably shouldn't be
208  // targeted by CSS that's targeting the parser output, and if
209  // they're inside they already are from the outer div.
210  $this->mParserOptions->setWrapOutputClass( false );
211  }
212 
213  return $this->mParserOptions;
214  }
215 
222  protected function getLocalCache( $code ) {
223  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
224 
225  return $this->srvCache->get( $cacheKey );
226  }
227 
234  protected function saveToLocalCache( $code, $cache ) {
235  $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
236  $this->srvCache->set( $cacheKey, $cache );
237  }
238 
260  protected function load( $code, $mode = null ) {
261  if ( !is_string( $code ) ) {
262  throw new InvalidArgumentException( "Missing language code" );
263  }
264 
265  # Don't do double loading...
266  if ( isset( $this->mLoadedLanguages[$code] ) && $mode != self::FOR_UPDATE ) {
267  return true;
268  }
269 
270  # 8 lines of code just to say (once) that message cache is disabled
271  if ( $this->mDisable ) {
272  static $shownDisabled = false;
273  if ( !$shownDisabled ) {
274  wfDebug( __METHOD__ . ": disabled\n" );
275  $shownDisabled = true;
276  }
277 
278  return true;
279  }
280 
281  # Loading code starts
282  $success = false; # Keep track of success
283  $staleCache = false; # a cache array with expired data, or false if none has been loaded
284  $where = []; # Debug info, delayed to avoid spamming debug log too much
285 
286  # Hash of the contents is stored in memcache, to detect if data-center cache
287  # or local cache goes out of date (e.g. due to replace() on some other server)
288  list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
289  $this->mCacheVolatile[$code] = $hashVolatile;
290 
291  # Try the local cache and check against the cluster hash key...
292  $cache = $this->getLocalCache( $code );
293  if ( !$cache ) {
294  $where[] = 'local cache is empty';
295  } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
296  $where[] = 'local cache has the wrong hash';
297  $staleCache = $cache;
298  } elseif ( $this->isCacheExpired( $cache ) ) {
299  $where[] = 'local cache is expired';
300  $staleCache = $cache;
301  } elseif ( $hashVolatile ) {
302  $where[] = 'local cache validation key is expired/volatile';
303  $staleCache = $cache;
304  } else {
305  $where[] = 'got from local cache';
306  $success = true;
307  $this->mCache[$code] = $cache;
308  }
309 
310  if ( !$success ) {
311  $cacheKey = $this->clusterCache->makeKey( 'messages', $code ); # Key in memc for messages
312  # Try the global cache. If it is empty, try to acquire a lock. If
313  # the lock can't be acquired, wait for the other thread to finish
314  # and then try the global cache a second time.
315  for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
316  if ( $hashVolatile && $staleCache ) {
317  # Do not bother fetching the whole cache blob to avoid I/O.
318  # Instead, just try to get the non-blocking $statusKey lock
319  # below, and use the local stale value if it was not acquired.
320  $where[] = 'global cache is presumed expired';
321  } else {
322  $cache = $this->clusterCache->get( $cacheKey );
323  if ( !$cache ) {
324  $where[] = 'global cache is empty';
325  } elseif ( $this->isCacheExpired( $cache ) ) {
326  $where[] = 'global cache is expired';
327  $staleCache = $cache;
328  } elseif ( $hashVolatile ) {
329  # DB results are replica DB lag prone until the holdoff TTL passes.
330  # By then, updates should be reflected in loadFromDBWithLock().
331  # One thread renerates the cache while others use old values.
332  $where[] = 'global cache is expired/volatile';
333  $staleCache = $cache;
334  } else {
335  $where[] = 'got from global cache';
336  $this->mCache[$code] = $cache;
337  $this->saveToCaches( $cache, 'local-only', $code );
338  $success = true;
339  }
340  }
341 
342  if ( $success ) {
343  # Done, no need to retry
344  break;
345  }
346 
347  # We need to call loadFromDB. Limit the concurrency to one process.
348  # This prevents the site from going down when the cache expires.
349  # Note that the DB slam protection lock here is non-blocking.
350  $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
351  if ( $loadStatus === true ) {
352  $success = true;
353  break;
354  } elseif ( $staleCache ) {
355  # Use the stale cache while some other thread constructs the new one
356  $where[] = 'using stale cache';
357  $this->mCache[$code] = $staleCache;
358  $success = true;
359  break;
360  } elseif ( $failedAttempts > 0 ) {
361  # Already blocked once, so avoid another lock/unlock cycle.
362  # This case will typically be hit if memcached is down, or if
363  # loadFromDB() takes longer than LOCK_WAIT.
364  $where[] = "could not acquire status key.";
365  break;
366  } elseif ( $loadStatus === 'cantacquire' ) {
367  # Wait for the other thread to finish, then retry. Normally,
368  # the memcached get() will then yeild the other thread's result.
369  $where[] = 'waited for other thread to complete';
370  $this->getReentrantScopedLock( $cacheKey );
371  } else {
372  # Disable cache; $loadStatus is 'disabled'
373  break;
374  }
375  }
376  }
377 
378  if ( !$success ) {
379  $where[] = 'loading FAILED - cache is disabled';
380  $this->mDisable = true;
381  $this->mCache = false;
382  wfDebugLog( 'MessageCacheError', __METHOD__ . ": Failed to load $code\n" );
383  # This used to throw an exception, but that led to nasty side effects like
384  # the whole wiki being instantly down if the memcached server died
385  } else {
386  # All good, just record the success
387  $this->mLoadedLanguages[$code] = true;
388  }
389 
390  $info = implode( ', ', $where );
391  wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
392 
393  return $success;
394  }
395 
402  protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
403  # If cache updates on all levels fail, give up on message overrides.
404  # This is to avoid easy site outages; see $saveSuccess comments below.
405  $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
406  $status = $this->clusterCache->get( $statusKey );
407  if ( $status === 'error' ) {
408  $where[] = "could not load; method is still globally disabled";
409  return 'disabled';
410  }
411 
412  # Now let's regenerate
413  $where[] = 'loading from database';
414 
415  # Lock the cache to prevent conflicting writes.
416  # This lock is non-blocking so stale cache can quickly be used.
417  # Note that load() will call a blocking getReentrantScopedLock()
418  # after this if it really need to wait for any current thread.
419  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
420  $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
421  if ( !$scopedLock ) {
422  $where[] = 'could not acquire main lock';
423  return 'cantacquire';
424  }
425 
426  $cache = $this->loadFromDB( $code, $mode );
427  $this->mCache[$code] = $cache;
428  $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
429 
430  if ( !$saveSuccess ) {
444  if ( $this->srvCache instanceof EmptyBagOStuff ) {
445  $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
446  $where[] = 'could not save cache, disabled globally for 5 minutes';
447  } else {
448  $where[] = "could not save global cache";
449  }
450  }
451 
452  return true;
453  }
454 
464  protected function loadFromDB( $code, $mode = null ) {
466 
467  // (T164666) The query here performs really poorly on WMF's
468  // contributions replicas. We don't have a way to say "any group except
469  // contributions", so for the moment let's specify 'api'.
470  // @todo: Get rid of this hack.
471  $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
472 
473  $cache = [];
474 
475  # Common conditions
476  $conds = [
477  'page_is_redirect' => 0,
478  'page_namespace' => NS_MEDIAWIKI,
479  ];
480 
481  $mostused = [];
483  if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
484  $this->load( $wgLanguageCode );
485  }
486  $mostused = array_keys( $this->mCache[$wgLanguageCode] );
487  foreach ( $mostused as $key => $value ) {
488  $mostused[$key] = "$value/$code";
489  }
490  }
491 
492  if ( count( $mostused ) ) {
493  $conds['page_title'] = $mostused;
494  } elseif ( $code !== $wgLanguageCode ) {
495  $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
496  } else {
497  # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
498  # other than language code.
499  $conds[] = 'page_title NOT' .
500  $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
501  }
502 
503  # Conditions to fetch oversized pages to ignore them
504  $bigConds = $conds;
505  $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
506 
507  # Load titles for all oversized pages in the MediaWiki namespace
508  $res = $dbr->select(
509  'page',
510  [ 'page_title', 'page_latest' ],
511  $bigConds,
512  __METHOD__ . "($code)-big"
513  );
514  foreach ( $res as $row ) {
515  $cache[$row->page_title] = '!TOO BIG';
516  // At least include revision ID so page changes are reflected in the hash
517  $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
518  }
519 
520  # Conditions to load the remaining pages with their contents
521  $smallConds = $conds;
522  $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
523 
524  $res = $dbr->select(
525  [ 'page', 'revision', 'text' ],
526  [ 'page_title', 'old_id', 'old_text', 'old_flags' ],
527  $smallConds,
528  __METHOD__ . "($code)-small",
529  [],
530  [
531  'revision' => [ 'JOIN', 'page_latest=rev_id' ],
532  'text' => [ 'JOIN', 'rev_text_id=old_id' ],
533  ]
534  );
535 
536  foreach ( $res as $row ) {
537  $text = Revision::getRevisionText( $row );
538  if ( $text === false ) {
539  // Failed to fetch data; possible ES errors?
540  // Store a marker to fetch on-demand as a workaround...
541  // TODO Use a differnt marker
542  $entry = '!TOO BIG';
543  wfDebugLog(
544  'MessageCache',
545  __METHOD__
546  . ": failed to load message page text for {$row->page_title} ($code)"
547  );
548  } else {
549  $entry = ' ' . $text;
550  }
551  $cache[$row->page_title] = $entry;
552  }
553 
554  $cache['VERSION'] = MSG_CACHE_VERSION;
555  ksort( $cache );
556 
557  # Hash for validating local cache (APC). No need to take into account
558  # messages larger than $wgMaxMsgCacheEntrySize, since those are only
559  # stored and fetched from memcache.
560  $cache['HASH'] = md5( serialize( $cache ) );
561  $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
562 
563  return $cache;
564  }
565 
572  public function replace( $title, $text ) {
574 
575  if ( $this->mDisable ) {
576  return;
577  }
578 
579  list( $msg, $code ) = $this->figureMessage( $title );
580  if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
581  // Content language overrides do not use the /<code> suffix
582  return;
583  }
584 
585  // (a) Update the process cache with the new message text
586  if ( $text === false ) {
587  // Page deleted
588  $this->mCache[$code][$title] = '!NONEXISTENT';
589  } else {
590  // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
591  $this->mCache[$code][$title] = ' ' . $text;
592  }
593 
594  // (b) Update the shared caches in a deferred update with a fresh DB snapshot
596  function () use ( $title, $msg, $code ) {
598  // Allow one caller at a time to avoid race conditions
599  $scopedLock = $this->getReentrantScopedLock(
600  $this->clusterCache->makeKey( 'messages', $code )
601  );
602  if ( !$scopedLock ) {
603  LoggerFactory::getInstance( 'MessageCache' )->error(
604  __METHOD__ . ': could not acquire lock to update {title} ({code})',
605  [ 'title' => $title, 'code' => $code ] );
606  return;
607  }
608  // Load the messages from the master DB to avoid race conditions
609  $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
610  $this->mCache[$code] = $cache;
611  // Load the process cache values and set the per-title cache keys
613  $page->loadPageData( $page::READ_LATEST );
614  $text = $this->getMessageTextFromContent( $page->getContent() );
615  // Check if an individual cache key should exist and update cache accordingly
616  if ( is_string( $text ) && strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
617  $titleKey = $this->bigMessageCacheKey( $this->mCache[$code]['HASH'], $title );
618  $this->wanCache->set( $titleKey, ' ' . $text, $this->mExpiry );
619  }
620  // Mark this cache as definitely being "latest" (non-volatile) so
621  // load() calls do try to refresh the cache with replica DB data
622  $this->mCache[$code]['LATEST'] = time();
623  // Pre-emptively update the local datacenter cache so things like edit filter and
624  // blacklist changes are reflect immediately, as these often use MediaWiki: pages.
625  // The datacenter handling replace() calls should be the same one handling edits
626  // as they require HTTP POST.
627  $this->saveToCaches( $this->mCache[$code], 'all', $code );
628  // Release the lock now that the cache is saved
629  ScopedCallback::consume( $scopedLock );
630 
631  // Relay the purge. Touching this check key expires cache contents
632  // and local cache (APC) validation hash across all datacenters.
633  $this->wanCache->touchCheckKey( $this->wanCache->makeKey( 'messages', $code ) );
634  // Also delete cached sidebar... just in case it is affected
635  // @TODO: shouldn't this be $code === $wgLanguageCode?
636  if ( $code === 'en' ) {
637  // Purge all language sidebars, e.g. on ?action=purge to the sidebar messages
638  $codes = array_keys( Language::fetchLanguageNames() );
639  } else {
640  // Purge only the sidebar for this language
641  $codes = [ $code ];
642  }
643  foreach ( $codes as $code ) {
644  $this->wanCache->delete( $this->wanCache->makeKey( 'sidebar', $code ) );
645  }
646 
647  // Purge the message in the message blob store
648  $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
649  $blobStore = $resourceloader->getMessageBlobStore();
650  $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
651 
652  Hooks::run( 'MessageCacheReplace', [ $title, $text ] );
653  },
655  );
656  }
657 
664  protected function isCacheExpired( $cache ) {
665  if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
666  return true;
667  }
668  if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
669  return true;
670  }
671  if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
672  return true;
673  }
674 
675  return false;
676  }
677 
687  protected function saveToCaches( array $cache, $dest, $code = false ) {
688  if ( $dest === 'all' ) {
689  $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
690  $success = $this->clusterCache->set( $cacheKey, $cache );
691  $this->setValidationHash( $code, $cache );
692  } else {
693  $success = true;
694  }
695 
696  $this->saveToLocalCache( $code, $cache );
697 
698  return $success;
699  }
700 
707  protected function getValidationHash( $code ) {
708  $curTTL = null;
709  $value = $this->wanCache->get(
710  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
711  $curTTL,
712  [ $this->wanCache->makeKey( 'messages', $code ) ]
713  );
714 
715  if ( $value ) {
716  $hash = $value['hash'];
717  if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
718  // Cache was recently updated via replace() and should be up-to-date.
719  // That method is only called in the primary datacenter and uses FOR_UPDATE.
720  // Also, it is unlikely that the current datacenter is *now* secondary one.
721  $expired = false;
722  } else {
723  // See if the "check" key was bumped after the hash was generated
724  $expired = ( $curTTL < 0 );
725  }
726  } else {
727  // No hash found at all; cache must regenerate to be safe
728  $hash = false;
729  $expired = true;
730  }
731 
732  return [ $hash, $expired ];
733  }
734 
745  protected function setValidationHash( $code, array $cache ) {
746  $this->wanCache->set(
747  $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
748  [
749  'hash' => $cache['HASH'],
750  'latest' => isset( $cache['LATEST'] ) ? $cache['LATEST'] : 0
751  ],
753  );
754  }
755 
761  protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
762  return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
763  }
764 
799  function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
800  if ( is_int( $key ) ) {
801  // Fix numerical strings that somehow become ints
802  // on their way here
803  $key = (string)$key;
804  } elseif ( !is_string( $key ) ) {
805  throw new MWException( 'Non-string key given' );
806  } elseif ( $key === '' ) {
807  // Shortcut: the empty key is always missing
808  return false;
809  }
810 
811  // For full keys, get the language code from the key
812  $pos = strrpos( $key, '/' );
813  if ( $isFullKey && $pos !== false ) {
814  $langcode = substr( $key, $pos + 1 );
815  $key = substr( $key, 0, $pos );
816  }
817 
818  // Normalise title-case input (with some inlining)
819  $lckey = self::normalizeKey( $key );
820 
821  Hooks::run( 'MessageCache::get', [ &$lckey ] );
822 
823  // Loop through each language in the fallback list until we find something useful
824  $lang = wfGetLangObj( $langcode );
825  $message = $this->getMessageFromFallbackChain(
826  $lang,
827  $lckey,
828  !$this->mDisable && $useDB
829  );
830 
831  // If we still have no message, maybe the key was in fact a full key so try that
832  if ( $message === false ) {
833  $parts = explode( '/', $lckey );
834  // We may get calls for things that are http-urls from sidebar
835  // Let's not load nonexistent languages for those
836  // They usually have more than one slash.
837  if ( count( $parts ) == 2 && $parts[1] !== '' ) {
838  $message = Language::getMessageFor( $parts[0], $parts[1] );
839  if ( $message === null ) {
840  $message = false;
841  }
842  }
843  }
844 
845  // Post-processing if the message exists
846  if ( $message !== false ) {
847  // Fix whitespace
848  $message = str_replace(
849  [
850  # Fix for trailing whitespace, removed by textarea
851  '&#32;',
852  # Fix for NBSP, converted to space by firefox
853  '&nbsp;',
854  '&#160;',
855  '&shy;'
856  ],
857  [
858  ' ',
859  "\xc2\xa0",
860  "\xc2\xa0",
861  "\xc2\xad"
862  ],
863  $message
864  );
865  }
866 
867  return $message;
868  }
869 
882  protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
884 
885  $alreadyTried = [];
886 
887  // First try the requested language.
888  $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
889  if ( $message !== false ) {
890  return $message;
891  }
892 
893  // Now try checking the site language.
894  $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
895  return $message;
896  }
897 
908  private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
910 
911  $langcode = $lang->getCode();
912 
913  // Try checking the database for the requested language
914  if ( $useDB ) {
915  $uckey = $wgContLang->ucfirst( $lckey );
916 
917  if ( !isset( $alreadyTried[ $langcode ] ) ) {
918  $message = $this->getMsgFromNamespace(
919  $this->getMessagePageName( $langcode, $uckey ),
920  $langcode
921  );
922 
923  if ( $message !== false ) {
924  return $message;
925  }
926  $alreadyTried[ $langcode ] = true;
927  }
928  } else {
929  $uckey = null;
930  }
931 
932  // Check the CDB cache
933  $message = $lang->getMessage( $lckey );
934  if ( $message !== null ) {
935  return $message;
936  }
937 
938  // Try checking the database for all of the fallback languages
939  if ( $useDB ) {
940  $fallbackChain = Language::getFallbacksFor( $langcode );
941 
942  foreach ( $fallbackChain as $code ) {
943  if ( isset( $alreadyTried[ $code ] ) ) {
944  continue;
945  }
946 
947  $message = $this->getMsgFromNamespace(
948  $this->getMessagePageName( $code, $uckey ), $code );
949 
950  if ( $message !== false ) {
951  return $message;
952  }
953  $alreadyTried[ $code ] = true;
954  }
955  }
956 
957  return false;
958  }
959 
967  private function getMessagePageName( $langcode, $uckey ) {
969 
970  if ( $langcode === $wgLanguageCode ) {
971  // Messages created in the content language will not have the /lang extension
972  return $uckey;
973  } else {
974  return "$uckey/$langcode";
975  }
976  }
977 
990  public function getMsgFromNamespace( $title, $code ) {
991  $this->load( $code );
992 
993  if ( isset( $this->mCache[$code][$title] ) ) {
994  $entry = $this->mCache[$code][$title];
995  if ( substr( $entry, 0, 1 ) === ' ' ) {
996  // The message exists, so make sure a string is returned.
997  return (string)substr( $entry, 1 );
998  } elseif ( $entry === '!NONEXISTENT' ) {
999  return false;
1000  } elseif ( $entry === '!TOO BIG' ) {
1001  // Fall through and try invididual message cache below
1002  }
1003  } else {
1004  // XXX: This is not cached in process cache, should it?
1005  $message = false;
1006  Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1007  if ( $message !== false ) {
1008  return $message;
1009  }
1010 
1011  return false;
1012  }
1013 
1014  // Individual message cache key
1015  $titleKey = $this->bigMessageCacheKey( $this->mCache[$code]['HASH'], $title );
1016 
1017  if ( $this->mCacheVolatile[$code] ) {
1018  $entry = false;
1019  // Make sure that individual keys respect the WAN cache holdoff period too
1020  LoggerFactory::getInstance( 'MessageCache' )->debug(
1021  __METHOD__ . ': loading volatile key \'{titleKey}\'',
1022  [ 'titleKey' => $titleKey, 'code' => $code ] );
1023  } else {
1024  // Try the individual message cache
1025  $entry = $this->wanCache->get( $titleKey );
1026  }
1027 
1028  if ( $entry !== false ) {
1029  if ( substr( $entry, 0, 1 ) === ' ' ) {
1030  $this->mCache[$code][$title] = $entry;
1031  // The message exists, so make sure a string is returned
1032  return (string)substr( $entry, 1 );
1033  } elseif ( $entry === '!NONEXISTENT' ) {
1034  $this->mCache[$code][$title] = '!NONEXISTENT';
1035 
1036  return false;
1037  } else {
1038  // Corrupt/obsolete entry, delete it
1039  $this->wanCache->delete( $titleKey );
1040  }
1041  }
1042 
1043  // Try loading the message from the database
1044  $dbr = wfGetDB( DB_REPLICA );
1045  $cacheOpts = Database::getCacheSetOptions( $dbr );
1046  // Use newKnownCurrent() to avoid querying revision/user tables
1047  $titleObj = Title::makeTitle( NS_MEDIAWIKI, $title );
1048  if ( $titleObj->getLatestRevID() ) {
1049  $revision = Revision::newKnownCurrent(
1050  $dbr,
1051  $titleObj->getArticleID(),
1052  $titleObj->getLatestRevID()
1053  );
1054  } else {
1055  $revision = false;
1056  }
1057 
1058  if ( $revision ) {
1059  $content = $revision->getContent();
1060  if ( $content ) {
1061  $message = $this->getMessageTextFromContent( $content );
1062  if ( is_string( $message ) ) {
1063  $this->mCache[$code][$title] = ' ' . $message;
1064  $this->wanCache->set( $titleKey, ' ' . $message, $this->mExpiry, $cacheOpts );
1065  }
1066  } else {
1067  // A possibly temporary loading failure
1068  LoggerFactory::getInstance( 'MessageCache' )->warning(
1069  __METHOD__ . ': failed to load message page text for \'{titleKey}\'',
1070  [ 'titleKey' => $titleKey, 'code' => $code ] );
1071  $message = null; // no negative caching
1072  }
1073  } else {
1074  $message = false; // negative caching
1075  }
1076 
1077  if ( $message === false ) {
1078  // Negative caching in case a "too big" message is no longer available (deleted)
1079  $this->mCache[$code][$title] = '!NONEXISTENT';
1080  $this->wanCache->set( $titleKey, '!NONEXISTENT', $this->mExpiry, $cacheOpts );
1081  }
1082 
1083  return $message;
1084  }
1085 
1093  function transform( $message, $interface = false, $language = null, $title = null ) {
1094  // Avoid creating parser if nothing to transform
1095  if ( strpos( $message, '{{' ) === false ) {
1096  return $message;
1097  }
1098 
1099  if ( $this->mInParser ) {
1100  return $message;
1101  }
1102 
1103  $parser = $this->getParser();
1104  if ( $parser ) {
1105  $popts = $this->getParserOptions();
1106  $popts->setInterfaceMessage( $interface );
1107  $popts->setTargetLanguage( $language );
1108 
1109  $userlang = $popts->setUserLang( $language );
1110  $this->mInParser = true;
1111  $message = $parser->transformMsg( $message, $popts, $title );
1112  $this->mInParser = false;
1113  $popts->setUserLang( $userlang );
1114  }
1115 
1116  return $message;
1117  }
1118 
1122  function getParser() {
1124 
1125  if ( !$this->mParser && isset( $wgParser ) ) {
1126  # Do some initialisation so that we don't have to do it twice
1127  $wgParser->firstCallInit();
1128  # Clone it and store it
1129  $class = $wgParserConf['class'];
1130  if ( $class == 'ParserDiffTest' ) {
1131  # Uncloneable
1132  $this->mParser = new $class( $wgParserConf );
1133  } else {
1134  $this->mParser = clone $wgParser;
1135  }
1136  }
1137 
1138  return $this->mParser;
1139  }
1140 
1149  public function parse( $text, $title = null, $linestart = true,
1150  $interface = false, $language = null
1151  ) {
1152  global $wgTitle;
1153 
1154  if ( $this->mInParser ) {
1155  return htmlspecialchars( $text );
1156  }
1157 
1158  $parser = $this->getParser();
1159  $popts = $this->getParserOptions();
1160  $popts->setInterfaceMessage( $interface );
1161 
1162  if ( is_string( $language ) ) {
1163  $language = Language::factory( $language );
1164  }
1165  $popts->setTargetLanguage( $language );
1166 
1167  if ( !$title || !$title instanceof Title ) {
1168  wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1169  wfGetAllCallers( 6 ) . ' with no title set.' );
1170  $title = $wgTitle;
1171  }
1172  // Sometimes $wgTitle isn't set either...
1173  if ( !$title ) {
1174  # It's not uncommon having a null $wgTitle in scripts. See r80898
1175  # Create a ghost title in such case
1176  $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1177  }
1178 
1179  $this->mInParser = true;
1180  $res = $parser->parse( $text, $title, $popts, $linestart );
1181  $this->mInParser = false;
1182 
1183  return $res;
1184  }
1185 
1186  function disable() {
1187  $this->mDisable = true;
1188  }
1189 
1190  function enable() {
1191  $this->mDisable = false;
1192  }
1193 
1206  public function isDisabled() {
1207  return $this->mDisable;
1208  }
1209 
1213  function clear() {
1214  $langs = Language::fetchLanguageNames( null, 'mw' );
1215  foreach ( array_keys( $langs ) as $code ) {
1216  # Global and local caches
1217  $this->wanCache->touchCheckKey( $this->wanCache->makeKey( 'messages', $code ) );
1218  }
1219 
1220  $this->mLoadedLanguages = [];
1221  }
1222 
1227  public function figureMessage( $key ) {
1229 
1230  $pieces = explode( '/', $key );
1231  if ( count( $pieces ) < 2 ) {
1232  return [ $key, $wgLanguageCode ];
1233  }
1234 
1235  $lang = array_pop( $pieces );
1236  if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1237  return [ $key, $wgLanguageCode ];
1238  }
1239 
1240  $message = implode( '/', $pieces );
1241 
1242  return [ $message, $lang ];
1243  }
1244 
1253  public function getAllMessageKeys( $code ) {
1255 
1256  $this->load( $code );
1257  if ( !isset( $this->mCache[$code] ) ) {
1258  // Apparently load() failed
1259  return null;
1260  }
1261  // Remove administrative keys
1262  $cache = $this->mCache[$code];
1263  unset( $cache['VERSION'] );
1264  unset( $cache['EXPIRY'] );
1265  unset( $cache['EXCESSIVE'] );
1266  // Remove any !NONEXISTENT keys
1267  $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1268 
1269  // Keys may appear with a capital first letter. lcfirst them.
1270  return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1271  }
1272 
1280  public function updateMessageOverride( Title $title, Content $content = null ) {
1282 
1283  $msgText = $this->getMessageTextFromContent( $content );
1284  if ( $msgText === null ) {
1285  $msgText = false; // treat as not existing
1286  }
1287 
1288  $this->replace( $title->getDBkey(), $msgText );
1289 
1290  if ( $wgContLang->hasVariants() ) {
1291  $wgContLang->updateConversionTable( $title );
1292  }
1293  }
1294 
1299  private function getMessageTextFromContent( Content $content = null ) {
1300  // @TODO: could skip pseudo-messages like js/css here, based on content model
1301  if ( $content ) {
1302  // Message page exists...
1303  // XXX: Is this the right way to turn a Content object into a message?
1304  // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1305  // CssContent. MessageContent is *not* used for storing messages, it's
1306  // only used for wrapping them when needed.
1307  $msgText = $content->getWikitextForTransclusion();
1308  if ( $msgText === false || $msgText === null ) {
1309  // This might be due to some kind of misconfiguration...
1310  $msgText = null;
1311  LoggerFactory::getInstance( 'MessageCache' )->warning(
1312  __METHOD__ . ": message content doesn't provide wikitext "
1313  . "(content model: " . $content->getModel() . ")" );
1314  }
1315  } else {
1316  // Message page does not exist...
1317  $msgText = false;
1318  }
1319 
1320  return $msgText;
1321  }
1322 
1328  private function bigMessageCacheKey( $hash, $title ) {
1329  return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1330  }
1331 }
Language\getFallbacksFor
static getFallbacksFor( $code)
Get the ordered list of fallback languages.
Definition: Language.php:4422
MessageCache\transform
transform( $message, $interface=false, $language=null, $title=null)
Definition: MessageCache.php:1093
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:45
$wgUser
$wgUser
Definition: Setup.php:809
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:745
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
MessageCache\$clusterCache
BagOStuff $clusterCache
Definition: MessageCache.php:96
$wgParser
$wgParser
Definition: Setup.php:824
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:1149
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:687
MessageCache\enable
enable()
Definition: MessageCache.php:1190
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
$wgParserConf
$wgParserConf
Parser configuration.
Definition: DefaultSettings.php:4178
captcha-old.count
count
Definition: captcha-old.py:249
MessageCache\$mParserOptions
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
Definition: MessageCache.php:78
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2040
MessageCache\$mInParser
$mInParser
Definition: MessageCache.php:91
$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). '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:1245
Revision\newKnownCurrent
static newKnownCurrent(IDatabase $db, $pageId, $revId)
Load a revision based on a known page ID and current revision ID from the DB.
Definition: Revision.php:1940
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$wgMaxMsgCacheEntrySize
$wgMaxMsgCacheEntrySize
Maximum entry size in the message cache, in bytes.
Definition: DefaultSettings.php:3027
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:177
Revision\getRevisionText
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row.
Definition: Revision.php:1266
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:234
$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:33
$success
$success
Definition: NoLocalSettings.php:44
cache
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1140
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
MessageCache\getValidationHash
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
Definition: MessageCache.php:707
MessageCache\getMessageTextFromContent
getMessageTextFromContent(Content $content=null)
Definition: MessageCache.php:1299
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:54
DeferredUpdates\addCallableUpdate
static addCallableUpdate( $callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
Definition: DeferredUpdates.php:111
$wgAdaptiveMessageCache
$wgAdaptiveMessageCache
Instead of caching everything, only cache those messages which have been customised in the site conte...
Definition: DefaultSettings.php:2487
MessageCache\$instance
static $instance
Singleton instance.
Definition: MessageCache.php:105
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:955
MessageCache\loadFromDB
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
Definition: MessageCache.php:464
MWException
MediaWiki exception.
Definition: MWException.php:26
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:932
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:121
a
</source > ! result< div class="mw-highlight mw-content-ltr" dir="ltr">< pre >< span ></span >< span class="kd"> var</span >< span class="nx"> a</span >< span class="p"></span ></pre ></div > ! end ! test Multiline< source/> in lists !input *< source > a b</source > *foo< source > a b</source > ! html< ul >< li >< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul >< ul >< li > foo< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul > ! html tidy< ul >< li >< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul >< ul >< li > foo< div class="mw-highlight mw-content-ltr" dir="ltr">< pre > a b</pre ></div ></li ></ul > ! end ! test Custom attributes !input< source lang="javascript" id="foo" class="bar" dir="rtl" style="font-size: larger;"> var a
Definition: parserTests.txt:89
MessageCache\getMsgFromNamespace
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
Definition: MessageCache.php:990
MessageCache\bigMessageCacheKey
bigMessageCacheKey( $hash, $title)
Definition: MessageCache.php:1328
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:2856
Language\getMessageFor
static getMessageFor( $key, $code)
Get a message for a given language.
Definition: Language.php:4482
in
null for the wiki Added in
Definition: hooks.txt:1581
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:3017
MessageCache\getMessagePageName
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
Definition: MessageCache.php:967
IExpiringStore\TTL_INDEFINITE
const TTL_INDEFINITE
Definition: IExpiringStore.php:44
MSG_CACHE_VERSION
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
Definition: MessageCache.php:32
MessageCache\figureMessage
figureMessage( $key)
Definition: MessageCache.php:1227
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1368
MessageCache\$srvCache
BagOStuff $srvCache
Definition: MessageCache.php:98
$parser
do that in ParserLimitReportFormat instead $parser
Definition: hooks.txt:2572
MessageCache\replace
replace( $title, $text)
Updates cache as necessary when message page is changed.
Definition: MessageCache.php:572
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:529
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:2069
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:49
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:1047
string
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
none
</source > ! result< p > Text< code class="mw-highlight" dir="ltr">< span class="kd"> var</span >< span class="nx"> a</span >< span class="p"></span ></code ></p > ! end ! test Enclose none(inline code) !!input Text< source lang
MessageCache\getMessageFromFallbackChain
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
Definition: MessageCache.php:882
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:1280
MessageCache\WAIT_SEC
const WAIT_SEC
How long to wait for memcached locks.
Definition: MessageCache.php:43
MessageCache\__construct
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $srvCache, $useDB, $expiry)
Definition: MessageCache.php:165
or
or
Definition: COPYING.txt:140
$wgMsgCacheExpiry
$wgMsgCacheExpiry
Expiry time for the message cache key.
Definition: DefaultSettings.php:3022
$value
$value
Definition: styleTest.css.php:45
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:79
MessageCache\clear
clear()
Clear all stored messages.
Definition: MessageCache.php:1213
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:80
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:2861
MessageCache\getReentrantScopedLock
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
Definition: MessageCache.php:761
Language\fetchLanguageName
static fetchLanguageName( $code, $inLanguage=null, $include='all')
Definition: Language.php:896
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:470
wfGetAllCallers
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
Definition: GlobalFunctions.php:1623
Content
Base interface for content objects.
Definition: Content.php:34
MessageCache\getParser
getParser()
Definition: MessageCache.php:1122
MessageCache\getLocalCache
getLocalCache( $code)
Try to load the cache from APC.
Definition: MessageCache.php:222
wfGetMessageCacheStorage
wfGetMessageCacheStorage()
Get the cache object used by the message cache.
Definition: GlobalFunctions.php:3214
Title
Represents a title within MediaWiki.
Definition: Title.php:39
MessageCache\loadFromDBWithLock
loadFromDBWithLock( $code, array &$where, $mode=null)
Definition: MessageCache.php:402
MessageCache\$mDisable
$mDisable
Should mean that database cannot be used, but check.
Definition: MessageCache.php:66
$dbr
if(! $regexes) $dbr
Definition: cleanup.php:94
$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:260
MessageCache\$wanCache
WANObjectCache $wanCache
Definition: MessageCache.php:94
DeferredUpdates\PRESEND
const PRESEND
Definition: DeferredUpdates.php:60
$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:781
MessageCache\isDisabled
isDisabled()
Whether DB/cache usage is disabled for determining messages.
Definition: MessageCache.php:1206
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
MessageCache\getParserOptions
getParserOptions()
ParserOptions is lazy initialised.
Definition: MessageCache.php:185
MessageCache\isCacheExpired
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
Definition: MessageCache.php:664
messages
passed in as a query string parameter to the various URLs constructed here(i.e. $prevlink) $ldel you ll need to handle error messages
Definition: hooks.txt:1265
ParserOptions\setEditSection
setEditSection( $x)
Create "edit section" links?
Definition: ParserOptions.php:883
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
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:73
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
MessageCache\disable
disable()
Definition: MessageCache.php:1186
MessageCache
Message cache Performs various MediaWiki namespace-related functions.
Definition: MessageCache.php:39
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
MessageCache\getMessageForLang
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
Definition: MessageCache.php:908
data
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of data
Definition: hooks.txt:6
$wgUseLocalMessageCache
$wgUseLocalMessageCache
Set this to true to maintain a copy of the message cache on the local server.
Definition: DefaultSettings.php:2479
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$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:56
MessageCache\getAllMessageKeys
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
Definition: MessageCache.php:1253
MessageCache\destroyInstance
static destroyInstance()
Destroy the singleton instance.
Definition: MessageCache.php:135