Merge "Remove "Misc" tab from Special:Preferences"
[lhc/web/wiklou.git] / includes / parser / ParserOutput.php
1 <?php
2
3 /**
4 * Output of the PHP parser.
5 *
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.
10 *
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.
15 *
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
20 *
21 * @file
22 * @ingroup Parser
23 */
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()
57
58 const EDITSECTION_REGEX = '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
59
60 function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
61 $containsOldMagic = false, $titletext = '' )
62 {
63 $this->mText = $text;
64 $this->mLanguageLinks = $languageLinks;
65 $this->mCategories = $categoryLinks;
66 $this->mContainsOldMagic = $containsOldMagic;
67 $this->mTitleText = $titletext;
68 }
69
70 function getText() {
71 if ( $this->mEditSectionTokens ) {
72 return preg_replace_callback( ParserOutput::EDITSECTION_REGEX,
73 array( &$this, 'replaceEditSectionLinksCallback' ), $this->mText );
74 }
75 return preg_replace( ParserOutput::EDITSECTION_REGEX, '', $this->mText );
76 }
77
78 /**
79 * callback used by getText to replace editsection tokens
80 * @private
81 * @param $m
82 * @throws MWException
83 * @return mixed
84 */
85 function replaceEditSectionLinksCallback( $m ) {
86 global $wgOut, $wgLang;
87 $args = array(
88 htmlspecialchars_decode( $m[1] ),
89 htmlspecialchars_decode( $m[2] ),
90 isset( $m[4] ) ? $m[3] : null,
91 );
92 $args[0] = Title::newFromText( $args[0] );
93 if ( !is_object( $args[0] ) ) {
94 throw new MWException( "Bad parser output text." );
95 }
96 $args[] = $wgLang->getCode();
97 $skin = $wgOut->getSkin();
98 return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args );
99 }
100
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; }
126
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 ); }
130
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 ); }
137
138 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
139 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
140 function addWarning( $s ) { $this->mWarnings[$s] = 1; }
141
142 function addOutputHook( $hook, $data = false ) {
143 $this->mOutputHooks[] = array( $hook, $data );
144 }
145
146 function setNewSection( $value ) {
147 $this->mNewSection = (bool)$value;
148 }
149 function hideNewSection( $value ) {
150 $this->mHideNewSection = (bool)$value;
151 }
152 function getHideNewSection() {
153 return (bool)$this->mHideNewSection;
154 }
155 function getNewSection() {
156 return (bool)$this->mNewSection;
157 }
158
159 /**
160 * Checks, if a url is pointing to the own server
161 *
162 * @param string $internal the server to check against
163 * @param string $url the url to check
164 * @return bool
165 */
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
172 '(?:[\?\/\#]|$)/i',
173 $url
174 );
175 }
176
177 function addExternalLink( $url ) {
178 # We don't register links pointing to our own server, unless... :-)
179 global $wgServer, $wgRegisterInternalExternals;
180
181 $registerExternalLink = true;
182 if ( !$wgRegisterInternalExternals ) {
183 $registerExternalLink = !self::isLinkInternal( $wgServer, $url );
184 }
185 if ( $registerExternalLink ) {
186 $this->mExternalLinks[$url] = 1;
187 }
188 }
189
190 /**
191 * Record a local or interwiki inline link for saving in future link tables.
192 *
193 * @param $title Title object
194 * @param $id Mixed: optional known page_id so we can skip the lookup
195 */
196 function addLink( Title $title, $id = null ) {
197 if ( $title->isExternal() ) {
198 // Don't record interwikis in pagelinks
199 $this->addInterwikiLink( $title );
200 return;
201 }
202 $ns = $title->getNamespace();
203 $dbk = $title->getDBkey();
204 if ( $ns == NS_MEDIA ) {
205 // Normalize this pseudo-alias if it makes it down here...
206 $ns = NS_FILE;
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.
210 return;
211 } elseif ( $dbk === '' ) {
212 // Don't record self links - [[#Foo]]
213 return;
214 }
215 if ( !isset( $this->mLinks[$ns] ) ) {
216 $this->mLinks[$ns] = array();
217 }
218 if ( is_null( $id ) ) {
219 $id = $title->getArticleID();
220 }
221 $this->mLinks[$ns][$dbk] = $id;
222 }
223
224 /**
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)
229 * @return void
230 */
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 );
235 }
236 }
237
238 /**
239 * Register a template dependency for this output
240 * @param $title Title
241 * @param $page_id
242 * @param $rev_id
243 * @return void
244 */
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();
250 }
251 $this->mTemplates[$ns][$dbk] = $page_id;
252 if ( !isset( $this->mTemplateIds[$ns] ) ) {
253 $this->mTemplateIds[$ns] = array();
254 }
255 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
256 }
257
258 /**
259 * @param $title Title object, must be an interwiki link
260 * @throws MWException if given invalid input
261 */
262 function addInterwikiLink( $title ) {
263 $prefix = $title->getInterwiki();
264 if ( $prefix == '' ) {
265 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
266 }
267 if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
268 $this->mInterwikiLinks[$prefix] = array();
269 }
270 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
271 }
272
273 /**
274 * Add some text to the "<head>".
275 * If $tag is set, the section with that tag will only be included once
276 * in a given page.
277 */
278 function addHeadItem( $section, $tag = false ) {
279 if ( $tag !== false ) {
280 $this->mHeadItems[$tag] = $section;
281 } else {
282 $this->mHeadItems[] = $section;
283 }
284 }
285
286 public function addModules( $modules ) {
287 $this->mModules = array_merge( $this->mModules, (array)$modules );
288 }
289
290 public function addModuleScripts( $modules ) {
291 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
292 }
293
294 public function addModuleStyles( $modules ) {
295 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
296 }
297
298 public function addModuleMessages( $modules ) {
299 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
300 }
301
302 /**
303 * Copy items from the OutputPage object into this one
304 *
305 * @param $out OutputPage object
306 */
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() );
312
313 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
314 }
315
316 /**
317 * Override the title to be used for display
318 * -- this is assumed to have been validated
319 * (check equal normalisation, etc.)
320 *
321 * @param string $text desired title text
322 */
323 public function setDisplayTitle( $text ) {
324 $this->setTitleText( $text );
325 $this->setProperty( 'displaytitle', $text );
326 }
327
328 /**
329 * Get the title to be used for display
330 *
331 * @return String
332 */
333 public function getDisplayTitle() {
334 $t = $this->getTitleText();
335 if ( $t === '' ) {
336 return false;
337 }
338 return $t;
339 }
340
341 /**
342 * Fairly generic flag setter thingy.
343 */
344 public function setFlag( $flag ) {
345 $this->mFlags[$flag] = true;
346 }
347
348 public function getFlag( $flag ) {
349 return isset( $this->mFlags[$flag] );
350 }
351
352 /**
353 * Set a property to be stored in the page_props database table.
354 *
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
358 * title.
359 *
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
362 * article.
363 *
364 * Some applications examples:
365 *
366 * * To implement hidden categories, hiding pages from category listings
367 * by storing a property.
368 *
369 * * Overriding the displayed article title.
370 * @see ParserOutput::setDisplayTitle()
371 *
372 * * To implement image tagging, for example displaying an icon on an
373 * image thumbnail to indicate that it is listed for deletion on
374 * Wikimedia Commons.
375 * This is not actually implemented, yet but would be pretty cool.
376 *
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.
382 *
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:
387 *
388 * @par Example:
389 * @code
390 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
391 * @endcode
392 *
393 * And then later, in OutputPageParserOutput or similar:
394 *
395 * @par Example:
396 * @code
397 * $output->getExtensionData( 'my_ext_foo' );
398 * @endcode
399 *
400 * In MediaWiki 1.20 and older, you have to use a custom member variable
401 * within the ParserOutput object:
402 *
403 * @par Example:
404 * @code
405 * $parser->getOutput()->my_ext_foo = '...';
406 * @endcode
407 *
408 */
409 public function setProperty( $name, $value ) {
410 $this->mProperties[$name] = $value;
411 }
412
413 public function getProperty( $name ) {
414 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
415 }
416
417 public function getProperties() {
418 if ( !isset( $this->mProperties ) ) {
419 $this->mProperties = array();
420 }
421 return $this->mProperties;
422 }
423
424 /**
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
428 */
429 public function getUsedOptions() {
430 if ( !isset( $this->mAccessedOptions ) ) {
431 return array();
432 }
433 return array_keys( $this->mAccessedOptions );
434 }
435
436 /**
437 * Callback passed by the Parser to the ParserOptions to keep track of which options are used.
438 * @access private
439 */
440 function recordOption( $option ) {
441 $this->mAccessedOptions[$option] = true;
442 }
443
444 /**
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.
447 *
448 * @since 1.20
449 *
450 * @param DataUpdate $update
451 */
452 public function addSecondaryDataUpdate( DataUpdate $update ) {
453 $this->mSecondaryDataUpdates[] = $update;
454 }
455
456 /**
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.
460 *
461 * @note: Avoid using this method directly, use ContentHandler::getSecondaryDataUpdates() instead! The content
462 * handler may provide additional update objects.
463 *
464 * @since 1.20
465 *
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?
469 *
470 * @return Array. An array of instances of DataUpdate
471 */
472 public function getSecondaryDataUpdates( Title $title = null, $recursive = true ) {
473 if ( is_null( $title ) ) {
474 $title = Title::newFromText( $this->getTitleText() );
475 }
476
477 $linksUpdate = new LinksUpdate( $title, $this, $recursive );
478
479 return array_merge( $this->mSecondaryDataUpdates, array( $linksUpdate ) );
480 }
481
482 /**
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
486 * database.
487 *
488 * This method is provided to overcome the unsafe practice of attaching extra information to a
489 * ParserObject by directly assigning member variables.
490 *
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:
493 *
494 * @par Example:
495 * @code
496 * $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
497 * @endcode
498 *
499 * And then later, in OutputPageParserOutput or similar:
500 *
501 * @par Example:
502 * @code
503 * $output->getExtensionData( 'my_ext_foo' );
504 * @endcode
505 *
506 * In MediaWiki 1.20 and older, you have to use a custom member variable
507 * within the ParserOutput object:
508 *
509 * @par Example:
510 * @code
511 * $parser->getOutput()->my_ext_foo = '...';
512 * @endcode
513 *
514 * @since 1.21
515 *
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
518 * prefix.
519 *
520 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
521 * the value.
522 */
523 public function setExtensionData( $key, $value ) {
524 if ( $value === null ) {
525 unset( $this->mExtensionData[$key] );
526 } else {
527 $this->mExtensionData[$key] = $value;
528 }
529 }
530
531 /**
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.
534 *
535 * @since 1.21
536 *
537 * @param string $key The key to look up.
538 *
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.
541 */
542 public function getExtensionData( $key ) {
543 if ( isset( $this->mExtensionData[$key] ) ) {
544 return $this->mExtensionData[$key];
545 }
546
547 return null;
548 }
549
550 private static function getTimes( $clock = null ) {
551 $ret = array();
552 if ( !$clock || $clock === 'wall' ) {
553 $ret['wall'] = microtime( true );
554 }
555 if ( ( !$clock || $clock === 'cpu' ) && function_exists( 'getrusage' ) ) {
556 $ru = 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;
559 }
560 return $ret;
561 }
562
563 /**
564 * Resets the parse start timestamps for future calls to getTimeSinceStart()
565 * @since 1.22
566 */
567 function resetParseStartTime() {
568 $this->mParseStartTime = self::getTimes();
569 }
570
571 /**
572 * Returns the time since resetParseStartTime() was last called
573 *
574 * Clocks available are:
575 * - wall: Wall clock time
576 * - cpu: CPU time (requires getrusage)
577 *
578 * @since 1.22
579 * @param string $clock
580 * @return float|null
581 */
582 function getTimeSinceStart( $clock ) {
583 if ( !isset( $this->mParseStartTime[$clock] ) ) {
584 return null;
585 }
586
587 $end = self::getTimes( $clock );
588 return $end[$clock] - $this->mParseStartTime[$clock];
589 }
590
591 /**
592 * Sets parser limit report data for a key
593 *
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".
601 *
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.
605 *
606 * @since 1.22
607 * @param string $key Message key
608 * @param mixed $value Appropriate for Message::params()
609 */
610 function setLimitReportData( $key, $value ) {
611 $this->mLimitReportData[$key] = $value;
612 }
613 }