MediaWiki REL1_31
ParserOutput.php
Go to the documentation of this file.
1<?php
2
25class ParserOutput extends CacheTime {
32
36 public $mText;
37
43
48
52 public $mIndicators = [];
53
58
63 public $mLinks = [];
64
69 public $mTemplates = [];
70
75 public $mTemplateIds = [];
76
80 public $mImages = [];
81
86
90 public $mExternalLinks = [];
91
96 public $mInterwikiLinks = [];
97
101 public $mNewSection = false;
102
106 public $mHideNewSection = false;
107
111 public $mNoGallery = false;
112
116 public $mHeadItems = [];
117
121 public $mModules = [];
122
126 public $mModuleScripts = [];
127
131 public $mModuleStyles = [];
132
136 public $mJsConfigVars = [];
137
141 public $mOutputHooks = [];
142
147 public $mWarnings = [];
148
152 public $mSections = [];
153
157 public $mProperties = [];
158
162 public $mTOCHTML = '';
163
168
172 public $mEnableOOUI = false;
173
177 private $mIndexPolicy = '';
178
182 private $mAccessedOptions = [];
183
187 private $mExtensionData = [];
188
192 private $mLimitReportData = [];
193
196
200 private $mParseStartTime = [];
201
205 private $mPreventClickjacking = false;
206
210 private $mFlags = [];
211
214
216 private $mMaxAdaptiveExpiry = INF;
217
219 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#s';
220
221 // finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
222 // Current values imply that m=3933.333333 and b=-333.333333
223 // See https://www.nngroup.com/articles/website-response-times/
224 const PARSE_FAST_SEC = 0.100; // perceived "fast" page parse
225 const PARSE_SLOW_SEC = 1.0; // perceived "slow" page parse
226 const FAST_AR_TTL = 60; // adaptive TTL for "fast" pages
227 const SLOW_AR_TTL = 3600; // adaptive TTL for "slow" pages
228 const MIN_AR_TTL = 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
229
230 public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
231 $unused = false, $titletext = ''
232 ) {
233 $this->mText = $text;
234 $this->mLanguageLinks = $languageLinks;
235 $this->mCategories = $categoryLinks;
236 $this->mTitleText = $titletext;
237 }
238
247 public function getRawText() {
248 return $this->mText;
249 }
250
270 public function getText( $options = [] ) {
271 $options += [
272 'allowTOC' => true,
273 'enableSectionEditLinks' => true,
274 'unwrap' => false,
275 'deduplicateStyles' => true,
276 ];
277 $text = $this->mText;
278
279 Hooks::runWithoutAbort( 'ParserOutputPostCacheTransform', [ $this, &$text, &$options ] );
280
281 if ( $options['unwrap'] !== false ) {
282 $start = Html::openElement( 'div', [
283 'class' => 'mw-parser-output'
284 ] );
285 $startLen = strlen( $start );
286 $end = Html::closeElement( 'div' );
287 $endPos = strrpos( $text, $end );
288 $endLen = strlen( $end );
289
290 if ( substr( $text, 0, $startLen ) === $start && $endPos !== false
291 // if the closing div is followed by real content, bail out of unwrapping
292 && preg_match( '/^(?>\s*<!--.*?-->)*\s*$/s', substr( $text, $endPos + $endLen ) )
293 ) {
294 $text = substr( $text, $startLen );
295 $text = substr( $text, 0, $endPos - $startLen )
296 . substr( $text, $endPos - $startLen + $endLen );
297 }
298 }
299
300 if ( $options['enableSectionEditLinks'] ) {
301 $text = preg_replace_callback(
302 self::EDITSECTION_REGEX,
303 function ( $m ) {
305 $editsectionPage = Title::newFromText( htmlspecialchars_decode( $m[1] ) );
306 $editsectionSection = htmlspecialchars_decode( $m[2] );
307 $editsectionContent = isset( $m[4] ) ? Sanitizer::decodeCharReferences( $m[3] ) : null;
308
309 if ( !is_object( $editsectionPage ) ) {
310 throw new MWException( "Bad parser output text." );
311 }
312
313 $skin = $wgOut->getSkin();
314 return call_user_func_array(
315 [ $skin, 'doEditSectionLink' ],
316 [ $editsectionPage, $editsectionSection,
317 $editsectionContent, $wgLang->getCode() ]
318 );
319 },
320 $text
321 );
322 } else {
323 $text = preg_replace( self::EDITSECTION_REGEX, '', $text );
324 }
325
326 if ( $options['allowTOC'] ) {
327 $text = str_replace( [ Parser::TOC_START, Parser::TOC_END ], '', $text );
328 } else {
329 $text = preg_replace(
330 '#' . preg_quote( Parser::TOC_START, '#' ) . '.*?' . preg_quote( Parser::TOC_END, '#' ) . '#s',
331 '',
332 $text
333 );
334 }
335
336 if ( $options['deduplicateStyles'] ) {
337 $seen = [];
338 $text = preg_replace_callback(
339 '#<style\s+([^>]*data-mw-deduplicate\s*=[^>]*)>.*?</style>#s',
340 function ( $m ) use ( &$seen ) {
341 $attr = Sanitizer::decodeTagAttributes( $m[1] );
342 if ( !isset( $attr['data-mw-deduplicate'] ) ) {
343 return $m[0];
344 }
345
346 $key = $attr['data-mw-deduplicate'];
347 if ( !isset( $seen[$key] ) ) {
348 $seen[$key] = true;
349 return $m[0];
350 }
351
352 // We were going to use an empty <style> here, but there
353 // was concern that would be too much overhead for browsers.
354 // So let's hope a <link> with a non-standard rel and href isn't
355 // going to be misinterpreted or mangled by any subsequent processing.
356 return Html::element( 'link', [
357 'rel' => 'mw-deduplicated-inline-style',
358 'href' => "mw-data:" . wfUrlencode( $key ),
359 ] );
360 },
361 $text
362 );
363 }
364
365 return $text;
366 }
367
372 public function setSpeculativeRevIdUsed( $id ) {
373 $this->mSpeculativeRevId = $id;
374 }
375
380 public function getSpeculativeRevIdUsed() {
381 return $this->mSpeculativeRevId;
382 }
383
384 public function &getLanguageLinks() {
385 return $this->mLanguageLinks;
386 }
387
388 public function getInterwikiLinks() {
389 return $this->mInterwikiLinks;
390 }
391
392 public function getCategoryLinks() {
393 return array_keys( $this->mCategories );
394 }
395
396 public function &getCategories() {
397 return $this->mCategories;
398 }
399
404 public function getIndicators() {
405 return $this->mIndicators;
406 }
407
408 public function getTitleText() {
409 return $this->mTitleText;
410 }
411
412 public function getSections() {
413 return $this->mSections;
414 }
415
419 public function getEditSectionTokens() {
420 wfDeprecated( __METHOD__, '1.31' );
421 return true;
422 }
423
424 public function &getLinks() {
425 return $this->mLinks;
426 }
427
428 public function &getTemplates() {
429 return $this->mTemplates;
430 }
431
432 public function &getTemplateIds() {
433 return $this->mTemplateIds;
434 }
435
436 public function &getImages() {
437 return $this->mImages;
438 }
439
440 public function &getFileSearchOptions() {
441 return $this->mFileSearchOptions;
442 }
443
444 public function &getExternalLinks() {
445 return $this->mExternalLinks;
446 }
447
448 public function getNoGallery() {
449 return $this->mNoGallery;
450 }
451
452 public function getHeadItems() {
453 return $this->mHeadItems;
454 }
455
456 public function getModules() {
457 return $this->mModules;
458 }
459
460 public function getModuleScripts() {
461 return $this->mModuleScripts;
462 }
463
464 public function getModuleStyles() {
465 return $this->mModuleStyles;
466 }
467
472 public function getJsConfigVars() {
473 return $this->mJsConfigVars;
474 }
475
476 public function getOutputHooks() {
477 return (array)$this->mOutputHooks;
478 }
479
480 public function getWarnings() {
481 return array_keys( $this->mWarnings );
482 }
483
484 public function getIndexPolicy() {
485 return $this->mIndexPolicy;
486 }
487
488 public function getTOCHTML() {
489 return $this->mTOCHTML;
490 }
491
495 public function getTimestamp() {
496 return $this->mTimestamp;
497 }
498
499 public function getLimitReportData() {
500 return $this->mLimitReportData;
501 }
502
503 public function getLimitReportJSData() {
504 return $this->mLimitReportJSData;
505 }
506
510 public function getTOCEnabled() {
511 wfDeprecated( __METHOD__, '1.31' );
512 return true;
513 }
514
515 public function getEnableOOUI() {
516 return $this->mEnableOOUI;
517 }
518
519 public function setText( $text ) {
520 return wfSetVar( $this->mText, $text );
521 }
522
523 public function setLanguageLinks( $ll ) {
524 return wfSetVar( $this->mLanguageLinks, $ll );
525 }
526
527 public function setCategoryLinks( $cl ) {
528 return wfSetVar( $this->mCategories, $cl );
529 }
530
531 public function setTitleText( $t ) {
532 return wfSetVar( $this->mTitleText, $t );
533 }
534
535 public function setSections( $toc ) {
536 return wfSetVar( $this->mSections, $toc );
537 }
538
542 public function setEditSectionTokens( $t ) {
543 wfDeprecated( __METHOD__, '1.31' );
544 return true;
545 }
546
547 public function setIndexPolicy( $policy ) {
548 return wfSetVar( $this->mIndexPolicy, $policy );
549 }
550
551 public function setTOCHTML( $tochtml ) {
552 return wfSetVar( $this->mTOCHTML, $tochtml );
553 }
554
555 public function setTimestamp( $timestamp ) {
556 return wfSetVar( $this->mTimestamp, $timestamp );
557 }
558
562 public function setTOCEnabled( $flag ) {
563 wfDeprecated( __METHOD__, '1.31' );
564 return true;
565 }
566
567 public function addCategory( $c, $sort ) {
568 $this->mCategories[$c] = $sort;
569 }
570
576 public function setIndicator( $id, $content ) {
577 $this->mIndicators[$id] = $content;
578 }
579
587 public function setEnableOOUI( $enable = false ) {
588 $this->mEnableOOUI = $enable;
589 }
590
591 public function addLanguageLink( $t ) {
592 $this->mLanguageLinks[] = $t;
593 }
594
595 public function addWarning( $s ) {
596 $this->mWarnings[$s] = 1;
597 }
598
599 public function addOutputHook( $hook, $data = false ) {
600 $this->mOutputHooks[] = [ $hook, $data ];
601 }
602
603 public function setNewSection( $value ) {
604 $this->mNewSection = (bool)$value;
605 }
606 public function hideNewSection( $value ) {
607 $this->mHideNewSection = (bool)$value;
608 }
609 public function getHideNewSection() {
610 return (bool)$this->mHideNewSection;
611 }
612 public function getNewSection() {
613 return (bool)$this->mNewSection;
614 }
615
623 public static function isLinkInternal( $internal, $url ) {
624 return (bool)preg_match( '/^' .
625 # If server is proto relative, check also for http/https links
626 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
627 preg_quote( $internal, '/' ) .
628 # check for query/path/anchor or end of link in each case
629 '(?:[\?\/\#]|$)/i',
630 $url
631 );
632 }
633
634 public function addExternalLink( $url ) {
635 # We don't register links pointing to our own server, unless... :-)
637
638 # Replace unnecessary URL escape codes with the referenced character
639 # This prevents spammers from hiding links from the filters
640 $url = Parser::normalizeLinkUrl( $url );
641
642 $registerExternalLink = true;
644 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
645 }
646 if ( $registerExternalLink ) {
647 $this->mExternalLinks[$url] = 1;
648 }
649 }
650
657 public function addLink( Title $title, $id = null ) {
658 if ( $title->isExternal() ) {
659 // Don't record interwikis in pagelinks
660 $this->addInterwikiLink( $title );
661 return;
662 }
663 $ns = $title->getNamespace();
664 $dbk = $title->getDBkey();
665 if ( $ns == NS_MEDIA ) {
666 // Normalize this pseudo-alias if it makes it down here...
667 $ns = NS_FILE;
668 } elseif ( $ns == NS_SPECIAL ) {
669 // We don't record Special: links currently
670 // It might actually be wise to, but we'd need to do some normalization.
671 return;
672 } elseif ( $dbk === '' ) {
673 // Don't record self links - [[#Foo]]
674 return;
675 }
676 if ( !isset( $this->mLinks[$ns] ) ) {
677 $this->mLinks[$ns] = [];
678 }
679 if ( is_null( $id ) ) {
680 $id = $title->getArticleID();
681 }
682 $this->mLinks[$ns][$dbk] = $id;
683 }
684
692 public function addImage( $name, $timestamp = null, $sha1 = null ) {
693 $this->mImages[$name] = 1;
694 if ( $timestamp !== null && $sha1 !== null ) {
695 $this->mFileSearchOptions[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
696 }
697 }
698
706 public function addTemplate( $title, $page_id, $rev_id ) {
707 $ns = $title->getNamespace();
708 $dbk = $title->getDBkey();
709 if ( !isset( $this->mTemplates[$ns] ) ) {
710 $this->mTemplates[$ns] = [];
711 }
712 $this->mTemplates[$ns][$dbk] = $page_id;
713 if ( !isset( $this->mTemplateIds[$ns] ) ) {
714 $this->mTemplateIds[$ns] = [];
715 }
716 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
717 }
718
723 public function addInterwikiLink( $title ) {
724 if ( !$title->isExternal() ) {
725 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
726 }
727 $prefix = $title->getInterwiki();
728 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
729 $this->mInterwikiLinks[$prefix] = [];
730 }
731 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
732 }
733
741 public function addHeadItem( $section, $tag = false ) {
742 if ( $tag !== false ) {
743 $this->mHeadItems[$tag] = $section;
744 } else {
745 $this->mHeadItems[] = $section;
746 }
747 }
748
749 public function addModules( $modules ) {
750 $this->mModules = array_merge( $this->mModules, (array)$modules );
751 }
752
753 public function addModuleScripts( $modules ) {
754 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
755 }
756
757 public function addModuleStyles( $modules ) {
758 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
759 }
760
768 public function addJsConfigVars( $keys, $value = null ) {
769 if ( is_array( $keys ) ) {
770 foreach ( $keys as $key => $value ) {
771 $this->mJsConfigVars[$key] = $value;
772 }
773 return;
774 }
775
776 $this->mJsConfigVars[$keys] = $value;
777 }
778
785 $this->addModules( $out->getModules() );
786 $this->addModuleScripts( $out->getModuleScripts() );
787 $this->addModuleStyles( $out->getModuleStyles() );
788 $this->addJsConfigVars( $out->getJsConfigVars() );
789
790 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
791 $this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
792 }
793
810 public function addTrackingCategory( $msg, $title ) {
811 if ( $title->isSpecialPage() ) {
812 wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
813 return false;
814 }
815
816 // Important to parse with correct title (T33469)
817 $cat = wfMessage( $msg )
818 ->title( $title )
819 ->inContentLanguage()
820 ->text();
821
822 # Allow tracking categories to be disabled by setting them to "-"
823 if ( $cat === '-' ) {
824 return false;
825 }
826
827 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
828 if ( $containerCategory ) {
829 $this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?: '' );
830 return true;
831 } else {
832 wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
833 return false;
834 }
835 }
836
848 public function setDisplayTitle( $text ) {
849 $this->setTitleText( $text );
850 $this->setProperty( 'displaytitle', $text );
851 }
852
861 public function getDisplayTitle() {
862 $t = $this->getTitleText();
863 if ( $t === '' ) {
864 return false;
865 }
866 return $t;
867 }
868
873 public function setFlag( $flag ) {
874 $this->mFlags[$flag] = true;
875 }
876
877 public function getFlag( $flag ) {
878 return isset( $this->mFlags[$flag] );
879 }
880
942 public function setProperty( $name, $value ) {
943 $this->mProperties[$name] = $value;
944 }
945
954 public function getProperty( $name ) {
955 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
956 }
957
958 public function unsetProperty( $name ) {
959 unset( $this->mProperties[$name] );
960 }
961
962 public function getProperties() {
963 if ( !isset( $this->mProperties ) ) {
964 $this->mProperties = [];
965 }
966 return $this->mProperties;
967 }
968
974 public function getUsedOptions() {
975 if ( !isset( $this->mAccessedOptions ) ) {
976 return [];
977 }
978 return array_keys( $this->mAccessedOptions );
979 }
980
993 public function recordOption( $option ) {
994 $this->mAccessedOptions[$option] = true;
995 }
996
1037 public function setExtensionData( $key, $value ) {
1038 if ( $value === null ) {
1039 unset( $this->mExtensionData[$key] );
1040 } else {
1041 $this->mExtensionData[$key] = $value;
1042 }
1043 }
1044
1056 public function getExtensionData( $key ) {
1057 if ( isset( $this->mExtensionData[$key] ) ) {
1058 return $this->mExtensionData[$key];
1059 }
1060
1061 return null;
1062 }
1063
1064 private static function getTimes( $clock = null ) {
1065 $ret = [];
1066 if ( !$clock || $clock === 'wall' ) {
1067 $ret['wall'] = microtime( true );
1068 }
1069 if ( !$clock || $clock === 'cpu' ) {
1070 $ru = wfGetRusage();
1071 if ( $ru ) {
1072 $ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
1073 $ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
1074 }
1075 }
1076 return $ret;
1077 }
1078
1083 public function resetParseStartTime() {
1084 $this->mParseStartTime = self::getTimes();
1085 }
1086
1098 public function getTimeSinceStart( $clock ) {
1099 if ( !isset( $this->mParseStartTime[$clock] ) ) {
1100 return null;
1101 }
1102
1103 $end = self::getTimes( $clock );
1104 return $end[$clock] - $this->mParseStartTime[$clock];
1105 }
1106
1126 public function setLimitReportData( $key, $value ) {
1127 $this->mLimitReportData[$key] = $value;
1128
1129 if ( is_array( $value ) ) {
1130 if ( array_keys( $value ) === [ 0, 1 ]
1131 && is_numeric( $value[0] )
1132 && is_numeric( $value[1] )
1133 ) {
1134 $data = [ 'value' => $value[0], 'limit' => $value[1] ];
1135 } else {
1136 $data = $value;
1137 }
1138 } else {
1139 $data = $value;
1140 }
1141
1142 if ( strpos( $key, '-' ) ) {
1143 list( $ns, $name ) = explode( '-', $key, 2 );
1144 $this->mLimitReportJSData[$ns][$name] = $data;
1145 } else {
1146 $this->mLimitReportJSData[$key] = $data;
1147 }
1148 }
1149
1160 public function hasDynamicContent() {
1162
1163 return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1164 }
1165
1173 public function preventClickjacking( $flag = null ) {
1174 return wfSetVar( $this->mPreventClickjacking, $flag );
1175 }
1176
1183 public function updateRuntimeAdaptiveExpiry( $ttl ) {
1184 $this->mMaxAdaptiveExpiry = min( $ttl, $this->mMaxAdaptiveExpiry );
1185 $this->updateCacheExpiry( $ttl );
1186 }
1187
1194 if ( is_infinite( $this->mMaxAdaptiveExpiry ) ) {
1195 return; // not set
1196 }
1197
1198 $runtime = $this->getTimeSinceStart( 'wall' );
1199 if ( is_float( $runtime ) ) {
1200 $slope = ( self::SLOW_AR_TTL - self::FAST_AR_TTL )
1201 / ( self::PARSE_SLOW_SEC - self::PARSE_FAST_SEC );
1202 // SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1203 $point = self::SLOW_AR_TTL - self::PARSE_SLOW_SEC * $slope;
1204
1205 $adaptiveTTL = min(
1206 max( $slope * $runtime + $point, self::MIN_AR_TTL ),
1207 $this->mMaxAdaptiveExpiry
1208 );
1209 $this->updateCacheExpiry( $adaptiveTTL );
1210 }
1211 }
1212
1213 public function __sleep() {
1214 return array_diff(
1215 array_keys( get_object_vars( $this ) ),
1216 [ 'mParseStartTime' ]
1217 );
1218 }
1219}
Apache License January http
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgRegisterInternalExternals
By default MediaWiki does not register links pointing to same server in externallinks dataset,...
$wgParserCacheExpireTime
The expiry time for the parser cache, in seconds.
$wgServer
URL of the server.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfGetRusage()
Get system resource usage of current request context.
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$wgOut
Definition Setup.php:912
Parser cache specific expiry check.
Definition CacheTime.php:29
updateCacheExpiry( $seconds)
Sets the number of seconds after which this object should expire.
Definition CacheTime.php:93
getCacheExpiry()
Returns the number of seconds after which this object should expire.
MediaWiki exception.
This class should be covered by a general architecture document which does not exist as of January 20...
addOutputPageMetadata(OutputPage $out)
Copy items from the OutputPage object into this one.
getProperty( $name)
unsetProperty( $name)
static getTimes( $clock=null)
hideNewSection( $value)
int null $mSpeculativeRevId
Assumed rev ID for {{REVISIONID}} if no revision is set.
setNewSection( $value)
addOutputHook( $hook, $data=false)
const SUPPORTS_UNWRAP_TRANSFORM
setDisplayTitle( $text)
Override the title to be used for display.
addJsConfigVars( $keys, $value=null)
Add one or more variables to be set in mw.config in JavaScript.
setIndicator( $id, $content)
addExternalLink( $url)
addModuleScripts( $modules)
setLanguageLinks( $ll)
setCategoryLinks( $cl)
addInterwikiLink( $title)
setEditSectionTokens( $t)
setEnableOOUI( $enable=false)
Enables OOUI, if true, in any OutputPage instance this ParserOutput object is added to.
getDisplayTitle()
Get the title to be used for display.
addTrackingCategory( $msg, $title)
Add a tracking category, getting the title from a system message, or print a debug message if the tit...
finalizeAdaptiveCacheExpiry()
Call this when parsing is done to lower the TTL based on low parse times.
addTemplate( $title, $page_id, $rev_id)
Register a template dependency for this output.
addLink(Title $title, $id=null)
Record a local or interwiki inline link for saving in future link tables.
addModules( $modules)
resetParseStartTime()
Resets the parse start timestamps for future calls to getTimeSinceStart()
preventClickjacking( $flag=null)
Get or set the prevent-clickjacking flag.
setProperty( $name, $value)
Set a property to be stored in the page_props database table.
recordOption( $option)
Tags a parser option for use in the cache key for this parser output.
addHeadItem( $section, $tag=false)
Add some text to the "<head>".
hasDynamicContent()
Check whether the cache TTL was lowered due to dynamic content.
getExtensionData( $key)
Gets extensions data previously attached to this ParserOutput using setExtensionData().
getText( $options=[])
Get the output HTML.
getTimeSinceStart( $clock)
Returns the time since resetParseStartTime() was last called.
getRawText()
Get the cacheable text with <mw:editsection> markers still in it.
addImage( $name, $timestamp=null, $sha1=null)
Register a file dependency for this output.
updateRuntimeAdaptiveExpiry( $ttl)
Lower the runtime adaptive TTL to at most this value.
setTOCHTML( $tochtml)
getUsedOptions()
Returns the options from its ParserOptions which have been taken into account to produce this output ...
const SUPPORTS_STATELESS_TRANSFORMS
Feature flags to indicate to extensions that MediaWiki core supports and uses getText() stateless tra...
setLimitReportData( $key, $value)
Sets parser limit report data for a key.
setExtensionData( $key, $value)
Attaches arbitrary data to this ParserObject.
setTimestamp( $timestamp)
setSpeculativeRevIdUsed( $id)
__construct( $text='', $languageLinks=[], $categoryLinks=[], $unused=false, $titletext='')
static isLinkInternal( $internal, $url)
Checks, if a url is pointing to the own server.
array $mLimitReportJSData
Parser limit report data for JSON.
setTOCEnabled( $flag)
addModuleStyles( $modules)
setFlag( $flag)
Fairly generic flag setter thingy.
const EDITSECTION_REGEX
addCategory( $c, $sort)
setIndexPolicy( $policy)
int $mMaxAdaptiveExpiry
Upper bound of expiry based on parse duration.
Represents a title within MediaWiki.
Definition Title.php:39
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------ Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server. Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It 's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use. Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves. The master writes thequery to the binlog when the transaction is committed. The slaves pollthe binlog and start executing the query as soon as it appears. They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes. Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load. MediaWiki 's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database. All edits and other write operations will berefused, with an error returned to the user. This gives the slaves achance to catch up. Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order. A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests. This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it. Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in "lagged slave mode". Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode(). The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time. Multi-row INSERT ...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it 's not practical to guarantee a low-lagenvironment. Lag will usually be less than one second, but mayoccasionally be up to 30 seconds. For scalability, it 's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer. So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn 't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum. In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------ Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks. By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent. Locks willbe held from the time when the query is done until the commit. So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction. Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
For a write query
Definition database.txt:26
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
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at https
Definition design.txt:12
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 $wgLang
Definition design.txt:56
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 MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break but it is *strongly *advised not to try any more intrusive changes to get MediaWiki to conform more closely to your filesystem hierarchy Any such attempt will almost certainly result in unnecessary bugs The standard recommended location to install relative to the web is it should be possible to enable the appropriate rewrite rules by if you can reconfigure the web server
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_FILE
Definition Defines.php:80
const NS_SPECIAL
Definition Defines.php:63
const NS_MEDIA
Definition Defines.php:62
const NS_CATEGORY
Definition Defines.php:88
the array() calling protocol came about after MediaWiki 1.4rc1.
in this case you re responsible for computing and outputting the entire conflict i the difference between revisions and your text headers and sections and Diff or overridable Default is either copyrightwarning or copyrightwarning2 overridable Default is editpage tos summary such as anonymity and the real check
Definition hooks.txt:1481
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 & $options
Definition hooks.txt:2001
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template to be included in the link
Definition hooks.txt:3023
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:964
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
null for the local wiki Added in
Definition hooks.txt:1591
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 & $ret
Definition hooks.txt:2005
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 $out
Definition hooks.txt:864
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
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 an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned $skin
Definition hooks.txt:2011
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition hooks.txt:3022
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
$sort
This document describes the XML format used to represent information about external sites known to a MediaWiki installation This information about external sites is used to allow inter wiki links
in the order they appear.
Definition sitelist.txt:3