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 $mText, # The output text
26 $mLanguageLinks, # List of the full text of language links, in the order they appear
27 $mCategories, # Map of category names to sort keys
28 $mTitleText, # title text of the chosen language variant
29 $mLinks = array(), # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
30 $mTemplates = array(), # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
31 $mTemplateIds = array(), # 2-D map of NS/DBK to rev ID for the template references. ID=zero for broken.
32 $mImages = array(), # DB keys of the images used, in the array key only
33 $mFileSearchOptions = array(), # DB keys of the images used mapped to sha1 and MW timestamp
34 $mExternalLinks = array(), # External link URLs, in the key only
35 $mInterwikiLinks = array(), # 2-D map of prefix/DBK (in keys only) for the inline interwiki links in the document.
36 $mNewSection = false, # Show a new section link?
37 $mHideNewSection = false, # Hide the new section link?
38 $mNoGallery = false, # No gallery on category page? (__NOGALLERY__)
39 $mHeadItems = array(), # Items to put in the <head> section
40 $mModules = array(), # Modules to be loaded by the resource loader
41 $mModuleScripts = array(), # Modules of which only the JS will be loaded by the resource loader
42 $mModuleStyles = array(), # Modules of which only the CSSS will be loaded by the resource loader
43 $mModuleMessages = array(), # Modules of which only the messages will be loaded by the resource loader
44 $mOutputHooks = array(), # Hook tags as per $wgParserOutputHooks
45 $mWarnings = array(), # Warning text to be returned to the user. Wikitext formatted, in the key only
46 $mSections = array(), # Table of contents
47 $mEditSectionTokens = false, # prefix/suffix markers if edit sections were output as tokens
48 $mProperties = array(), # Name/value pairs to be cached in the DB
49 $mTOCHTML = '', # HTML of the TOC
50 $mTimestamp; # Timestamp of the revision
51 private $mIndexPolicy = ''; # 'index' or 'noindex'? Any other value will result in no change.
52 private $mAccessedOptions = array(); # List of ParserOptions (stored in the keys)
53 private $mSecondaryDataUpdates = array(); # List of DataUpdate, used to save info from the page somewhere else.
54 private $mExtensionData = array(); # extra data used by extensions
55 private $mLimitReportData = array(); # Parser limit report data
56 private $mParseStartTime = array(); # Timestamps for getTimeSinceStart()
58 const EDITSECTION_REGEX
= '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
60 function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
61 $containsOldMagic = false, $titletext = '' )
64 $this->mLanguageLinks
= $languageLinks;
65 $this->mCategories
= $categoryLinks;
66 $this->mContainsOldMagic
= $containsOldMagic;
67 $this->mTitleText
= $titletext;
71 if ( $this->mEditSectionTokens
) {
72 return preg_replace_callback( ParserOutput
::EDITSECTION_REGEX
,
73 array( &$this, 'replaceEditSectionLinksCallback' ), $this->mText
);
75 return preg_replace( ParserOutput
::EDITSECTION_REGEX
, '', $this->mText
);
79 * callback used by getText to replace editsection tokens
85 function replaceEditSectionLinksCallback( $m ) {
86 global $wgOut, $wgLang;
88 htmlspecialchars_decode( $m[1] ),
89 htmlspecialchars_decode( $m[2] ),
90 isset( $m[4] ) ?
$m[3] : null,
92 $args[0] = Title
::newFromText( $args[0] );
93 if ( !is_object( $args[0] ) ) {
94 throw new MWException( "Bad parser output text." );
96 $args[] = $wgLang->getCode();
97 $skin = $wgOut->getSkin();
98 return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args );
101 function &getLanguageLinks() { return $this->mLanguageLinks
; }
102 function getInterwikiLinks() { return $this->mInterwikiLinks
; }
103 function getCategoryLinks() { return array_keys( $this->mCategories
); }
104 function &getCategories() { return $this->mCategories
; }
105 function getTitleText() { return $this->mTitleText
; }
106 function getSections() { return $this->mSections
; }
107 function getEditSectionTokens() { return $this->mEditSectionTokens
; }
108 function &getLinks() { return $this->mLinks
; }
109 function &getTemplates() { return $this->mTemplates
; }
110 function &getTemplateIds() { return $this->mTemplateIds
; }
111 function &getImages() { return $this->mImages
; }
112 function &getFileSearchOptions() { return $this->mFileSearchOptions
; }
113 function &getExternalLinks() { return $this->mExternalLinks
; }
114 function getNoGallery() { return $this->mNoGallery
; }
115 function getHeadItems() { return $this->mHeadItems
; }
116 function getModules() { return $this->mModules
; }
117 function getModuleScripts() { return $this->mModuleScripts
; }
118 function getModuleStyles() { return $this->mModuleStyles
; }
119 function getModuleMessages() { return $this->mModuleMessages
; }
120 function getOutputHooks() { return (array)$this->mOutputHooks
; }
121 function getWarnings() { return array_keys( $this->mWarnings
); }
122 function getIndexPolicy() { return $this->mIndexPolicy
; }
123 function getTOCHTML() { return $this->mTOCHTML
; }
124 function getTimestamp() { return $this->mTimestamp
; }
125 function getLimitReportData() { return $this->mLimitReportData
; }
127 function setText( $text ) { return wfSetVar( $this->mText
, $text ); }
128 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks
, $ll ); }
129 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories
, $cl ); }
131 function setTitleText( $t ) { return wfSetVar( $this->mTitleText
, $t ); }
132 function setSections( $toc ) { return wfSetVar( $this->mSections
, $toc ); }
133 function setEditSectionTokens( $t ) { return wfSetVar( $this->mEditSectionTokens
, $t ); }
134 function setIndexPolicy( $policy ) { return wfSetVar( $this->mIndexPolicy
, $policy ); }
135 function setTOCHTML( $tochtml ) { return wfSetVar( $this->mTOCHTML
, $tochtml ); }
136 function setTimestamp( $timestamp ) { return wfSetVar( $this->mTimestamp
, $timestamp ); }
138 function addCategory( $c, $sort ) { $this->mCategories
[$c] = $sort; }
139 function addLanguageLink( $t ) { $this->mLanguageLinks
[] = $t; }
140 function addWarning( $s ) { $this->mWarnings
[$s] = 1; }
142 function addOutputHook( $hook, $data = false ) {
143 $this->mOutputHooks
[] = array( $hook, $data );
146 function setNewSection( $value ) {
147 $this->mNewSection
= (bool)$value;
149 function hideNewSection( $value ) {
150 $this->mHideNewSection
= (bool)$value;
152 function getHideNewSection() {
153 return (bool)$this->mHideNewSection
;
155 function getNewSection() {
156 return (bool)$this->mNewSection
;
160 * Checks, if a url is pointing to the own server
162 * @param string $internal the server to check against
163 * @param string $url the url to check
166 static function isLinkInternal( $internal, $url ) {
167 return (bool)preg_match( '/^' .
168 # If server is proto relative, check also for http/https links
169 ( substr( $internal, 0, 2 ) === '//' ?
'(?:https?:)?' : '' ) .
170 preg_quote( $internal, '/' ) .
171 # check for query/path/anchor or end of link in each case
177 function addExternalLink( $url ) {
178 # We don't register links pointing to our own server, unless... :-)
179 global $wgServer, $wgRegisterInternalExternals;
181 $registerExternalLink = true;
182 if ( !$wgRegisterInternalExternals ) {
183 $registerExternalLink = !self
::isLinkInternal( $wgServer, $url );
185 if ( $registerExternalLink ) {
186 $this->mExternalLinks
[$url] = 1;
191 * Record a local or interwiki inline link for saving in future link tables.
193 * @param $title Title object
194 * @param $id Mixed: optional known page_id so we can skip the lookup
196 function addLink( Title
$title, $id = null ) {
197 if ( $title->isExternal() ) {
198 // Don't record interwikis in pagelinks
199 $this->addInterwikiLink( $title );
202 $ns = $title->getNamespace();
203 $dbk = $title->getDBkey();
204 if ( $ns == NS_MEDIA
) {
205 // Normalize this pseudo-alias if it makes it down here...
207 } elseif ( $ns == NS_SPECIAL
) {
208 // We don't record Special: links currently
209 // It might actually be wise to, but we'd need to do some normalization.
211 } elseif ( $dbk === '' ) {
212 // Don't record self links - [[#Foo]]
215 if ( !isset( $this->mLinks
[$ns] ) ) {
216 $this->mLinks
[$ns] = array();
218 if ( is_null( $id ) ) {
219 $id = $title->getArticleID();
221 $this->mLinks
[$ns][$dbk] = $id;
225 * Register a file dependency for this output
226 * @param string $name Title dbKey
227 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
228 * @param string $sha1 base 36 SHA-1 of file (or false if non-existing)
231 function addImage( $name, $timestamp = null, $sha1 = null ) {
232 $this->mImages
[$name] = 1;
233 if ( $timestamp !== null && $sha1 !== null ) {
234 $this->mFileSearchOptions
[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
239 * Register a template dependency for this output
240 * @param $title Title
245 function addTemplate( $title, $page_id, $rev_id ) {
246 $ns = $title->getNamespace();
247 $dbk = $title->getDBkey();
248 if ( !isset( $this->mTemplates
[$ns] ) ) {
249 $this->mTemplates
[$ns] = array();
251 $this->mTemplates
[$ns][$dbk] = $page_id;
252 if ( !isset( $this->mTemplateIds
[$ns] ) ) {
253 $this->mTemplateIds
[$ns] = array();
255 $this->mTemplateIds
[$ns][$dbk] = $rev_id; // For versioning
259 * @param $title Title object, must be an interwiki link
260 * @throws MWException if given invalid input
262 function addInterwikiLink( $title ) {
263 $prefix = $title->getInterwiki();
264 if ( $prefix == '' ) {
265 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
267 if ( !isset( $this->mInterwikiLinks
[$prefix] ) ) {
268 $this->mInterwikiLinks
[$prefix] = array();
270 $this->mInterwikiLinks
[$prefix][$title->getDBkey()] = 1;
274 * Add some text to the "<head>".
275 * If $tag is set, the section with that tag will only be included once
278 function addHeadItem( $section, $tag = false ) {
279 if ( $tag !== false ) {
280 $this->mHeadItems
[$tag] = $section;
282 $this->mHeadItems
[] = $section;
286 public function addModules( $modules ) {
287 $this->mModules
= array_merge( $this->mModules
, (array) $modules );
290 public function addModuleScripts( $modules ) {
291 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
294 public function addModuleStyles( $modules ) {
295 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
298 public function addModuleMessages( $modules ) {
299 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
303 * Copy items from the OutputPage object into this one
305 * @param $out OutputPage object
307 public function addOutputPageMetadata( OutputPage
$out ) {
308 $this->addModules( $out->getModules() );
309 $this->addModuleScripts( $out->getModuleScripts() );
310 $this->addModuleStyles( $out->getModuleStyles() );
311 $this->addModuleMessages( $out->getModuleMessages() );
313 $this->mHeadItems
= array_merge( $this->mHeadItems
, $out->getHeadItemsArray() );
317 * Override the title to be used for display
318 * -- this is assumed to have been validated
319 * (check equal normalisation, etc.)
321 * @param string $text desired title text
323 public function setDisplayTitle( $text ) {
324 $this->setTitleText( $text );
325 $this->setProperty( 'displaytitle', $text );
329 * Get the title to be used for display
333 public function getDisplayTitle() {
334 $t = $this->getTitleText();
342 * Fairly generic flag setter thingy.
344 public function setFlag( $flag ) {
345 $this->mFlags
[$flag] = true;
348 public function getFlag( $flag ) {
349 return isset( $this->mFlags
[$flag] );
353 * Set a property to be stored in the page_props database table.
355 * page_props is a key value store indexed by the page ID. This allows
356 * the parser to set a property on a page which can then be quickly
357 * retrieved given the page ID or via a DB join when given the page
360 * setProperty() is thus used to propagate properties from the parsed
361 * page to request contexts other than a page view of the currently parsed
364 * Some applications examples:
366 * * To implement hidden categories, hiding pages from category listings
367 * by storing a property.
369 * * Overriding the displayed article title.
370 * @see ParserOutput::setDisplayTitle()
372 * * To implement image tagging, for example displaying an icon on an
373 * image thumbnail to indicate that it is listed for deletion on
375 * This is not actually implemented, yet but would be pretty cool.
377 * @note: Do not use setProperty() to set a property which is only used
378 * in a context where the ParserOutput object itself is already available,
379 * for example a normal page view. There is no need to save such a property
380 * in the database since it the text is already parsed. You can just hook
381 * OutputPageParserOutput and get your data out of the ParserOutput object.
383 * If you are writing an extension where you want to set a property in the
384 * parser which is used by an OutputPageParserOutput hook, you have to
385 * associate the extension data directly with the ParserOutput object.
386 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
390 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
393 * And then later, in OutputPageParserOutput or similar:
397 * $output->getExtensionData( 'my_ext_foo' );
400 * In MediaWiki 1.20 and older, you have to use a custom member variable
401 * within the ParserOutput object:
405 * $parser->getOutput()->my_ext_foo = '...';
409 public function setProperty( $name, $value ) {
410 $this->mProperties
[$name] = $value;
413 public function getProperty( $name ) {
414 return isset( $this->mProperties
[$name] ) ?
$this->mProperties
[$name] : false;
417 public function getProperties() {
418 if ( !isset( $this->mProperties
) ) {
419 $this->mProperties
= array();
421 return $this->mProperties
;
425 * Returns the options from its ParserOptions which have been taken
426 * into account to produce this output or false if not available.
427 * @return mixed Array
429 public function getUsedOptions() {
430 if ( !isset( $this->mAccessedOptions
) ) {
433 return array_keys( $this->mAccessedOptions
);
437 * Callback passed by the Parser to the ParserOptions to keep track of which options are used.
440 function recordOption( $option ) {
441 $this->mAccessedOptions
[$option] = true;
445 * Adds an update job to the output. Any update jobs added to the output will eventually bexecuted in order to
446 * store any secondary information extracted from the page's content.
450 * @param DataUpdate $update
452 public function addSecondaryDataUpdate( DataUpdate
$update ) {
453 $this->mSecondaryDataUpdates
[] = $update;
457 * Returns any DataUpdate jobs to be executed in order to store secondary information
458 * extracted from the page's content, including a LinksUpdate object for all links stored in
459 * this ParserOutput object.
461 * @note: Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates() instead! The content
462 * handler may provide additional update objects.
466 * @param $title Title The title of the page we're updating. If not given, a title object will be created
467 * based on $this->getTitleText()
468 * @param $recursive Boolean: queue jobs for recursive updates?
470 * @return Array. An array of instances of DataUpdate
472 public function getSecondaryDataUpdates( Title
$title = null, $recursive = true ) {
473 if ( is_null( $title ) ) {
474 $title = Title
::newFromText( $this->getTitleText() );
477 $linksUpdate = new LinksUpdate( $title, $this, $recursive );
479 return array_merge( $this->mSecondaryDataUpdates
, array( $linksUpdate ) );
483 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
484 * the ParserOutput object for later use during page output. The data will be cached along with
485 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
488 * This method is provided to overcome the unsafe practice of attaching extra information to a
489 * ParserObject by directly assigning member variables.
491 * To use setExtensionData() to pass extension information from a hook inside the parser to a
492 * hook in the page output, use this in the parser hook:
496 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
499 * And then later, in OutputPageParserOutput or similar:
503 * $output->getExtensionData( 'my_ext_foo' );
506 * In MediaWiki 1.20 and older, you have to use a custom member variable
507 * within the ParserOutput object:
511 * $parser->getOutput()->my_ext_foo = '...';
516 * @param string $key The key for accessing the data. Extensions should take care to avoid
517 * conflicts in naming keys. It is suggested to use the extension's name as a
520 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
523 public function setExtensionData( $key, $value ) {
524 if ( $value === null ) {
525 unset( $this->mExtensionData
[$key] );
527 $this->mExtensionData
[$key] = $value;
532 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
533 * Typically, such data would be set while parsing the page, e.g. by a parser function.
537 * @param string $key The key to look up.
539 * @return mixed The value previously set for the given key using setExtensionData( $key ),
540 * or null if no value was set for this key.
542 public function getExtensionData( $key ) {
543 if ( isset( $this->mExtensionData
[$key] ) ) {
544 return $this->mExtensionData
[$key];
550 private static function getTimes( $clock = null ) {
552 if ( !$clock ||
$clock === 'wall' ) {
553 $ret['wall'] = microtime( true );
555 if ( ( !$clock ||
$clock === 'cpu' ) && function_exists( 'getrusage' ) ) {
557 $ret['cpu'] = $ru['ru_utime.tv_sec'] +
$ru['ru_utime.tv_usec'] / 1e6
;
558 $ret['cpu'] +
= $ru['ru_stime.tv_sec'] +
$ru['ru_stime.tv_usec'] / 1e6
;
564 * Resets the parse start timestamps for future calls to getTimeSinceStart()
567 function resetParseStartTime() {
568 $this->mParseStartTime
= self
::getTimes();
572 * Returns the time since resetParseStartTime() was last called
574 * Clocks available are:
575 * - wall: Wall clock time
576 * - cpu: CPU time (requires getrusage)
579 * @param string $clock
582 function getTimeSinceStart( $clock ) {
583 if ( !isset( $this->mParseStartTime
[$clock] ) ) {
587 $end = self
::getTimes( $clock );
588 return $end[$clock] - $this->mParseStartTime
[$clock];
592 * Sets parser limit report data for a key
594 * The key is used as the prefix for various messages used for formatting:
595 * - $key: The label for the field in the limit report
596 * - $key-value-text: Message used to format the value in the "NewPP limit
597 * report" HTML comment. If missing, uses $key-format.
598 * - $key-value-html: Message used to format the value in the preview
599 * limit report table. If missing, uses $key-format.
600 * - $key-value: Message used to format the value. If missing, uses "$1".
602 * Note that all values are interpreted as wikitext, and so should be
603 * encoded with htmlspecialchars() as necessary, but should avoid complex
604 * HTML for sanity of display in the "NewPP limit report" comment.
607 * @param string $key Message key
608 * @param mixed $value Appropriate for Message::params()
610 function setLimitReportData( $key, $value ) {
611 $this->mLimitReportData
[$key] = $value;