4 * Output of the PHP parser.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
24 class ParserOutput
extends CacheTime
{
25 /** @var string The output text */
28 /** @var array List of the full text of language links; in the order they appear */
29 public $mLanguageLinks;
31 /** @var array Map of category names to sort keys */
34 /** @var array DB keys of the images used; in the array key only */
35 public $mImages = array();
37 /** @var array Modules to be loaded by the resource loader */
38 public $mModules = array();
40 /** @var array Name/value pairs to be cached in the DB */
41 public $mProperties = array();
43 /** @var string Title text of the chosen language variant */
44 protected $mTitleText;
46 /** @var array 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken. */
47 protected $mLinks = array();
49 /** @var array 2-D map of NS/DBK to ID for the template references. ID=zero for broken. */
50 protected $mTemplates = array();
52 /** @var array 2-D map of NS/DBK to rev ID for the template references. ID=zero for broken. */
53 protected $mTemplateIds = array();
55 /** @var array DB keys of the images used mapped to sha1 and MW timestamp */
56 protected $mFileSearchOptions = array();
58 /** @var array External link URLs; in the key only */
59 protected $mExternalLinks = array();
62 * @var array 2-D map of prefix/DBK (in keys only) for the inline interwiki
63 * links in the document.
65 protected $mInterwikiLinks = array();
67 /** @var bool Show a new section link? */
68 protected $mNewSection = false;
70 /** @var bool Hide the new section link? */
71 protected $mHideNewSection = false;
73 /** @var bool No gallery on category page? (__NOGALLERY__) */
74 public $mNoGallery = false;
76 /** @var array Items to put in the <head> section */
77 protected $mHeadItems = array();
79 /** @var array Modules of which only the JS will be loaded by the resource loader */
80 protected $mModuleScripts = array();
82 /** @var array Modules of which only the CSSS will be loaded by the resource loader */
83 protected $mModuleStyles = array();
85 /** @var array Modules of which only the messages will be loaded by the resource loader */
86 protected $mModuleMessages = array();
88 /** @var array JavaScript config variable for mw.config combined with this page */
89 protected $mJsConfigVars = array();
91 /** @var array Hook tags as per $wgParserOutputHooks */
92 protected $mOutputHooks = array();
94 /** @var array Warning text to be returned to the user. Wikitext formatted; in the key only */
95 protected $mWarnings = array();
97 /** @var array Table of contents */
98 protected $mSections = array();
100 /** @var bool Prefix/suffix markers if edit sections were output as tokens */
101 protected $mEditSectionTokens = false;
103 /** @var string HTML of the TOC */
104 protected $mTOCHTML = '';
106 /** @var string Timestamp of the revision */
107 protected $mTimestamp;
109 /** @var bool Whether TOC should be shown, can't override __NOTOC__ */
110 protected $mTOCEnabled = true;
112 /** @var string 'index' or 'noindex'? Any other value will result in no change. */
113 private $mIndexPolicy = '';
115 /** @var array List of ParserOptions (stored in the keys) */
116 private $mAccessedOptions = array();
118 /** @var array List of DataUpdate, used to save info from the page somewhere else. */
119 private $mSecondaryDataUpdates = array();
121 /** @var array Extra data used by extensions */
122 private $mExtensionData = array();
124 /** @var array Parser limit report data */
125 private $mLimitReportData = array();
127 /** @var array Timestamps for getTimeSinceStart() */
128 private $mParseStartTime = array();
130 const EDITSECTION_REGEX
=
131 '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
133 function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
134 $containsOldMagic = false, $titletext = ''
136 $this->mText
= $text;
137 $this->mLanguageLinks
= $languageLinks;
138 $this->mCategories
= $categoryLinks;
139 $this->mContainsOldMagic
= $containsOldMagic;
140 $this->mTitleText
= $titletext;
144 wfProfileIn( __METHOD__
);
145 $text = $this->mText
;
146 if ( $this->mEditSectionTokens
) {
147 $text = preg_replace_callback( ParserOutput
::EDITSECTION_REGEX
,
148 array( &$this, 'replaceEditSectionLinksCallback' ), $text );
150 $text = preg_replace( ParserOutput
::EDITSECTION_REGEX
, '', $text );
153 // If you have an old cached version of this class - sorry, you can't disable the TOC
154 if ( isset( $this->mTOCEnabled
) && $this->mTOCEnabled
) {
155 $text = str_replace( array( Parser
::TOC_START
, Parser
::TOC_END
), '', $text );
157 $text = preg_replace(
158 '#' . preg_quote( Parser
::TOC_START
) . '.*?' . preg_quote( Parser
::TOC_END
) . '#s',
163 wfProfileOut( __METHOD__
);
168 * callback used by getText to replace editsection tokens
171 * @throws MWException
174 function replaceEditSectionLinksCallback( $m ) {
175 global $wgOut, $wgLang;
177 htmlspecialchars_decode( $m[1] ),
178 htmlspecialchars_decode( $m[2] ),
179 isset( $m[4] ) ?
$m[3] : null,
181 $args[0] = Title
::newFromText( $args[0] );
182 if ( !is_object( $args[0] ) ) {
183 throw new MWException( "Bad parser output text." );
185 $args[] = $wgLang->getCode();
186 $skin = $wgOut->getSkin();
187 return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args );
190 function &getLanguageLinks() {
191 return $this->mLanguageLinks
;
194 function getInterwikiLinks() {
195 return $this->mInterwikiLinks
;
198 function getCategoryLinks() {
199 return array_keys( $this->mCategories
);
202 function &getCategories() {
203 return $this->mCategories
;
206 function getTitleText() {
207 return $this->mTitleText
;
210 function getSections() {
211 return $this->mSections
;
214 function getEditSectionTokens() {
215 return $this->mEditSectionTokens
;
218 function &getLinks() {
219 return $this->mLinks
;
222 function &getTemplates() {
223 return $this->mTemplates
;
226 function &getTemplateIds() {
227 return $this->mTemplateIds
;
230 function &getImages() {
231 return $this->mImages
;
234 function &getFileSearchOptions() {
235 return $this->mFileSearchOptions
;
238 function &getExternalLinks() {
239 return $this->mExternalLinks
;
242 function getNoGallery() {
243 return $this->mNoGallery
;
246 function getHeadItems() {
247 return $this->mHeadItems
;
250 function getModules() {
251 return $this->mModules
;
254 function getModuleScripts() {
255 return $this->mModuleScripts
;
258 function getModuleStyles() {
259 return $this->mModuleStyles
;
262 function getModuleMessages() {
263 return $this->mModuleMessages
;
267 function getJsConfigVars() {
268 return $this->mJsConfigVars
;
271 function getOutputHooks() {
272 return (array)$this->mOutputHooks
;
275 function getWarnings() {
276 return array_keys( $this->mWarnings
);
279 function getIndexPolicy() {
280 return $this->mIndexPolicy
;
283 function getTOCHTML() {
284 return $this->mTOCHTML
;
287 function getTimestamp() {
288 return $this->mTimestamp
;
291 function getLimitReportData() {
292 return $this->mLimitReportData
;
295 function getTOCEnabled() {
296 return $this->mTOCEnabled
;
299 function setText( $text ) {
300 return wfSetVar( $this->mText
, $text );
303 function setLanguageLinks( $ll ) {
304 return wfSetVar( $this->mLanguageLinks
, $ll );
307 function setCategoryLinks( $cl ) {
308 return wfSetVar( $this->mCategories
, $cl );
311 function setTitleText( $t ) {
312 return wfSetVar( $this->mTitleText
, $t );
315 function setSections( $toc ) {
316 return wfSetVar( $this->mSections
, $toc );
319 function setEditSectionTokens( $t ) {
320 return wfSetVar( $this->mEditSectionTokens
, $t );
323 function setIndexPolicy( $policy ) {
324 return wfSetVar( $this->mIndexPolicy
, $policy );
327 function setTOCHTML( $tochtml ) {
328 return wfSetVar( $this->mTOCHTML
, $tochtml );
331 function setTimestamp( $timestamp ) {
332 return wfSetVar( $this->mTimestamp
, $timestamp );
335 function setTOCEnabled( $flag ) {
336 return wfSetVar( $this->mTOCEnabled
, $flag );
339 function addCategory( $c, $sort ) {
340 $this->mCategories
[$c] = $sort;
343 function addLanguageLink( $t ) {
344 $this->mLanguageLinks
[] = $t;
347 function addWarning( $s ) {
348 $this->mWarnings
[$s] = 1;
351 function addOutputHook( $hook, $data = false ) {
352 $this->mOutputHooks
[] = array( $hook, $data );
355 function setNewSection( $value ) {
356 $this->mNewSection
= (bool)$value;
358 function hideNewSection( $value ) {
359 $this->mHideNewSection
= (bool)$value;
361 function getHideNewSection() {
362 return (bool)$this->mHideNewSection
;
364 function getNewSection() {
365 return (bool)$this->mNewSection
;
369 * Checks, if a url is pointing to the own server
371 * @param string $internal The server to check against
372 * @param string $url The url to check
375 static function isLinkInternal( $internal, $url ) {
376 return (bool)preg_match( '/^' .
377 # If server is proto relative, check also for http/https links
378 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
379 preg_quote( $internal, '/' ) .
380 # check for query/path/anchor or end of link in each case
386 function addExternalLink( $url ) {
387 # We don't register links pointing to our own server, unless... :-)
388 global $wgServer, $wgRegisterInternalExternals;
390 $registerExternalLink = true;
391 if ( !$wgRegisterInternalExternals ) {
392 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
394 if ( $registerExternalLink ) {
395 $this->mExternalLinks
[$url] = 1;
400 * Record a local or interwiki inline link for saving in future link tables.
402 * @param Title $title
403 * @param int|null $id Optional known page_id so we can skip the lookup
405 function addLink( Title
$title, $id = null ) {
406 if ( $title->isExternal() ) {
407 // Don't record interwikis in pagelinks
408 $this->addInterwikiLink( $title );
411 $ns = $title->getNamespace();
412 $dbk = $title->getDBkey();
413 if ( $ns == NS_MEDIA
) {
414 // Normalize this pseudo-alias if it makes it down here...
416 } elseif ( $ns == NS_SPECIAL
) {
417 // We don't record Special: links currently
418 // It might actually be wise to, but we'd need to do some normalization.
420 } elseif ( $dbk === '' ) {
421 // Don't record self links - [[#Foo]]
424 if ( !isset( $this->mLinks
[$ns] ) ) {
425 $this->mLinks
[$ns] = array();
427 if ( is_null( $id ) ) {
428 $id = $title->getArticleID();
430 $this->mLinks
[$ns][$dbk] = $id;
434 * Register a file dependency for this output
435 * @param string $name Title dbKey
436 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
437 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
440 function addImage( $name, $timestamp = null, $sha1 = null ) {
441 $this->mImages
[$name] = 1;
442 if ( $timestamp !== null && $sha1 !== null ) {
443 $this->mFileSearchOptions
[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
448 * Register a template dependency for this output
449 * @param Title $title
450 * @param int $page_id
454 function addTemplate( $title, $page_id, $rev_id ) {
455 $ns = $title->getNamespace();
456 $dbk = $title->getDBkey();
457 if ( !isset( $this->mTemplates
[$ns] ) ) {
458 $this->mTemplates
[$ns] = array();
460 $this->mTemplates
[$ns][$dbk] = $page_id;
461 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
462 $this->mTemplateIds
[$ns] = array();
464 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
468 * @param Title $title Title object, must be an interwiki link
469 * @throws MWException if given invalid input
471 function addInterwikiLink( $title ) {
472 if ( !$title->isExternal() ) {
473 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
475 $prefix = $title->getInterwiki();
476 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
477 $this->mInterwikiLinks
[$prefix] = array();
479 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
483 * Add some text to the "<head>".
484 * If $tag is set, the section with that tag will only be included once
486 * @param string $section
487 * @param string|bool $tag
489 function addHeadItem( $section, $tag = false ) {
490 if ( $tag !== false ) {
491 $this->mHeadItems
[$tag] = $section;
493 $this->mHeadItems
[] = $section;
497 public function addModules( $modules ) {
498 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
501 public function addModuleScripts( $modules ) {
502 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
505 public function addModuleStyles( $modules ) {
506 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
509 public function addModuleMessages( $modules ) {
510 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
514 * Add one or more variables to be set in mw.config in JavaScript.
516 * @param string|array $keys Key or array of key/value pairs.
517 * @param mixed $value [optional] Value of the configuration variable.
520 public function addJsConfigVars( $keys, $value = null ) {
521 if ( is_array( $keys ) ) {
522 foreach ( $keys as $key => $value ) {
523 $this->mJsConfigVars
[$key] = $value;
528 $this->mJsConfigVars
[$keys] = $value;
532 * Copy items from the OutputPage object into this one
534 * @param OutputPage $out
536 public function addOutputPageMetadata( OutputPage
$out ) {
537 $this->addModules( $out->getModules() );
538 $this->addModuleScripts( $out->getModuleScripts() );
539 $this->addModuleStyles( $out->getModuleStyles() );
540 $this->addModuleMessages( $out->getModuleMessages() );
541 $this->addJsConfigVars( $out->getJsConfigVars() );
543 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
547 * Override the title to be used for display
548 * -- this is assumed to have been validated
549 * (check equal normalisation, etc.)
551 * @param string $text desired title text
553 public function setDisplayTitle( $text ) {
554 $this->setTitleText( $text );
555 $this->setProperty( 'displaytitle', $text );
559 * Get the title to be used for display
563 public function getDisplayTitle() {
564 $t = $this->getTitleText();
572 * Fairly generic flag setter thingy.
574 public function setFlag( $flag ) {
575 $this->mFlags
[$flag] = true;
578 public function getFlag( $flag ) {
579 return isset( $this->mFlags
[$flag] );
583 * Set a property to be stored in the page_props database table.
585 * page_props is a key value store indexed by the page ID. This allows
586 * the parser to set a property on a page which can then be quickly
587 * retrieved given the page ID or via a DB join when given the page
590 * Since 1.23, page_props are also indexed by numeric value, to allow
591 * for efficient "top k" queries of pages wrt a given property.
593 * setProperty() is thus used to propagate properties from the parsed
594 * page to request contexts other than a page view of the currently parsed
597 * Some applications examples:
599 * * To implement hidden categories, hiding pages from category listings
600 * by storing a property.
602 * * Overriding the displayed article title.
603 * @see ParserOutput::setDisplayTitle()
605 * * To implement image tagging, for example displaying an icon on an
606 * image thumbnail to indicate that it is listed for deletion on
608 * This is not actually implemented, yet but would be pretty cool.
610 * @note: Do not use setProperty() to set a property which is only used
611 * in a context where the ParserOutput object itself is already available,
612 * for example a normal page view. There is no need to save such a property
613 * in the database since the text is already parsed. You can just hook
614 * OutputPageParserOutput and get your data out of the ParserOutput object.
616 * If you are writing an extension where you want to set a property in the
617 * parser which is used by an OutputPageParserOutput hook, you have to
618 * associate the extension data directly with the ParserOutput object.
619 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
623 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
626 * And then later, in OutputPageParserOutput or similar:
630 * $output->getExtensionData( 'my_ext_foo' );
633 * In MediaWiki 1.20 and older, you have to use a custom member variable
634 * within the ParserOutput object:
638 * $parser->getOutput()->my_ext_foo = '...';
642 public function setProperty( $name, $value ) {
643 $this->mProperties
[$name] = $value;
646 public function getProperty( $name ) {
647 return isset( $this->mProperties
[$name] ) ?
$this->mProperties
[$name] : false;
650 public function getProperties() {
651 if ( !isset( $this->mProperties
) ) {
652 $this->mProperties
= array();
654 return $this->mProperties
;
658 * Returns the options from its ParserOptions which have been taken
659 * into account to produce this output or false if not available.
662 public function getUsedOptions() {
663 if ( !isset( $this->mAccessedOptions
) ) {
666 return array_keys( $this->mAccessedOptions
);
670 * Tags a parser option for use in the cache key for this parser output.
671 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
673 * @see ParserCache::getKey
674 * @see ParserCache::save
675 * @see ParserOptions::addExtraKey
676 * @see ParserOptions::optionsHash
677 * @param string $option
679 public function recordOption( $option ) {
680 $this->mAccessedOptions
[$option] = true;
684 * Adds an update job to the output. Any update jobs added to the output will
685 * eventually be executed in order to store any secondary information extracted
686 * from the page's content. This is triggered by calling getSecondaryDataUpdates()
687 * and is used for forward links updates on edit and backlink updates by jobs.
691 * @param DataUpdate $update
693 public function addSecondaryDataUpdate( DataUpdate
$update ) {
694 $this->mSecondaryDataUpdates
[] = $update;
698 * Returns any DataUpdate jobs to be executed in order to store secondary information
699 * extracted from the page's content, including a LinksUpdate object for all links stored in
700 * this ParserOutput object.
702 * @note Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates()
703 * instead! The content handler may provide additional update objects.
707 * @param Title $title The title of the page we're updating. If not given, a title object will
708 * be created based on $this->getTitleText()
709 * @param bool $recursive Queue jobs for recursive updates?
711 * @return array An array of instances of DataUpdate
713 public function getSecondaryDataUpdates( Title
$title = null, $recursive = true ) {
714 if ( is_null( $title ) ) {
715 $title = Title
::newFromText( $this->getTitleText() );
718 $linksUpdate = new LinksUpdate( $title, $this, $recursive );
720 return array_merge( $this->mSecondaryDataUpdates
, array( $linksUpdate ) );
724 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
725 * the ParserOutput object for later use during page output. The data will be cached along with
726 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
729 * This method is provided to overcome the unsafe practice of attaching extra information to a
730 * ParserObject by directly assigning member variables.
732 * To use setExtensionData() to pass extension information from a hook inside the parser to a
733 * hook in the page output, use this in the parser hook:
737 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
740 * And then later, in OutputPageParserOutput or similar:
744 * $output->getExtensionData( 'my_ext_foo' );
747 * In MediaWiki 1.20 and older, you have to use a custom member variable
748 * within the ParserOutput object:
752 * $parser->getOutput()->my_ext_foo = '...';
757 * @param string $key The key for accessing the data. Extensions should take care to avoid
758 * conflicts in naming keys. It is suggested to use the extension's name as a prefix.
760 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
763 public function setExtensionData( $key, $value ) {
764 if ( $value === null ) {
765 unset( $this->mExtensionData
[$key] );
767 $this->mExtensionData
[$key] = $value;
772 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
773 * Typically, such data would be set while parsing the page, e.g. by a parser function.
777 * @param string $key The key to look up.
779 * @return mixed The value previously set for the given key using setExtensionData( $key ),
780 * or null if no value was set for this key.
782 public function getExtensionData( $key ) {
783 if ( isset( $this->mExtensionData
[$key] ) ) {
784 return $this->mExtensionData
[$key];
790 private static function getTimes( $clock = null ) {
792 if ( !$clock ||
$clock === 'wall' ) {
793 $ret['wall'] = microtime( true );
795 if ( ( !$clock ||
$clock === 'cpu' ) && function_exists( 'getrusage' ) ) {
797 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
798 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
804 * Resets the parse start timestamps for future calls to getTimeSinceStart()
807 function resetParseStartTime() {
808 $this->mParseStartTime
= self
::getTimes();
812 * Returns the time since resetParseStartTime() was last called
814 * Clocks available are:
815 * - wall: Wall clock time
816 * - cpu: CPU time (requires getrusage)
819 * @param string $clock
822 function getTimeSinceStart( $clock ) {
823 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
827 $end = self
::getTimes( $clock );
828 return $end[$clock] - $this->mParseStartTime
[$clock];
832 * Sets parser limit report data for a key
834 * The key is used as the prefix for various messages used for formatting:
835 * - $key: The label for the field in the limit report
836 * - $key-value-text: Message used to format the value in the "NewPP limit
837 * report" HTML comment. If missing, uses $key-format.
838 * - $key-value-html: Message used to format the value in the preview
839 * limit report table. If missing, uses $key-format.
840 * - $key-value: Message used to format the value. If missing, uses "$1".
842 * Note that all values are interpreted as wikitext, and so should be
843 * encoded with htmlspecialchars() as necessary, but should avoid complex
844 * HTML for sanity of display in the "NewPP limit report" comment.
847 * @param string $key Message key
848 * @param mixed $value Appropriate for Message::params()
850 function setLimitReportData( $key, $value ) {
851 $this->mLimitReportData
[$key] = $value;
855 * Save space for for serialization by removing useless values
859 array_keys( get_object_vars( $this ) ),
860 array( 'mSecondaryDataUpdates', 'mParseStartTime' )