MediaWiki REL1_32
MessageCache.php
Go to the documentation of this file.
1<?php
24use Wikimedia\ScopedCallback;
27
32define( 'MSG_CACHE_VERSION', 2 );
33
41 const FOR_UPDATE = 1; // force message reload
42
44 const WAIT_SEC = 15;
46 const LOCK_TTL = 30;
47
53 protected $cache;
54
60 protected $overridable;
61
65 protected $cacheVolatile = [];
66
71 protected $mDisable;
72
77 protected $mExpiry;
78
83 protected $mParserOptions;
85 protected $mParser;
86
90 protected $mInParser = false;
91
93 protected $wanCache;
95 protected $clusterCache;
97 protected $srvCache;
99 protected $contLang;
100
105 private $loadedLanguages = [];
106
112 private static $instance;
113
120 public static function singleton() {
121 if ( self::$instance === null ) {
123 $services = MediaWikiServices::getInstance();
124 self::$instance = new self(
125 $services->getMainWANObjectCache(),
128 ? $services->getLocalServerObjectCache()
129 : new EmptyBagOStuff(),
132 $services->getContentLanguage()
133 );
134 }
135
136 return self::$instance;
137 }
138
144 public static function destroyInstance() {
145 self::$instance = null;
146 }
147
154 public static function normalizeKey( $key ) {
155 $lckey = strtr( $key, ' ', '_' );
156 if ( ord( $lckey ) < 128 ) {
157 $lckey[0] = strtolower( $lckey[0] );
158 } else {
159 $lckey = MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $lckey );
160 }
161
162 return $lckey;
163 }
164
173 public function __construct(
174 WANObjectCache $wanCache,
175 BagOStuff $clusterCache,
176 BagOStuff $serverCache,
177 $useDB,
178 $expiry,
179 Language $contLang = null
180 ) {
181 $this->wanCache = $wanCache;
182 $this->clusterCache = $clusterCache;
183 $this->srvCache = $serverCache;
184
185 $this->cache = new MapCacheLRU( 5 ); // limit size for sanity
186
187 $this->mDisable = !$useDB;
188 $this->mExpiry = $expiry;
189 $this->contLang = $contLang ?? MediaWikiServices::getInstance()->getContentLanguage();
190 }
191
197 function getParserOptions() {
198 global $wgUser;
199
200 if ( !$this->mParserOptions ) {
201 if ( !$wgUser->isSafeToLoad() ) {
202 // $wgUser isn't unstubbable yet, so don't try to get a
203 // ParserOptions for it. And don't cache this ParserOptions
204 // either.
205 $po = ParserOptions::newFromAnon();
206 $po->setAllowUnsafeRawHtml( false );
207 return $po;
208 }
209
210 $this->mParserOptions = new ParserOptions;
211 // Messages may take parameters that could come
212 // from malicious sources. As a precaution, disable
213 // the <html> parser tag when parsing messages.
214 $this->mParserOptions->setAllowUnsafeRawHtml( false );
215 }
216
217 return $this->mParserOptions;
218 }
219
226 protected function getLocalCache( $code ) {
227 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
228
229 return $this->srvCache->get( $cacheKey );
230 }
231
238 protected function saveToLocalCache( $code, $cache ) {
239 $cacheKey = $this->srvCache->makeKey( __CLASS__, $code );
240 $this->srvCache->set( $cacheKey, $cache );
241 }
242
264 protected function load( $code, $mode = null ) {
265 if ( !is_string( $code ) ) {
266 throw new InvalidArgumentException( "Missing language code" );
267 }
268
269 # Don't do double loading...
270 if ( isset( $this->loadedLanguages[$code] ) && $mode != self::FOR_UPDATE ) {
271 return true;
272 }
273
274 $this->overridable = array_flip( Language::getMessageKeysFor( $code ) );
275
276 # 8 lines of code just to say (once) that message cache is disabled
277 if ( $this->mDisable ) {
278 static $shownDisabled = false;
279 if ( !$shownDisabled ) {
280 wfDebug( __METHOD__ . ": disabled\n" );
281 $shownDisabled = true;
282 }
283
284 return true;
285 }
286
287 # Loading code starts
288 $success = false; # Keep track of success
289 $staleCache = false; # a cache array with expired data, or false if none has been loaded
290 $where = []; # Debug info, delayed to avoid spamming debug log too much
291
292 # Hash of the contents is stored in memcache, to detect if data-center cache
293 # or local cache goes out of date (e.g. due to replace() on some other server)
294 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
295 $this->cacheVolatile[$code] = $hashVolatile;
296
297 # Try the local cache and check against the cluster hash key...
298 $cache = $this->getLocalCache( $code );
299 if ( !$cache ) {
300 $where[] = 'local cache is empty';
301 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
302 $where[] = 'local cache has the wrong hash';
303 $staleCache = $cache;
304 } elseif ( $this->isCacheExpired( $cache ) ) {
305 $where[] = 'local cache is expired';
306 $staleCache = $cache;
307 } elseif ( $hashVolatile ) {
308 $where[] = 'local cache validation key is expired/volatile';
309 $staleCache = $cache;
310 } else {
311 $where[] = 'got from local cache';
312 $this->cache->set( $code, $cache );
313 $success = true;
314 }
315
316 if ( !$success ) {
317 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
318 # Try the global cache. If it is empty, try to acquire a lock. If
319 # the lock can't be acquired, wait for the other thread to finish
320 # and then try the global cache a second time.
321 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
322 if ( $hashVolatile && $staleCache ) {
323 # Do not bother fetching the whole cache blob to avoid I/O.
324 # Instead, just try to get the non-blocking $statusKey lock
325 # below, and use the local stale value if it was not acquired.
326 $where[] = 'global cache is presumed expired';
327 } else {
328 $cache = $this->clusterCache->get( $cacheKey );
329 if ( !$cache ) {
330 $where[] = 'global cache is empty';
331 } elseif ( $this->isCacheExpired( $cache ) ) {
332 $where[] = 'global cache is expired';
333 $staleCache = $cache;
334 } elseif ( $hashVolatile ) {
335 # DB results are replica DB lag prone until the holdoff TTL passes.
336 # By then, updates should be reflected in loadFromDBWithLock().
337 # One thread regenerates the cache while others use old values.
338 $where[] = 'global cache is expired/volatile';
339 $staleCache = $cache;
340 } else {
341 $where[] = 'got from global cache';
342 $this->cache->set( $code, $cache );
343 $this->saveToCaches( $cache, 'local-only', $code );
344 $success = true;
345 }
346 }
347
348 if ( $success ) {
349 # Done, no need to retry
350 break;
351 }
352
353 # We need to call loadFromDB. Limit the concurrency to one process.
354 # This prevents the site from going down when the cache expires.
355 # Note that the DB slam protection lock here is non-blocking.
356 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
357 if ( $loadStatus === true ) {
358 $success = true;
359 break;
360 } elseif ( $staleCache ) {
361 # Use the stale cache while some other thread constructs the new one
362 $where[] = 'using stale cache';
363 $this->cache->set( $code, $staleCache );
364 $success = true;
365 break;
366 } elseif ( $failedAttempts > 0 ) {
367 # Already blocked once, so avoid another lock/unlock cycle.
368 # This case will typically be hit if memcached is down, or if
369 # loadFromDB() takes longer than LOCK_WAIT.
370 $where[] = "could not acquire status key.";
371 break;
372 } elseif ( $loadStatus === 'cantacquire' ) {
373 # Wait for the other thread to finish, then retry. Normally,
374 # the memcached get() will then yield the other thread's result.
375 $where[] = 'waited for other thread to complete';
376 $this->getReentrantScopedLock( $cacheKey );
377 } else {
378 # Disable cache; $loadStatus is 'disabled'
379 break;
380 }
381 }
382 }
383
384 if ( !$success ) {
385 $where[] = 'loading FAILED - cache is disabled';
386 $this->mDisable = true;
387 $this->cache->set( $code, [] );
388 wfDebugLog( 'MessageCacheError', __METHOD__ . ": Failed to load $code\n" );
389 # This used to throw an exception, but that led to nasty side effects like
390 # the whole wiki being instantly down if the memcached server died
391 } else {
392 # All good, just record the success
393 $this->loadedLanguages[$code] = true;
394 }
395
396 if ( !$this->cache->has( $code ) ) { // sanity
397 throw new LogicException( "Process cache for '$code' should be set by now." );
398 }
399
400 $info = implode( ', ', $where );
401 wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
402
403 return $success;
404 }
405
412 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
413 # If cache updates on all levels fail, give up on message overrides.
414 # This is to avoid easy site outages; see $saveSuccess comments below.
415 $statusKey = $this->clusterCache->makeKey( 'messages', $code, 'status' );
416 $status = $this->clusterCache->get( $statusKey );
417 if ( $status === 'error' ) {
418 $where[] = "could not load; method is still globally disabled";
419 return 'disabled';
420 }
421
422 # Now let's regenerate
423 $where[] = 'loading from database';
424
425 # Lock the cache to prevent conflicting writes.
426 # This lock is non-blocking so stale cache can quickly be used.
427 # Note that load() will call a blocking getReentrantScopedLock()
428 # after this if it really need to wait for any current thread.
429 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
430 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
431 if ( !$scopedLock ) {
432 $where[] = 'could not acquire main lock';
433 return 'cantacquire';
434 }
435
436 $cache = $this->loadFromDB( $code, $mode );
437 $this->cache->set( $code, $cache );
438 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
439
440 if ( !$saveSuccess ) {
454 if ( $this->srvCache instanceof EmptyBagOStuff ) {
455 $this->clusterCache->set( $statusKey, 'error', 60 * 5 );
456 $where[] = 'could not save cache, disabled globally for 5 minutes';
457 } else {
458 $where[] = "could not save global cache";
459 }
460 }
461
462 return true;
463 }
464
474 protected function loadFromDB( $code, $mode = null ) {
476
477 // (T164666) The query here performs really poorly on WMF's
478 // contributions replicas. We don't have a way to say "any group except
479 // contributions", so for the moment let's specify 'api'.
480 // @todo: Get rid of this hack.
481 $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_REPLICA, 'api' );
482
483 $cache = [];
484
485 $mostused = []; // list of "<cased message key>/<code>"
487 if ( !$this->cache->has( $wgLanguageCode ) ) {
488 $this->load( $wgLanguageCode );
489 }
490 $mostused = array_keys( $this->cache->get( $wgLanguageCode ) );
491 foreach ( $mostused as $key => $value ) {
492 $mostused[$key] = "$value/$code";
493 }
494 }
495
496 // Get the list of software-defined messages in core/extensions
497 $overridable = array_flip( Language::getMessageKeysFor( $wgLanguageCode ) );
498
499 // Common conditions
500 $conds = [
501 'page_is_redirect' => 0,
502 'page_namespace' => NS_MEDIAWIKI,
503 ];
504 if ( count( $mostused ) ) {
505 $conds['page_title'] = $mostused;
506 } elseif ( $code !== $wgLanguageCode ) {
507 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
508 } else {
509 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
510 # other than language code.
511 $conds[] = 'page_title NOT' .
512 $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
513 }
514
515 // Set the stubs for oversized software-defined messages in the main cache map
516 $res = $dbr->select(
517 'page',
518 [ 'page_title', 'page_latest' ],
519 array_merge( $conds, [ 'page_len > ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
520 __METHOD__ . "($code)-big"
521 );
522 foreach ( $res as $row ) {
523 $name = $this->contLang->lcfirst( $row->page_title );
524 // Include entries/stubs for all keys in $mostused in adaptive mode
526 $cache[$row->page_title] = '!TOO BIG';
527 }
528 // At least include revision ID so page changes are reflected in the hash
529 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
530 }
531
532 // Set the text for small software-defined messages in the main cache map
533 $res = $dbr->select(
534 [ 'page', 'revision', 'text' ],
535 [ 'page_title', 'page_latest', 'old_id', 'old_text', 'old_flags' ],
536 array_merge( $conds, [ 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize ) ] ),
537 __METHOD__ . "($code)-small",
538 [],
539 [
540 'revision' => [ 'JOIN', 'page_latest=rev_id' ],
541 'text' => [ 'JOIN', 'rev_text_id=old_id' ],
542 ]
543 );
544 foreach ( $res as $row ) {
545 $name = $this->contLang->lcfirst( $row->page_title );
546 // Include entries/stubs for all keys in $mostused in adaptive mode
548 $text = Revision::getRevisionText( $row );
549 if ( $text === false ) {
550 // Failed to fetch data; possible ES errors?
551 // Store a marker to fetch on-demand as a workaround...
552 // TODO Use a differnt marker
553 $entry = '!TOO BIG';
555 'MessageCache',
556 __METHOD__
557 . ": failed to load message page text for {$row->page_title} ($code)"
558 );
559 } else {
560 $entry = ' ' . $text;
561 }
562 $cache[$row->page_title] = $entry;
563 } else {
564 // T193271: cache object gets too big and slow to generate.
565 // At least include revision ID so page changes are reflected in the hash.
566 $cache['EXCESSIVE'][$row->page_title] = $row->page_latest;
567 }
568 }
569
570 $cache['VERSION'] = MSG_CACHE_VERSION;
571 ksort( $cache );
572
573 # Hash for validating local cache (APC). No need to take into account
574 # messages larger than $wgMaxMsgCacheEntrySize, since those are only
575 # stored and fetched from memcache.
576 $cache['HASH'] = md5( serialize( $cache ) );
577 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
578 unset( $cache['EXCESSIVE'] ); // only needed for hash
579
580 return $cache;
581 }
582
588 private function isMainCacheable( $name, array $overridable ) {
589 // Include common conversion table pages. This also avoids problems with
590 // Installer::parse() bailing out due to disallowed DB queries (T207979).
591 return ( isset( $overridable[$name] ) || strpos( $name, 'conversiontable/' ) === 0 );
592 }
593
600 public function replace( $title, $text ) {
601 global $wgLanguageCode;
602
603 if ( $this->mDisable ) {
604 return;
605 }
606
607 list( $msg, $code ) = $this->figureMessage( $title );
608 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
609 // Content language overrides do not use the /<code> suffix
610 return;
611 }
612
613 // (a) Update the process cache with the new message text
614 if ( $text === false ) {
615 // Page deleted
616 $this->cache->setField( $code, $title, '!NONEXISTENT' );
617 } else {
618 // Ignore $wgMaxMsgCacheEntrySize so the process cache is up to date
619 $this->cache->setField( $code, $title, ' ' . $text );
620 }
621
622 // (b) Update the shared caches in a deferred update with a fresh DB snapshot
623 DeferredUpdates::addUpdate(
624 new MessageCacheUpdate( $code, $title, $msg ),
625 DeferredUpdates::PRESEND
626 );
627 }
628
634 public function refreshAndReplaceInternal( $code, array $replacements ) {
636
637 // Allow one caller at a time to avoid race conditions
638 $scopedLock = $this->getReentrantScopedLock(
639 $this->clusterCache->makeKey( 'messages', $code )
640 );
641 if ( !$scopedLock ) {
642 foreach ( $replacements as list( $title ) ) {
643 LoggerFactory::getInstance( 'MessageCache' )->error(
644 __METHOD__ . ': could not acquire lock to update {title} ({code})',
645 [ 'title' => $title, 'code' => $code ] );
646 }
647
648 return;
649 }
650
651 // Load the existing cache to update it in the local DC cache.
652 // The other DCs will see a hash mismatch.
653 if ( $this->load( $code, self::FOR_UPDATE ) ) {
654 $cache = $this->cache->get( $code );
655 } else {
656 // Err? Fall back to loading from the database.
657 $cache = $this->loadFromDB( $code, self::FOR_UPDATE );
658 }
659 // Check if individual cache keys should exist and update cache accordingly
660 $newTextByTitle = []; // map of (title => content)
661 $newBigTitles = []; // map of (title => latest revision ID), like EXCESSIVE in loadFromDB()
662 foreach ( $replacements as list( $title ) ) {
663 $page = WikiPage::factory( Title::makeTitle( NS_MEDIAWIKI, $title ) );
664 $page->loadPageData( $page::READ_LATEST );
665 $text = $this->getMessageTextFromContent( $page->getContent() );
666 // Remember the text for the blob store update later on
667 $newTextByTitle[$title] = $text;
668 // Note that if $text is false, then $cache should have a !NONEXISTANT entry
669 if ( !is_string( $text ) ) {
670 $cache[$title] = '!NONEXISTENT';
671 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
672 $cache[$title] = '!TOO BIG';
673 $newBigTitles[$title] = $page->getLatest();
674 } else {
675 $cache[$title] = ' ' . $text;
676 }
677 }
678 // Update HASH for the new key. Incorporates various administrative keys,
679 // including the old HASH (and thereby the EXCESSIVE value from loadFromDB()
680 // and previous replace() calls), but that doesn't really matter since we
681 // only ever compare it for equality with a copy saved by saveToCaches().
682 $cache['HASH'] = md5( serialize( $cache + [ 'EXCESSIVE' => $newBigTitles ] ) );
683 // Update the too-big WAN cache entries now that we have the new HASH
684 foreach ( $newBigTitles as $title => $id ) {
685 // Match logic of loadCachedMessagePageEntry()
686 $this->wanCache->set(
687 $this->bigMessageCacheKey( $cache['HASH'], $title ),
688 ' ' . $newTextByTitle[$title],
689 $this->mExpiry
690 );
691 }
692 // Mark this cache as definitely being "latest" (non-volatile) so
693 // load() calls do not try to refresh the cache with replica DB data
694 $cache['LATEST'] = time();
695 // Update the process cache
696 $this->cache->set( $code, $cache );
697 // Pre-emptively update the local datacenter cache so things like edit filter and
698 // blacklist changes are reflected immediately; these often use MediaWiki: pages.
699 // The datacenter handling replace() calls should be the same one handling edits
700 // as they require HTTP POST.
701 $this->saveToCaches( $cache, 'all', $code );
702 // Release the lock now that the cache is saved
703 ScopedCallback::consume( $scopedLock );
704
705 // Relay the purge. Touching this check key expires cache contents
706 // and local cache (APC) validation hash across all datacenters.
707 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
708
709 // Purge the messages in the message blob store and fire any hook handlers
710 $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
711 $blobStore = $resourceloader->getMessageBlobStore();
712 foreach ( $replacements as list( $title, $msg ) ) {
713 $blobStore->updateMessage( $this->contLang->lcfirst( $msg ) );
714 Hooks::run( 'MessageCacheReplace', [ $title, $newTextByTitle[$title] ] );
715 }
716 }
717
724 protected function isCacheExpired( $cache ) {
725 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
726 return true;
727 }
728 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
729 return true;
730 }
731 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
732 return true;
733 }
734
735 return false;
736 }
737
747 protected function saveToCaches( array $cache, $dest, $code = false ) {
748 if ( $dest === 'all' ) {
749 $cacheKey = $this->clusterCache->makeKey( 'messages', $code );
750 $success = $this->clusterCache->set( $cacheKey, $cache );
751 $this->setValidationHash( $code, $cache );
752 } else {
753 $success = true;
754 }
755
756 $this->saveToLocalCache( $code, $cache );
757
758 return $success;
759 }
760
767 protected function getValidationHash( $code ) {
768 $curTTL = null;
769 $value = $this->wanCache->get(
770 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
771 $curTTL,
772 [ $this->getCheckKey( $code ) ]
773 );
774
775 if ( $value ) {
776 $hash = $value['hash'];
777 if ( ( time() - $value['latest'] ) < WANObjectCache::TTL_MINUTE ) {
778 // Cache was recently updated via replace() and should be up-to-date.
779 // That method is only called in the primary datacenter and uses FOR_UPDATE.
780 // Also, it is unlikely that the current datacenter is *now* secondary one.
781 $expired = false;
782 } else {
783 // See if the "check" key was bumped after the hash was generated
784 $expired = ( $curTTL < 0 );
785 }
786 } else {
787 // No hash found at all; cache must regenerate to be safe
788 $hash = false;
789 $expired = true;
790 }
791
792 return [ $hash, $expired ];
793 }
794
805 protected function setValidationHash( $code, array $cache ) {
806 $this->wanCache->set(
807 $this->wanCache->makeKey( 'messages', $code, 'hash', 'v1' ),
808 [
809 'hash' => $cache['HASH'],
810 'latest' => $cache['LATEST'] ?? 0
811 ],
812 WANObjectCache::TTL_INDEFINITE
813 );
814 }
815
821 protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
822 return $this->clusterCache->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
823 }
824
858 function get( $key, $useDB = true, $langcode = true ) {
859 if ( is_int( $key ) ) {
860 // Fix numerical strings that somehow become ints
861 // on their way here
862 $key = (string)$key;
863 } elseif ( !is_string( $key ) ) {
864 throw new MWException( 'Non-string key given' );
865 } elseif ( $key === '' ) {
866 // Shortcut: the empty key is always missing
867 return false;
868 }
869
870 // Normalise title-case input (with some inlining)
871 $lckey = self::normalizeKey( $key );
872
873 Hooks::run( 'MessageCache::get', [ &$lckey ] );
874
875 // Loop through each language in the fallback list until we find something useful
876 $message = $this->getMessageFromFallbackChain(
877 wfGetLangObj( $langcode ),
878 $lckey,
879 !$this->mDisable && $useDB
880 );
881
882 // If we still have no message, maybe the key was in fact a full key so try that
883 if ( $message === false ) {
884 $parts = explode( '/', $lckey );
885 // We may get calls for things that are http-urls from sidebar
886 // Let's not load nonexistent languages for those
887 // They usually have more than one slash.
888 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
889 $message = Language::getMessageFor( $parts[0], $parts[1] );
890 if ( $message === null ) {
891 $message = false;
892 }
893 }
894 }
895
896 // Post-processing if the message exists
897 if ( $message !== false ) {
898 // Fix whitespace
899 $message = str_replace(
900 [
901 # Fix for trailing whitespace, removed by textarea
902 '&#32;',
903 # Fix for NBSP, converted to space by firefox
904 '&nbsp;',
905 '&#160;',
906 '&shy;'
907 ],
908 [
909 ' ',
910 "\u{00A0}",
911 "\u{00A0}",
912 "\u{00AD}"
913 ],
914 $message
915 );
916 }
917
918 return $message;
919 }
920
933 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
934 $alreadyTried = [];
935
936 // First try the requested language.
937 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
938 if ( $message !== false ) {
939 return $message;
940 }
941
942 // Now try checking the site language.
943 $message = $this->getMessageForLang( $this->contLang, $lckey, $useDB, $alreadyTried );
944 return $message;
945 }
946
957 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
958 $langcode = $lang->getCode();
959
960 // Try checking the database for the requested language
961 if ( $useDB ) {
962 $uckey = $this->contLang->ucfirst( $lckey );
963
964 if ( !isset( $alreadyTried[$langcode] ) ) {
965 $message = $this->getMsgFromNamespace(
966 $this->getMessagePageName( $langcode, $uckey ),
967 $langcode
968 );
969 if ( $message !== false ) {
970 return $message;
971 }
972 $alreadyTried[$langcode] = true;
973 }
974 } else {
975 $uckey = null;
976 }
977
978 // Check the CDB cache
979 $message = $lang->getMessage( $lckey );
980 if ( $message !== null ) {
981 return $message;
982 }
983
984 // Try checking the database for all of the fallback languages
985 if ( $useDB ) {
986 $fallbackChain = Language::getFallbacksFor( $langcode );
987
988 foreach ( $fallbackChain as $code ) {
989 if ( isset( $alreadyTried[$code] ) ) {
990 continue;
991 }
992
993 $message = $this->getMsgFromNamespace(
994 $this->getMessagePageName( $code, $uckey ), $code );
995
996 if ( $message !== false ) {
997 return $message;
998 }
999 $alreadyTried[$code] = true;
1000 }
1001 }
1002
1003 return false;
1004 }
1005
1013 private function getMessagePageName( $langcode, $uckey ) {
1014 global $wgLanguageCode;
1015
1016 if ( $langcode === $wgLanguageCode ) {
1017 // Messages created in the content language will not have the /lang extension
1018 return $uckey;
1019 } else {
1020 return "$uckey/$langcode";
1021 }
1022 }
1023
1036 public function getMsgFromNamespace( $title, $code ) {
1037 // Load all MediaWiki page definitions into cache. Note that individual keys
1038 // already loaded into cache during this request remain in the cache, which
1039 // includes the value of hook-defined messages.
1040 $this->load( $code );
1041
1042 $entry = $this->cache->getField( $code, $title );
1043
1044 if ( $entry !== null ) {
1045 // Message page exists as an override of a software messages
1046 if ( substr( $entry, 0, 1 ) === ' ' ) {
1047 // The message exists and is not '!TOO BIG'
1048 return (string)substr( $entry, 1 );
1049 } elseif ( $entry === '!NONEXISTENT' ) {
1050 // The text might be '-' or missing due to some data loss
1051 return false;
1052 }
1053 // Load the message page, utilizing the individual message cache.
1054 // If the page does not exist, there will be no hook handler fallbacks.
1055 $entry = $this->loadCachedMessagePageEntry(
1056 $title,
1057 $code,
1058 $this->cache->getField( $code, 'HASH' )
1059 );
1060 } else {
1061 // Message page either does not exist or does not override a software message
1062 $name = $this->contLang->lcfirst( $title );
1063 if ( !$this->isMainCacheable( $name, $this->overridable ) ) {
1064 // Message page does not override any software-defined message. A custom
1065 // message might be defined to have content or settings specific to the wiki.
1066 // Load the message page, utilizing the individual message cache as needed.
1067 $entry = $this->loadCachedMessagePageEntry(
1068 $title,
1069 $code,
1070 $this->cache->getField( $code, 'HASH' )
1071 );
1072 }
1073 if ( $entry === null || substr( $entry, 0, 1 ) !== ' ' ) {
1074 // Message does not have a MediaWiki page definition; try hook handlers
1075 $message = false;
1076 Hooks::run( 'MessagesPreLoad', [ $title, &$message, $code ] );
1077 if ( $message !== false ) {
1078 $this->cache->setField( $code, $title, ' ' . $message );
1079 } else {
1080 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1081 }
1082
1083 return $message;
1084 }
1085 }
1086
1087 if ( $entry !== false && substr( $entry, 0, 1 ) === ' ' ) {
1088 if ( $this->cacheVolatile[$code] ) {
1089 // Make sure that individual keys respect the WAN cache holdoff period too
1090 LoggerFactory::getInstance( 'MessageCache' )->debug(
1091 __METHOD__ . ': loading volatile key \'{titleKey}\'',
1092 [ 'titleKey' => $title, 'code' => $code ] );
1093 } else {
1094 $this->cache->setField( $code, $title, $entry );
1095 }
1096 // The message exists, so make sure a string is returned
1097 return (string)substr( $entry, 1 );
1098 }
1099
1100 $this->cache->setField( $code, $title, '!NONEXISTENT' );
1101
1102 return false;
1103 }
1104
1111 private function loadCachedMessagePageEntry( $dbKey, $code, $hash ) {
1112 $fname = __METHOD__;
1113 return $this->srvCache->getWithSetCallback(
1114 $this->srvCache->makeKey( 'messages-big', $hash, $dbKey ),
1115 IExpiringStore::TTL_MINUTE,
1116 function () use ( $code, $dbKey, $hash, $fname ) {
1117 return $this->wanCache->getWithSetCallback(
1118 $this->bigMessageCacheKey( $hash, $dbKey ),
1119 $this->mExpiry,
1120 function ( $oldValue, &$ttl, &$setOpts ) use ( $dbKey, $code, $fname ) {
1121 // Try loading the message from the database
1122 $dbr = wfGetDB( DB_REPLICA );
1123 $setOpts += Database::getCacheSetOptions( $dbr );
1124 // Use newKnownCurrent() to avoid querying revision/user tables
1125 $title = Title::makeTitle( NS_MEDIAWIKI, $dbKey );
1126 $revision = Revision::newKnownCurrent( $dbr, $title );
1127 if ( !$revision ) {
1128 // The wiki doesn't have a local override page. Cache absence with normal TTL.
1129 // When overrides are created, self::replace() takes care of the cache.
1130 return '!NONEXISTENT';
1131 }
1132 $content = $revision->getContent();
1133 if ( $content ) {
1134 $message = $this->getMessageTextFromContent( $content );
1135 } else {
1136 LoggerFactory::getInstance( 'MessageCache' )->warning(
1137 $fname . ': failed to load page text for \'{titleKey}\'',
1138 [ 'titleKey' => $dbKey, 'code' => $code ]
1139 );
1140 $message = null;
1141 }
1142
1143 if ( !is_string( $message ) ) {
1144 // Revision failed to load Content, or Content is incompatible with wikitext.
1145 // Possibly a temporary loading failure.
1146 $ttl = 5;
1147
1148 return '!NONEXISTENT';
1149 }
1150
1151 return ' ' . $message;
1152 }
1153 );
1154 }
1155 );
1156 }
1157
1165 public function transform( $message, $interface = false, $language = null, $title = null ) {
1166 // Avoid creating parser if nothing to transform
1167 if ( strpos( $message, '{{' ) === false ) {
1168 return $message;
1169 }
1170
1171 if ( $this->mInParser ) {
1172 return $message;
1173 }
1174
1175 $parser = $this->getParser();
1176 if ( $parser ) {
1177 $popts = $this->getParserOptions();
1178 $popts->setInterfaceMessage( $interface );
1179 $popts->setTargetLanguage( $language );
1180
1181 $userlang = $popts->setUserLang( $language );
1182 $this->mInParser = true;
1183 $message = $parser->transformMsg( $message, $popts, $title );
1184 $this->mInParser = false;
1185 $popts->setUserLang( $userlang );
1186 }
1187
1188 return $message;
1189 }
1190
1194 public function getParser() {
1195 global $wgParser, $wgParserConf;
1196
1197 if ( !$this->mParser && isset( $wgParser ) ) {
1198 # Do some initialisation so that we don't have to do it twice
1199 $wgParser->firstCallInit();
1200 # Clone it and store it
1201 $class = $wgParserConf['class'];
1202 if ( $class == ParserDiffTest::class ) {
1203 # Uncloneable
1204 $this->mParser = new $class( $wgParserConf );
1205 } else {
1206 $this->mParser = clone $wgParser;
1207 }
1208 }
1209
1210 return $this->mParser;
1211 }
1212
1221 public function parse( $text, $title = null, $linestart = true,
1222 $interface = false, $language = null
1223 ) {
1224 global $wgTitle;
1225
1226 if ( $this->mInParser ) {
1227 return htmlspecialchars( $text );
1228 }
1229
1230 $parser = $this->getParser();
1231 $popts = $this->getParserOptions();
1232 $popts->setInterfaceMessage( $interface );
1233
1234 if ( is_string( $language ) ) {
1235 $language = Language::factory( $language );
1236 }
1237 $popts->setTargetLanguage( $language );
1238
1239 if ( !$title || !$title instanceof Title ) {
1240 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1241 wfGetAllCallers( 6 ) . ' with no title set.' );
1242 $title = $wgTitle;
1243 }
1244 // Sometimes $wgTitle isn't set either...
1245 if ( !$title ) {
1246 # It's not uncommon having a null $wgTitle in scripts. See r80898
1247 # Create a ghost title in such case
1248 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1249 }
1250
1251 $this->mInParser = true;
1252 $res = $parser->parse( $text, $title, $popts, $linestart );
1253 $this->mInParser = false;
1254
1255 return $res;
1256 }
1257
1258 public function disable() {
1259 $this->mDisable = true;
1260 }
1261
1262 public function enable() {
1263 $this->mDisable = false;
1264 }
1265
1278 public function isDisabled() {
1279 return $this->mDisable;
1280 }
1281
1287 public function clear() {
1288 $langs = Language::fetchLanguageNames( null, 'mw' );
1289 foreach ( array_keys( $langs ) as $code ) {
1290 $this->wanCache->touchCheckKey( $this->getCheckKey( $code ) );
1291 }
1292 $this->cache->clear();
1293 $this->loadedLanguages = [];
1294 }
1295
1300 public function figureMessage( $key ) {
1301 global $wgLanguageCode;
1302
1303 $pieces = explode( '/', $key );
1304 if ( count( $pieces ) < 2 ) {
1305 return [ $key, $wgLanguageCode ];
1306 }
1307
1308 $lang = array_pop( $pieces );
1309 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1310 return [ $key, $wgLanguageCode ];
1311 }
1312
1313 $message = implode( '/', $pieces );
1314
1315 return [ $message, $lang ];
1316 }
1317
1326 public function getAllMessageKeys( $code ) {
1327 $this->load( $code );
1328 if ( !$this->cache->has( $code ) ) {
1329 // Apparently load() failed
1330 return null;
1331 }
1332 // Remove administrative keys
1333 $cache = $this->cache->get( $code );
1334 unset( $cache['VERSION'] );
1335 unset( $cache['EXPIRY'] );
1336 unset( $cache['EXCESSIVE'] );
1337 // Remove any !NONEXISTENT keys
1338 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1339
1340 // Keys may appear with a capital first letter. lcfirst them.
1341 return array_map( [ $this->contLang, 'lcfirst' ], array_keys( $cache ) );
1342 }
1343
1351 public function updateMessageOverride( Title $title, Content $content = null ) {
1352 $msgText = $this->getMessageTextFromContent( $content );
1353 if ( $msgText === null ) {
1354 $msgText = false; // treat as not existing
1355 }
1356
1357 $this->replace( $title->getDBkey(), $msgText );
1358
1359 if ( $this->contLang->hasVariants() ) {
1360 $this->contLang->updateConversionTable( $title );
1361 }
1362 }
1363
1368 public function getCheckKey( $code ) {
1369 return $this->wanCache->makeKey( 'messages', $code );
1370 }
1371
1376 private function getMessageTextFromContent( Content $content = null ) {
1377 // @TODO: could skip pseudo-messages like js/css here, based on content model
1378 if ( $content ) {
1379 // Message page exists...
1380 // XXX: Is this the right way to turn a Content object into a message?
1381 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
1382 // CssContent. MessageContent is *not* used for storing messages, it's
1383 // only used for wrapping them when needed.
1384 $msgText = $content->getWikitextForTransclusion();
1385 if ( $msgText === false || $msgText === null ) {
1386 // This might be due to some kind of misconfiguration...
1387 $msgText = null;
1388 LoggerFactory::getInstance( 'MessageCache' )->warning(
1389 __METHOD__ . ": message content doesn't provide wikitext "
1390 . "(content model: " . $content->getModel() . ")" );
1391 }
1392 } else {
1393 // Message page does not exist...
1394 $msgText = false;
1395 }
1396
1397 return $msgText;
1398 }
1399
1405 private function bigMessageCacheKey( $hash, $title ) {
1406 return $this->wanCache->makeKey( 'messages-big', $hash, $title );
1407 }
1408}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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
serialize()
$wgLanguageCode
Site language code.
$wgUseLocalMessageCache
Set this to true to maintain a copy of the message cache on the local server.
$wgAdaptiveMessageCache
Instead of caching everything, only cache those messages which have been customised in the site conte...
$wgUseDatabaseMessages
Translation using MediaWiki: namespace.
$wgMaxMsgCacheEntrySize
Maximum entry size in the message cache, in bytes.
$wgParserConf
Parser configuration.
$wgMsgCacheExpiry
Expiry time for the message cache key.
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfGetMessageCacheStorage()
Get the cache object used by the message cache.
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:121
$wgParser
Definition Setup.php:921
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') $wgTitle
Definition api.php:57
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:58
A BagOStuff object with no objects in it.
Internationalisation code.
Definition Language.php:35
MediaWiki exception.
Handles a simple LRU key/value map with a maximum number of entries.
PSR-3 logger instance factory.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Message cache purging and in-place update handler for specific message page changes.
Cache of messages that are defined by MediaWiki namespace pages or by hooks.
getValidationHash( $code)
Get the md5 used to validate the local APC cache.
loadFromDBWithLock( $code, array &$where, $mode=null)
const LOCK_TTL
How long memcached locks last.
loadFromDB( $code, $mode=null)
Loads cacheable messages from the database.
getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried)
Given a language, try and fetch messages from that language and its fallbacks.
$mExpiry
Lifetime for cache, used by object caching.
saveToLocalCache( $code, $cache)
Save the cache to APC.
getMessagePageName( $langcode, $uckey)
Get the message page name for a given language.
static $instance
Singleton instance.
Language $contLang
getCheckKey( $code)
saveToCaches(array $cache, $dest, $code=false)
Shortcut to update caches.
refreshAndReplaceInternal( $code, array $replacements)
setValidationHash( $code, array $cache)
Set the md5 used to validate the local disk cache.
isCacheExpired( $cache)
Is the given cache array expired due to time passing or a version change?
getMsgFromNamespace( $title, $code)
Get a message from the MediaWiki namespace, with caching.
getReentrantScopedLock( $key, $timeout=self::WAIT_SEC)
const WAIT_SEC
How long to wait for memcached locks.
$mDisable
Should mean that database cannot be used, but check.
getLocalCache( $code)
Try to load the cache from APC.
static destroyInstance()
Destroy the singleton instance.
load( $code, $mode=null)
Loads messages from caches or from database in this order: (1) local message cache (if $wgUseLocalMes...
BagOStuff $srvCache
transform( $message, $interface=false, $language=null, $title=null)
updateMessageOverride(Title $title, Content $content=null)
Purge message caches when a MediaWiki: page is created, updated, or deleted.
array $loadedLanguages
Track which languages have been loaded by load().
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
isDisabled()
Whether DB/cache usage is disabled for determining messages.
BagOStuff $clusterCache
isMainCacheable( $name, array $overridable)
loadCachedMessagePageEntry( $dbKey, $code, $hash)
getMessageTextFromContent(Content $content=null)
clear()
Clear all stored messages in global and local cache.
static singleton()
Get the signleton instance of this class.
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
MapCacheLRU $cache
Process cache of loaded messages that are defined in MediaWiki namespace.
WANObjectCache $wanCache
static normalizeKey( $key)
Normalize message key input.
bool[] $cacheVolatile
Map of (language code => boolean)
parse( $text, $title=null, $linestart=true, $interface=false, $language=null)
ParserOptions $mParserOptions
Message cache has its own parser which it uses to transform messages.
replace( $title, $text)
Updates cache as necessary when message page is changed.
__construct(WANObjectCache $wanCache, BagOStuff $clusterCache, BagOStuff $serverCache, $useDB, $expiry, Language $contLang=null)
getParserOptions()
ParserOptions is lazy initialised.
bigMessageCacheKey( $hash, $title)
array $overridable
Map of (lowercase message key => index) for all software defined messages.
Set options of the Parser.
setAllowUnsafeRawHtml( $x)
If the wiki is configured to allow raw html ($wgRawHtml = true) is it allowed in the specific case of...
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:68
static newKnownCurrent(IDatabase $db, $pageIdOrTitle, $revId=0)
Load a revision based on a known page ID and current revision ID from the DB.
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row.
Represents a title within MediaWiki.
Definition Title.php:39
getDBkey()
Get the main part with underscores.
Definition Title.php:951
Multi-datacenter aware caching interface.
Relational database abstraction object.
Definition Database.php:48
$res
Definition database.txt:21
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
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
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access too
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
const NS_MEDIAWIKI
Definition Defines.php:72
const NS_SPECIAL
Definition Defines.php:53
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition hooks.txt:1873
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place replace
Definition hooks.txt:2317
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
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1305
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:994
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:895
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2055
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition hooks.txt:2335
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
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 function
Definition injection.txt:30
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
Base interface for content objects.
Definition Content.php:34
you have access to all of the normal MediaWiki so you can get a DB use the cache
$cache
Definition mcc.php:33
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
MediaWiki has optional support for a high distributed memory object caching system For general information on but for a larger site with heavy load
Definition memcached.txt:6
$content
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN boolean columns are always mapped to as the code does not always treat the column as a and VARBINARY columns should simply be TEXT The only exception is when VARBINARY is used to store true binary data
Definition postgres.txt:43
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26
if(!isset( $args[0])) $lang