CSP: Allow an option of disabling nonces
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 /**
3 * Preparation for the final page rendering.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\Linker\LinkTarget;
24 use MediaWiki\Logger\LoggerFactory;
25 use MediaWiki\MediaWikiServices;
26 use MediaWiki\Session\SessionManager;
27 use Wikimedia\Rdbms\IResultWrapper;
28 use Wikimedia\RelPath;
29 use Wikimedia\WrappedString;
30 use Wikimedia\WrappedStringList;
31
32 /**
33 * This class should be covered by a general architecture document which does
34 * not exist as of January 2011. This is one of the Core classes and should
35 * be read at least once by any new developers.
36 *
37 * This class is used to prepare the final rendering. A skin is then
38 * applied to the output parameters (links, javascript, html, categories ...).
39 *
40 * @todo FIXME: Another class handles sending the whole page to the client.
41 *
42 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
43 * in November 2010.
44 *
45 * @todo document
46 */
47 class OutputPage extends ContextSource {
48 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
49 protected $mMetatags = [];
50
51 /** @var array */
52 protected $mLinktags = [];
53
54 /** @var bool */
55 protected $mCanonicalUrl = false;
56
57 /**
58 * @var string Should be private - has getter and setter. Contains
59 * the HTML title */
60 public $mPagetitle = '';
61
62 /**
63 * @var string Contains all of the "<body>" content. Should be private we
64 * got set/get accessors and the append() method.
65 */
66 public $mBodytext = '';
67
68 /** @var string Stores contents of "<title>" tag */
69 private $mHTMLtitle = '';
70
71 /**
72 * @var bool Is the displayed content related to the source of the
73 * corresponding wiki article.
74 */
75 private $mIsarticle = false;
76
77 /** @var bool Stores "article flag" toggle. */
78 private $mIsArticleRelated = true;
79
80 /**
81 * @var bool We have to set isPrintable(). Some pages should
82 * never be printed (ex: redirections).
83 */
84 private $mPrintable = false;
85
86 /**
87 * @var array Contains the page subtitle. Special pages usually have some
88 * links here. Don't confuse with site subtitle added by skins.
89 */
90 private $mSubtitle = [];
91
92 /** @var string */
93 public $mRedirect = '';
94
95 /** @var int */
96 protected $mStatusCode;
97
98 /**
99 * @var string Used for sending cache control.
100 * The whole caching system should probably be moved into its own class.
101 */
102 protected $mLastModified = '';
103
104 /** @var array */
105 protected $mCategoryLinks = [];
106
107 /** @var array */
108 protected $mCategories = [
109 'hidden' => [],
110 'normal' => [],
111 ];
112
113 /** @var array */
114 protected $mIndicators = [];
115
116 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
117 private $mLanguageLinks = [];
118
119 /**
120 * Used for JavaScript (predates ResourceLoader)
121 * @todo We should split JS / CSS.
122 * mScripts content is inserted as is in "<head>" by Skin. This might
123 * contain either a link to a stylesheet or inline CSS.
124 */
125 private $mScripts = '';
126
127 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
128 protected $mInlineStyles = '';
129
130 /**
131 * @var string Used by skin template.
132 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
133 */
134 public $mPageLinkTitle = '';
135
136 /** @var array Array of elements in "<head>". Parser might add its own headers! */
137 protected $mHeadItems = [];
138
139 /** @var array Additional <body> classes; there are also <body> classes from other sources */
140 protected $mAdditionalBodyClasses = [];
141
142 /** @var array */
143 protected $mModules = [];
144
145 /** @var array */
146 protected $mModuleScripts = [];
147
148 /** @var array */
149 protected $mModuleStyles = [];
150
151 /** @var ResourceLoader */
152 protected $mResourceLoader;
153
154 /** @var ResourceLoaderClientHtml */
155 private $rlClient;
156
157 /** @var ResourceLoaderContext */
158 private $rlClientContext;
159
160 /** @var array */
161 private $rlExemptStyleModules;
162
163 /** @var array */
164 protected $mJsConfigVars = [];
165
166 /** @var array */
167 protected $mTemplateIds = [];
168
169 /** @var array */
170 protected $mImageTimeKeys = [];
171
172 /** @var string */
173 public $mRedirectCode = '';
174
175 protected $mFeedLinksAppendQuery = null;
176
177 /** @var array
178 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
179 * @see ResourceLoaderModule::$origin
180 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
181 */
182 protected $mAllowedModules = [
183 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
184 ];
185
186 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
187 protected $mDoNothing = false;
188
189 // Parser related.
190
191 /** @var int */
192 protected $mContainsNewMagic = 0;
193
194 /**
195 * lazy initialised, use parserOptions()
196 * @var ParserOptions
197 */
198 protected $mParserOptions = null;
199
200 /**
201 * Handles the Atom / RSS links.
202 * We probably only support Atom in 2011.
203 * @see $wgAdvertisedFeedTypes
204 */
205 private $mFeedLinks = [];
206
207 // Gwicke work on squid caching? Roughly from 2003.
208 protected $mEnableClientCache = true;
209
210 /** @var bool Flag if output should only contain the body of the article. */
211 private $mArticleBodyOnly = false;
212
213 /** @var bool */
214 protected $mNewSectionLink = false;
215
216 /** @var bool */
217 protected $mHideNewSectionLink = false;
218
219 /**
220 * @var bool Comes from the parser. This was probably made to load CSS/JS
221 * only if we had "<gallery>". Used directly in CategoryPage.php.
222 * Looks like ResourceLoader can replace this.
223 */
224 public $mNoGallery = false;
225
226 /** @var string */
227 private $mPageTitleActionText = '';
228
229 /** @var int Cache stuff. Looks like mEnableClientCache */
230 protected $mCdnMaxage = 0;
231 /** @var int Upper limit on mCdnMaxage */
232 protected $mCdnMaxageLimit = INF;
233
234 /**
235 * @var bool Controls if anti-clickjacking / frame-breaking headers will
236 * be sent. This should be done for pages where edit actions are possible.
237 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
238 */
239 protected $mPreventClickjacking = true;
240
241 /** @var int To include the variable {{REVISIONID}} */
242 private $mRevisionId = null;
243
244 /** @var string */
245 private $mRevisionTimestamp = null;
246
247 /** @var array */
248 protected $mFileVersion = null;
249
250 /**
251 * @var array An array of stylesheet filenames (relative from skins path),
252 * with options for CSS media, IE conditions, and RTL/LTR direction.
253 * For internal use; add settings in the skin via $this->addStyle()
254 *
255 * Style again! This seems like a code duplication since we already have
256 * mStyles. This is what makes Open Source amazing.
257 */
258 protected $styles = [];
259
260 private $mIndexPolicy = 'index';
261 private $mFollowPolicy = 'follow';
262 private $mVaryHeader = [
263 'Accept-Encoding' => [ 'match=gzip' ],
264 ];
265
266 /**
267 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
268 * of the redirect.
269 *
270 * @var Title
271 */
272 private $mRedirectedFrom = null;
273
274 /**
275 * Additional key => value data
276 */
277 private $mProperties = [];
278
279 /**
280 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
281 */
282 private $mTarget = null;
283
284 /**
285 * @var bool Whether parser output contains a table of contents
286 */
287 private $mEnableTOC = false;
288
289 /**
290 * @var string|null The URL to send in a <link> element with rel=license
291 */
292 private $copyrightUrl;
293
294 /** @var array Profiling data */
295 private $limitReportJSData = [];
296
297 /** @var array Map Title to Content */
298 private $contentOverrides = [];
299
300 /** @var callable[] */
301 private $contentOverrideCallbacks = [];
302
303 /**
304 * Link: header contents
305 */
306 private $mLinkHeader = [];
307
308 /**
309 * @var string The nonce for Content-Security-Policy
310 */
311 private $CSPNonce;
312
313 /**
314 * Constructor for OutputPage. This should not be called directly.
315 * Instead a new RequestContext should be created and it will implicitly create
316 * a OutputPage tied to that context.
317 * @param IContextSource $context
318 */
319 function __construct( IContextSource $context ) {
320 $this->setContext( $context );
321 }
322
323 /**
324 * Redirect to $url rather than displaying the normal page
325 *
326 * @param string $url
327 * @param string $responsecode HTTP status code
328 */
329 public function redirect( $url, $responsecode = '302' ) {
330 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
331 $this->mRedirect = str_replace( "\n", '', $url );
332 $this->mRedirectCode = $responsecode;
333 }
334
335 /**
336 * Get the URL to redirect to, or an empty string if not redirect URL set
337 *
338 * @return string
339 */
340 public function getRedirect() {
341 return $this->mRedirect;
342 }
343
344 /**
345 * Set the copyright URL to send with the output.
346 * Empty string to omit, null to reset.
347 *
348 * @since 1.26
349 *
350 * @param string|null $url
351 */
352 public function setCopyrightUrl( $url ) {
353 $this->copyrightUrl = $url;
354 }
355
356 /**
357 * Set the HTTP status code to send with the output.
358 *
359 * @param int $statusCode
360 */
361 public function setStatusCode( $statusCode ) {
362 $this->mStatusCode = $statusCode;
363 }
364
365 /**
366 * Add a new "<meta>" tag
367 * To add an http-equiv meta tag, precede the name with "http:"
368 *
369 * @param string $name Name of the meta tag
370 * @param string $val Value of the meta tag
371 */
372 function addMeta( $name, $val ) {
373 array_push( $this->mMetatags, [ $name, $val ] );
374 }
375
376 /**
377 * Returns the current <meta> tags
378 *
379 * @since 1.25
380 * @return array
381 */
382 public function getMetaTags() {
383 return $this->mMetatags;
384 }
385
386 /**
387 * Add a new \<link\> tag to the page header.
388 *
389 * Note: use setCanonicalUrl() for rel=canonical.
390 *
391 * @param array $linkarr Associative array of attributes.
392 */
393 function addLink( array $linkarr ) {
394 array_push( $this->mLinktags, $linkarr );
395 }
396
397 /**
398 * Returns the current <link> tags
399 *
400 * @since 1.25
401 * @return array
402 */
403 public function getLinkTags() {
404 return $this->mLinktags;
405 }
406
407 /**
408 * Add a new \<link\> with "rel" attribute set to "meta"
409 *
410 * @param array $linkarr Associative array mapping attribute names to their
411 * values, both keys and values will be escaped, and the
412 * "rel" attribute will be automatically added
413 */
414 function addMetadataLink( array $linkarr ) {
415 $linkarr['rel'] = $this->getMetadataAttribute();
416 $this->addLink( $linkarr );
417 }
418
419 /**
420 * Set the URL to be used for the <link rel=canonical>. This should be used
421 * in preference to addLink(), to avoid duplicate link tags.
422 * @param string $url
423 */
424 function setCanonicalUrl( $url ) {
425 $this->mCanonicalUrl = $url;
426 }
427
428 /**
429 * Returns the URL to be used for the <link rel=canonical> if
430 * one is set.
431 *
432 * @since 1.25
433 * @return bool|string
434 */
435 public function getCanonicalUrl() {
436 return $this->mCanonicalUrl;
437 }
438
439 /**
440 * Get the value of the "rel" attribute for metadata links
441 *
442 * @return string
443 */
444 public function getMetadataAttribute() {
445 # note: buggy CC software only reads first "meta" link
446 static $haveMeta = false;
447 if ( $haveMeta ) {
448 return 'alternate meta';
449 } else {
450 $haveMeta = true;
451 return 'meta';
452 }
453 }
454
455 /**
456 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
457 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
458 * if possible.
459 *
460 * @param string $script Raw HTML
461 */
462 function addScript( $script ) {
463 $this->mScripts .= $script;
464 }
465
466 /**
467 * Add a JavaScript file to be loaded as `<script>` on this page.
468 *
469 * Internal use only. Use OutputPage::addModules() if possible.
470 *
471 * @param string $file URL to file (absolute path, protocol-relative, or full url)
472 * @param string|null $unused Previously used to change the cache-busting query parameter
473 */
474 public function addScriptFile( $file, $unused = null ) {
475 if ( substr( $file, 0, 1 ) !== '/' && !preg_match( '#^[a-z]*://#i', $file ) ) {
476 // This is not an absolute path, protocol-relative url, or full scheme url,
477 // presumed to be an old call intended to include a file from /w/skins/common,
478 // which doesn't exist anymore as of MediaWiki 1.24 per T71277. Ignore.
479 wfDeprecated( __METHOD__, '1.24' );
480 return;
481 }
482 $this->addScript( Html::linkedScript( $file, $this->getCSPNonce() ) );
483 }
484
485 /**
486 * Add a self-contained script tag with the given contents
487 * Internal use only. Use OutputPage::addModules() if possible.
488 *
489 * @param string $script JavaScript text, no script tags
490 */
491 public function addInlineScript( $script ) {
492 $this->mScripts .= Html::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
493 }
494
495 /**
496 * Filter an array of modules to remove insufficiently trustworthy members, and modules
497 * which are no longer registered (eg a page is cached before an extension is disabled)
498 * @param array $modules
499 * @param string|null $position Unused
500 * @param string $type
501 * @return array
502 */
503 protected function filterModules( array $modules, $position = null,
504 $type = ResourceLoaderModule::TYPE_COMBINED
505 ) {
506 $resourceLoader = $this->getResourceLoader();
507 $filteredModules = [];
508 foreach ( $modules as $val ) {
509 $module = $resourceLoader->getModule( $val );
510 if ( $module instanceof ResourceLoaderModule
511 && $module->getOrigin() <= $this->getAllowedModules( $type )
512 ) {
513 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
514 $this->warnModuleTargetFilter( $module->getName() );
515 continue;
516 }
517 $filteredModules[] = $val;
518 }
519 }
520 return $filteredModules;
521 }
522
523 private function warnModuleTargetFilter( $moduleName ) {
524 static $warnings = [];
525 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
526 return;
527 }
528 $warnings[$this->mTarget][$moduleName] = true;
529 $this->getResourceLoader()->getLogger()->debug(
530 'Module "{module}" not loadable on target "{target}".',
531 [
532 'module' => $moduleName,
533 'target' => $this->mTarget,
534 ]
535 );
536 }
537
538 /**
539 * Get the list of modules to include on this page
540 *
541 * @param bool $filter Whether to filter out insufficiently trustworthy modules
542 * @param string|null $position Unused
543 * @param string $param
544 * @param string $type
545 * @return array Array of module names
546 */
547 public function getModules( $filter = false, $position = null, $param = 'mModules',
548 $type = ResourceLoaderModule::TYPE_COMBINED
549 ) {
550 $modules = array_values( array_unique( $this->$param ) );
551 return $filter
552 ? $this->filterModules( $modules, null, $type )
553 : $modules;
554 }
555
556 /**
557 * Load one or more ResourceLoader modules on this page.
558 *
559 * @param string|array $modules Module name (string) or array of module names
560 */
561 public function addModules( $modules ) {
562 $this->mModules = array_merge( $this->mModules, (array)$modules );
563 }
564
565 /**
566 * Get the list of script-only modules to load on this page.
567 *
568 * @param bool $filter
569 * @param string|null $position Unused
570 * @return array Array of module names
571 */
572 public function getModuleScripts( $filter = false, $position = null ) {
573 return $this->getModules( $filter, null, 'mModuleScripts',
574 ResourceLoaderModule::TYPE_SCRIPTS
575 );
576 }
577
578 /**
579 * Load the scripts of one or more ResourceLoader modules, on this page.
580 *
581 * This method exists purely to provide the legacy behaviour of loading
582 * a module's scripts in the global scope, and without dependency resolution.
583 * See <https://phabricator.wikimedia.org/T188689>.
584 *
585 * @deprecated since 1.31 Use addModules() instead.
586 * @param string|array $modules Module name (string) or array of module names
587 */
588 public function addModuleScripts( $modules ) {
589 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
590 }
591
592 /**
593 * Get the list of style-only modules to load on this page.
594 *
595 * @param bool $filter
596 * @param string|null $position Unused
597 * @return array Array of module names
598 */
599 public function getModuleStyles( $filter = false, $position = null ) {
600 return $this->getModules( $filter, null, 'mModuleStyles',
601 ResourceLoaderModule::TYPE_STYLES
602 );
603 }
604
605 /**
606 * Load the styles of one or more ResourceLoader modules on this page.
607 *
608 * Module styles added through this function will be loaded as a stylesheet,
609 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
610 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
611 *
612 * @param string|array $modules Module name (string) or array of module names
613 */
614 public function addModuleStyles( $modules ) {
615 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
616 }
617
618 /**
619 * @return null|string ResourceLoader target
620 */
621 public function getTarget() {
622 return $this->mTarget;
623 }
624
625 /**
626 * Sets ResourceLoader target for load.php links. If null, will be omitted
627 *
628 * @param string|null $target
629 */
630 public function setTarget( $target ) {
631 $this->mTarget = $target;
632 }
633
634 /**
635 * Add a mapping from a LinkTarget to a Content, for things like page preview.
636 * @see self::addContentOverrideCallback()
637 * @since 1.32
638 * @param LinkTarget $target
639 * @param Content $content
640 */
641 public function addContentOverride( LinkTarget $target, Content $content ) {
642 if ( !$this->contentOverrides ) {
643 // Register a callback for $this->contentOverrides on the first call
644 $this->addContentOverrideCallback( function ( LinkTarget $target ) {
645 $key = $target->getNamespace() . ':' . $target->getDBkey();
646 return $this->contentOverrides[$key] ?? null;
647 } );
648 }
649
650 $key = $target->getNamespace() . ':' . $target->getDBkey();
651 $this->contentOverrides[$key] = $content;
652 }
653
654 /**
655 * Add a callback for mapping from a Title to a Content object, for things
656 * like page preview.
657 * @see ResourceLoaderContext::getContentOverrideCallback()
658 * @since 1.32
659 * @param callable $callback
660 */
661 public function addContentOverrideCallback( callable $callback ) {
662 $this->contentOverrideCallbacks[] = $callback;
663 }
664
665 /**
666 * Get an array of head items
667 *
668 * @return array
669 */
670 function getHeadItemsArray() {
671 return $this->mHeadItems;
672 }
673
674 /**
675 * Add or replace a head item to the output
676 *
677 * Whenever possible, use more specific options like ResourceLoader modules,
678 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
679 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
680 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
681 * This would be your very LAST fallback.
682 *
683 * @param string $name Item name
684 * @param string $value Raw HTML
685 */
686 public function addHeadItem( $name, $value ) {
687 $this->mHeadItems[$name] = $value;
688 }
689
690 /**
691 * Add one or more head items to the output
692 *
693 * @since 1.28
694 * @param string|string[] $values Raw HTML
695 */
696 public function addHeadItems( $values ) {
697 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
698 }
699
700 /**
701 * Check if the header item $name is already set
702 *
703 * @param string $name Item name
704 * @return bool
705 */
706 public function hasHeadItem( $name ) {
707 return isset( $this->mHeadItems[$name] );
708 }
709
710 /**
711 * Add a class to the <body> element
712 *
713 * @since 1.30
714 * @param string|string[] $classes One or more classes to add
715 */
716 public function addBodyClasses( $classes ) {
717 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
718 }
719
720 /**
721 * Set whether the output should only contain the body of the article,
722 * without any skin, sidebar, etc.
723 * Used e.g. when calling with "action=render".
724 *
725 * @param bool $only Whether to output only the body of the article
726 */
727 public function setArticleBodyOnly( $only ) {
728 $this->mArticleBodyOnly = $only;
729 }
730
731 /**
732 * Return whether the output will contain only the body of the article
733 *
734 * @return bool
735 */
736 public function getArticleBodyOnly() {
737 return $this->mArticleBodyOnly;
738 }
739
740 /**
741 * Set an additional output property
742 * @since 1.21
743 *
744 * @param string $name
745 * @param mixed $value
746 */
747 public function setProperty( $name, $value ) {
748 $this->mProperties[$name] = $value;
749 }
750
751 /**
752 * Get an additional output property
753 * @since 1.21
754 *
755 * @param string $name
756 * @return mixed Property value or null if not found
757 */
758 public function getProperty( $name ) {
759 return $this->mProperties[$name] ?? null;
760 }
761
762 /**
763 * checkLastModified tells the client to use the client-cached page if
764 * possible. If successful, the OutputPage is disabled so that
765 * any future call to OutputPage->output() have no effect.
766 *
767 * Side effect: sets mLastModified for Last-Modified header
768 *
769 * @param string $timestamp
770 *
771 * @return bool True if cache-ok headers was sent.
772 */
773 public function checkLastModified( $timestamp ) {
774 if ( !$timestamp || $timestamp == '19700101000000' ) {
775 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
776 return false;
777 }
778 $config = $this->getConfig();
779 if ( !$config->get( 'CachePages' ) ) {
780 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
781 return false;
782 }
783
784 $timestamp = wfTimestamp( TS_MW, $timestamp );
785 $modifiedTimes = [
786 'page' => $timestamp,
787 'user' => $this->getUser()->getTouched(),
788 'epoch' => $config->get( 'CacheEpoch' )
789 ];
790 if ( $config->get( 'UseSquid' ) ) {
791 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
792 time(),
793 $config->get( 'SquidMaxage' )
794 ) );
795 }
796 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
797
798 $maxModified = max( $modifiedTimes );
799 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
800
801 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
802 if ( $clientHeader === false ) {
803 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
804 return false;
805 }
806
807 # IE sends sizes after the date like this:
808 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
809 # this breaks strtotime().
810 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
811
812 Wikimedia\suppressWarnings(); // E_STRICT system time bitching
813 $clientHeaderTime = strtotime( $clientHeader );
814 Wikimedia\restoreWarnings();
815 if ( !$clientHeaderTime ) {
816 wfDebug( __METHOD__
817 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
818 return false;
819 }
820 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
821
822 # Make debug info
823 $info = '';
824 foreach ( $modifiedTimes as $name => $value ) {
825 if ( $info !== '' ) {
826 $info .= ', ';
827 }
828 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
829 }
830
831 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
832 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
833 wfDebug( __METHOD__ . ": effective Last-Modified: " .
834 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
835 if ( $clientHeaderTime < $maxModified ) {
836 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
837 return false;
838 }
839
840 # Not modified
841 # Give a 304 Not Modified response code and disable body output
842 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
843 ini_set( 'zlib.output_compression', 0 );
844 $this->getRequest()->response()->statusHeader( 304 );
845 $this->sendCacheControl();
846 $this->disable();
847
848 // Don't output a compressed blob when using ob_gzhandler;
849 // it's technically against HTTP spec and seems to confuse
850 // Firefox when the response gets split over two packets.
851 wfClearOutputBuffers();
852
853 return true;
854 }
855
856 /**
857 * @param int $reqTime Time of request (eg. now)
858 * @param int $maxAge Cache TTL in seconds
859 * @return int Timestamp
860 */
861 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
862 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
863 // because even if the wiki page content hasn't changed since, static
864 // resources may have changed (skin HTML, interface messages, urls, etc.)
865 // and must roll-over in a timely manner (T46570)
866 return $reqTime - $maxAge;
867 }
868
869 /**
870 * Override the last modified timestamp
871 *
872 * @param string $timestamp New timestamp, in a format readable by
873 * wfTimestamp()
874 */
875 public function setLastModified( $timestamp ) {
876 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
877 }
878
879 /**
880 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
881 *
882 * @param string $policy The literal string to output as the contents of
883 * the meta tag. Will be parsed according to the spec and output in
884 * standardized form.
885 * @return null
886 */
887 public function setRobotPolicy( $policy ) {
888 $policy = Article::formatRobotPolicy( $policy );
889
890 if ( isset( $policy['index'] ) ) {
891 $this->setIndexPolicy( $policy['index'] );
892 }
893 if ( isset( $policy['follow'] ) ) {
894 $this->setFollowPolicy( $policy['follow'] );
895 }
896 }
897
898 /**
899 * Set the index policy for the page, but leave the follow policy un-
900 * touched.
901 *
902 * @param string $policy Either 'index' or 'noindex'.
903 * @return null
904 */
905 public function setIndexPolicy( $policy ) {
906 $policy = trim( $policy );
907 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
908 $this->mIndexPolicy = $policy;
909 }
910 }
911
912 /**
913 * Set the follow policy for the page, but leave the index policy un-
914 * touched.
915 *
916 * @param string $policy Either 'follow' or 'nofollow'.
917 * @return null
918 */
919 public function setFollowPolicy( $policy ) {
920 $policy = trim( $policy );
921 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
922 $this->mFollowPolicy = $policy;
923 }
924 }
925
926 /**
927 * Set the new value of the "action text", this will be added to the
928 * "HTML title", separated from it with " - ".
929 *
930 * @param string $text New value of the "action text"
931 */
932 public function setPageTitleActionText( $text ) {
933 $this->mPageTitleActionText = $text;
934 }
935
936 /**
937 * Get the value of the "action text"
938 *
939 * @return string
940 */
941 public function getPageTitleActionText() {
942 return $this->mPageTitleActionText;
943 }
944
945 /**
946 * "HTML title" means the contents of "<title>".
947 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
948 *
949 * @param string|Message $name
950 */
951 public function setHTMLTitle( $name ) {
952 if ( $name instanceof Message ) {
953 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
954 } else {
955 $this->mHTMLtitle = $name;
956 }
957 }
958
959 /**
960 * Return the "HTML title", i.e. the content of the "<title>" tag.
961 *
962 * @return string
963 */
964 public function getHTMLTitle() {
965 return $this->mHTMLtitle;
966 }
967
968 /**
969 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
970 *
971 * @param Title $t
972 */
973 public function setRedirectedFrom( $t ) {
974 $this->mRedirectedFrom = $t;
975 }
976
977 /**
978 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
979 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
980 * but not bad tags like \<script\>. This function automatically sets
981 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
982 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
983 * good tags like \<i\> will be dropped entirely.
984 *
985 * @param string|Message $name
986 */
987 public function setPageTitle( $name ) {
988 if ( $name instanceof Message ) {
989 $name = $name->setContext( $this->getContext() )->text();
990 }
991
992 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
993 # but leave "<i>foobar</i>" alone
994 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
995 $this->mPagetitle = $nameWithTags;
996
997 # change "<i>foo&amp;bar</i>" to "foo&bar"
998 $this->setHTMLTitle(
999 $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
1000 ->inContentLanguage()
1001 );
1002 }
1003
1004 /**
1005 * Return the "page title", i.e. the content of the \<h1\> tag.
1006 *
1007 * @return string
1008 */
1009 public function getPageTitle() {
1010 return $this->mPagetitle;
1011 }
1012
1013 /**
1014 * Set the Title object to use
1015 *
1016 * @param Title $t
1017 */
1018 public function setTitle( Title $t ) {
1019 $this->getContext()->setTitle( $t );
1020 }
1021
1022 /**
1023 * Replace the subtitle with $str
1024 *
1025 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1026 */
1027 public function setSubtitle( $str ) {
1028 $this->clearSubtitle();
1029 $this->addSubtitle( $str );
1030 }
1031
1032 /**
1033 * Add $str to the subtitle
1034 *
1035 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1036 */
1037 public function addSubtitle( $str ) {
1038 if ( $str instanceof Message ) {
1039 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1040 } else {
1041 $this->mSubtitle[] = $str;
1042 }
1043 }
1044
1045 /**
1046 * Build message object for a subtitle containing a backlink to a page
1047 *
1048 * @param Title $title Title to link to
1049 * @param array $query Array of additional parameters to include in the link
1050 * @return Message
1051 * @since 1.25
1052 */
1053 public static function buildBacklinkSubtitle( Title $title, $query = [] ) {
1054 if ( $title->isRedirect() ) {
1055 $query['redirect'] = 'no';
1056 }
1057 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1058 return wfMessage( 'backlinksubtitle' )
1059 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1060 }
1061
1062 /**
1063 * Add a subtitle containing a backlink to a page
1064 *
1065 * @param Title $title Title to link to
1066 * @param array $query Array of additional parameters to include in the link
1067 */
1068 public function addBacklinkSubtitle( Title $title, $query = [] ) {
1069 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1070 }
1071
1072 /**
1073 * Clear the subtitles
1074 */
1075 public function clearSubtitle() {
1076 $this->mSubtitle = [];
1077 }
1078
1079 /**
1080 * Get the subtitle
1081 *
1082 * @return string
1083 */
1084 public function getSubtitle() {
1085 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1086 }
1087
1088 /**
1089 * Set the page as printable, i.e. it'll be displayed with all
1090 * print styles included
1091 */
1092 public function setPrintable() {
1093 $this->mPrintable = true;
1094 }
1095
1096 /**
1097 * Return whether the page is "printable"
1098 *
1099 * @return bool
1100 */
1101 public function isPrintable() {
1102 return $this->mPrintable;
1103 }
1104
1105 /**
1106 * Disable output completely, i.e. calling output() will have no effect
1107 */
1108 public function disable() {
1109 $this->mDoNothing = true;
1110 }
1111
1112 /**
1113 * Return whether the output will be completely disabled
1114 *
1115 * @return bool
1116 */
1117 public function isDisabled() {
1118 return $this->mDoNothing;
1119 }
1120
1121 /**
1122 * Show an "add new section" link?
1123 *
1124 * @return bool
1125 */
1126 public function showNewSectionLink() {
1127 return $this->mNewSectionLink;
1128 }
1129
1130 /**
1131 * Forcibly hide the new section link?
1132 *
1133 * @return bool
1134 */
1135 public function forceHideNewSectionLink() {
1136 return $this->mHideNewSectionLink;
1137 }
1138
1139 /**
1140 * Add or remove feed links in the page header
1141 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1142 * for the new version
1143 * @see addFeedLink()
1144 *
1145 * @param bool $show True: add default feeds, false: remove all feeds
1146 */
1147 public function setSyndicated( $show = true ) {
1148 if ( $show ) {
1149 $this->setFeedAppendQuery( false );
1150 } else {
1151 $this->mFeedLinks = [];
1152 }
1153 }
1154
1155 /**
1156 * Add default feeds to the page header
1157 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1158 * for the new version
1159 * @see addFeedLink()
1160 *
1161 * @param string $val Query to append to feed links or false to output
1162 * default links
1163 */
1164 public function setFeedAppendQuery( $val ) {
1165 $this->mFeedLinks = [];
1166
1167 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1168 $query = "feed=$type";
1169 if ( is_string( $val ) ) {
1170 $query .= '&' . $val;
1171 }
1172 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1173 }
1174 }
1175
1176 /**
1177 * Add a feed link to the page header
1178 *
1179 * @param string $format Feed type, should be a key of $wgFeedClasses
1180 * @param string $href URL
1181 */
1182 public function addFeedLink( $format, $href ) {
1183 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1184 $this->mFeedLinks[$format] = $href;
1185 }
1186 }
1187
1188 /**
1189 * Should we output feed links for this page?
1190 * @return bool
1191 */
1192 public function isSyndicated() {
1193 return count( $this->mFeedLinks ) > 0;
1194 }
1195
1196 /**
1197 * Return URLs for each supported syndication format for this page.
1198 * @return array Associating format keys with URLs
1199 */
1200 public function getSyndicationLinks() {
1201 return $this->mFeedLinks;
1202 }
1203
1204 /**
1205 * Will currently always return null
1206 *
1207 * @return null
1208 */
1209 public function getFeedAppendQuery() {
1210 return $this->mFeedLinksAppendQuery;
1211 }
1212
1213 /**
1214 * Set whether the displayed content is related to the source of the
1215 * corresponding article on the wiki
1216 * Setting true will cause the change "article related" toggle to true
1217 *
1218 * @param bool $v
1219 */
1220 public function setArticleFlag( $v ) {
1221 $this->mIsarticle = $v;
1222 if ( $v ) {
1223 $this->mIsArticleRelated = $v;
1224 }
1225 }
1226
1227 /**
1228 * Return whether the content displayed page is related to the source of
1229 * the corresponding article on the wiki
1230 *
1231 * @return bool
1232 */
1233 public function isArticle() {
1234 return $this->mIsarticle;
1235 }
1236
1237 /**
1238 * Set whether this page is related an article on the wiki
1239 * Setting false will cause the change of "article flag" toggle to false
1240 *
1241 * @param bool $v
1242 */
1243 public function setArticleRelated( $v ) {
1244 $this->mIsArticleRelated = $v;
1245 if ( !$v ) {
1246 $this->mIsarticle = false;
1247 }
1248 }
1249
1250 /**
1251 * Return whether this page is related an article on the wiki
1252 *
1253 * @return bool
1254 */
1255 public function isArticleRelated() {
1256 return $this->mIsArticleRelated;
1257 }
1258
1259 /**
1260 * Add new language links
1261 *
1262 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1263 * (e.g. 'fr:Test page')
1264 */
1265 public function addLanguageLinks( array $newLinkArray ) {
1266 $this->mLanguageLinks += $newLinkArray;
1267 }
1268
1269 /**
1270 * Reset the language links and add new language links
1271 *
1272 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1273 * (e.g. 'fr:Test page')
1274 */
1275 public function setLanguageLinks( array $newLinkArray ) {
1276 $this->mLanguageLinks = $newLinkArray;
1277 }
1278
1279 /**
1280 * Get the list of language links
1281 *
1282 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1283 */
1284 public function getLanguageLinks() {
1285 return $this->mLanguageLinks;
1286 }
1287
1288 /**
1289 * Add an array of categories, with names in the keys
1290 *
1291 * @param array $categories Mapping category name => sort key
1292 */
1293 public function addCategoryLinks( array $categories ) {
1294 global $wgContLang;
1295
1296 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1297 return;
1298 }
1299
1300 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1301
1302 # Set all the values to 'normal'.
1303 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1304
1305 # Mark hidden categories
1306 foreach ( $res as $row ) {
1307 if ( isset( $row->pp_value ) ) {
1308 $categories[$row->page_title] = 'hidden';
1309 }
1310 }
1311
1312 // Avoid PHP 7.1 warning of passing $this by reference
1313 $outputPage = $this;
1314 # Add the remaining categories to the skin
1315 if ( Hooks::run(
1316 'OutputPageMakeCategoryLinks',
1317 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1318 ) {
1319 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1320 foreach ( $categories as $category => $type ) {
1321 // array keys will cast numeric category names to ints, so cast back to string
1322 $category = (string)$category;
1323 $origcategory = $category;
1324 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1325 if ( !$title ) {
1326 continue;
1327 }
1328 $wgContLang->findVariantLink( $category, $title, true );
1329 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1330 continue;
1331 }
1332 $text = $wgContLang->convertHtml( $title->getText() );
1333 $this->mCategories[$type][] = $title->getText();
1334 $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1335 }
1336 }
1337 }
1338
1339 /**
1340 * @param array $categories
1341 * @return bool|IResultWrapper
1342 */
1343 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1344 # Add the links to a LinkBatch
1345 $arr = [ NS_CATEGORY => $categories ];
1346 $lb = new LinkBatch;
1347 $lb->setArray( $arr );
1348
1349 # Fetch existence plus the hiddencat property
1350 $dbr = wfGetDB( DB_REPLICA );
1351 $fields = array_merge(
1352 LinkCache::getSelectFields(),
1353 [ 'page_namespace', 'page_title', 'pp_value' ]
1354 );
1355
1356 $res = $dbr->select( [ 'page', 'page_props' ],
1357 $fields,
1358 $lb->constructSet( 'page', $dbr ),
1359 __METHOD__,
1360 [],
1361 [ 'page_props' => [ 'LEFT JOIN', [
1362 'pp_propname' => 'hiddencat',
1363 'pp_page = page_id'
1364 ] ] ]
1365 );
1366
1367 # Add the results to the link cache
1368 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1369 $lb->addResultToCache( $linkCache, $res );
1370
1371 return $res;
1372 }
1373
1374 /**
1375 * Reset the category links (but not the category list) and add $categories
1376 *
1377 * @param array $categories Mapping category name => sort key
1378 */
1379 public function setCategoryLinks( array $categories ) {
1380 $this->mCategoryLinks = [];
1381 $this->addCategoryLinks( $categories );
1382 }
1383
1384 /**
1385 * Get the list of category links, in a 2-D array with the following format:
1386 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1387 * hidden categories) and $link a HTML fragment with a link to the category
1388 * page
1389 *
1390 * @return array
1391 */
1392 public function getCategoryLinks() {
1393 return $this->mCategoryLinks;
1394 }
1395
1396 /**
1397 * Get the list of category names this page belongs to.
1398 *
1399 * @param string $type The type of categories which should be returned. Possible values:
1400 * * all: all categories of all types
1401 * * hidden: only the hidden categories
1402 * * normal: all categories, except hidden categories
1403 * @return array Array of strings
1404 */
1405 public function getCategories( $type = 'all' ) {
1406 if ( $type === 'all' ) {
1407 $allCategories = [];
1408 foreach ( $this->mCategories as $categories ) {
1409 $allCategories = array_merge( $allCategories, $categories );
1410 }
1411 return $allCategories;
1412 }
1413 if ( !isset( $this->mCategories[$type] ) ) {
1414 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1415 }
1416 return $this->mCategories[$type];
1417 }
1418
1419 /**
1420 * Add an array of indicators, with their identifiers as array
1421 * keys and HTML contents as values.
1422 *
1423 * In case of duplicate keys, existing values are overwritten.
1424 *
1425 * @param array $indicators
1426 * @since 1.25
1427 */
1428 public function setIndicators( array $indicators ) {
1429 $this->mIndicators = $indicators + $this->mIndicators;
1430 // Keep ordered by key
1431 ksort( $this->mIndicators );
1432 }
1433
1434 /**
1435 * Get the indicators associated with this page.
1436 *
1437 * The array will be internally ordered by item keys.
1438 *
1439 * @return array Keys: identifiers, values: HTML contents
1440 * @since 1.25
1441 */
1442 public function getIndicators() {
1443 return $this->mIndicators;
1444 }
1445
1446 /**
1447 * Adds help link with an icon via page indicators.
1448 * Link target can be overridden by a local message containing a wikilink:
1449 * the message key is: lowercase action or special page name + '-helppage'.
1450 * @param string $to Target MediaWiki.org page title or encoded URL.
1451 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1452 * @since 1.25
1453 */
1454 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1455 $this->addModuleStyles( 'mediawiki.helplink' );
1456 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1457
1458 if ( $overrideBaseUrl ) {
1459 $helpUrl = $to;
1460 } else {
1461 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1462 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1463 }
1464
1465 $link = Html::rawElement(
1466 'a',
1467 [
1468 'href' => $helpUrl,
1469 'target' => '_blank',
1470 'class' => 'mw-helplink',
1471 ],
1472 $text
1473 );
1474
1475 $this->setIndicators( [ 'mw-helplink' => $link ] );
1476 }
1477
1478 /**
1479 * Do not allow scripts which can be modified by wiki users to load on this page;
1480 * only allow scripts bundled with, or generated by, the software.
1481 * Site-wide styles are controlled by a config setting, since they can be
1482 * used to create a custom skin/theme, but not user-specific ones.
1483 *
1484 * @todo this should be given a more accurate name
1485 */
1486 public function disallowUserJs() {
1487 $this->reduceAllowedModules(
1488 ResourceLoaderModule::TYPE_SCRIPTS,
1489 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1490 );
1491
1492 // Site-wide styles are controlled by a config setting, see T73621
1493 // for background on why. User styles are never allowed.
1494 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1495 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1496 } else {
1497 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1498 }
1499 $this->reduceAllowedModules(
1500 ResourceLoaderModule::TYPE_STYLES,
1501 $styleOrigin
1502 );
1503 }
1504
1505 /**
1506 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1507 * @see ResourceLoaderModule::$origin
1508 * @param string $type ResourceLoaderModule TYPE_ constant
1509 * @return int ResourceLoaderModule ORIGIN_ class constant
1510 */
1511 public function getAllowedModules( $type ) {
1512 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1513 return min( array_values( $this->mAllowedModules ) );
1514 } else {
1515 return $this->mAllowedModules[$type] ?? ResourceLoaderModule::ORIGIN_ALL;
1516 }
1517 }
1518
1519 /**
1520 * Limit the highest level of CSS/JS untrustworthiness allowed.
1521 *
1522 * If passed the same or a higher level than the current level of untrustworthiness set, the
1523 * level will remain unchanged.
1524 *
1525 * @param string $type
1526 * @param int $level ResourceLoaderModule class constant
1527 */
1528 public function reduceAllowedModules( $type, $level ) {
1529 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1530 }
1531
1532 /**
1533 * Prepend $text to the body HTML
1534 *
1535 * @param string $text HTML
1536 */
1537 public function prependHTML( $text ) {
1538 $this->mBodytext = $text . $this->mBodytext;
1539 }
1540
1541 /**
1542 * Append $text to the body HTML
1543 *
1544 * @param string $text HTML
1545 */
1546 public function addHTML( $text ) {
1547 $this->mBodytext .= $text;
1548 }
1549
1550 /**
1551 * Shortcut for adding an Html::element via addHTML.
1552 *
1553 * @since 1.19
1554 *
1555 * @param string $element
1556 * @param array $attribs
1557 * @param string $contents
1558 */
1559 public function addElement( $element, array $attribs = [], $contents = '' ) {
1560 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1561 }
1562
1563 /**
1564 * Clear the body HTML
1565 */
1566 public function clearHTML() {
1567 $this->mBodytext = '';
1568 }
1569
1570 /**
1571 * Get the body HTML
1572 *
1573 * @return string HTML
1574 */
1575 public function getHTML() {
1576 return $this->mBodytext;
1577 }
1578
1579 /**
1580 * Get/set the ParserOptions object to use for wikitext parsing
1581 *
1582 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1583 * current ParserOption object. This parameter is deprecated since 1.31.
1584 * @return ParserOptions
1585 */
1586 public function parserOptions( $options = null ) {
1587 if ( $options !== null ) {
1588 wfDeprecated( __METHOD__ . ' with non-null $options', '1.31' );
1589 }
1590
1591 if ( $options !== null && !empty( $options->isBogus ) ) {
1592 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1593 // been changed somehow, and keep it if so.
1594 $anonPO = ParserOptions::newFromAnon();
1595 $anonPO->setAllowUnsafeRawHtml( false );
1596 if ( !$options->matches( $anonPO ) ) {
1597 wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1598 $options->isBogus = false;
1599 }
1600 }
1601
1602 if ( !$this->mParserOptions ) {
1603 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1604 // $wgUser isn't unstubbable yet, so don't try to get a
1605 // ParserOptions for it. And don't cache this ParserOptions
1606 // either.
1607 $po = ParserOptions::newFromAnon();
1608 $po->setAllowUnsafeRawHtml( false );
1609 $po->isBogus = true;
1610 if ( $options !== null ) {
1611 $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
1612 }
1613 return $po;
1614 }
1615
1616 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1617 $this->mParserOptions->setAllowUnsafeRawHtml( false );
1618 }
1619
1620 if ( $options !== null && !empty( $options->isBogus ) ) {
1621 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1622 // thing.
1623 return wfSetVar( $this->mParserOptions, null, true );
1624 } else {
1625 return wfSetVar( $this->mParserOptions, $options );
1626 }
1627 }
1628
1629 /**
1630 * Set the revision ID which will be seen by the wiki text parser
1631 * for things such as embedded {{REVISIONID}} variable use.
1632 *
1633 * @param int|null $revid An positive integer, or null
1634 * @return mixed Previous value
1635 */
1636 public function setRevisionId( $revid ) {
1637 $val = is_null( $revid ) ? null : intval( $revid );
1638 return wfSetVar( $this->mRevisionId, $val );
1639 }
1640
1641 /**
1642 * Get the displayed revision ID
1643 *
1644 * @return int
1645 */
1646 public function getRevisionId() {
1647 return $this->mRevisionId;
1648 }
1649
1650 /**
1651 * Set the timestamp of the revision which will be displayed. This is used
1652 * to avoid a extra DB call in Skin::lastModified().
1653 *
1654 * @param string|null $timestamp
1655 * @return mixed Previous value
1656 */
1657 public function setRevisionTimestamp( $timestamp ) {
1658 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1659 }
1660
1661 /**
1662 * Get the timestamp of displayed revision.
1663 * This will be null if not filled by setRevisionTimestamp().
1664 *
1665 * @return string|null
1666 */
1667 public function getRevisionTimestamp() {
1668 return $this->mRevisionTimestamp;
1669 }
1670
1671 /**
1672 * Set the displayed file version
1673 *
1674 * @param File|bool $file
1675 * @return mixed Previous value
1676 */
1677 public function setFileVersion( $file ) {
1678 $val = null;
1679 if ( $file instanceof File && $file->exists() ) {
1680 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1681 }
1682 return wfSetVar( $this->mFileVersion, $val, true );
1683 }
1684
1685 /**
1686 * Get the displayed file version
1687 *
1688 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1689 */
1690 public function getFileVersion() {
1691 return $this->mFileVersion;
1692 }
1693
1694 /**
1695 * Get the templates used on this page
1696 *
1697 * @return array (namespace => dbKey => revId)
1698 * @since 1.18
1699 */
1700 public function getTemplateIds() {
1701 return $this->mTemplateIds;
1702 }
1703
1704 /**
1705 * Get the files used on this page
1706 *
1707 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1708 * @since 1.18
1709 */
1710 public function getFileSearchOptions() {
1711 return $this->mImageTimeKeys;
1712 }
1713
1714 /**
1715 * Convert wikitext to HTML and add it to the buffer
1716 * Default assumes that the current page title will be used.
1717 *
1718 * @param string $text
1719 * @param bool $linestart Is this the start of a line?
1720 * @param bool $interface Is this text in the user interface language?
1721 * @throws MWException
1722 */
1723 public function addWikiText( $text, $linestart = true, $interface = true ) {
1724 $title = $this->getTitle(); // Work around E_STRICT
1725 if ( !$title ) {
1726 throw new MWException( 'Title is null' );
1727 }
1728 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1729 }
1730
1731 /**
1732 * Add wikitext with a custom Title object
1733 *
1734 * @param string $text Wikitext
1735 * @param Title &$title
1736 * @param bool $linestart Is this the start of a line?
1737 */
1738 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1739 $this->addWikiTextTitle( $text, $title, $linestart );
1740 }
1741
1742 /**
1743 * Add wikitext with a custom Title object and tidy enabled.
1744 *
1745 * @param string $text Wikitext
1746 * @param Title &$title
1747 * @param bool $linestart Is this the start of a line?
1748 */
1749 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1750 $this->addWikiTextTitle( $text, $title, $linestart, true );
1751 }
1752
1753 /**
1754 * Add wikitext with tidy enabled
1755 *
1756 * @param string $text Wikitext
1757 * @param bool $linestart Is this the start of a line?
1758 */
1759 public function addWikiTextTidy( $text, $linestart = true ) {
1760 $title = $this->getTitle();
1761 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1762 }
1763
1764 /**
1765 * Add wikitext with a custom Title object
1766 *
1767 * @param string $text Wikitext
1768 * @param Title $title
1769 * @param bool $linestart Is this the start of a line?
1770 * @param bool $tidy Whether to use tidy
1771 * @param bool $interface Whether it is an interface message
1772 * (for example disables conversion)
1773 */
1774 public function addWikiTextTitle( $text, Title $title, $linestart,
1775 $tidy = false, $interface = false
1776 ) {
1777 global $wgParser;
1778
1779 $popts = $this->parserOptions();
1780 $oldTidy = $popts->setTidy( $tidy );
1781 $popts->setInterfaceMessage( (bool)$interface );
1782
1783 $parserOutput = $wgParser->getFreshParser()->parse(
1784 $text, $title, $popts,
1785 $linestart, true, $this->mRevisionId
1786 );
1787
1788 $popts->setTidy( $oldTidy );
1789
1790 $this->addParserOutput( $parserOutput, [
1791 'enableSectionEditLinks' => false,
1792 ] );
1793 }
1794
1795 /**
1796 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1797 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1798 * and so on.
1799 *
1800 * @since 1.24
1801 * @param ParserOutput $parserOutput
1802 */
1803 public function addParserOutputMetadata( $parserOutput ) {
1804 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1805 $this->addCategoryLinks( $parserOutput->getCategories() );
1806 $this->setIndicators( $parserOutput->getIndicators() );
1807 $this->mNewSectionLink = $parserOutput->getNewSection();
1808 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1809
1810 if ( !$parserOutput->isCacheable() ) {
1811 $this->enableClientCache( false );
1812 }
1813 $this->mNoGallery = $parserOutput->getNoGallery();
1814 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1815 $this->addModules( $parserOutput->getModules() );
1816 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1817 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1818 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1819 $this->mPreventClickjacking = $this->mPreventClickjacking
1820 || $parserOutput->preventClickjacking();
1821
1822 // Template versioning...
1823 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1824 if ( isset( $this->mTemplateIds[$ns] ) ) {
1825 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1826 } else {
1827 $this->mTemplateIds[$ns] = $dbks;
1828 }
1829 }
1830 // File versioning...
1831 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1832 $this->mImageTimeKeys[$dbk] = $data;
1833 }
1834
1835 // Hooks registered in the object
1836 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1837 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1838 list( $hookName, $data ) = $hookInfo;
1839 if ( isset( $parserOutputHooks[$hookName] ) ) {
1840 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1841 }
1842 }
1843
1844 // Enable OOUI if requested via ParserOutput
1845 if ( $parserOutput->getEnableOOUI() ) {
1846 $this->enableOOUI();
1847 }
1848
1849 // Include parser limit report
1850 if ( !$this->limitReportJSData ) {
1851 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
1852 }
1853
1854 // Link flags are ignored for now, but may in the future be
1855 // used to mark individual language links.
1856 $linkFlags = [];
1857 // Avoid PHP 7.1 warning of passing $this by reference
1858 $outputPage = $this;
1859 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1860 Hooks::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1861
1862 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1863 // so that extensions may modify ParserOutput to toggle TOC.
1864 // This cannot be moved to addParserOutputText because that is not
1865 // called by EditPage for Preview.
1866 if ( $parserOutput->getTOCHTML() ) {
1867 $this->mEnableTOC = true;
1868 }
1869 }
1870
1871 /**
1872 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1873 * ParserOutput object, without any other metadata.
1874 *
1875 * @since 1.24
1876 * @param ParserOutput $parserOutput
1877 * @param array $poOptions Options to ParserOutput::getText()
1878 */
1879 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1880 $this->addParserOutputText( $parserOutput, $poOptions );
1881
1882 $this->addModules( $parserOutput->getModules() );
1883 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1884 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1885
1886 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1887 }
1888
1889 /**
1890 * Add the HTML associated with a ParserOutput object, without any metadata.
1891 *
1892 * @since 1.24
1893 * @param ParserOutput $parserOutput
1894 * @param array $poOptions Options to ParserOutput::getText()
1895 */
1896 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1897 $text = $parserOutput->getText( $poOptions );
1898 // Avoid PHP 7.1 warning of passing $this by reference
1899 $outputPage = $this;
1900 Hooks::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1901 $this->addHTML( $text );
1902 }
1903
1904 /**
1905 * Add everything from a ParserOutput object.
1906 *
1907 * @param ParserOutput $parserOutput
1908 * @param array $poOptions Options to ParserOutput::getText()
1909 */
1910 function addParserOutput( $parserOutput, $poOptions = [] ) {
1911 $this->addParserOutputMetadata( $parserOutput );
1912 $this->addParserOutputText( $parserOutput, $poOptions );
1913 }
1914
1915 /**
1916 * Add the output of a QuickTemplate to the output buffer
1917 *
1918 * @param QuickTemplate &$template
1919 */
1920 public function addTemplate( &$template ) {
1921 $this->addHTML( $template->getHTML() );
1922 }
1923
1924 /**
1925 * Parse wikitext and return the HTML.
1926 *
1927 * @param string $text
1928 * @param bool $linestart Is this the start of a line?
1929 * @param bool $interface Use interface language ($wgLang instead of
1930 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1931 * This also disables LanguageConverter.
1932 * @param Language|null $language Target language object, will override $interface
1933 * @throws MWException
1934 * @return string HTML
1935 */
1936 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1937 global $wgParser;
1938
1939 if ( is_null( $this->getTitle() ) ) {
1940 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1941 }
1942
1943 $popts = $this->parserOptions();
1944 if ( $interface ) {
1945 $popts->setInterfaceMessage( true );
1946 }
1947 if ( $language !== null ) {
1948 $oldLang = $popts->setTargetLanguage( $language );
1949 }
1950
1951 $parserOutput = $wgParser->getFreshParser()->parse(
1952 $text, $this->getTitle(), $popts,
1953 $linestart, true, $this->mRevisionId
1954 );
1955
1956 if ( $interface ) {
1957 $popts->setInterfaceMessage( false );
1958 }
1959 if ( $language !== null ) {
1960 $popts->setTargetLanguage( $oldLang );
1961 }
1962
1963 return $parserOutput->getText( [
1964 'enableSectionEditLinks' => false,
1965 ] );
1966 }
1967
1968 /**
1969 * Parse wikitext, strip paragraphs, and return the HTML.
1970 *
1971 * @param string $text
1972 * @param bool $linestart Is this the start of a line?
1973 * @param bool $interface Use interface language ($wgLang instead of
1974 * $wgContLang) while parsing language sensitive magic
1975 * words like GRAMMAR and PLURAL
1976 * @return string HTML
1977 */
1978 public function parseInline( $text, $linestart = true, $interface = false ) {
1979 $parsed = $this->parse( $text, $linestart, $interface );
1980 return Parser::stripOuterParagraph( $parsed );
1981 }
1982
1983 /**
1984 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1985 *
1986 * @param int $maxage Maximum cache time on the CDN, in seconds.
1987 */
1988 public function setCdnMaxage( $maxage ) {
1989 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
1990 }
1991
1992 /**
1993 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1994 *
1995 * @param int $maxage Maximum cache time on the CDN, in seconds
1996 * @since 1.27
1997 */
1998 public function lowerCdnMaxage( $maxage ) {
1999 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2000 $this->setCdnMaxage( $this->mCdnMaxage );
2001 }
2002
2003 /**
2004 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2005 *
2006 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2007 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2008 * TTL is 90% of the age of the object, subject to the min and max.
2009 *
2010 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2011 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
2012 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2013 * @return int TTL in seconds
2014 * @since 1.28
2015 */
2016 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2017 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2018 $maxTTL = $maxTTL ?: $this->getConfig()->get( 'SquidMaxage' );
2019
2020 if ( $mtime === null || $mtime === false ) {
2021 return $minTTL; // entity does not exist
2022 }
2023
2024 $age = time() - wfTimestamp( TS_UNIX, $mtime );
2025 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2026 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2027
2028 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2029
2030 return $adaptiveTTL;
2031 }
2032
2033 /**
2034 * Use enableClientCache(false) to force it to send nocache headers
2035 *
2036 * @param bool $state
2037 *
2038 * @return bool
2039 */
2040 public function enableClientCache( $state ) {
2041 return wfSetVar( $this->mEnableClientCache, $state );
2042 }
2043
2044 /**
2045 * Get the list of cookies that will influence on the cache
2046 *
2047 * @return array
2048 */
2049 function getCacheVaryCookies() {
2050 static $cookies;
2051 if ( $cookies === null ) {
2052 $config = $this->getConfig();
2053 $cookies = array_merge(
2054 SessionManager::singleton()->getVaryCookies(),
2055 [
2056 'forceHTTPS',
2057 ],
2058 $config->get( 'CacheVaryCookies' )
2059 );
2060 Hooks::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2061 }
2062 return $cookies;
2063 }
2064
2065 /**
2066 * Check if the request has a cache-varying cookie header
2067 * If it does, it's very important that we don't allow public caching
2068 *
2069 * @return bool
2070 */
2071 function haveCacheVaryCookies() {
2072 $request = $this->getRequest();
2073 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2074 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2075 wfDebug( __METHOD__ . ": found $cookieName\n" );
2076 return true;
2077 }
2078 }
2079 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2080 return false;
2081 }
2082
2083 /**
2084 * Add an HTTP header that will influence on the cache
2085 *
2086 * @param string $header Header name
2087 * @param string[]|null $option Options for the Key header. See
2088 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2089 * for the list of valid options.
2090 */
2091 public function addVaryHeader( $header, array $option = null ) {
2092 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2093 $this->mVaryHeader[$header] = [];
2094 }
2095 if ( !is_array( $option ) ) {
2096 $option = [];
2097 }
2098 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2099 }
2100
2101 /**
2102 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2103 * such as Accept-Encoding or Cookie
2104 *
2105 * @return string
2106 */
2107 public function getVaryHeader() {
2108 // If we vary on cookies, let's make sure it's always included here too.
2109 if ( $this->getCacheVaryCookies() ) {
2110 $this->addVaryHeader( 'Cookie' );
2111 }
2112
2113 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2114 $this->addVaryHeader( $header, $options );
2115 }
2116 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2117 }
2118
2119 /**
2120 * Add an HTTP Link: header
2121 *
2122 * @param string $header Header value
2123 */
2124 public function addLinkHeader( $header ) {
2125 $this->mLinkHeader[] = $header;
2126 }
2127
2128 /**
2129 * Return a Link: header. Based on the values of $mLinkHeader.
2130 *
2131 * @return string
2132 */
2133 public function getLinkHeader() {
2134 if ( !$this->mLinkHeader ) {
2135 return false;
2136 }
2137
2138 return 'Link: ' . implode( ',', $this->mLinkHeader );
2139 }
2140
2141 /**
2142 * Get a complete Key header
2143 *
2144 * @return string
2145 */
2146 public function getKeyHeader() {
2147 $cvCookies = $this->getCacheVaryCookies();
2148
2149 $cookiesOption = [];
2150 foreach ( $cvCookies as $cookieName ) {
2151 $cookiesOption[] = 'param=' . $cookieName;
2152 }
2153 $this->addVaryHeader( 'Cookie', $cookiesOption );
2154
2155 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2156 $this->addVaryHeader( $header, $options );
2157 }
2158
2159 $headers = [];
2160 foreach ( $this->mVaryHeader as $header => $option ) {
2161 $newheader = $header;
2162 if ( is_array( $option ) && count( $option ) > 0 ) {
2163 $newheader .= ';' . implode( ';', $option );
2164 }
2165 $headers[] = $newheader;
2166 }
2167 $key = 'Key: ' . implode( ',', $headers );
2168
2169 return $key;
2170 }
2171
2172 /**
2173 * T23672: Add Accept-Language to Vary and Key headers
2174 * if there's no 'variant' parameter existed in GET.
2175 *
2176 * For example:
2177 * /w/index.php?title=Main_page should always be served; but
2178 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2179 */
2180 function addAcceptLanguage() {
2181 $title = $this->getTitle();
2182 if ( !$title instanceof Title ) {
2183 return;
2184 }
2185
2186 $lang = $title->getPageLanguage();
2187 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2188 $variants = $lang->getVariants();
2189 $aloption = [];
2190 foreach ( $variants as $variant ) {
2191 if ( $variant === $lang->getCode() ) {
2192 continue;
2193 } else {
2194 $aloption[] = 'substr=' . $variant;
2195
2196 // IE and some other browsers use BCP 47 standards in
2197 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2198 // We should handle these too.
2199 $variantBCP47 = LanguageCode::bcp47( $variant );
2200 if ( $variantBCP47 !== $variant ) {
2201 $aloption[] = 'substr=' . $variantBCP47;
2202 }
2203 }
2204 }
2205 $this->addVaryHeader( 'Accept-Language', $aloption );
2206 }
2207 }
2208
2209 /**
2210 * Set a flag which will cause an X-Frame-Options header appropriate for
2211 * edit pages to be sent. The header value is controlled by
2212 * $wgEditPageFrameOptions.
2213 *
2214 * This is the default for special pages. If you display a CSRF-protected
2215 * form on an ordinary view page, then you need to call this function.
2216 *
2217 * @param bool $enable
2218 */
2219 public function preventClickjacking( $enable = true ) {
2220 $this->mPreventClickjacking = $enable;
2221 }
2222
2223 /**
2224 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2225 * This can be called from pages which do not contain any CSRF-protected
2226 * HTML form.
2227 */
2228 public function allowClickjacking() {
2229 $this->mPreventClickjacking = false;
2230 }
2231
2232 /**
2233 * Get the prevent-clickjacking flag
2234 *
2235 * @since 1.24
2236 * @return bool
2237 */
2238 public function getPreventClickjacking() {
2239 return $this->mPreventClickjacking;
2240 }
2241
2242 /**
2243 * Get the X-Frame-Options header value (without the name part), or false
2244 * if there isn't one. This is used by Skin to determine whether to enable
2245 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2246 *
2247 * @return string|false
2248 */
2249 public function getFrameOptions() {
2250 $config = $this->getConfig();
2251 if ( $config->get( 'BreakFrames' ) ) {
2252 return 'DENY';
2253 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2254 return $config->get( 'EditPageFrameOptions' );
2255 }
2256 return false;
2257 }
2258
2259 /**
2260 * Send cache control HTTP headers
2261 */
2262 public function sendCacheControl() {
2263 $response = $this->getRequest()->response();
2264 $config = $this->getConfig();
2265
2266 $this->addVaryHeader( 'Cookie' );
2267 $this->addAcceptLanguage();
2268
2269 # don't serve compressed data to clients who can't handle it
2270 # maintain different caches for logged-in users and non-logged in ones
2271 $response->header( $this->getVaryHeader() );
2272
2273 if ( $config->get( 'UseKeyHeader' ) ) {
2274 $response->header( $this->getKeyHeader() );
2275 }
2276
2277 if ( $this->mEnableClientCache ) {
2278 if (
2279 $config->get( 'UseSquid' ) &&
2280 !$response->hasCookies() &&
2281 !SessionManager::getGlobalSession()->isPersistent() &&
2282 !$this->isPrintable() &&
2283 $this->mCdnMaxage != 0 &&
2284 !$this->haveCacheVaryCookies()
2285 ) {
2286 if ( $config->get( 'UseESI' ) ) {
2287 # We'll purge the proxy cache explicitly, but require end user agents
2288 # to revalidate against the proxy on each visit.
2289 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2290 wfDebug( __METHOD__ .
2291 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2292 # start with a shorter timeout for initial testing
2293 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2294 $response->header(
2295 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2296 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2297 );
2298 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2299 } else {
2300 # We'll purge the proxy cache for anons explicitly, but require end user agents
2301 # to revalidate against the proxy on each visit.
2302 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2303 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2304 wfDebug( __METHOD__ .
2305 ": local proxy caching; {$this->mLastModified} **", 'private' );
2306 # start with a shorter timeout for initial testing
2307 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2308 $response->header( "Cache-Control: " .
2309 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2310 }
2311 } else {
2312 # We do want clients to cache if they can, but they *must* check for updates
2313 # on revisiting the page.
2314 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2315 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2316 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2317 }
2318 if ( $this->mLastModified ) {
2319 $response->header( "Last-Modified: {$this->mLastModified}" );
2320 }
2321 } else {
2322 wfDebug( __METHOD__ . ": no caching **", 'private' );
2323
2324 # In general, the absence of a last modified header should be enough to prevent
2325 # the client from using its cache. We send a few other things just to make sure.
2326 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2327 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2328 $response->header( 'Pragma: no-cache' );
2329 }
2330 }
2331
2332 /**
2333 * Transfer styles and JavaScript modules from skin.
2334 *
2335 * @param Skin $sk to load modules for
2336 */
2337 public function loadSkinModules( $sk ) {
2338 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2339 if ( $group === 'styles' ) {
2340 foreach ( $modules as $key => $moduleMembers ) {
2341 $this->addModuleStyles( $moduleMembers );
2342 }
2343 } else {
2344 $this->addModules( $modules );
2345 }
2346 }
2347 }
2348
2349 /**
2350 * Finally, all the text has been munged and accumulated into
2351 * the object, let's actually output it:
2352 *
2353 * @param bool $return Set to true to get the result as a string rather than sending it
2354 * @return string|null
2355 * @throws Exception
2356 * @throws FatalError
2357 * @throws MWException
2358 */
2359 public function output( $return = false ) {
2360 global $wgContLang;
2361
2362 if ( $this->mDoNothing ) {
2363 return $return ? '' : null;
2364 }
2365
2366 $response = $this->getRequest()->response();
2367 $config = $this->getConfig();
2368
2369 if ( $this->mRedirect != '' ) {
2370 # Standards require redirect URLs to be absolute
2371 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2372
2373 $redirect = $this->mRedirect;
2374 $code = $this->mRedirectCode;
2375
2376 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2377 if ( $code == '301' || $code == '303' ) {
2378 if ( !$config->get( 'DebugRedirects' ) ) {
2379 $response->statusHeader( $code );
2380 }
2381 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2382 }
2383 if ( $config->get( 'VaryOnXFP' ) ) {
2384 $this->addVaryHeader( 'X-Forwarded-Proto' );
2385 }
2386 $this->sendCacheControl();
2387
2388 $response->header( "Content-Type: text/html; charset=utf-8" );
2389 if ( $config->get( 'DebugRedirects' ) ) {
2390 $url = htmlspecialchars( $redirect );
2391 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2392 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2393 print "</body>\n</html>\n";
2394 } else {
2395 $response->header( 'Location: ' . $redirect );
2396 }
2397 }
2398
2399 return $return ? '' : null;
2400 } elseif ( $this->mStatusCode ) {
2401 $response->statusHeader( $this->mStatusCode );
2402 }
2403
2404 # Buffer output; final headers may depend on later processing
2405 ob_start();
2406
2407 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2408 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2409
2410 if ( !$this->mArticleBodyOnly ) {
2411 $sk = $this->getSkin();
2412
2413 if ( $sk->shouldPreloadLogo() ) {
2414 $this->addLogoPreloadLinkHeaders();
2415 }
2416 }
2417
2418 $linkHeader = $this->getLinkHeader();
2419 if ( $linkHeader ) {
2420 $response->header( $linkHeader );
2421 }
2422
2423 // Prevent framing, if requested
2424 $frameOptions = $this->getFrameOptions();
2425 if ( $frameOptions ) {
2426 $response->header( "X-Frame-Options: $frameOptions" );
2427 }
2428
2429 ContentSecurityPolicy::sendHeaders( $this );
2430
2431 if ( $this->mArticleBodyOnly ) {
2432 echo $this->mBodytext;
2433 } else {
2434 // Enable safe mode if requested (T152169)
2435 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2436 $this->disallowUserJs();
2437 }
2438
2439 $sk = $this->getSkin();
2440 $this->loadSkinModules( $sk );
2441
2442 MWDebug::addModules( $this );
2443
2444 // Avoid PHP 7.1 warning of passing $this by reference
2445 $outputPage = $this;
2446 // Hook that allows last minute changes to the output page, e.g.
2447 // adding of CSS or Javascript by extensions.
2448 Hooks::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2449
2450 try {
2451 $sk->outputPage();
2452 } catch ( Exception $e ) {
2453 ob_end_clean(); // bug T129657
2454 throw $e;
2455 }
2456 }
2457
2458 try {
2459 // This hook allows last minute changes to final overall output by modifying output buffer
2460 Hooks::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2461 } catch ( Exception $e ) {
2462 ob_end_clean(); // bug T129657
2463 throw $e;
2464 }
2465
2466 $this->sendCacheControl();
2467
2468 if ( $return ) {
2469 return ob_get_clean();
2470 } else {
2471 ob_end_flush();
2472 return null;
2473 }
2474 }
2475
2476 /**
2477 * Prepare this object to display an error page; disable caching and
2478 * indexing, clear the current text and redirect, set the page's title
2479 * and optionally an custom HTML title (content of the "<title>" tag).
2480 *
2481 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2482 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2483 * optional, if not passed the "<title>" attribute will be
2484 * based on $pageTitle
2485 */
2486 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2487 $this->setPageTitle( $pageTitle );
2488 if ( $htmlTitle !== false ) {
2489 $this->setHTMLTitle( $htmlTitle );
2490 }
2491 $this->setRobotPolicy( 'noindex,nofollow' );
2492 $this->setArticleRelated( false );
2493 $this->enableClientCache( false );
2494 $this->mRedirect = '';
2495 $this->clearSubtitle();
2496 $this->clearHTML();
2497 }
2498
2499 /**
2500 * Output a standard error page
2501 *
2502 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2503 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2504 * showErrorPage( 'titlemsg', $messageObject );
2505 * showErrorPage( $titleMessageObject, $messageObject );
2506 *
2507 * @param string|Message $title Message key (string) for page title, or a Message object
2508 * @param string|Message $msg Message key (string) for page text, or a Message object
2509 * @param array $params Message parameters; ignored if $msg is a Message object
2510 */
2511 public function showErrorPage( $title, $msg, $params = [] ) {
2512 if ( !$title instanceof Message ) {
2513 $title = $this->msg( $title );
2514 }
2515
2516 $this->prepareErrorPage( $title );
2517
2518 if ( $msg instanceof Message ) {
2519 if ( $params !== [] ) {
2520 trigger_error( 'Argument ignored: $params. The message parameters argument '
2521 . 'is discarded when the $msg argument is a Message object instead of '
2522 . 'a string.', E_USER_NOTICE );
2523 }
2524 $this->addHTML( $msg->parseAsBlock() );
2525 } else {
2526 $this->addWikiMsgArray( $msg, $params );
2527 }
2528
2529 $this->returnToMain();
2530 }
2531
2532 /**
2533 * Output a standard permission error page
2534 *
2535 * @param array $errors Error message keys or [key, param...] arrays
2536 * @param string|null $action Action that was denied or null if unknown
2537 */
2538 public function showPermissionsErrorPage( array $errors, $action = null ) {
2539 foreach ( $errors as $key => $error ) {
2540 $errors[$key] = (array)$error;
2541 }
2542
2543 // For some action (read, edit, create and upload), display a "login to do this action"
2544 // error if all of the following conditions are met:
2545 // 1. the user is not logged in
2546 // 2. the only error is insufficient permissions (i.e. no block or something else)
2547 // 3. the error can be avoided simply by logging in
2548 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2549 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2550 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2551 && ( User::groupHasPermission( 'user', $action )
2552 || User::groupHasPermission( 'autoconfirmed', $action ) )
2553 ) {
2554 $displayReturnto = null;
2555
2556 # Due to T34276, if a user does not have read permissions,
2557 # $this->getTitle() will just give Special:Badtitle, which is
2558 # not especially useful as a returnto parameter. Use the title
2559 # from the request instead, if there was one.
2560 $request = $this->getRequest();
2561 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2562 if ( $action == 'edit' ) {
2563 $msg = 'whitelistedittext';
2564 $displayReturnto = $returnto;
2565 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2566 $msg = 'nocreatetext';
2567 } elseif ( $action == 'upload' ) {
2568 $msg = 'uploadnologintext';
2569 } else { # Read
2570 $msg = 'loginreqpagetext';
2571 $displayReturnto = Title::newMainPage();
2572 }
2573
2574 $query = [];
2575
2576 if ( $returnto ) {
2577 $query['returnto'] = $returnto->getPrefixedText();
2578
2579 if ( !$request->wasPosted() ) {
2580 $returntoquery = $request->getValues();
2581 unset( $returntoquery['title'] );
2582 unset( $returntoquery['returnto'] );
2583 unset( $returntoquery['returntoquery'] );
2584 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2585 }
2586 }
2587 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
2588 $loginLink = $linkRenderer->makeKnownLink(
2589 SpecialPage::getTitleFor( 'Userlogin' ),
2590 $this->msg( 'loginreqlink' )->text(),
2591 [],
2592 $query
2593 );
2594
2595 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2596 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2597
2598 # Don't return to a page the user can't read otherwise
2599 # we'll end up in a pointless loop
2600 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2601 $this->returnToMain( null, $displayReturnto );
2602 }
2603 } else {
2604 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2605 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2606 }
2607 }
2608
2609 /**
2610 * Display an error page indicating that a given version of MediaWiki is
2611 * required to use it
2612 *
2613 * @param mixed $version The version of MediaWiki needed to use the page
2614 */
2615 public function versionRequired( $version ) {
2616 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2617
2618 $this->addWikiMsg( 'versionrequiredtext', $version );
2619 $this->returnToMain();
2620 }
2621
2622 /**
2623 * Format a list of error messages
2624 *
2625 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2626 * @param string|null $action Action that was denied or null if unknown
2627 * @return string The wikitext error-messages, formatted into a list.
2628 */
2629 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2630 if ( $action == null ) {
2631 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2632 } else {
2633 $action_desc = $this->msg( "action-$action" )->plain();
2634 $text = $this->msg(
2635 'permissionserrorstext-withaction',
2636 count( $errors ),
2637 $action_desc
2638 )->plain() . "\n\n";
2639 }
2640
2641 if ( count( $errors ) > 1 ) {
2642 $text .= '<ul class="permissions-errors">' . "\n";
2643
2644 foreach ( $errors as $error ) {
2645 $text .= '<li>';
2646 $text .= $this->msg( ...$error )->plain();
2647 $text .= "</li>\n";
2648 }
2649 $text .= '</ul>';
2650 } else {
2651 $text .= "<div class=\"permissions-errors\">\n" .
2652 $this->msg( ...reset( $errors ) )->plain() .
2653 "\n</div>";
2654 }
2655
2656 return $text;
2657 }
2658
2659 /**
2660 * Show a warning about replica DB lag
2661 *
2662 * If the lag is higher than $wgSlaveLagCritical seconds,
2663 * then the warning is a bit more obvious. If the lag is
2664 * lower than $wgSlaveLagWarning, then no warning is shown.
2665 *
2666 * @param int $lag Slave lag
2667 */
2668 public function showLagWarning( $lag ) {
2669 $config = $this->getConfig();
2670 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2671 $lag = floor( $lag ); // floor to avoid nano seconds to display
2672 $message = $lag < $config->get( 'SlaveLagCritical' )
2673 ? 'lag-warn-normal'
2674 : 'lag-warn-high';
2675 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2676 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2677 }
2678 }
2679
2680 public function showFatalError( $message ) {
2681 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2682
2683 $this->addHTML( $message );
2684 }
2685
2686 public function showUnexpectedValueError( $name, $val ) {
2687 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2688 }
2689
2690 public function showFileCopyError( $old, $new ) {
2691 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2692 }
2693
2694 public function showFileRenameError( $old, $new ) {
2695 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2696 }
2697
2698 public function showFileDeleteError( $name ) {
2699 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2700 }
2701
2702 public function showFileNotFoundError( $name ) {
2703 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2704 }
2705
2706 /**
2707 * Add a "return to" link pointing to a specified title
2708 *
2709 * @param Title $title Title to link
2710 * @param array $query Query string parameters
2711 * @param string|null $text Text of the link (input is not escaped)
2712 * @param array $options Options array to pass to Linker
2713 */
2714 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2715 $linkRenderer = MediaWikiServices::getInstance()
2716 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2717 $link = $this->msg( 'returnto' )->rawParams(
2718 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2719 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2720 }
2721
2722 /**
2723 * Add a "return to" link pointing to a specified title,
2724 * or the title indicated in the request, or else the main page
2725 *
2726 * @param mixed|null $unused
2727 * @param Title|string|null $returnto Title or String to return to
2728 * @param string|null $returntoquery Query string for the return to link
2729 */
2730 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2731 if ( $returnto == null ) {
2732 $returnto = $this->getRequest()->getText( 'returnto' );
2733 }
2734
2735 if ( $returntoquery == null ) {
2736 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2737 }
2738
2739 if ( $returnto === '' ) {
2740 $returnto = Title::newMainPage();
2741 }
2742
2743 if ( is_object( $returnto ) ) {
2744 $titleObj = $returnto;
2745 } else {
2746 $titleObj = Title::newFromText( $returnto );
2747 }
2748 // We don't want people to return to external interwiki. That
2749 // might potentially be used as part of a phishing scheme
2750 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
2751 $titleObj = Title::newMainPage();
2752 }
2753
2754 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2755 }
2756
2757 private function getRlClientContext() {
2758 if ( !$this->rlClientContext ) {
2759 $query = ResourceLoader::makeLoaderQuery(
2760 [], // modules; not relevant
2761 $this->getLanguage()->getCode(),
2762 $this->getSkin()->getSkinName(),
2763 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2764 null, // version; not relevant
2765 ResourceLoader::inDebugMode(),
2766 null, // only; not relevant
2767 $this->isPrintable(),
2768 $this->getRequest()->getBool( 'handheld' )
2769 );
2770 $this->rlClientContext = new ResourceLoaderContext(
2771 $this->getResourceLoader(),
2772 new FauxRequest( $query )
2773 );
2774 if ( $this->contentOverrideCallbacks ) {
2775 $this->rlClientContext = new DerivativeResourceLoaderContext( $this->rlClientContext );
2776 $this->rlClientContext->setContentOverrideCallback( function ( Title $title ) {
2777 foreach ( $this->contentOverrideCallbacks as $callback ) {
2778 $content = call_user_func( $callback, $title );
2779 if ( $content !== null ) {
2780 return $content;
2781 }
2782 }
2783 return null;
2784 } );
2785 }
2786 }
2787 return $this->rlClientContext;
2788 }
2789
2790 /**
2791 * Call this to freeze the module queue and JS config and create a formatter.
2792 *
2793 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2794 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2795 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2796 * the module filters retroactively. Skins and extension hooks may also add modules until very
2797 * late in the request lifecycle.
2798 *
2799 * @return ResourceLoaderClientHtml
2800 */
2801 public function getRlClient() {
2802 if ( !$this->rlClient ) {
2803 $context = $this->getRlClientContext();
2804 $rl = $this->getResourceLoader();
2805 $this->addModules( [
2806 'user',
2807 'user.options',
2808 'user.tokens',
2809 ] );
2810 $this->addModuleStyles( [
2811 'site.styles',
2812 'noscript',
2813 'user.styles',
2814 ] );
2815 $this->getSkin()->setupSkinUserCss( $this );
2816
2817 // Prepare exempt modules for buildExemptModules()
2818 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2819 $exemptStates = [];
2820 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2821
2822 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2823 // Separate user-specific batch for improved cache-hit ratio.
2824 $userBatch = [ 'user.styles', 'user' ];
2825 $siteBatch = array_diff( $moduleStyles, $userBatch );
2826 $dbr = wfGetDB( DB_REPLICA );
2827 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2828 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2829
2830 // Filter out modules handled by buildExemptModules()
2831 $moduleStyles = array_filter( $moduleStyles,
2832 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2833 $module = $rl->getModule( $name );
2834 if ( $module ) {
2835 $group = $module->getGroup();
2836 if ( isset( $exemptGroups[$group] ) ) {
2837 $exemptStates[$name] = 'ready';
2838 if ( !$module->isKnownEmpty( $context ) ) {
2839 // E.g. Don't output empty <styles>
2840 $exemptGroups[$group][] = $name;
2841 }
2842 return false;
2843 }
2844 }
2845 return true;
2846 }
2847 );
2848 $this->rlExemptStyleModules = $exemptGroups;
2849
2850 $rlClient = new ResourceLoaderClientHtml( $context, [
2851 'target' => $this->getTarget(),
2852 'nonce' => $this->getCSPNonce(),
2853 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2854 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2855 // modules enqueud for loading on this page is filtered to just those.
2856 // However, to make sure we also apply the restriction to dynamic dependencies and
2857 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2858 // StartupModule so that the client-side registry will not contain any restricted
2859 // modules either. (T152169, T185303)
2860 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2861 <= ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
2862 ) ? '1' : null,
2863 ] );
2864 $rlClient->setConfig( $this->getJSVars() );
2865 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2866 $rlClient->setModuleStyles( $moduleStyles );
2867 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2868 $rlClient->setExemptStates( $exemptStates );
2869 $this->rlClient = $rlClient;
2870 }
2871 return $this->rlClient;
2872 }
2873
2874 /**
2875 * @param Skin $sk The given Skin
2876 * @param bool $includeStyle Unused
2877 * @return string The doctype, opening "<html>", and head element.
2878 */
2879 public function headElement( Skin $sk, $includeStyle = true ) {
2880 global $wgContLang;
2881
2882 $userdir = $this->getLanguage()->getDir();
2883 $sitedir = $wgContLang->getDir();
2884
2885 $pieces = [];
2886 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
2887 $this->getRlClient()->getDocumentAttributes(),
2888 $sk->getHtmlElementAttributes()
2889 ) );
2890 $pieces[] = Html::openElement( 'head' );
2891
2892 if ( $this->getHTMLTitle() == '' ) {
2893 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2894 }
2895
2896 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2897 // Add <meta charset="UTF-8">
2898 // This should be before <title> since it defines the charset used by
2899 // text including the text inside <title>.
2900 // The spec recommends defining XHTML5's charset using the XML declaration
2901 // instead of meta.
2902 // Our XML declaration is output by Html::htmlHeader.
2903 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2904 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2905 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
2906 }
2907
2908 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
2909 $pieces[] = $this->getRlClient()->getHeadHtml();
2910 $pieces[] = $this->buildExemptModules();
2911 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2912 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
2913
2914 // Use an IE conditional comment to serve the script only to old IE
2915 $pieces[] = '<!--[if lt IE 9]>' .
2916 ResourceLoaderClientHtml::makeLoad(
2917 ResourceLoaderContext::newDummyContext(),
2918 [ 'html5shiv' ],
2919 ResourceLoaderModule::TYPE_SCRIPTS,
2920 [ 'sync' => true ],
2921 $this->getCSPNonce()
2922 ) .
2923 '<![endif]-->';
2924
2925 $pieces[] = Html::closeElement( 'head' );
2926
2927 $bodyClasses = $this->mAdditionalBodyClasses;
2928 $bodyClasses[] = 'mediawiki';
2929
2930 # Classes for LTR/RTL directionality support
2931 $bodyClasses[] = $userdir;
2932 $bodyClasses[] = "sitedir-$sitedir";
2933
2934 $underline = $this->getUser()->getOption( 'underline' );
2935 if ( $underline < 2 ) {
2936 // The following classes can be used here:
2937 // * mw-underline-always
2938 // * mw-underline-never
2939 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
2940 }
2941
2942 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2943 # A <body> class is probably not the best way to do this . . .
2944 $bodyClasses[] = 'capitalize-all-nouns';
2945 }
2946
2947 // Parser feature migration class
2948 // The idea is that this will eventually be removed, after the wikitext
2949 // which requires it is cleaned up.
2950 $bodyClasses[] = 'mw-hide-empty-elt';
2951
2952 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2953 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2954 $bodyClasses[] =
2955 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2956
2957 $bodyAttrs = [];
2958 // While the implode() is not strictly needed, it's used for backwards compatibility
2959 // (this used to be built as a string and hooks likely still expect that).
2960 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2961
2962 // Allow skins and extensions to add body attributes they need
2963 $sk->addToBodyAttributes( $this, $bodyAttrs );
2964 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2965
2966 $pieces[] = Html::openElement( 'body', $bodyAttrs );
2967
2968 return self::combineWrappedStrings( $pieces );
2969 }
2970
2971 /**
2972 * Get a ResourceLoader object associated with this OutputPage
2973 *
2974 * @return ResourceLoader
2975 */
2976 public function getResourceLoader() {
2977 if ( is_null( $this->mResourceLoader ) ) {
2978 $this->mResourceLoader = new ResourceLoader(
2979 $this->getConfig(),
2980 LoggerFactory::getInstance( 'resourceloader' )
2981 );
2982 }
2983 return $this->mResourceLoader;
2984 }
2985
2986 /**
2987 * Explicily load or embed modules on a page.
2988 *
2989 * @param array|string $modules One or more module names
2990 * @param string $only ResourceLoaderModule TYPE_ class constant
2991 * @param array $extraQuery [optional] Array with extra query parameters for the request
2992 * @return string|WrappedStringList HTML
2993 */
2994 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2995 // Apply 'target' and 'origin' filters
2996 $modules = $this->filterModules( (array)$modules, null, $only );
2997
2998 return ResourceLoaderClientHtml::makeLoad(
2999 $this->getRlClientContext(),
3000 $modules,
3001 $only,
3002 $extraQuery,
3003 $this->getCSPNonce()
3004 );
3005 }
3006
3007 /**
3008 * Combine WrappedString chunks and filter out empty ones
3009 *
3010 * @param array $chunks
3011 * @return string|WrappedStringList HTML
3012 */
3013 protected static function combineWrappedStrings( array $chunks ) {
3014 // Filter out empty values
3015 $chunks = array_filter( $chunks, 'strlen' );
3016 return WrappedString::join( "\n", $chunks );
3017 }
3018
3019 /**
3020 * JS stuff to put at the bottom of the `<body>`.
3021 * These are legacy scripts ($this->mScripts), and user JS.
3022 *
3023 * @return string|WrappedStringList HTML
3024 */
3025 public function getBottomScripts() {
3026 $chunks = [];
3027 $chunks[] = $this->getRlClient()->getBodyHtml();
3028
3029 // Legacy non-ResourceLoader scripts
3030 $chunks[] = $this->mScripts;
3031
3032 if ( $this->limitReportJSData ) {
3033 $chunks[] = ResourceLoader::makeInlineScript(
3034 ResourceLoader::makeConfigSetScript(
3035 [ 'wgPageParseReport' => $this->limitReportJSData ]
3036 ),
3037 $this->getCSPNonce()
3038 );
3039 }
3040
3041 return self::combineWrappedStrings( $chunks );
3042 }
3043
3044 /**
3045 * Get the javascript config vars to include on this page
3046 *
3047 * @return array Array of javascript config vars
3048 * @since 1.23
3049 */
3050 public function getJsConfigVars() {
3051 return $this->mJsConfigVars;
3052 }
3053
3054 /**
3055 * Add one or more variables to be set in mw.config in JavaScript
3056 *
3057 * @param string|array $keys Key or array of key/value pairs
3058 * @param mixed|null $value [optional] Value of the configuration variable
3059 */
3060 public function addJsConfigVars( $keys, $value = null ) {
3061 if ( is_array( $keys ) ) {
3062 foreach ( $keys as $key => $value ) {
3063 $this->mJsConfigVars[$key] = $value;
3064 }
3065 return;
3066 }
3067
3068 $this->mJsConfigVars[$keys] = $value;
3069 }
3070
3071 /**
3072 * Get an array containing the variables to be set in mw.config in JavaScript.
3073 *
3074 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3075 * - in other words, page-independent/site-wide variables (without state).
3076 * You will only be adding bloat to the html page and causing page caches to
3077 * have to be purged on configuration changes.
3078 * @return array
3079 */
3080 public function getJSVars() {
3081 global $wgContLang;
3082
3083 $curRevisionId = 0;
3084 $articleId = 0;
3085 $canonicalSpecialPageName = false; # T23115
3086
3087 $title = $this->getTitle();
3088 $ns = $title->getNamespace();
3089 $canonicalNamespace = MWNamespace::exists( $ns )
3090 ? MWNamespace::getCanonicalName( $ns )
3091 : $title->getNsText();
3092
3093 $sk = $this->getSkin();
3094 // Get the relevant title so that AJAX features can use the correct page name
3095 // when making API requests from certain special pages (T36972).
3096 $relevantTitle = $sk->getRelevantTitle();
3097 $relevantUser = $sk->getRelevantUser();
3098
3099 if ( $ns == NS_SPECIAL ) {
3100 list( $canonicalSpecialPageName, /*...*/ ) =
3101 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3102 } elseif ( $this->canUseWikiPage() ) {
3103 $wikiPage = $this->getWikiPage();
3104 $curRevisionId = $wikiPage->getLatest();
3105 $articleId = $wikiPage->getId();
3106 }
3107
3108 $lang = $title->getPageViewLanguage();
3109
3110 // Pre-process information
3111 $separatorTransTable = $lang->separatorTransformTable();
3112 $separatorTransTable = $separatorTransTable ?: [];
3113 $compactSeparatorTransTable = [
3114 implode( "\t", array_keys( $separatorTransTable ) ),
3115 implode( "\t", $separatorTransTable ),
3116 ];
3117 $digitTransTable = $lang->digitTransformTable();
3118 $digitTransTable = $digitTransTable ?: [];
3119 $compactDigitTransTable = [
3120 implode( "\t", array_keys( $digitTransTable ) ),
3121 implode( "\t", $digitTransTable ),
3122 ];
3123
3124 $user = $this->getUser();
3125
3126 $vars = [
3127 'wgCanonicalNamespace' => $canonicalNamespace,
3128 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3129 'wgNamespaceNumber' => $title->getNamespace(),
3130 'wgPageName' => $title->getPrefixedDBkey(),
3131 'wgTitle' => $title->getText(),
3132 'wgCurRevisionId' => $curRevisionId,
3133 'wgRevisionId' => (int)$this->getRevisionId(),
3134 'wgArticleId' => $articleId,
3135 'wgIsArticle' => $this->isArticle(),
3136 'wgIsRedirect' => $title->isRedirect(),
3137 'wgAction' => Action::getActionName( $this->getContext() ),
3138 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3139 'wgUserGroups' => $user->getEffectiveGroups(),
3140 'wgCategories' => $this->getCategories(),
3141 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3142 'wgPageContentLanguage' => $lang->getCode(),
3143 'wgPageContentModel' => $title->getContentModel(),
3144 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3145 'wgDigitTransformTable' => $compactDigitTransTable,
3146 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3147 'wgMonthNames' => $lang->getMonthNamesArray(),
3148 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3149 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3150 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3151 'wgRequestId' => WebRequest::getRequestId(),
3152 ];
3153
3154 if ( $user->isLoggedIn() ) {
3155 $vars['wgUserId'] = $user->getId();
3156 $vars['wgUserEditCount'] = $user->getEditCount();
3157 $userReg = $user->getRegistration();
3158 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3159 // Get the revision ID of the oldest new message on the user's talk
3160 // page. This can be used for constructing new message alerts on
3161 // the client side.
3162 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3163 }
3164
3165 if ( $wgContLang->hasVariants() ) {
3166 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3167 }
3168 // Same test as SkinTemplate
3169 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3170 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3171
3172 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3173 && $relevantTitle->quickUserCan( 'edit', $user )
3174 && ( $relevantTitle->exists() || $relevantTitle->quickUserCan( 'create', $user ) );
3175
3176 foreach ( $title->getRestrictionTypes() as $type ) {
3177 // Following keys are set in $vars:
3178 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3179 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3180 }
3181
3182 if ( $title->isMainPage() ) {
3183 $vars['wgIsMainPage'] = true;
3184 }
3185
3186 if ( $this->mRedirectedFrom ) {
3187 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3188 }
3189
3190 if ( $relevantUser ) {
3191 $vars['wgRelevantUserName'] = $relevantUser->getName();
3192 }
3193
3194 // Allow extensions to add their custom variables to the mw.config map.
3195 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3196 // page-dependant but site-wide (without state).
3197 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3198 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3199
3200 // Merge in variables from addJsConfigVars last
3201 return array_merge( $vars, $this->getJsConfigVars() );
3202 }
3203
3204 /**
3205 * To make it harder for someone to slip a user a fake
3206 * JavaScript or CSS preview, a random token
3207 * is associated with the login session. If it's not
3208 * passed back with the preview request, we won't render
3209 * the code.
3210 *
3211 * @return bool
3212 */
3213 public function userCanPreview() {
3214 $request = $this->getRequest();
3215 if (
3216 $request->getVal( 'action' ) !== 'submit' ||
3217 !$request->wasPosted()
3218 ) {
3219 return false;
3220 }
3221
3222 $user = $this->getUser();
3223
3224 if ( !$user->isLoggedIn() ) {
3225 // Anons have predictable edit tokens
3226 return false;
3227 }
3228 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3229 return false;
3230 }
3231
3232 $title = $this->getTitle();
3233 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3234 if ( count( $errors ) !== 0 ) {
3235 return false;
3236 }
3237
3238 return true;
3239 }
3240
3241 /**
3242 * @return array Array in format "link name or number => 'link html'".
3243 */
3244 public function getHeadLinksArray() {
3245 global $wgVersion;
3246
3247 $tags = [];
3248 $config = $this->getConfig();
3249
3250 $canonicalUrl = $this->mCanonicalUrl;
3251
3252 $tags['meta-generator'] = Html::element( 'meta', [
3253 'name' => 'generator',
3254 'content' => "MediaWiki $wgVersion",
3255 ] );
3256
3257 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3258 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3259 // fallbacks should come before the primary value so we need to reverse the array.
3260 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3261 $tags["meta-referrer-$i"] = Html::element( 'meta', [
3262 'name' => 'referrer',
3263 'content' => $policy,
3264 ] );
3265 }
3266 }
3267
3268 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3269 if ( $p !== 'index,follow' ) {
3270 // http://www.robotstxt.org/wc/meta-user.html
3271 // Only show if it's different from the default robots policy
3272 $tags['meta-robots'] = Html::element( 'meta', [
3273 'name' => 'robots',
3274 'content' => $p,
3275 ] );
3276 }
3277
3278 foreach ( $this->mMetatags as $tag ) {
3279 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3280 $a = 'http-equiv';
3281 $tag[0] = substr( $tag[0], 5 );
3282 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3283 $a = 'property';
3284 } else {
3285 $a = 'name';
3286 }
3287 $tagName = "meta-{$tag[0]}";
3288 if ( isset( $tags[$tagName] ) ) {
3289 $tagName .= $tag[1];
3290 }
3291 $tags[$tagName] = Html::element( 'meta',
3292 [
3293 $a => $tag[0],
3294 'content' => $tag[1]
3295 ]
3296 );
3297 }
3298
3299 foreach ( $this->mLinktags as $tag ) {
3300 $tags[] = Html::element( 'link', $tag );
3301 }
3302
3303 # Universal edit button
3304 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3305 $user = $this->getUser();
3306 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3307 && ( $this->getTitle()->exists() ||
3308 $this->getTitle()->quickUserCan( 'create', $user ) )
3309 ) {
3310 // Original UniversalEditButton
3311 $msg = $this->msg( 'edit' )->text();
3312 $tags['universal-edit-button'] = Html::element( 'link', [
3313 'rel' => 'alternate',
3314 'type' => 'application/x-wiki',
3315 'title' => $msg,
3316 'href' => $this->getTitle()->getEditURL(),
3317 ] );
3318 // Alternate edit link
3319 $tags['alternative-edit'] = Html::element( 'link', [
3320 'rel' => 'edit',
3321 'title' => $msg,
3322 'href' => $this->getTitle()->getEditURL(),
3323 ] );
3324 }
3325 }
3326
3327 # Generally the order of the favicon and apple-touch-icon links
3328 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3329 # uses whichever one appears later in the HTML source. Make sure
3330 # apple-touch-icon is specified first to avoid this.
3331 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3332 $tags['apple-touch-icon'] = Html::element( 'link', [
3333 'rel' => 'apple-touch-icon',
3334 'href' => $config->get( 'AppleTouchIcon' )
3335 ] );
3336 }
3337
3338 if ( $config->get( 'Favicon' ) !== false ) {
3339 $tags['favicon'] = Html::element( 'link', [
3340 'rel' => 'shortcut icon',
3341 'href' => $config->get( 'Favicon' )
3342 ] );
3343 }
3344
3345 # OpenSearch description link
3346 $tags['opensearch'] = Html::element( 'link', [
3347 'rel' => 'search',
3348 'type' => 'application/opensearchdescription+xml',
3349 'href' => wfScript( 'opensearch_desc' ),
3350 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3351 ] );
3352
3353 # Real Simple Discovery link, provides auto-discovery information
3354 # for the MediaWiki API (and potentially additional custom API
3355 # support such as WordPress or Twitter-compatible APIs for a
3356 # blogging extension, etc)
3357 $tags['rsd'] = Html::element( 'link', [
3358 'rel' => 'EditURI',
3359 'type' => 'application/rsd+xml',
3360 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3361 // Whether RSD accepts relative or protocol-relative URLs is completely
3362 // undocumented, though.
3363 'href' => wfExpandUrl( wfAppendQuery(
3364 wfScript( 'api' ),
3365 [ 'action' => 'rsd' ] ),
3366 PROTO_RELATIVE
3367 ),
3368 ] );
3369
3370 # Language variants
3371 if ( !$config->get( 'DisableLangConversion' ) ) {
3372 $lang = $this->getTitle()->getPageLanguage();
3373 if ( $lang->hasVariants() ) {
3374 $variants = $lang->getVariants();
3375 foreach ( $variants as $variant ) {
3376 $tags["variant-$variant"] = Html::element( 'link', [
3377 'rel' => 'alternate',
3378 'hreflang' => LanguageCode::bcp47( $variant ),
3379 'href' => $this->getTitle()->getLocalURL(
3380 [ 'variant' => $variant ] )
3381 ]
3382 );
3383 }
3384 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3385 $tags["variant-x-default"] = Html::element( 'link', [
3386 'rel' => 'alternate',
3387 'hreflang' => 'x-default',
3388 'href' => $this->getTitle()->getLocalURL() ] );
3389 }
3390 }
3391
3392 # Copyright
3393 if ( $this->copyrightUrl !== null ) {
3394 $copyright = $this->copyrightUrl;
3395 } else {
3396 $copyright = '';
3397 if ( $config->get( 'RightsPage' ) ) {
3398 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3399
3400 if ( $copy ) {
3401 $copyright = $copy->getLocalURL();
3402 }
3403 }
3404
3405 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3406 $copyright = $config->get( 'RightsUrl' );
3407 }
3408 }
3409
3410 if ( $copyright ) {
3411 $tags['copyright'] = Html::element( 'link', [
3412 'rel' => 'license',
3413 'href' => $copyright ]
3414 );
3415 }
3416
3417 # Feeds
3418 if ( $config->get( 'Feed' ) ) {
3419 $feedLinks = [];
3420
3421 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3422 # Use the page name for the title. In principle, this could
3423 # lead to issues with having the same name for different feeds
3424 # corresponding to the same page, but we can't avoid that at
3425 # this low a level.
3426
3427 $feedLinks[] = $this->feedLink(
3428 $format,
3429 $link,
3430 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3431 $this->msg(
3432 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3433 )->text()
3434 );
3435 }
3436
3437 # Recent changes feed should appear on every page (except recentchanges,
3438 # that would be redundant). Put it after the per-page feed to avoid
3439 # changing existing behavior. It's still available, probably via a
3440 # menu in your browser. Some sites might have a different feed they'd
3441 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3442 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3443 # If so, use it instead.
3444 $sitename = $config->get( 'Sitename' );
3445 if ( $config->get( 'OverrideSiteFeed' ) ) {
3446 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3447 // Note, this->feedLink escapes the url.
3448 $feedLinks[] = $this->feedLink(
3449 $type,
3450 $feedUrl,
3451 $this->msg( "site-{$type}-feed", $sitename )->text()
3452 );
3453 }
3454 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3455 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3456 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3457 $feedLinks[] = $this->feedLink(
3458 $format,
3459 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3460 # For grep: 'site-rss-feed', 'site-atom-feed'
3461 $this->msg( "site-{$format}-feed", $sitename )->text()
3462 );
3463 }
3464 }
3465
3466 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3467 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3468 # use OutputPage::addFeedLink() instead.
3469 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3470
3471 $tags += $feedLinks;
3472 }
3473
3474 # Canonical URL
3475 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3476 if ( $canonicalUrl !== false ) {
3477 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3478 } else {
3479 if ( $this->isArticleRelated() ) {
3480 // This affects all requests where "setArticleRelated" is true. This is
3481 // typically all requests that show content (query title, curid, oldid, diff),
3482 // and all wikipage actions (edit, delete, purge, info, history etc.).
3483 // It does not apply to File pages and Special pages.
3484 // 'history' and 'info' actions address page metadata rather than the page
3485 // content itself, so they may not be canonicalized to the view page url.
3486 // TODO: this ought to be better encapsulated in the Action class.
3487 $action = Action::getActionName( $this->getContext() );
3488 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3489 $query = "action={$action}";
3490 } else {
3491 $query = '';
3492 }
3493 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3494 } else {
3495 $reqUrl = $this->getRequest()->getRequestURL();
3496 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3497 }
3498 }
3499 }
3500 if ( $canonicalUrl !== false ) {
3501 $tags[] = Html::element( 'link', [
3502 'rel' => 'canonical',
3503 'href' => $canonicalUrl
3504 ] );
3505 }
3506
3507 return $tags;
3508 }
3509
3510 /**
3511 * Generate a "<link rel/>" for a feed.
3512 *
3513 * @param string $type Feed type
3514 * @param string $url URL to the feed
3515 * @param string $text Value of the "title" attribute
3516 * @return string HTML fragment
3517 */
3518 private function feedLink( $type, $url, $text ) {
3519 return Html::element( 'link', [
3520 'rel' => 'alternate',
3521 'type' => "application/$type+xml",
3522 'title' => $text,
3523 'href' => $url ]
3524 );
3525 }
3526
3527 /**
3528 * Add a local or specified stylesheet, with the given media options.
3529 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3530 *
3531 * @param string $style URL to the file
3532 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3533 * @param string $condition For IE conditional comments, specifying an IE version
3534 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3535 */
3536 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3537 $options = [];
3538 if ( $media ) {
3539 $options['media'] = $media;
3540 }
3541 if ( $condition ) {
3542 $options['condition'] = $condition;
3543 }
3544 if ( $dir ) {
3545 $options['dir'] = $dir;
3546 }
3547 $this->styles[$style] = $options;
3548 }
3549
3550 /**
3551 * Adds inline CSS styles
3552 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3553 *
3554 * @param mixed $style_css Inline CSS
3555 * @param string $flip Set to 'flip' to flip the CSS if needed
3556 */
3557 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3558 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3559 # If wanted, and the interface is right-to-left, flip the CSS
3560 $style_css = CSSJanus::transform( $style_css, true, false );
3561 }
3562 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3563 }
3564
3565 /**
3566 * Build exempt modules and legacy non-ResourceLoader styles.
3567 *
3568 * @return string|WrappedStringList HTML
3569 */
3570 protected function buildExemptModules() {
3571 $chunks = [];
3572 // Things that go after the ResourceLoaderDynamicStyles marker
3573 $append = [];
3574
3575 // We want site, private and user styles to override dynamically added styles from
3576 // general modules, but we want dynamically added styles to override statically added
3577 // style modules. So the order has to be:
3578 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3579 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3580 // - ResourceLoaderDynamicStyles marker
3581 // - site/private/user styles
3582
3583 // Add legacy styles added through addStyle()/addInlineStyle() here
3584 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3585
3586 $chunks[] = Html::element(
3587 'meta',
3588 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3589 );
3590
3591 $separateReq = [ 'site.styles', 'user.styles' ];
3592 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3593 // Combinable modules
3594 $chunks[] = $this->makeResourceLoaderLink(
3595 array_diff( $moduleNames, $separateReq ),
3596 ResourceLoaderModule::TYPE_STYLES
3597 );
3598
3599 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3600 // These require their own dedicated request in order to support "@import"
3601 // syntax, which is incompatible with concatenation. (T147667, T37562)
3602 $chunks[] = $this->makeResourceLoaderLink( $name,
3603 ResourceLoaderModule::TYPE_STYLES
3604 );
3605 }
3606 }
3607
3608 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3609 }
3610
3611 /**
3612 * @return array
3613 */
3614 public function buildCssLinksArray() {
3615 $links = [];
3616
3617 foreach ( $this->styles as $file => $options ) {
3618 $link = $this->styleLink( $file, $options );
3619 if ( $link ) {
3620 $links[$file] = $link;
3621 }
3622 }
3623 return $links;
3624 }
3625
3626 /**
3627 * Generate \<link\> tags for stylesheets
3628 *
3629 * @param string $style URL to the file
3630 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3631 * @return string HTML fragment
3632 */
3633 protected function styleLink( $style, array $options ) {
3634 if ( isset( $options['dir'] ) ) {
3635 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3636 return '';
3637 }
3638 }
3639
3640 if ( isset( $options['media'] ) ) {
3641 $media = self::transformCssMedia( $options['media'] );
3642 if ( is_null( $media ) ) {
3643 return '';
3644 }
3645 } else {
3646 $media = 'all';
3647 }
3648
3649 if ( substr( $style, 0, 1 ) == '/' ||
3650 substr( $style, 0, 5 ) == 'http:' ||
3651 substr( $style, 0, 6 ) == 'https:' ) {
3652 $url = $style;
3653 } else {
3654 $config = $this->getConfig();
3655 // Append file hash as query parameter
3656 $url = self::transformResourcePath(
3657 $config,
3658 $config->get( 'StylePath' ) . '/' . $style
3659 );
3660 }
3661
3662 $link = Html::linkedStyle( $url, $media );
3663
3664 if ( isset( $options['condition'] ) ) {
3665 $condition = htmlspecialchars( $options['condition'] );
3666 $link = "<!--[if $condition]>$link<![endif]-->";
3667 }
3668 return $link;
3669 }
3670
3671 /**
3672 * Transform path to web-accessible static resource.
3673 *
3674 * This is used to add a validation hash as query string.
3675 * This aids various behaviors:
3676 *
3677 * - Put long Cache-Control max-age headers on responses for improved
3678 * cache performance.
3679 * - Get the correct version of a file as expected by the current page.
3680 * - Instantly get the updated version of a file after deployment.
3681 *
3682 * Avoid using this for urls included in HTML as otherwise clients may get different
3683 * versions of a resource when navigating the site depending on when the page was cached.
3684 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3685 * an external stylesheet).
3686 *
3687 * @since 1.27
3688 * @param Config $config
3689 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3690 * @return string URL
3691 */
3692 public static function transformResourcePath( Config $config, $path ) {
3693 global $IP;
3694
3695 $localDir = $IP;
3696 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3697 if ( $remotePathPrefix === '' ) {
3698 // The configured base path is required to be empty string for
3699 // wikis in the domain root
3700 $remotePath = '/';
3701 } else {
3702 $remotePath = $remotePathPrefix;
3703 }
3704 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
3705 // - Path is outside wgResourceBasePath, ignore.
3706 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3707 return $path;
3708 }
3709 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3710 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3711 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3712 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3713 $uploadPath = $config->get( 'UploadPath' );
3714 if ( strpos( $path, $uploadPath ) === 0 ) {
3715 $localDir = $config->get( 'UploadDirectory' );
3716 $remotePathPrefix = $remotePath = $uploadPath;
3717 }
3718
3719 $path = RelPath::getRelativePath( $path, $remotePath );
3720 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
3721 }
3722
3723 /**
3724 * Utility method for transformResourceFilePath().
3725 *
3726 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3727 *
3728 * @since 1.27
3729 * @param string $remotePathPrefix URL path prefix that points to $localPath
3730 * @param string $localPath File directory exposed at $remotePath
3731 * @param string $file Path to target file relative to $localPath
3732 * @return string URL
3733 */
3734 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3735 $hash = md5_file( "$localPath/$file" );
3736 if ( $hash === false ) {
3737 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3738 $hash = '';
3739 }
3740 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3741 }
3742
3743 /**
3744 * Transform "media" attribute based on request parameters
3745 *
3746 * @param string $media Current value of the "media" attribute
3747 * @return string Modified value of the "media" attribute, or null to skip
3748 * this stylesheet
3749 */
3750 public static function transformCssMedia( $media ) {
3751 global $wgRequest;
3752
3753 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3754 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3755
3756 // Switch in on-screen display for media testing
3757 $switches = [
3758 'printable' => 'print',
3759 'handheld' => 'handheld',
3760 ];
3761 foreach ( $switches as $switch => $targetMedia ) {
3762 if ( $wgRequest->getBool( $switch ) ) {
3763 if ( $media == $targetMedia ) {
3764 $media = '';
3765 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3766 /* This regex will not attempt to understand a comma-separated media_query_list
3767 *
3768 * Example supported values for $media:
3769 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3770 * Example NOT supported value for $media:
3771 * '3d-glasses, screen, print and resolution > 90dpi'
3772 *
3773 * If it's a print request, we never want any kind of screen stylesheets
3774 * If it's a handheld request (currently the only other choice with a switch),
3775 * we don't want simple 'screen' but we might want screen queries that
3776 * have a max-width or something, so we'll pass all others on and let the
3777 * client do the query.
3778 */
3779 if ( $targetMedia == 'print' || $media == 'screen' ) {
3780 return null;
3781 }
3782 }
3783 }
3784 }
3785
3786 return $media;
3787 }
3788
3789 /**
3790 * Add a wikitext-formatted message to the output.
3791 * This is equivalent to:
3792 *
3793 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3794 */
3795 public function addWikiMsg( /*...*/ ) {
3796 $args = func_get_args();
3797 $name = array_shift( $args );
3798 $this->addWikiMsgArray( $name, $args );
3799 }
3800
3801 /**
3802 * Add a wikitext-formatted message to the output.
3803 * Like addWikiMsg() except the parameters are taken as an array
3804 * instead of a variable argument list.
3805 *
3806 * @param string $name
3807 * @param array $args
3808 */
3809 public function addWikiMsgArray( $name, $args ) {
3810 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3811 }
3812
3813 /**
3814 * This function takes a number of message/argument specifications, wraps them in
3815 * some overall structure, and then parses the result and adds it to the output.
3816 *
3817 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3818 * and so on. The subsequent arguments may be either
3819 * 1) strings, in which case they are message names, or
3820 * 2) arrays, in which case, within each array, the first element is the message
3821 * name, and subsequent elements are the parameters to that message.
3822 *
3823 * Don't use this for messages that are not in the user's interface language.
3824 *
3825 * For example:
3826 *
3827 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3828 *
3829 * Is equivalent to:
3830 *
3831 * $wgOut->addWikiText( "<div class='error'>\n"
3832 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3833 *
3834 * The newline after the opening div is needed in some wikitext. See T21226.
3835 *
3836 * @param string $wrap
3837 */
3838 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3839 $msgSpecs = func_get_args();
3840 array_shift( $msgSpecs );
3841 $msgSpecs = array_values( $msgSpecs );
3842 $s = $wrap;
3843 foreach ( $msgSpecs as $n => $spec ) {
3844 if ( is_array( $spec ) ) {
3845 $args = $spec;
3846 $name = array_shift( $args );
3847 if ( isset( $args['options'] ) ) {
3848 unset( $args['options'] );
3849 wfDeprecated(
3850 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3851 '1.20'
3852 );
3853 }
3854 } else {
3855 $args = [];
3856 $name = $spec;
3857 }
3858 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3859 }
3860 $this->addWikiText( $s );
3861 }
3862
3863 /**
3864 * Whether the output has a table of contents
3865 * @return bool
3866 * @since 1.22
3867 */
3868 public function isTOCEnabled() {
3869 return $this->mEnableTOC;
3870 }
3871
3872 /**
3873 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3874 * @param bool $flag
3875 * @since 1.23
3876 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3877 */
3878 public function enableSectionEditLinks( $flag = true ) {
3879 wfDeprecated( __METHOD__, '1.31' );
3880 }
3881
3882 /**
3883 * @return bool
3884 * @since 1.23
3885 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3886 */
3887 public function sectionEditLinksEnabled() {
3888 wfDeprecated( __METHOD__, '1.31' );
3889 return true;
3890 }
3891
3892 /**
3893 * Helper function to setup the PHP implementation of OOUI to use in this request.
3894 *
3895 * @since 1.26
3896 * @param String $skinName The Skin name to determine the correct OOUI theme
3897 * @param String $dir Language direction
3898 */
3899 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3900 $themes = ResourceLoaderOOUIModule::getSkinThemeMap();
3901 $theme = $themes[$skinName] ?? $themes['default'];
3902 // For example, 'OOUI\WikimediaUITheme'.
3903 $themeClass = "OOUI\\{$theme}Theme";
3904 OOUI\Theme::setSingleton( new $themeClass() );
3905 OOUI\Element::setDefaultDir( $dir );
3906 }
3907
3908 /**
3909 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3910 * MediaWiki and this OutputPage instance.
3911 *
3912 * @since 1.25
3913 */
3914 public function enableOOUI() {
3915 self::setupOOUI(
3916 strtolower( $this->getSkin()->getSkinName() ),
3917 $this->getLanguage()->getDir()
3918 );
3919 $this->addModuleStyles( [
3920 'oojs-ui-core.styles',
3921 'oojs-ui.styles.indicators',
3922 'oojs-ui.styles.textures',
3923 'mediawiki.widgets.styles',
3924 'oojs-ui.styles.icons-content',
3925 'oojs-ui.styles.icons-alerts',
3926 'oojs-ui.styles.icons-interactions',
3927 ] );
3928 }
3929
3930 /**
3931 * Add Link headers for preloading the wiki's logo.
3932 *
3933 * @since 1.26
3934 */
3935 protected function addLogoPreloadLinkHeaders() {
3936 $logo = ResourceLoaderSkinModule::getLogo( $this->getConfig() );
3937
3938 $tags = [];
3939 $logosPerDppx = [];
3940 $logos = [];
3941
3942 if ( !is_array( $logo ) ) {
3943 // No media queries required if we only have one variant
3944 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3945 return;
3946 }
3947
3948 if ( isset( $logo['svg'] ) ) {
3949 // No media queries required if we only have a 1x and svg variant
3950 // because all preload-capable browsers support SVGs
3951 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3952 return;
3953 }
3954
3955 foreach ( $logo as $dppx => $src ) {
3956 // Keys are in this format: "1.5x"
3957 $dppx = substr( $dppx, 0, -1 );
3958 $logosPerDppx[$dppx] = $src;
3959 }
3960
3961 // Because PHP can't have floats as array keys
3962 uksort( $logosPerDppx, function ( $a , $b ) {
3963 $a = floatval( $a );
3964 $b = floatval( $b );
3965 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3966 return $a <=> $b;
3967 } );
3968
3969 foreach ( $logosPerDppx as $dppx => $src ) {
3970 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3971 }
3972
3973 $logosCount = count( $logos );
3974 // Logic must match ResourceLoaderSkinModule:
3975 // - 1x applies to resolution < 1.5dppx
3976 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3977 // - 2x applies to resolution >= 2dppx
3978 // Note that min-resolution and max-resolution are both inclusive.
3979 for ( $i = 0; $i < $logosCount; $i++ ) {
3980 if ( $i === 0 ) {
3981 // Smallest dppx
3982 // min-resolution is ">=" (larger than or equal to)
3983 // "not min-resolution" is essentially "<"
3984 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
3985 } elseif ( $i !== $logosCount - 1 ) {
3986 // In between
3987 // Media query expressions can only apply "not" to the entire expression
3988 // (e.g. can't express ">= 1.5 and not >= 2).
3989 // Workaround: Use <= 1.9999 in place of < 2.
3990 $upper_bound = floatval( $logos[ $i + 1 ]['dppx'] ) - 0.000001;
3991 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
3992 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
3993 } else {
3994 // Largest dppx
3995 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
3996 }
3997
3998 $this->addLinkHeader(
3999 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query
4000 );
4001 }
4002 }
4003
4004 /**
4005 * Get (and set if not yet set) the CSP nonce.
4006 *
4007 * This value needs to be included in any <script> tags on the
4008 * page.
4009 *
4010 * @return string|bool Nonce or false to mean don't output nonce
4011 * @since 1.32
4012 */
4013 public function getCSPNonce() {
4014 if ( !ContentSecurityPolicy::isNonceRequired( $this->getConfig() ) ) {
4015 return false;
4016 }
4017 if ( $this->CSPNonce === null ) {
4018 // XXX It might be expensive to generate randomness
4019 // on every request, on Windows.
4020 $rand = random_bytes( 15 );
4021 $this->CSPNonce = base64_encode( $rand );
4022 }
4023 return $this->CSPNonce;
4024 }
4025 }