Completed
Branch master (90e9fc)
by
unknown
29:23
created

ParserOutput::getExternalLinks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
	/**
26
	 * @var string $mText The output text
27
	 */
28
	public $mText;
29
30
	/**
31
	 * @var array $mLanguageLinks List of the full text of language links,
32
	 *  in the order they appear.
33
	 */
34
	public $mLanguageLinks;
35
36
	/**
37
	 * @var array $mCategoriesMap of category names to sort keys
38
	 */
39
	public $mCategories;
40
41
	/**
42
	 * @var array $mIndicators Page status indicators, usually displayed in top-right corner.
43
	 */
44
	public $mIndicators = [];
45
46
	/**
47
	 * @var string $mTitleText Title text of the chosen language variant, as HTML.
48
	 */
49
	public $mTitleText;
50
51
	/**
52
	 * @var array $mLinks 2-D map of NS/DBK to ID for the links in the document.
53
	 *  ID=zero for broken.
54
	 */
55
	public $mLinks = [];
56
57
	/**
58
	 * @var array $mTemplates 2-D map of NS/DBK to ID for the template references.
59
	 *  ID=zero for broken.
60
	 */
61
	public $mTemplates = [];
62
63
	/**
64
	 * @var array $mTemplateIds 2-D map of NS/DBK to rev ID for the template references.
65
	 *  ID=zero for broken.
66
	 */
67
	public $mTemplateIds = [];
68
69
	/**
70
	 * @var array $mImages DB keys of the images used, in the array key only
71
	 */
72
	public $mImages = [];
73
74
	/**
75
	 * @var array $mFileSearchOptions DB keys of the images used mapped to sha1 and MW timestamp.
76
	 */
77
	public $mFileSearchOptions = [];
78
79
	/**
80
	 * @var array $mExternalLinks External link URLs, in the key only.
81
	 */
82
	public $mExternalLinks = [];
83
84
	/**
85
	 * @var array $mInterwikiLinks 2-D map of prefix/DBK (in keys only)
86
	 *  for the inline interwiki links in the document.
87
	 */
88
	public $mInterwikiLinks = [];
89
90
	/**
91
	 * @var bool $mNewSection Show a new section link?
92
	 */
93
	public $mNewSection = false;
94
95
	/**
96
	 * @var bool $mHideNewSection Hide the new section link?
97
	 */
98
	public $mHideNewSection = false;
99
100
	/**
101
	 * @var bool $mNoGallery No gallery on category page? (__NOGALLERY__).
102
	 */
103
	public $mNoGallery = false;
104
105
	/**
106
	 * @var array $mHeadItems Items to put in the <head> section
107
	 */
108
	public $mHeadItems = [];
109
110
	/**
111
	 * @var array $mModules Modules to be loaded by ResourceLoader
112
	 */
113
	public $mModules = [];
114
115
	/**
116
	 * @var array $mModuleScripts Modules of which only the JS will be loaded by ResourceLoader.
117
	 */
118
	public $mModuleScripts = [];
119
120
	/**
121
	 * @var array $mModuleStyles Modules of which only the CSSS will be loaded by ResourceLoader.
122
	 */
123
	public $mModuleStyles = [];
124
125
	/**
126
	 * @var array $mJsConfigVars JavaScript config variable for mw.config combined with this page.
127
	 */
128
	public $mJsConfigVars = [];
129
130
	/**
131
	 * @var array $mOutputHooks Hook tags as per $wgParserOutputHooks.
132
	 */
133
	public $mOutputHooks = [];
134
135
	/**
136
	 * @var array $mWarnings Warning text to be returned to the user.
137
	 *  Wikitext formatted, in the key only.
138
	 */
139
	public $mWarnings = [];
140
141
	/**
142
	 * @var array $mSections Table of contents
143
	 */
144
	public $mSections = [];
145
146
	/**
147
	 * @var bool $mEditSectionTokens prefix/suffix markers if edit sections were output as tokens.
148
	 */
149
	public $mEditSectionTokens = false;
150
151
	/**
152
	 * @var array $mProperties Name/value pairs to be cached in the DB.
153
	 */
154
	public $mProperties = [];
155
156
	/**
157
	 * @var string $mTOCHTML HTML of the TOC.
158
	 */
159
	public $mTOCHTML = '';
160
161
	/**
162
	 * @var string $mTimestamp Timestamp of the revision.
163
	 */
164
	public $mTimestamp;
165
166
	/**
167
	 * @var bool $mTOCEnabled Whether TOC should be shown, can't override __NOTOC__.
168
	 */
169
	public $mTOCEnabled = true;
170
171
	/**
172
	 * @var bool $mEnableOOUI Whether OOUI should be enabled.
173
	 */
174
	public $mEnableOOUI = false;
175
176
	/**
177
	 * @var string $mIndexPolicy 'index' or 'noindex'?  Any other value will result in no change.
178
	 */
179
	private $mIndexPolicy = '';
180
181
	/**
182
	 * @var array $mAccessedOptions List of ParserOptions (stored in the keys).
183
	 */
184
	private $mAccessedOptions = [];
185
186
	/**
187
	 * @var array $mExtensionData extra data used by extensions.
188
	 */
189
	private $mExtensionData = [];
190
191
	/** @var array $mLimitReportData Parser limit report data. */
192
	private $mLimitReportData = [];
193
194
	/**
195
	 * @var array $mParseStartTime Timestamps for getTimeSinceStart().
196
	 */
197
	private $mParseStartTime = [];
198
199
	/**
200
	 * @var bool $mPreventClickjacking Whether to emit X-Frame-Options: DENY.
201
	 */
202
	private $mPreventClickjacking = false;
203
204
	/**
205
	 * @var array $mFlags Generic flags.
206
	 */
207
	private $mFlags = [];
208
209
	/** @var integer|null Assumed rev ID for {{REVISIONID}} if no revision is set */
210
	private $mSpeculativeRevId;
211
212
	/** @var integer Upper bound of expiry based on parse duration */
213
	private $mMaxAdaptiveExpiry = INF;
214
215
	const EDITSECTION_REGEX =
216
		'#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
217
218
	// finalizeAdaptiveCacheExpiry() uses TTL = MAX( m * PARSE_TIME + b, MIN_AR_TTL)
219
	// Current values imply that m=3933.333333 and b=-333.333333
220
	// See https://www.nngroup.com/articles/website-response-times/
221
	const PARSE_FAST_SEC = .100; // perceived "fast" page parse
222
	const PARSE_SLOW_SEC = 1.0; // perceived "slow" page parse
223
	const FAST_AR_TTL = 60; // adaptive TTL for "fast" pages
224
	const SLOW_AR_TTL = 3600; // adaptive TTL for "slow" pages
225
	const MIN_AR_TTL = 15; // min adaptive TTL (for sanity, pool counter, and edit stashing)
226
227
	public function __construct( $text = '', $languageLinks = [], $categoryLinks = [],
228
		$unused = false, $titletext = ''
229
	) {
230
		$this->mText = $text;
231
		$this->mLanguageLinks = $languageLinks;
232
		$this->mCategories = $categoryLinks;
233
		$this->mTitleText = $titletext;
234
	}
235
236
	/**
237
	 * Get the cacheable text with <mw:editsection> markers still in it. The
238
	 * return value is suitable for writing back via setText() but is not valid
239
	 * for display to the user.
240
	 *
241
	 * @since 1.27
242
	 */
243
	public function getRawText() {
244
		return $this->mText;
245
	}
246
247
	public function getText() {
248
		$text = $this->mText;
249
		if ( $this->mEditSectionTokens ) {
250
			$text = preg_replace_callback(
251
				ParserOutput::EDITSECTION_REGEX,
252
				function ( $m ) {
253
					global $wgOut, $wgLang;
254
					$editsectionPage = Title::newFromText( htmlspecialchars_decode( $m[1] ) );
255
					$editsectionSection = htmlspecialchars_decode( $m[2] );
256
					$editsectionContent = isset( $m[4] ) ? $m[3] : null;
257
258
					if ( !is_object( $editsectionPage ) ) {
259
						throw new MWException( "Bad parser output text." );
260
					}
261
262
					$skin = $wgOut->getSkin();
263
					return call_user_func_array(
264
						[ $skin, 'doEditSectionLink' ],
265
						[ $editsectionPage, $editsectionSection,
266
							$editsectionContent, $wgLang->getCode() ]
267
					);
268
				},
269
				$text
270
			);
271
		} else {
272
			$text = preg_replace( ParserOutput::EDITSECTION_REGEX, '', $text );
273
		}
274
275
		// If you have an old cached version of this class - sorry, you can't disable the TOC
276
		if ( isset( $this->mTOCEnabled ) && $this->mTOCEnabled ) {
277
			$text = str_replace( [ Parser::TOC_START, Parser::TOC_END ], '', $text );
278
		} else {
279
			$text = preg_replace(
280
				'#' . preg_quote( Parser::TOC_START, '#' ) . '.*?' . preg_quote( Parser::TOC_END, '#' ) . '#s',
281
				'',
282
				$text
283
			);
284
		}
285
		return $text;
286
	}
287
288
	/**
289
	 * @param integer $id
290
	 * @since 1.28
291
	 */
292
	public function setSpeculativeRevIdUsed( $id ) {
293
		$this->mSpeculativeRevId = $id;
294
	}
295
296
	/** @since 1.28 */
297
	public function getSpeculativeRevIdUsed() {
298
		return $this->mSpeculativeRevId;
299
	}
300
301
	public function &getLanguageLinks() {
302
		return $this->mLanguageLinks;
303
	}
304
305
	public function getInterwikiLinks() {
306
		return $this->mInterwikiLinks;
307
	}
308
309
	public function getCategoryLinks() {
310
		return array_keys( $this->mCategories );
311
	}
312
313
	public function &getCategories() {
314
		return $this->mCategories;
315
	}
316
317
	/**
318
	 * @since 1.25
319
	 */
320
	public function getIndicators() {
321
		return $this->mIndicators;
322
	}
323
324
	public function getTitleText() {
325
		return $this->mTitleText;
326
	}
327
328
	public function getSections() {
329
		return $this->mSections;
330
	}
331
332
	public function getEditSectionTokens() {
333
		return $this->mEditSectionTokens;
334
	}
335
336
	public function &getLinks() {
337
		return $this->mLinks;
338
	}
339
340
	public function &getTemplates() {
341
		return $this->mTemplates;
342
	}
343
344
	public function &getTemplateIds() {
345
		return $this->mTemplateIds;
346
	}
347
348
	public function &getImages() {
349
		return $this->mImages;
350
	}
351
352
	public function &getFileSearchOptions() {
353
		return $this->mFileSearchOptions;
354
	}
355
356
	public function &getExternalLinks() {
357
		return $this->mExternalLinks;
358
	}
359
360
	public function getNoGallery() {
361
		return $this->mNoGallery;
362
	}
363
364
	public function getHeadItems() {
365
		return $this->mHeadItems;
366
	}
367
368
	public function getModules() {
369
		return $this->mModules;
370
	}
371
372
	public function getModuleScripts() {
373
		return $this->mModuleScripts;
374
	}
375
376
	public function getModuleStyles() {
377
		return $this->mModuleStyles;
378
	}
379
380
	/** @since 1.23 */
381
	public function getJsConfigVars() {
382
		return $this->mJsConfigVars;
383
	}
384
385
	public function getOutputHooks() {
386
		return (array)$this->mOutputHooks;
387
	}
388
389
	public function getWarnings() {
390
		return array_keys( $this->mWarnings );
391
	}
392
393
	public function getIndexPolicy() {
394
		return $this->mIndexPolicy;
395
	}
396
397
	public function getTOCHTML() {
398
		return $this->mTOCHTML;
399
	}
400
401
	/**
402
	 * @return string|null TS_MW timestamp of the revision content
403
	 */
404
	public function getTimestamp() {
405
		return $this->mTimestamp;
406
	}
407
408
	public function getLimitReportData() {
409
		return $this->mLimitReportData;
410
	}
411
412
	public function getTOCEnabled() {
413
		return $this->mTOCEnabled;
414
	}
415
416
	public function getEnableOOUI() {
417
		return $this->mEnableOOUI;
418
	}
419
420
	public function setText( $text ) {
421
		return wfSetVar( $this->mText, $text );
422
	}
423
424
	public function setLanguageLinks( $ll ) {
425
		return wfSetVar( $this->mLanguageLinks, $ll );
426
	}
427
428
	public function setCategoryLinks( $cl ) {
429
		return wfSetVar( $this->mCategories, $cl );
430
	}
431
432
	public function setTitleText( $t ) {
433
		return wfSetVar( $this->mTitleText, $t );
434
	}
435
436
	public function setSections( $toc ) {
437
		return wfSetVar( $this->mSections, $toc );
438
	}
439
440
	public function setEditSectionTokens( $t ) {
441
		return wfSetVar( $this->mEditSectionTokens, $t );
442
	}
443
444
	public function setIndexPolicy( $policy ) {
445
		return wfSetVar( $this->mIndexPolicy, $policy );
446
	}
447
448
	public function setTOCHTML( $tochtml ) {
449
		return wfSetVar( $this->mTOCHTML, $tochtml );
450
	}
451
452
	public function setTimestamp( $timestamp ) {
453
		return wfSetVar( $this->mTimestamp, $timestamp );
454
	}
455
456
	public function setTOCEnabled( $flag ) {
457
		return wfSetVar( $this->mTOCEnabled, $flag );
458
	}
459
460
	public function addCategory( $c, $sort ) {
461
		$this->mCategories[$c] = $sort;
462
	}
463
464
	/**
465
	 * @since 1.25
466
	 */
467
	public function setIndicator( $id, $content ) {
468
		$this->mIndicators[$id] = $content;
469
	}
470
471
	/**
472
	 * Enables OOUI, if true, in any OutputPage instance this ParserOutput
473
	 * object is added to.
474
	 *
475
	 * @since 1.26
476
	 * @param bool $enable If OOUI should be enabled or not
477
	 */
478
	public function setEnableOOUI( $enable = false ) {
479
		$this->mEnableOOUI = $enable;
480
	}
481
482
	public function addLanguageLink( $t ) {
483
		$this->mLanguageLinks[] = $t;
484
	}
485
486
	public function addWarning( $s ) {
487
		$this->mWarnings[$s] = 1;
488
	}
489
490
	public function addOutputHook( $hook, $data = false ) {
491
		$this->mOutputHooks[] = [ $hook, $data ];
492
	}
493
494
	public function setNewSection( $value ) {
495
		$this->mNewSection = (bool)$value;
496
	}
497
	public function hideNewSection( $value ) {
498
		$this->mHideNewSection = (bool)$value;
499
	}
500
	public function getHideNewSection() {
501
		return (bool)$this->mHideNewSection;
502
	}
503
	public function getNewSection() {
504
		return (bool)$this->mNewSection;
505
	}
506
507
	/**
508
	 * Checks, if a url is pointing to the own server
509
	 *
510
	 * @param string $internal The server to check against
511
	 * @param string $url The url to check
512
	 * @return bool
513
	 */
514
	public static function isLinkInternal( $internal, $url ) {
515
		return (bool)preg_match( '/^' .
516
			# If server is proto relative, check also for http/https links
517
			( substr( $internal, 0, 2 ) === '//' ? '(?:https?:)?' : '' ) .
518
			preg_quote( $internal, '/' ) .
519
			# check for query/path/anchor or end of link in each case
520
			'(?:[\?\/\#]|$)/i',
521
			$url
522
		);
523
	}
524
525
	public function addExternalLink( $url ) {
526
		# We don't register links pointing to our own server, unless... :-)
527
		global $wgServer, $wgRegisterInternalExternals;
528
529
		$registerExternalLink = true;
530
		if ( !$wgRegisterInternalExternals ) {
531
			$registerExternalLink = !self::isLinkInternal( $wgServer, $url );
532
		}
533
		if ( $registerExternalLink ) {
534
			$this->mExternalLinks[$url] = 1;
535
		}
536
	}
537
538
	/**
539
	 * Record a local or interwiki inline link for saving in future link tables.
540
	 *
541
	 * @param Title $title
542
	 * @param int|null $id Optional known page_id so we can skip the lookup
543
	 */
544
	public function addLink( Title $title, $id = null ) {
545
		if ( $title->isExternal() ) {
546
			// Don't record interwikis in pagelinks
547
			$this->addInterwikiLink( $title );
548
			return;
549
		}
550
		$ns = $title->getNamespace();
551
		$dbk = $title->getDBkey();
552
		if ( $ns == NS_MEDIA ) {
553
			// Normalize this pseudo-alias if it makes it down here...
554
			$ns = NS_FILE;
555
		} elseif ( $ns == NS_SPECIAL ) {
556
			// We don't record Special: links currently
557
			// It might actually be wise to, but we'd need to do some normalization.
558
			return;
559
		} elseif ( $dbk === '' ) {
560
			// Don't record self links -  [[#Foo]]
561
			return;
562
		}
563
		if ( !isset( $this->mLinks[$ns] ) ) {
564
			$this->mLinks[$ns] = [];
565
		}
566
		if ( is_null( $id ) ) {
567
			$id = $title->getArticleID();
568
		}
569
		$this->mLinks[$ns][$dbk] = $id;
570
	}
571
572
	/**
573
	 * Register a file dependency for this output
574
	 * @param string $name Title dbKey
575
	 * @param string $timestamp MW timestamp of file creation (or false if non-existing)
576
	 * @param string $sha1 Base 36 SHA-1 of file (or false if non-existing)
577
	 * @return void
578
	 */
579
	public function addImage( $name, $timestamp = null, $sha1 = null ) {
580
		$this->mImages[$name] = 1;
581
		if ( $timestamp !== null && $sha1 !== null ) {
582
			$this->mFileSearchOptions[$name] = [ 'time' => $timestamp, 'sha1' => $sha1 ];
583
		}
584
	}
585
586
	/**
587
	 * Register a template dependency for this output
588
	 * @param Title $title
589
	 * @param int $page_id
590
	 * @param int $rev_id
591
	 * @return void
592
	 */
593
	public function addTemplate( $title, $page_id, $rev_id ) {
594
		$ns = $title->getNamespace();
595
		$dbk = $title->getDBkey();
596
		if ( !isset( $this->mTemplates[$ns] ) ) {
597
			$this->mTemplates[$ns] = [];
598
		}
599
		$this->mTemplates[$ns][$dbk] = $page_id;
600
		if ( !isset( $this->mTemplateIds[$ns] ) ) {
601
			$this->mTemplateIds[$ns] = [];
602
		}
603
		$this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
604
	}
605
606
	/**
607
	 * @param Title $title Title object, must be an interwiki link
608
	 * @throws MWException If given invalid input
609
	 */
610
	public function addInterwikiLink( $title ) {
611
		if ( !$title->isExternal() ) {
612
			throw new MWException( 'Non-interwiki link passed, internal parser error.' );
613
		}
614
		$prefix = $title->getInterwiki();
615
		if ( !isset( $this->mInterwikiLinks[$prefix] ) ) {
616
			$this->mInterwikiLinks[$prefix] = [];
617
		}
618
		$this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
619
	}
620
621
	/**
622
	 * Add some text to the "<head>".
623
	 * If $tag is set, the section with that tag will only be included once
624
	 * in a given page.
625
	 * @param string $section
626
	 * @param string|bool $tag
627
	 */
628
	public function addHeadItem( $section, $tag = false ) {
629
		if ( $tag !== false ) {
630
			$this->mHeadItems[$tag] = $section;
631
		} else {
632
			$this->mHeadItems[] = $section;
633
		}
634
	}
635
636
	public function addModules( $modules ) {
637
		$this->mModules = array_merge( $this->mModules, (array)$modules );
638
	}
639
640
	public function addModuleScripts( $modules ) {
641
		$this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
642
	}
643
644
	public function addModuleStyles( $modules ) {
645
		$this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
646
	}
647
648
	/**
649
	 * Add one or more variables to be set in mw.config in JavaScript.
650
	 *
651
	 * @param string|array $keys Key or array of key/value pairs.
652
	 * @param mixed $value [optional] Value of the configuration variable.
653
	 * @since 1.23
654
	 */
655 View Code Duplication
	public function addJsConfigVars( $keys, $value = null ) {
656
		if ( is_array( $keys ) ) {
657
			foreach ( $keys as $key => $value ) {
658
				$this->mJsConfigVars[$key] = $value;
659
			}
660
			return;
661
		}
662
663
		$this->mJsConfigVars[$keys] = $value;
664
	}
665
666
	/**
667
	 * Copy items from the OutputPage object into this one
668
	 *
669
	 * @param OutputPage $out
670
	 */
671
	public function addOutputPageMetadata( OutputPage $out ) {
672
		$this->addModules( $out->getModules() );
673
		$this->addModuleScripts( $out->getModuleScripts() );
674
		$this->addModuleStyles( $out->getModuleStyles() );
675
		$this->addJsConfigVars( $out->getJsConfigVars() );
676
677
		$this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
678
		$this->mPreventClickjacking = $this->mPreventClickjacking || $out->getPreventClickjacking();
679
	}
680
681
	/**
682
	 * Add a tracking category, getting the title from a system message,
683
	 * or print a debug message if the title is invalid.
684
	 *
685
	 * Any message used with this function should be registered so it will
686
	 * show up on Special:TrackingCategories. Core messages should be added
687
	 * to SpecialTrackingCategories::$coreTrackingCategories, and extensions
688
	 * should add to "TrackingCategories" in their extension.json.
689
	 *
690
	 * @param string $msg Message key
691
	 * @param Title $title title of the page which is being tracked
692
	 * @return bool Whether the addition was successful
693
	 * @since 1.25
694
	 */
695
	public function addTrackingCategory( $msg, $title ) {
696
		if ( $title->getNamespace() === NS_SPECIAL ) {
697
			wfDebug( __METHOD__ . ": Not adding tracking category $msg to special page!\n" );
698
			return false;
699
		}
700
701
		// Important to parse with correct title (bug 31469)
702
		$cat = wfMessage( $msg )
703
			->title( $title )
704
			->inContentLanguage()
705
			->text();
706
707
		# Allow tracking categories to be disabled by setting them to "-"
708
		if ( $cat === '-' ) {
709
			return false;
710
		}
711
712
		$containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
713
		if ( $containerCategory ) {
714
			$this->addCategory( $containerCategory->getDBkey(), $this->getProperty( 'defaultsort' ) ?: '' );
715
			return true;
716
		} else {
717
			wfDebug( __METHOD__ . ": [[MediaWiki:$msg]] is not a valid title!\n" );
718
			return false;
719
		}
720
	}
721
722
	/**
723
	 * Override the title to be used for display
724
	 *
725
	 * @note this is assumed to have been validated
726
	 * (check equal normalisation, etc.)
727
	 *
728
	 * @note this is expected to be safe HTML,
729
	 * ready to be served to the client.
730
	 *
731
	 * @param string $text Desired title text
732
	 */
733
	public function setDisplayTitle( $text ) {
734
		$this->setTitleText( $text );
735
		$this->setProperty( 'displaytitle', $text );
736
	}
737
738
	/**
739
	 * Get the title to be used for display.
740
	 *
741
	 * As per the contract of setDisplayTitle(), this is safe HTML,
742
	 * ready to be served to the client.
743
	 *
744
	 * @return string HTML
745
	 */
746
	public function getDisplayTitle() {
747
		$t = $this->getTitleText();
748
		if ( $t === '' ) {
749
			return false;
750
		}
751
		return $t;
752
	}
753
754
	/**
755
	 * Fairly generic flag setter thingy.
756
	 * @param string $flag
757
	 */
758
	public function setFlag( $flag ) {
759
		$this->mFlags[$flag] = true;
760
	}
761
762
	public function getFlag( $flag ) {
763
		return isset( $this->mFlags[$flag] );
764
	}
765
766
	/**
767
	 * Set a property to be stored in the page_props database table.
768
	 *
769
	 * page_props is a key value store indexed by the page ID. This allows
770
	 * the parser to set a property on a page which can then be quickly
771
	 * retrieved given the page ID or via a DB join when given the page
772
	 * title.
773
	 *
774
	 * Since 1.23, page_props are also indexed by numeric value, to allow
775
	 * for efficient "top k" queries of pages wrt a given property.
776
	 *
777
	 * setProperty() is thus used to propagate properties from the parsed
778
	 * page to request contexts other than a page view of the currently parsed
779
	 * article.
780
	 *
781
	 * Some applications examples:
782
	 *
783
	 *   * To implement hidden categories, hiding pages from category listings
784
	 *     by storing a property.
785
	 *
786
	 *   * Overriding the displayed article title.
787
	 *   @see ParserOutput::setDisplayTitle()
788
	 *
789
	 *   * To implement image tagging, for example displaying an icon on an
790
	 *     image thumbnail to indicate that it is listed for deletion on
791
	 *     Wikimedia Commons.
792
	 *     This is not actually implemented, yet but would be pretty cool.
793
	 *
794
	 * @note Do not use setProperty() to set a property which is only used
795
	 * in a context where the ParserOutput object itself is already available,
796
	 * for example a normal page view. There is no need to save such a property
797
	 * in the database since the text is already parsed. You can just hook
798
	 * OutputPageParserOutput and get your data out of the ParserOutput object.
799
	 *
800
	 * If you are writing an extension where you want to set a property in the
801
	 * parser which is used by an OutputPageParserOutput hook, you have to
802
	 * associate the extension data directly with the ParserOutput object.
803
	 * Since MediaWiki 1.21, you can use setExtensionData() to do this:
804
	 *
805
	 * @par Example:
806
	 * @code
807
	 *    $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
808
	 * @endcode
809
	 *
810
	 * And then later, in OutputPageParserOutput or similar:
811
	 *
812
	 * @par Example:
813
	 * @code
814
	 *    $output->getExtensionData( 'my_ext_foo' );
815
	 * @endcode
816
	 *
817
	 * In MediaWiki 1.20 and older, you have to use a custom member variable
818
	 * within the ParserOutput object:
819
	 *
820
	 * @par Example:
821
	 * @code
822
	 *    $parser->getOutput()->my_ext_foo = '...';
823
	 * @endcode
824
	 *
825
	 */
826
	public function setProperty( $name, $value ) {
827
		$this->mProperties[$name] = $value;
828
	}
829
830
	/**
831
	 * @param string $name The property name to look up.
832
	 *
833
	 * @return mixed|bool The value previously set using setProperty(). False if null or no value
834
	 * was set for the given property name.
835
	 *
836
	 * @note You need to use getProperties() to check for boolean and null properties.
837
	 */
838
	public function getProperty( $name ) {
839
		return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
840
	}
841
842
	public function unsetProperty( $name ) {
843
		unset( $this->mProperties[$name] );
844
	}
845
846
	public function getProperties() {
847
		if ( !isset( $this->mProperties ) ) {
848
			$this->mProperties = [];
849
		}
850
		return $this->mProperties;
851
	}
852
853
	/**
854
	 * Returns the options from its ParserOptions which have been taken
855
	 * into account to produce this output or false if not available.
856
	 * @return array
857
	 */
858
	public function getUsedOptions() {
859
		if ( !isset( $this->mAccessedOptions ) ) {
860
			return [];
861
		}
862
		return array_keys( $this->mAccessedOptions );
863
	}
864
865
	/**
866
	 * Tags a parser option for use in the cache key for this parser output.
867
	 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
868
	 * The information gathered here is available via getUsedOptions(),
869
	 * and is used by ParserCache::save().
870
	 *
871
	 * @see ParserCache::getKey
872
	 * @see ParserCache::save
873
	 * @see ParserOptions::addExtraKey
874
	 * @see ParserOptions::optionsHash
875
	 * @param string $option
876
	 */
877
	public function recordOption( $option ) {
878
		$this->mAccessedOptions[$option] = true;
879
	}
880
881
	/**
882
	 * Attaches arbitrary data to this ParserObject. This can be used to store some information in
883
	 * the ParserOutput object for later use during page output. The data will be cached along with
884
	 * the ParserOutput object, but unlike data set using setProperty(), it is not recorded in the
885
	 * database.
886
	 *
887
	 * This method is provided to overcome the unsafe practice of attaching extra information to a
888
	 * ParserObject by directly assigning member variables.
889
	 *
890
	 * To use setExtensionData() to pass extension information from a hook inside the parser to a
891
	 * hook in the page output, use this in the parser hook:
892
	 *
893
	 * @par Example:
894
	 * @code
895
	 *    $parser->getOutput()->setExtensionData( 'my_ext_foo', '...' );
896
	 * @endcode
897
	 *
898
	 * And then later, in OutputPageParserOutput or similar:
899
	 *
900
	 * @par Example:
901
	 * @code
902
	 *    $output->getExtensionData( 'my_ext_foo' );
903
	 * @endcode
904
	 *
905
	 * In MediaWiki 1.20 and older, you have to use a custom member variable
906
	 * within the ParserOutput object:
907
	 *
908
	 * @par Example:
909
	 * @code
910
	 *    $parser->getOutput()->my_ext_foo = '...';
911
	 * @endcode
912
	 *
913
	 * @since 1.21
914
	 *
915
	 * @param string $key The key for accessing the data. Extensions should take care to avoid
916
	 *   conflicts in naming keys. It is suggested to use the extension's name as a prefix.
917
	 *
918
	 * @param mixed $value The value to set. Setting a value to null is equivalent to removing
919
	 *   the value.
920
	 */
921
	public function setExtensionData( $key, $value ) {
922
		if ( $value === null ) {
923
			unset( $this->mExtensionData[$key] );
924
		} else {
925
			$this->mExtensionData[$key] = $value;
926
		}
927
	}
928
929
	/**
930
	 * Gets extensions data previously attached to this ParserOutput using setExtensionData().
931
	 * Typically, such data would be set while parsing the page, e.g. by a parser function.
932
	 *
933
	 * @since 1.21
934
	 *
935
	 * @param string $key The key to look up.
936
	 *
937
	 * @return mixed|null The value previously set for the given key using setExtensionData()
938
	 *         or null if no value was set for this key.
939
	 */
940
	public function getExtensionData( $key ) {
941
		if ( isset( $this->mExtensionData[$key] ) ) {
942
			return $this->mExtensionData[$key];
943
		}
944
945
		return null;
946
	}
947
948
	private static function getTimes( $clock = null ) {
949
		$ret = [];
950
		if ( !$clock || $clock === 'wall' ) {
951
			$ret['wall'] = microtime( true );
952
		}
953
		if ( !$clock || $clock === 'cpu' ) {
954
			$ru = wfGetRusage();
955
			if ( $ru ) {
956
				$ret['cpu'] = $ru['ru_utime.tv_sec'] + $ru['ru_utime.tv_usec'] / 1e6;
957
				$ret['cpu'] += $ru['ru_stime.tv_sec'] + $ru['ru_stime.tv_usec'] / 1e6;
958
			}
959
		}
960
		return $ret;
961
	}
962
963
	/**
964
	 * Resets the parse start timestamps for future calls to getTimeSinceStart()
965
	 * @since 1.22
966
	 */
967
	public function resetParseStartTime() {
968
		$this->mParseStartTime = self::getTimes();
969
	}
970
971
	/**
972
	 * Returns the time since resetParseStartTime() was last called
973
	 *
974
	 * Clocks available are:
975
	 *  - wall: Wall clock time
976
	 *  - cpu: CPU time (requires getrusage)
977
	 *
978
	 * @since 1.22
979
	 * @param string $clock
980
	 * @return float|null
981
	 */
982
	public function getTimeSinceStart( $clock ) {
983
		if ( !isset( $this->mParseStartTime[$clock] ) ) {
984
			return null;
985
		}
986
987
		$end = self::getTimes( $clock );
988
		return $end[$clock] - $this->mParseStartTime[$clock];
989
	}
990
991
	/**
992
	 * Sets parser limit report data for a key
993
	 *
994
	 * If $value consist of a list of two floats, it will be interpreted as
995
	 * (actual value, maximum allowed value). The presence of a "-" in $key will cause
996
	 * the first part of the key to be interpreted as a namespace.
997
	 *
998
	 * @since 1.22
999
	 * @param string $key Data key
1000
	 * @param mixed $value Data value One of (float, string, bool, JSON serializable array)
1001
	 */
1002
	public function setLimitReportData( $key, $value ) {
1003
		if ( is_array( $value ) ) {
1004
			if ( array_keys( $value ) === [ 0, 1 ]
1005
				&& is_numeric( $value[0] )
1006
				&& is_numeric( $value[1] )
1007
			) {
1008
				$data = [ 'value' => $value[0], 'limit' => $value[1] ];
1009
			} else {
1010
				$data = $value;
1011
			}
1012
		} else {
1013
			$data = $value;
1014
		}
1015
1016
		if ( strpos( $key, '-' ) ) {
1017
			list( $ns, $name ) = explode( '-', $key, 2 );
1018
			$this->mLimitReportData[$ns][$name] = $data;
1019
		} else {
1020
			$this->mLimitReportData[$key] = $data;
1021
		}
1022
	}
1023
1024
	/**
1025
	 * Check whether the cache TTL was lowered due to dynamic content
1026
	 *
1027
	 * When content is determined by more than hard state (e.g. page edits),
1028
	 * such as template/file transclusions based on the current timestamp or
1029
	 * extension tags that generate lists based on queries, this return true.
1030
	 *
1031
	 * @return bool
1032
	 * @since 1.25
1033
	 */
1034
	public function hasDynamicContent() {
1035
		global $wgParserCacheExpireTime;
1036
1037
		return $this->getCacheExpiry() < $wgParserCacheExpireTime;
1038
	}
1039
1040
	/**
1041
	 * Get or set the prevent-clickjacking flag
1042
	 *
1043
	 * @since 1.24
1044
	 * @param bool|null $flag New flag value, or null to leave it unchanged
1045
	 * @return bool Old flag value
1046
	 */
1047
	public function preventClickjacking( $flag = null ) {
1048
		return wfSetVar( $this->mPreventClickjacking, $flag );
1049
	}
1050
1051
	/**
1052
	 * Lower the runtime adaptive TTL to at most this value
1053
	 *
1054
	 * @param integer $ttl
1055
	 * @since 1.28
1056
	 */
1057
	public function updateRuntimeAdaptiveExpiry( $ttl ) {
1058
		$this->mMaxAdaptiveExpiry = min( $ttl, $this->mMaxAdaptiveExpiry );
1059
		$this->updateCacheExpiry( $ttl );
1060
	}
1061
1062
	/**
1063
	 * Call this when parsing is done to lower the TTL based on low parse times
1064
	 *
1065
	 * @since 1.28
1066
	 */
1067
	public function finalizeAdaptiveCacheExpiry() {
1068
		if ( is_infinite( $this->mMaxAdaptiveExpiry ) ) {
1069
			return; // not set
1070
		}
1071
1072
		$runtime = $this->getTimeSinceStart( 'wall' );
1073
		if ( is_float( $runtime ) ) {
1074
			$slope = ( self::SLOW_AR_TTL - self::FAST_AR_TTL )
1075
				/ ( self::PARSE_SLOW_SEC - self::PARSE_FAST_SEC );
1076
			// SLOW_AR_TTL = PARSE_SLOW_SEC * $slope + $point
1077
			$point = self::SLOW_AR_TTL - self::PARSE_SLOW_SEC * $slope;
1078
1079
			$adaptiveTTL = min(
1080
				max( $slope * $runtime + $point, self::MIN_AR_TTL ),
1081
				$this->mMaxAdaptiveExpiry
1082
			);
1083
			$this->updateCacheExpiry( $adaptiveTTL );
1084
		}
1085
	}
1086
1087
	public function __sleep() {
1088
		return array_diff(
1089
			array_keys( get_object_vars( $this ) ),
1090
			[ 'mParseStartTime' ]
1091
		);
1092
	}
1093
}
1094