Completed
Branch master (1655eb)
by
unknown
22:24
created

ParserOutput   F

Complexity

Total Complexity 129

Size/Duplication

Total Lines 1062
Duplicated Lines 0.94 %

Coupling/Cohesion

Components 22
Dependencies 5

Importance

Changes 0
Metric Value
dl 10
loc 1062
rs 0.7244
c 0
b 0
f 0
wmc 129
lcom 22
cbo 5

87 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A getRawText() 0 3 1
B getText() 0 40 6
A setSpeculativeRevIdUsed() 0 3 1
A getSpeculativeRevIdUsed() 0 3 1
A getLanguageLinks() 0 3 1
A getInterwikiLinks() 0 3 1
A getCategoryLinks() 0 3 1
A getCategories() 0 3 1
A getIndicators() 0 3 1
A getTitleText() 0 3 1
A getSections() 0 3 1
A getEditSectionTokens() 0 3 1
A getLinks() 0 3 1
A getTemplates() 0 3 1
A getTemplateIds() 0 3 1
A getImages() 0 3 1
A getFileSearchOptions() 0 3 1
A getExternalLinks() 0 3 1
A getNoGallery() 0 3 1
A getHeadItems() 0 3 1
A getModules() 0 3 1
A getModuleScripts() 0 3 1
A getModuleStyles() 0 3 1
A getJsConfigVars() 0 3 1
A getOutputHooks() 0 3 1
A getWarnings() 0 3 1
A getIndexPolicy() 0 3 1
A getTOCHTML() 0 3 1
A getTimestamp() 0 3 1
A getLimitReportData() 0 3 1
A getTOCEnabled() 0 3 1
A getEnableOOUI() 0 3 1
A setText() 0 3 1
A setLanguageLinks() 0 3 1
A setCategoryLinks() 0 3 1
A setTitleText() 0 3 1
A setSections() 0 3 1
A setEditSectionTokens() 0 3 1
A setIndexPolicy() 0 3 1
A setTOCHTML() 0 3 1
A setTimestamp() 0 3 1
A setTOCEnabled() 0 3 1
A addCategory() 0 3 1
A setIndicator() 0 3 1
A setEnableOOUI() 0 3 1
A addLanguageLink() 0 3 1
A addWarning() 0 3 1
A addOutputHook() 0 3 1
A setNewSection() 0 3 1
A hideNewSection() 0 3 1
A getHideNewSection() 0 3 1
A getNewSection() 0 3 1
A isLinkInternal() 0 10 2
A addExternalLink() 0 12 3
C addLink() 0 27 7
A addImage() 0 6 3
A addTemplate() 0 12 3
A addInterwikiLink() 0 10 3
A addHeadItem() 0 7 2
A addModules() 0 3 1
A addModuleScripts() 0 3 1
A addModuleStyles() 0 3 1
A addJsConfigVars() 10 10 3
A addOutputPageMetadata() 0 9 2
B addTrackingCategory() 0 26 5
A setDisplayTitle() 0 4 1
A getDisplayTitle() 0 7 2
A setFlag() 0 3 1
A getFlag() 0 3 1
A setProperty() 0 3 1
A getProperty() 0 3 2
A unsetProperty() 0 3 1
A getProperties() 0 6 2
A getUsedOptions() 0 6 2
A recordOption() 0 3 1
A setExtensionData() 0 7 2
A getExtensionData() 0 7 2
B getTimes() 0 14 6
A resetParseStartTime() 0 3 1
A getTimeSinceStart() 0 8 2
A setLimitReportData() 0 3 1
A hasDynamicContent() 0 5 1
A preventClickjacking() 0 3 1
A updateRuntimeAdaptiveExpiry() 0 4 1
A finalizeAdaptiveCacheExpiry() 0 19 3
A __sleep() 0 6 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ParserOutput often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ParserOutput, and based on these observations, apply Extract Interface, too.

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