Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / parser / ParserOutput.php
blobc5e42a4d2d22b33b7f34d99826cc3ed80cadf871
1 <?php
3 /**
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
21 * @file
22 * @ingroup Parser
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
56 const EDITSECTION_REGEX = '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
58 function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
59 $containsOldMagic = false, $titletext = '' )
61 $this->mText = $text;
62 $this->mLanguageLinks = $languageLinks;
63 $this->mCategories = $categoryLinks;
64 $this->mContainsOldMagic = $containsOldMagic;
65 $this->mTitleText = $titletext;
68 function getText() {
69 if ( $this->mEditSectionTokens ) {
70 return preg_replace_callback( ParserOutput::EDITSECTION_REGEX,
71 array( &$this, 'replaceEditSectionLinksCallback' ), $this->mText );
73 return preg_replace( ParserOutput::EDITSECTION_REGEX, '', $this->mText );
76 /**
77 * callback used by getText to replace editsection tokens
78 * @private
79 * @param $m
80 * @throws MWException
81 * @return mixed
83 function replaceEditSectionLinksCallback( $m ) {
84 global $wgOut, $wgLang;
85 $args = array(
86 htmlspecialchars_decode( $m[1] ),
87 htmlspecialchars_decode( $m[2] ),
88 isset( $m[4] ) ? $m[3] : null,
90 $args[0] = Title::newFromText( $args[0] );
91 if ( !is_object( $args[0] ) ) {
92 throw new MWException( "Bad parser output text." );
94 $args[] = $wgLang->getCode();
95 $skin = $wgOut->getSkin();
96 return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args );
99 function &getLanguageLinks() { return $this->mLanguageLinks; }
100 function getInterwikiLinks() { return $this->mInterwikiLinks; }
101 function getCategoryLinks() { return array_keys( $this->mCategories ); }
102 function &getCategories() { return $this->mCategories; }
103 function getTitleText() { return $this->mTitleText; }
104 function getSections() { return $this->mSections; }
105 function getEditSectionTokens() { return $this->mEditSectionTokens; }
106 function &getLinks() { return $this->mLinks; }
107 function &getTemplates() { return $this->mTemplates; }
108 function &getTemplateIds() { return $this->mTemplateIds; }
109 function &getImages() { return $this->mImages; }
110 function &getFileSearchOptions() { return $this->mFileSearchOptions; }
111 function &getExternalLinks() { return $this->mExternalLinks; }
112 function getNoGallery() { return $this->mNoGallery; }
113 function getHeadItems() { return $this->mHeadItems; }
114 function getModules() { return $this->mModules; }
115 function getModuleScripts() { return $this->mModuleScripts; }
116 function getModuleStyles() { return $this->mModuleStyles; }
117 function getModuleMessages() { return $this->mModuleMessages; }
118 function getOutputHooks() { return (array)$this->mOutputHooks; }
119 function getWarnings() { return array_keys( $this->mWarnings ); }
120 function getIndexPolicy() { return $this->mIndexPolicy; }
121 function getTOCHTML() { return $this->mTOCHTML; }
122 function getTimestamp() { return $this->mTimestamp; }
124 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
125 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
126 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
128 function setTitleText( $t ) { return wfSetVar( $this->mTitleText, $t ); }
129 function setSections( $toc ) { return wfSetVar( $this->mSections, $toc ); }
130 function setEditSectionTokens( $t ) { return wfSetVar( $this->mEditSectionTokens, $t ); }
131 function setIndexPolicy( $policy ) { return wfSetVar( $this->mIndexPolicy, $policy ); }
132 function setTOCHTML( $tochtml ) { return wfSetVar( $this->mTOCHTML, $tochtml ); }
133 function setTimestamp( $timestamp ) { return wfSetVar( $this->mTimestamp, $timestamp ); }
135 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
136 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
137 function addWarning( $s ) { $this->mWarnings[$s] = 1; }
139 function addOutputHook( $hook, $data = false ) {
140 $this->mOutputHooks[] = array( $hook, $data );
143 function setNewSection( $value ) {
144 $this->mNewSection = (bool)$value;
146 function hideNewSection( $value ) {
147 $this->mHideNewSection = (bool)$value;
149 function getHideNewSection() {
150 return (bool)$this->mHideNewSection;
152 function getNewSection() {
153 return (bool)$this->mNewSection;
157 * Checks, if a url is pointing to the own server
159 * @param string $internal the server to check against
160 * @param string $url the url to check
161 * @return bool
163 static function isLinkInternal( $internal, $url ) {
164 return (bool)preg_match( '/^' .
165 # If server is proto relative, check also for http/https links
166 ( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
167 preg_quote( $internal, '/' ) .
168 # check for query/path/anchor or end of link in each case
169 '(?:[\?\/\#]|$)/i',
170 $url
174 function addExternalLink( $url ) {
175 # We don't register links pointing to our own server, unless... :-)
176 global $wgServer, $wgRegisterInternalExternals;
178 $registerExternalLink = true;
179 if ( !$wgRegisterInternalExternals ) {
180 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
182 if ( $registerExternalLink ) {
183 $this->mExternalLinks[$url] = 1;
188 * Record a local or interwiki inline link for saving in future link tables.
190 * @param $title Title object
191 * @param $id Mixed: optional known page_id so we can skip the lookup
193 function addLink( Title $title, $id = null ) {
194 if ( $title->isExternal() ) {
195 // Don't record interwikis in pagelinks
196 $this->addInterwikiLink( $title );
197 return;
199 $ns = $title->getNamespace();
200 $dbk = $title->getDBkey();
201 if ( $ns == NS_MEDIA ) {
202 // Normalize this pseudo-alias if it makes it down here...
203 $ns = NS_FILE;
204 } elseif ( $ns == NS_SPECIAL ) {
205 // We don't record Special: links currently
206 // It might actually be wise to, but we'd need to do some normalization.
207 return;
208 } elseif ( $dbk === '' ) {
209 // Don't record self links - [[#Foo]]
210 return;
212 if ( !isset( $this->mLinks[$ns] ) ) {
213 $this->mLinks[$ns] = array();
215 if ( is_null( $id ) ) {
216 $id = $title->getArticleID();
218 $this->mLinks[$ns][$dbk] = $id;
222 * Register a file dependency for this output
223 * @param string $name Title dbKey
224 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
225 * @param string $sha1 base 36 SHA-1 of file (or false if non-existing)
226 * @return void
228 function addImage( $name, $timestamp = null, $sha1 = null ) {
229 $this->mImages[$name] = 1;
230 if ( $timestamp !== null && $sha1 !== null ) {
231 $this->mFileSearchOptions[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
236 * Register a template dependency for this output
237 * @param $title Title
238 * @param $page_id
239 * @param $rev_id
240 * @return void
242 function addTemplate( $title, $page_id, $rev_id ) {
243 $ns = $title->getNamespace();
244 $dbk = $title->getDBkey();
245 if ( !isset( $this->mTemplates[$ns] ) ) {
246 $this->mTemplates[$ns] = array();
248 $this->mTemplates[$ns][$dbk] = $page_id;
249 if ( !isset( $this->mTemplateIds[$ns] ) ) {
250 $this->mTemplateIds[$ns] = array();
252 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
256 * @param $title Title object, must be an interwiki link
257 * @throws MWException if given invalid input
259 function addInterwikiLink( $title ) {
260 $prefix = $title->getInterwiki();
261 if ( $prefix == '' ) {
262 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
264 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
265 $this->mInterwikiLinks[$prefix] = array();
267 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
271 * Add some text to the "<head>".
272 * If $tag is set, the section with that tag will only be included once
273 * in a given page.
275 function addHeadItem( $section, $tag = false ) {
276 if ( $tag !== false ) {
277 $this->mHeadItems[$tag] = $section;
278 } else {
279 $this->mHeadItems[] = $section;
283 public function addModules( $modules ) {
284 $this->mModules = array_merge( $this->mModules, (array) $modules );
287 public function addModuleScripts( $modules ) {
288 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
291 public function addModuleStyles( $modules ) {
292 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
295 public function addModuleMessages( $modules ) {
296 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
300 * Copy items from the OutputPage object into this one
302 * @param $out OutputPage object
304 public function addOutputPageMetadata( OutputPage $out ) {
305 $this->addModules( $out->getModules() );
306 $this->addModuleScripts( $out->getModuleScripts() );
307 $this->addModuleStyles( $out->getModuleStyles() );
308 $this->addModuleMessages( $out->getModuleMessages() );
310 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
314 * Override the title to be used for display
315 * -- this is assumed to have been validated
316 * (check equal normalisation, etc.)
318 * @param string $text desired title text
320 public function setDisplayTitle( $text ) {
321 $this->setTitleText( $text );
322 $this->setProperty( 'displaytitle', $text );
326 * Get the title to be used for display
328 * @return String
330 public function getDisplayTitle() {
331 $t = $this->getTitleText();
332 if ( $t === '' ) {
333 return false;
335 return $t;
339 * Fairly generic flag setter thingy.
341 public function setFlag( $flag ) {
342 $this->mFlags[$flag] = true;
345 public function getFlag( $flag ) {
346 return isset( $this->mFlags[$flag] );
350 * Set a property to be stored in the page_props database table.
352 * page_props is a key value store indexed by the page ID. This allows
353 * the parser to set a property on a page which can then be quickly
354 * retrieved given the page ID or via a DB join when given the page
355 * title.
357 * setProperty() is thus used to propagate properties from the parsed
358 * page to request contexts other than a page view of the currently parsed
359 * article.
361 * Some applications examples:
363 * * To implement hidden categories, hiding pages from category listings
364 * by storing a property.
366 * * Overriding the displayed article title.
367 * @see ParserOutput::setDisplayTitle()
369 * * To implement image tagging, for example displaying an icon on an
370 * image thumbnail to indicate that it is listed for deletion on
371 * Wikimedia Commons.
372 * This is not actually implemented, yet but would be pretty cool.
374 * @note: Do not use setProperty() to set a property which is only used
375 * in a context where the ParserOutput object itself is already available,
376 * for example a normal page view. There is no need to save such a property
377 * in the database since it the text is already parsed. You can just hook
378 * OutputPageParserOutput and get your data out of the ParserOutput object.
380 * If you are writing an extension where you want to set a property in the
381 * parser which is used by an OutputPageParserOutput hook, you have to
382 * associate the extension data directly with the ParserOutput object.
383 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
385 * @par Example:
386 * @code
387 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
388 * @endcode
390 * And then later, in OutputPageParserOutput or similar:
392 * @par Example:
393 * @code
394 * $output->getExtensionData( 'my_ext_foo' );
395 * @endcode
397 * In MediaWiki 1.20 and older, you have to use a custom member variable
398 * within the ParserOutput object:
400 * @par Example:
401 * @code
402 * $parser->getOutput()->my_ext_foo = '...';
403 * @endcode
406 public function setProperty( $name, $value ) {
407 $this->mProperties[$name] = $value;
410 public function getProperty( $name ) {
411 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
414 public function getProperties() {
415 if ( !isset( $this->mProperties ) ) {
416 $this->mProperties = array();
418 return $this->mProperties;
422 * Returns the options from its ParserOptions which have been taken
423 * into account to produce this output or false if not available.
424 * @return mixed Array
426 public function getUsedOptions() {
427 if ( !isset( $this->mAccessedOptions ) ) {
428 return array();
430 return array_keys( $this->mAccessedOptions );
434 * Callback passed by the Parser to the ParserOptions to keep track of which options are used.
435 * @access private
437 function recordOption( $option ) {
438 $this->mAccessedOptions[$option] = true;
442 * Adds an update job to the output. Any update jobs added to the output will eventually bexecuted in order to
443 * store any secondary information extracted from the page's content.
445 * @since 1.20
447 * @param DataUpdate $update
449 public function addSecondaryDataUpdate( DataUpdate $update ) {
450 $this->mSecondaryDataUpdates[] = $update;
454 * Returns any DataUpdate jobs to be executed in order to store secondary information
455 * extracted from the page's content, including a LinksUpdate object for all links stored in
456 * this ParserOutput object.
458 * @note: Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates() instead! The content
459 * handler may provide additional update objects.
461 * @since 1.20
463 * @param $title Title The title of the page we're updating. If not given, a title object will be created
464 * based on $this->getTitleText()
465 * @param $recursive Boolean: queue jobs for recursive updates?
467 * @return Array. An array of instances of DataUpdate
469 public function getSecondaryDataUpdates( Title $title = null, $recursive = true ) {
470 if ( is_null( $title ) ) {
471 $title = Title::newFromText( $this->getTitleText() );
474 $linksUpdate = new LinksUpdate( $title, $this, $recursive );
476 return array_merge( $this->mSecondaryDataUpdates, array( $linksUpdate ) );
480 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
481 * the ParserOutput object for later use during page output. The data will be cached along with
482 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
483 * database.
485 * This method is provided to overcome the unsafe practice of attaching extra information to a
486 * ParserObject by directly assigning member variables.
488 * To use setExtensionData() to pass extension information from a hook inside the parser to a
489 * hook in the page output, use this in the parser hook:
491 * @par Example:
492 * @code
493 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
494 * @endcode
496 * And then later, in OutputPageParserOutput or similar:
498 * @par Example:
499 * @code
500 * $output->getExtensionData( 'my_ext_foo' );
501 * @endcode
503 * In MediaWiki 1.20 and older, you have to use a custom member variable
504 * within the ParserOutput object:
506 * @par Example:
507 * @code
508 * $parser->getOutput()->my_ext_foo = '...';
509 * @endcode
511 * @since 1.21
513 * @param string $key The key for accessing the data. Extensions should take care to avoid
514 * conflicts in naming keys. It is suggested to use the extension's name as a
515 * prefix.
517 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
518 * the value.
520 public function setExtensionData( $key, $value ) {
521 if ( $value === null ) {
522 unset( $this->mExtensionData[$key] );
523 } else {
524 $this->mExtensionData[$key] = $value;
529 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
530 * Typically, such data would be set while parsing the page, e.g. by a parser function.
532 * @since 1.21
534 * @param string $key The key to look up.
536 * @return mixed The value previously set for the given key using setExtensionData( $key ),
537 * or null if no value was set for this key.
539 public function getExtensionData( $key ) {
540 if ( isset( $this->mExtensionData[$key] ) ) {
541 return $this->mExtensionData[$key];
544 return null;