Completed
Branch master (9259dd)
by
unknown
27:26
created

ParserOutput   F

Complexity

Total Complexity 125

Size/Duplication

Total Lines 1019
Duplicated Lines 0.98 %

Coupling/Cohesion

Components 22
Dependencies 5

Importance

Changes 0
Metric Value
dl 10
loc 1019
rs 0.9502
c 0
b 0
f 0
wmc 125
lcom 22
cbo 5

85 Methods

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