MediaWiki REL1_27
MessageCache.php
Go to the documentation of this file.
1<?php
28define( 'MSG_CACHE_VERSION', 2 );
29
36 const FOR_UPDATE = 1; // force message reload
37
39 const WAIT_SEC = 15;
41 const LOCK_TTL = 30;
42
51 protected $mCache;
52
57 protected $mDisable;
58
63 protected $mExpiry;
64
70
75 protected $mLoadedLanguages = [];
76
80 protected $mInParser = false;
81
83 protected $mMemc;
85 protected $wanCache;
86
92 private static $instance;
93
100 public static function singleton() {
101 if ( self::$instance === null ) {
103 self::$instance = new self(
107 );
108 }
109
110 return self::$instance;
111 }
112
118 public static function destroyInstance() {
119 self::$instance = null;
120 }
121
128 public static function normalizeKey( $key ) {
130 $lckey = strtr( $key, ' ', '_' );
131 if ( ord( $lckey ) < 128 ) {
132 $lckey[0] = strtolower( $lckey[0] );
133 } else {
134 $lckey = $wgContLang->lcfirst( $lckey );
135 }
136
137 return $lckey;
138 }
139
145 function __construct( $memCached, $useDB, $expiry ) {
147
148 if ( !$memCached ) {
149 $memCached = wfGetCache( CACHE_NONE );
150 }
151
152 $this->mMemc = $memCached;
153 $this->mDisable = !$useDB;
154 $this->mExpiry = $expiry;
155
157 $this->localCache = ObjectCache::getLocalServerInstance( CACHE_NONE );
158 } else {
159 $this->localCache = wfGetCache( CACHE_NONE );
160 }
161
162 $this->wanCache = ObjectCache::getMainWANInstance();
163 }
164
170 function getParserOptions() {
172
173 if ( !$this->mParserOptions ) {
174 if ( !$wgUser->isSafeToLoad() ) {
175 // $wgUser isn't unstubbable yet, so don't try to get a
176 // ParserOptions for it. And don't cache this ParserOptions
177 // either.
179 $po->setEditSection( false );
180 $po->setAllowUnsafeRawHtml( false );
181 return $po;
182 }
183
184 $this->mParserOptions = new ParserOptions;
185 $this->mParserOptions->setEditSection( false );
186 // Messages may take parameters that could come
187 // from malicious sources. As a precaution, disable
188 // the <html> parser tag when parsing messages.
189 $this->mParserOptions->setAllowUnsafeRawHtml( false );
190 }
191
193 }
194
201 protected function getLocalCache( $code ) {
202 $cacheKey = wfMemcKey( __CLASS__, $code );
203
204 return $this->localCache->get( $cacheKey );
205 }
206
213 protected function saveToLocalCache( $code, $cache ) {
214 $cacheKey = wfMemcKey( __CLASS__, $code );
215 $this->localCache->set( $cacheKey, $cache );
216 }
217
239 function load( $code = false, $mode = null ) {
240 if ( !is_string( $code ) ) {
241 # This isn't really nice, so at least make a note about it and try to
242 # fall back
243 wfDebug( __METHOD__ . " called without providing a language code\n" );
244 $code = 'en';
245 }
246
247 # Don't do double loading...
248 if ( isset( $this->mLoadedLanguages[$code] ) && $mode != self::FOR_UPDATE ) {
249 return true;
250 }
251
252 # 8 lines of code just to say (once) that message cache is disabled
253 if ( $this->mDisable ) {
254 static $shownDisabled = false;
255 if ( !$shownDisabled ) {
256 wfDebug( __METHOD__ . ": disabled\n" );
257 $shownDisabled = true;
258 }
259
260 return true;
261 }
262
263 # Loading code starts
264 $success = false; # Keep track of success
265 $staleCache = false; # a cache array with expired data, or false if none has been loaded
266 $where = []; # Debug info, delayed to avoid spamming debug log too much
267
268 # Hash of the contents is stored in memcache, to detect if data-center cache
269 # or local cache goes out of date (e.g. due to replace() on some other server)
270 list( $hash, $hashVolatile ) = $this->getValidationHash( $code );
271
272 # Try the local cache and check against the cluster hash key...
273 $cache = $this->getLocalCache( $code );
274 if ( !$cache ) {
275 $where[] = 'local cache is empty';
276 } elseif ( !isset( $cache['HASH'] ) || $cache['HASH'] !== $hash ) {
277 $where[] = 'local cache has the wrong hash';
278 $staleCache = $cache;
279 } elseif ( $this->isCacheExpired( $cache ) ) {
280 $where[] = 'local cache is expired';
281 $staleCache = $cache;
282 } elseif ( $hashVolatile ) {
283 $where[] = 'local cache validation key is expired/volatile';
284 $staleCache = $cache;
285 } else {
286 $where[] = 'got from local cache';
287 $success = true;
288 $this->mCache[$code] = $cache;
289 }
290
291 if ( !$success ) {
292 $cacheKey = wfMemcKey( 'messages', $code ); # Key in memc for messages
293 # Try the global cache. If it is empty, try to acquire a lock. If
294 # the lock can't be acquired, wait for the other thread to finish
295 # and then try the global cache a second time.
296 for ( $failedAttempts = 0; $failedAttempts <= 1; $failedAttempts++ ) {
297 if ( $hashVolatile && $staleCache ) {
298 # Do not bother fetching the whole cache blob to avoid I/O.
299 # Instead, just try to get the non-blocking $statusKey lock
300 # below, and use the local stale value if it was not acquired.
301 $where[] = 'global cache is presumed expired';
302 } else {
303 $cache = $this->mMemc->get( $cacheKey );
304 if ( !$cache ) {
305 $where[] = 'global cache is empty';
306 } elseif ( $this->isCacheExpired( $cache ) ) {
307 $where[] = 'global cache is expired';
308 $staleCache = $cache;
309 } elseif ( $hashVolatile ) {
310 # DB results are slave lag prone until the holdoff TTL passes.
311 # By then, updates should be reflected in loadFromDBWithLock().
312 # One thread renerates the cache while others use old values.
313 $where[] = 'global cache is expired/volatile';
314 $staleCache = $cache;
315 } else {
316 $where[] = 'got from global cache';
317 $this->mCache[$code] = $cache;
318 $this->saveToCaches( $cache, 'local-only', $code );
319 $success = true;
320 }
321 }
322
323 if ( $success ) {
324 # Done, no need to retry
325 break;
326 }
327
328 # We need to call loadFromDB. Limit the concurrency to one process.
329 # This prevents the site from going down when the cache expires.
330 # Note that the DB slam protection lock here is non-blocking.
331 $loadStatus = $this->loadFromDBWithLock( $code, $where, $mode );
332 if ( $loadStatus === true ) {
333 $success = true;
334 break;
335 } elseif ( $staleCache ) {
336 # Use the stale cache while some other thread constructs the new one
337 $where[] = 'using stale cache';
338 $this->mCache[$code] = $staleCache;
339 $success = true;
340 break;
341 } elseif ( $failedAttempts > 0 ) {
342 # Already blocked once, so avoid another lock/unlock cycle.
343 # This case will typically be hit if memcached is down, or if
344 # loadFromDB() takes longer than LOCK_WAIT.
345 $where[] = "could not acquire status key.";
346 break;
347 } elseif ( $loadStatus === 'cantacquire' ) {
348 # Wait for the other thread to finish, then retry. Normally,
349 # the memcached get() will then yeild the other thread's result.
350 $where[] = 'waited for other thread to complete';
351 $this->getReentrantScopedLock( $cacheKey );
352 } else {
353 # Disable cache; $loadStatus is 'disabled'
354 break;
355 }
356 }
357 }
358
359 if ( !$success ) {
360 $where[] = 'loading FAILED - cache is disabled';
361 $this->mDisable = true;
362 $this->mCache = false;
363 wfDebugLog( 'MessageCacheError', __METHOD__ . ": Failed to load $code\n" );
364 # This used to throw an exception, but that led to nasty side effects like
365 # the whole wiki being instantly down if the memcached server died
366 } else {
367 # All good, just record the success
368 $this->mLoadedLanguages[$code] = true;
369 }
370
371 $info = implode( ', ', $where );
372 wfDebugLog( 'MessageCache', __METHOD__ . ": Loading $code... $info\n" );
373
374 return $success;
375 }
376
383 protected function loadFromDBWithLock( $code, array &$where, $mode = null ) {
385
386 # If cache updates on all levels fail, give up on message overrides.
387 # This is to avoid easy site outages; see $saveSuccess comments below.
388 $statusKey = wfMemcKey( 'messages', $code, 'status' );
389 $status = $this->mMemc->get( $statusKey );
390 if ( $status === 'error' ) {
391 $where[] = "could not load; method is still globally disabled";
392 return 'disabled';
393 }
394
395 # Now let's regenerate
396 $where[] = 'loading from database';
397
398 # Lock the cache to prevent conflicting writes.
399 # This lock is non-blocking so stale cache can quickly be used.
400 # Note that load() will call a blocking getReentrantScopedLock()
401 # after this if it really need to wait for any current thread.
402 $cacheKey = wfMemcKey( 'messages', $code );
403 $scopedLock = $this->getReentrantScopedLock( $cacheKey, 0 );
404 if ( !$scopedLock ) {
405 $where[] = 'could not acquire main lock';
406 return 'cantacquire';
407 }
408
409 $cache = $this->loadFromDB( $code, $mode );
410 $this->mCache[$code] = $cache;
411 $saveSuccess = $this->saveToCaches( $cache, 'all', $code );
412
413 if ( !$saveSuccess ) {
428 $this->mMemc->set( $statusKey, 'error', 60 * 5 );
429 $where[] = 'could not save cache, disabled globally for 5 minutes';
430 } else {
431 $where[] = "could not save global cache";
432 }
433 }
434
435 return true;
436 }
437
447 function loadFromDB( $code, $mode = null ) {
449
450 $dbr = wfGetDB( ( $mode == self::FOR_UPDATE ) ? DB_MASTER : DB_SLAVE );
451
452 $cache = [];
453
454 # Common conditions
455 $conds = [
456 'page_is_redirect' => 0,
457 'page_namespace' => NS_MEDIAWIKI,
458 ];
459
460 $mostused = [];
462 if ( !isset( $this->mCache[$wgLanguageCode] ) ) {
463 $this->load( $wgLanguageCode );
464 }
465 $mostused = array_keys( $this->mCache[$wgLanguageCode] );
466 foreach ( $mostused as $key => $value ) {
467 $mostused[$key] = "$value/$code";
468 }
469 }
470
471 if ( count( $mostused ) ) {
472 $conds['page_title'] = $mostused;
473 } elseif ( $code !== $wgLanguageCode ) {
474 $conds[] = 'page_title' . $dbr->buildLike( $dbr->anyString(), '/', $code );
475 } else {
476 # Effectively disallows use of '/' character in NS_MEDIAWIKI for uses
477 # other than language code.
478 $conds[] = 'page_title NOT' . $dbr->buildLike( $dbr->anyString(), '/', $dbr->anyString() );
479 }
480
481 # Conditions to fetch oversized pages to ignore them
482 $bigConds = $conds;
483 $bigConds[] = 'page_len > ' . intval( $wgMaxMsgCacheEntrySize );
484
485 # Load titles for all oversized pages in the MediaWiki namespace
486 $res = $dbr->select( 'page', 'page_title', $bigConds, __METHOD__ . "($code)-big" );
487 foreach ( $res as $row ) {
488 $cache[$row->page_title] = '!TOO BIG';
489 }
490
491 # Conditions to load the remaining pages with their contents
492 $smallConds = $conds;
493 $smallConds[] = 'page_latest=rev_id';
494 $smallConds[] = 'rev_text_id=old_id';
495 $smallConds[] = 'page_len <= ' . intval( $wgMaxMsgCacheEntrySize );
496
497 $res = $dbr->select(
498 [ 'page', 'revision', 'text' ],
499 [ 'page_title', 'old_text', 'old_flags' ],
500 $smallConds,
501 __METHOD__ . "($code)-small"
502 );
503
504 foreach ( $res as $row ) {
505 $text = Revision::getRevisionText( $row );
506 if ( $text === false ) {
507 // Failed to fetch data; possible ES errors?
508 // Store a marker to fetch on-demand as a workaround...
509 $entry = '!TOO BIG';
511 'MessageCache',
512 __METHOD__
513 . ": failed to load message page text for {$row->page_title} ($code)"
514 );
515 } else {
516 $entry = ' ' . $text;
517 }
518 $cache[$row->page_title] = $entry;
519 }
520
521 $cache['VERSION'] = MSG_CACHE_VERSION;
522 ksort( $cache );
523 $cache['HASH'] = md5( serialize( $cache ) );
524 $cache['EXPIRY'] = wfTimestamp( TS_MW, time() + $this->mExpiry );
525
526 return $cache;
527 }
528
535 public function replace( $title, $text ) {
537
538 if ( $this->mDisable ) {
539 return;
540 }
541
542 list( $msg, $code ) = $this->figureMessage( $title );
543 if ( strpos( $title, '/' ) !== false && $code === $wgLanguageCode ) {
544 // Content language overrides do not use the /<code> suffix
545 return;
546 }
547
548 // Note that if the cache is volatile, load() may trigger a DB fetch.
549 // In that case we reenter/reuse the existing cache key lock to avoid
550 // a self-deadlock. This is safe as no reads happen *directly* in this
551 // method between getReentrantScopedLock() and load() below. There is
552 // no risk of data "changing under our feet" for replace().
553 $cacheKey = wfMemcKey( 'messages', $code );
554 $scopedLock = $this->getReentrantScopedLock( $cacheKey );
555 $this->load( $code, self::FOR_UPDATE );
556
557 $titleKey = wfMemcKey( 'messages', 'individual', $title );
558 if ( $text === false ) {
559 // Article was deleted
560 $this->mCache[$code][$title] = '!NONEXISTENT';
561 $this->wanCache->delete( $titleKey );
562 } elseif ( strlen( $text ) > $wgMaxMsgCacheEntrySize ) {
563 // Check for size
564 $this->mCache[$code][$title] = '!TOO BIG';
565 $this->wanCache->set( $titleKey, ' ' . $text, $this->mExpiry );
566 } else {
567 $this->mCache[$code][$title] = ' ' . $text;
568 $this->wanCache->delete( $titleKey );
569 }
570
571 // Mark this cache as definitely "latest" (non-volatile) so
572 // load() calls do try to refresh the cache with slave data
573 $this->mCache[$code]['LATEST'] = time();
574
575 // Update caches if the lock was acquired
576 if ( $scopedLock ) {
577 $this->saveToCaches( $this->mCache[$code], 'all', $code );
578 }
579
580 ScopedCallback::consume( $scopedLock );
581 // Relay the purge to APC and other DCs
582 $this->wanCache->touchCheckKey( wfMemcKey( 'messages', $code ) );
583
584 // Also delete cached sidebar... just in case it is affected
585 $codes = [ $code ];
586 if ( $code === 'en' ) {
587 // Delete all sidebars, like for example on action=purge on the
588 // sidebar messages
589 $codes = array_keys( Language::fetchLanguageNames() );
590 }
591
592 foreach ( $codes as $code ) {
593 $sidebarKey = wfMemcKey( 'sidebar', $code );
594 $this->wanCache->delete( $sidebarKey );
595 }
596
597 // Update the message in the message blob store
598 $resourceloader = RequestContext::getMain()->getOutput()->getResourceLoader();
599 $blobStore = $resourceloader->getMessageBlobStore();
600 $blobStore->updateMessage( $wgContLang->lcfirst( $msg ) );
601
602 Hooks::run( 'MessageCacheReplace', [ $title, $text ] );
603 }
604
611 protected function isCacheExpired( $cache ) {
612 if ( !isset( $cache['VERSION'] ) || !isset( $cache['EXPIRY'] ) ) {
613 return true;
614 }
615 if ( $cache['VERSION'] != MSG_CACHE_VERSION ) {
616 return true;
617 }
618 if ( wfTimestampNow() >= $cache['EXPIRY'] ) {
619 return true;
620 }
621
622 return false;
623 }
624
634 protected function saveToCaches( array $cache, $dest, $code = false ) {
635 if ( $dest === 'all' ) {
636 $cacheKey = wfMemcKey( 'messages', $code );
637 $success = $this->mMemc->set( $cacheKey, $cache );
638 } else {
639 $success = true;
640 }
641
642 $this->setValidationHash( $code, $cache );
643 $this->saveToLocalCache( $code, $cache );
644
645 return $success;
646 }
647
654 protected function getValidationHash( $code ) {
655 $curTTL = null;
656 $value = $this->wanCache->get(
657 wfMemcKey( 'messages', $code, 'hash', 'v1' ),
658 $curTTL,
659 [ wfMemcKey( 'messages', $code ) ]
660 );
661
662 if ( !$value ) {
663 // No hash found at all; cache must regenerate to be safe
664 $hash = false;
665 $expired = true;
666 } else {
667 $hash = $value['hash'];
668 if ( ( time() - $value['latest'] ) < WANObjectCache::HOLDOFF_TTL ) {
669 // Cache was recently updated via replace() and should be up-to-date
670 $expired = false;
671 } else {
672 // See if the "check" key was bumped after the hash was generated
673 $expired = ( $curTTL < 0 );
674 }
675 }
676
677 return [ $hash, $expired ];
678 }
679
689 protected function setValidationHash( $code, array $cache ) {
690 $this->wanCache->set(
691 wfMemcKey( 'messages', $code, 'hash', 'v1' ),
692 [
693 'hash' => $cache['HASH'],
694 'latest' => isset( $cache['LATEST'] ) ? $cache['LATEST'] : 0
695 ],
697 );
698 }
699
705 protected function getReentrantScopedLock( $key, $timeout = self::WAIT_SEC ) {
706 return $this->mMemc->getScopedLock( $key, $timeout, self::LOCK_TTL, __METHOD__ );
707 }
708
743 function get( $key, $useDB = true, $langcode = true, $isFullKey = false ) {
744 if ( is_int( $key ) ) {
745 // Fix numerical strings that somehow become ints
746 // on their way here
747 $key = (string)$key;
748 } elseif ( !is_string( $key ) ) {
749 throw new MWException( 'Non-string key given' );
750 } elseif ( $key === '' ) {
751 // Shortcut: the empty key is always missing
752 return false;
753 }
754
755 // For full keys, get the language code from the key
756 $pos = strrpos( $key, '/' );
757 if ( $isFullKey && $pos !== false ) {
758 $langcode = substr( $key, $pos + 1 );
759 $key = substr( $key, 0, $pos );
760 }
761
762 // Normalise title-case input (with some inlining)
763 $lckey = MessageCache::normalizeKey( $key );
764
765 Hooks::run( 'MessageCache::get', [ &$lckey ] );
766
767 // Loop through each language in the fallback list until we find something useful
768 $lang = wfGetLangObj( $langcode );
769 $message = $this->getMessageFromFallbackChain(
770 $lang,
771 $lckey,
772 !$this->mDisable && $useDB
773 );
774
775 // If we still have no message, maybe the key was in fact a full key so try that
776 if ( $message === false ) {
777 $parts = explode( '/', $lckey );
778 // We may get calls for things that are http-urls from sidebar
779 // Let's not load nonexistent languages for those
780 // They usually have more than one slash.
781 if ( count( $parts ) == 2 && $parts[1] !== '' ) {
782 $message = Language::getMessageFor( $parts[0], $parts[1] );
783 if ( $message === null ) {
784 $message = false;
785 }
786 }
787 }
788
789 // Post-processing if the message exists
790 if ( $message !== false ) {
791 // Fix whitespace
792 $message = str_replace(
793 [
794 # Fix for trailing whitespace, removed by textarea
795 '&#32;',
796 # Fix for NBSP, converted to space by firefox
797 '&nbsp;',
798 '&#160;',
799 '&shy;'
800 ],
801 [
802 ' ',
803 "\xc2\xa0",
804 "\xc2\xa0",
805 "\xc2\xad"
806 ],
807 $message
808 );
809 }
810
811 return $message;
812 }
813
826 protected function getMessageFromFallbackChain( $lang, $lckey, $useDB ) {
828
829 $alreadyTried = [];
830
831 // First try the requested language.
832 $message = $this->getMessageForLang( $lang, $lckey, $useDB, $alreadyTried );
833 if ( $message !== false ) {
834 return $message;
835 }
836
837 // Now try checking the site language.
838 $message = $this->getMessageForLang( $wgContLang, $lckey, $useDB, $alreadyTried );
839 return $message;
840 }
841
852 private function getMessageForLang( $lang, $lckey, $useDB, &$alreadyTried ) {
854 $langcode = $lang->getCode();
855
856 // Try checking the database for the requested language
857 if ( $useDB ) {
858 $uckey = $wgContLang->ucfirst( $lckey );
859
860 if ( !isset( $alreadyTried[ $langcode ] ) ) {
861 $message = $this->getMsgFromNamespace(
862 $this->getMessagePageName( $langcode, $uckey ),
863 $langcode
864 );
865
866 if ( $message !== false ) {
867 return $message;
868 }
869 $alreadyTried[ $langcode ] = true;
870 }
871 }
872
873 // Check the CDB cache
874 $message = $lang->getMessage( $lckey );
875 if ( $message !== null ) {
876 return $message;
877 }
878
879 // Try checking the database for all of the fallback languages
880 if ( $useDB ) {
881 $fallbackChain = Language::getFallbacksFor( $langcode );
882
883 foreach ( $fallbackChain as $code ) {
884 if ( isset( $alreadyTried[ $code ] ) ) {
885 continue;
886 }
887
888 $message = $this->getMsgFromNamespace( $this->getMessagePageName( $code, $uckey ), $code );
889
890 if ( $message !== false ) {
891 return $message;
892 }
893 $alreadyTried[ $code ] = true;
894 }
895 }
896
897 return false;
898 }
899
907 private function getMessagePageName( $langcode, $uckey ) {
909 if ( $langcode === $wgLanguageCode ) {
910 // Messages created in the content language will not have the /lang extension
911 return $uckey;
912 } else {
913 return "$uckey/$langcode";
914 }
915 }
916
929 public function getMsgFromNamespace( $title, $code ) {
930 $this->load( $code );
931 if ( isset( $this->mCache[$code][$title] ) ) {
932 $entry = $this->mCache[$code][$title];
933 if ( substr( $entry, 0, 1 ) === ' ' ) {
934 // The message exists, so make sure a string
935 // is returned.
936 return (string)substr( $entry, 1 );
937 } elseif ( $entry === '!NONEXISTENT' ) {
938 return false;
939 } elseif ( $entry === '!TOO BIG' ) {
940 // Fall through and try invididual message cache below
941 }
942 } else {
943 // XXX: This is not cached in process cache, should it?
944 $message = false;
945 Hooks::run( 'MessagesPreLoad', [ $title, &$message ] );
946 if ( $message !== false ) {
947 return $message;
948 }
949
950 return false;
951 }
952
953 # Try the individual message cache
954 $titleKey = wfMemcKey( 'messages', 'individual', $title );
955 $entry = $this->wanCache->get( $titleKey );
956 if ( $entry ) {
957 if ( substr( $entry, 0, 1 ) === ' ' ) {
958 $this->mCache[$code][$title] = $entry;
959
960 // The message exists, so make sure a string
961 // is returned.
962 return (string)substr( $entry, 1 );
963 } elseif ( $entry === '!NONEXISTENT' ) {
964 $this->mCache[$code][$title] = '!NONEXISTENT';
965
966 return false;
967 } else {
968 # Corrupt/obsolete entry, delete it
969 $this->wanCache->delete( $titleKey );
970 }
971 }
972
973 # Try loading it from the database
975 if ( $revision ) {
976 $content = $revision->getContent();
977 if ( !$content ) {
978 // A possibly temporary loading failure.
980 'MessageCache',
981 __METHOD__ . ": failed to load message page text for {$title} ($code)"
982 );
983 $message = null; // no negative caching
984 } else {
985 // XXX: Is this the right way to turn a Content object into a message?
986 // NOTE: $content is typically either WikitextContent, JavaScriptContent or
987 // CssContent. MessageContent is *not* used for storing messages, it's
988 // only used for wrapping them when needed.
989 $message = $content->getWikitextForTransclusion();
990
991 if ( $message === false || $message === null ) {
993 'MessageCache',
994 __METHOD__ . ": message content doesn't provide wikitext "
995 . "(content model: " . $content->getModel() . ")"
996 );
997
998 $message = false; // negative caching
999 } else {
1000 $this->mCache[$code][$title] = ' ' . $message;
1001 $this->wanCache->set( $titleKey, ' ' . $message, $this->mExpiry );
1002 }
1003 }
1004 } else {
1005 $message = false; // negative caching
1006 }
1007
1008 if ( $message === false ) { // negative caching
1009 $this->mCache[$code][$title] = '!NONEXISTENT';
1010 $this->wanCache->set( $titleKey, '!NONEXISTENT', $this->mExpiry );
1011 }
1012
1013 return $message;
1014 }
1015
1023 function transform( $message, $interface = false, $language = null, $title = null ) {
1024 // Avoid creating parser if nothing to transform
1025 if ( strpos( $message, '{{' ) === false ) {
1026 return $message;
1027 }
1028
1029 if ( $this->mInParser ) {
1030 return $message;
1031 }
1032
1033 $parser = $this->getParser();
1034 if ( $parser ) {
1035 $popts = $this->getParserOptions();
1036 $popts->setInterfaceMessage( $interface );
1037 $popts->setTargetLanguage( $language );
1038
1039 $userlang = $popts->setUserLang( $language );
1040 $this->mInParser = true;
1041 $message = $parser->transformMsg( $message, $popts, $title );
1042 $this->mInParser = false;
1043 $popts->setUserLang( $userlang );
1044 }
1045
1046 return $message;
1047 }
1048
1052 function getParser() {
1054 if ( !$this->mParser && isset( $wgParser ) ) {
1055 # Do some initialisation so that we don't have to do it twice
1056 $wgParser->firstCallInit();
1057 # Clone it and store it
1058 $class = $wgParserConf['class'];
1059 if ( $class == 'ParserDiffTest' ) {
1060 # Uncloneable
1061 $this->mParser = new $class( $wgParserConf );
1062 } else {
1063 $this->mParser = clone $wgParser;
1064 }
1065 }
1066
1067 return $this->mParser;
1068 }
1069
1078 public function parse( $text, $title = null, $linestart = true,
1079 $interface = false, $language = null
1080 ) {
1081 if ( $this->mInParser ) {
1082 return htmlspecialchars( $text );
1083 }
1084
1085 $parser = $this->getParser();
1086 $popts = $this->getParserOptions();
1087 $popts->setInterfaceMessage( $interface );
1088
1089 if ( is_string( $language ) ) {
1090 $language = Language::factory( $language );
1091 }
1092 $popts->setTargetLanguage( $language );
1093
1094 if ( !$title || !$title instanceof Title ) {
1096 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' .
1097 wfGetAllCallers( 5 ) . ' with no title set.' );
1098 $title = $wgTitle;
1099 }
1100 // Sometimes $wgTitle isn't set either...
1101 if ( !$title ) {
1102 # It's not uncommon having a null $wgTitle in scripts. See r80898
1103 # Create a ghost title in such case
1104 $title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
1105 }
1106
1107 $this->mInParser = true;
1108 $res = $parser->parse( $text, $title, $popts, $linestart );
1109 $this->mInParser = false;
1110
1111 return $res;
1112 }
1113
1114 function disable() {
1115 $this->mDisable = true;
1116 }
1117
1118 function enable() {
1119 $this->mDisable = false;
1120 }
1121
1134 public function isDisabled() {
1135 return $this->mDisable;
1136 }
1137
1141 function clear() {
1142 $langs = Language::fetchLanguageNames( null, 'mw' );
1143 foreach ( array_keys( $langs ) as $code ) {
1144 # Global and local caches
1145 $this->wanCache->touchCheckKey( wfMemcKey( 'messages', $code ) );
1146 }
1147
1148 $this->mLoadedLanguages = [];
1149 }
1150
1155 public function figureMessage( $key ) {
1157
1158 $pieces = explode( '/', $key );
1159 if ( count( $pieces ) < 2 ) {
1160 return [ $key, $wgLanguageCode ];
1161 }
1162
1163 $lang = array_pop( $pieces );
1164 if ( !Language::fetchLanguageName( $lang, null, 'mw' ) ) {
1165 return [ $key, $wgLanguageCode ];
1166 }
1167
1168 $message = implode( '/', $pieces );
1169
1170 return [ $message, $lang ];
1171 }
1172
1181 public function getAllMessageKeys( $code ) {
1183 $this->load( $code );
1184 if ( !isset( $this->mCache[$code] ) ) {
1185 // Apparently load() failed
1186 return null;
1187 }
1188 // Remove administrative keys
1189 $cache = $this->mCache[$code];
1190 unset( $cache['VERSION'] );
1191 unset( $cache['EXPIRY'] );
1192 // Remove any !NONEXISTENT keys
1193 $cache = array_diff( $cache, [ '!NONEXISTENT' ] );
1194
1195 // Keys may appear with a capital first letter. lcfirst them.
1196 return array_map( [ $wgContLang, 'lcfirst' ], array_keys( $cache ) );
1197 }
1198}
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.
wfMemcKey()
Make a cache key for the local wiki.
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.
wfGetCache( $cacheType)
Get a specific cache object.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const MSG_CACHE_VERSION
MediaWiki message cache structure version.
$wgUser
Definition Setup.php:794
$wgParser
Definition Setup.php:809
if(! $wgRequest->checkUrlExtension()) if(isset($_SERVER[ 'PATH_INFO']) &&$_SERVER[ 'PATH_INFO'] !='') if(! $wgEnableAPI) $wgTitle
Definition api.php:68
interface is intended to be more or less compatible with the PHP memcached client.
Definition BagOStuff.php:45
MediaWiki exception.
Message cache Performs various MediaWiki namespace-related functions.
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.
__construct( $memCached, $useDB, $expiry)
saveToCaches(array $cache, $dest, $code=false)
Shortcut to update caches.
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.
load( $code=false, $mode=null)
Loads messages from caches or from database in this order: (1) local message cache (if $wgUseLocalMes...
getLocalCache( $code)
Try to load the cache from APC.
static destroyInstance()
Destroy the singleton instance.
transform( $message, $interface=false, $language=null, $title=null)
getMessageFromFallbackChain( $lang, $lckey, $useDB)
Given a language, try and fetch messages from that language.
$mLoadedLanguages
Variable for tracking which variables are already loaded.
isDisabled()
Whether DB/cache usage is disabled for determining messages.
clear()
Clear all stored messages.
static singleton()
Get the signleton instance of this class.
getAllMessageKeys( $code)
Get all message keys stored in the message cache for a given language.
$mParserOptions
Message cache has its own parser which it uses to transform messages.
$mCache
Process local cache of loaded messages that are defined in MediaWiki namespace.
WANObjectCache $wanCache
static normalizeKey( $key)
Normalize message key input.
parse( $text, $title=null, $linestart=true, $interface=false, $language=null)
replace( $title, $text)
Updates cache as necessary when message page is changed.
getParserOptions()
ParserOptions is lazy initialised.
BagOStuff $mMemc
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
static getMainWANInstance()
Get the main WAN cache object.
Set options of the Parser.
static newFromAnon()
Get a ParserOptions object for an anonymous user.
static getMain()
Static methods.
static getRevisionText( $row, $prefix='old_', $wiki=false)
Get revision text associated with an old or archive row $row is usually an object from wfFetchRow(),...
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Definition Revision.php:117
static consume(ScopedCallback &$sc=null)
Trigger a scoped callback and destroy it.
Represents a title within MediaWiki.
Definition Title.php:34
static & makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition Title.php:524
Multi-datacenter aware caching interface.
const HOLDOFF_TTL
Seconds to tombstone keys on delete()
$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 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 local content language as $wgContLang
Definition design.txt:57
I won t presume to tell you how to I m just describing the methods I chose to use for myself If you do choose to follow these it will probably be easier for you to collaborate with others on the but if you want to contribute without by all means do which work well I also use K &R brace matching style I know that s a religious issue for so if you want to use a style that puts opening braces on the next that s OK too
Definition design.txt:80
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
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
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 DB_MASTER
Definition Defines.php:48
const CACHE_NONE
Definition Defines.php:103
const NS_MEDIAWIKI
Definition Defines.php:78
const NS_SPECIAL
Definition Defines.php:59
const DB_SLAVE
Definition Defines.php:47
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition hooks.txt:1007
the array() calling protocol came about after MediaWiki 1.4rc1.
do that in ParserLimitReportFormat instead $parser
Definition hooks.txt:2341
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:183
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition hooks.txt:1040
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:944
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired 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 inclusive false for true for descending in case the handler function wants to provide a converted Content object Note that $result getContentModel() must return $toModel. 'CustomEditor' you ll need to handle error messages
Definition hooks.txt:1102
null for the local wiki Added in
Definition hooks.txt:1421
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
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:847
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
you have access to all of the normal MediaWiki so you can get a DB use the cache
$cache
Definition mcc.php:33
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
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
if(!isset( $args[0])) $lang