OutputPage::addScriptFile: Drop silencing invalid paths, deprecated in 1.24
[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\MediaWikiServices;
25 use MediaWiki\Session\SessionManager;
26 use Wikimedia\Rdbms\IResultWrapper;
27 use Wikimedia\RelPath;
28 use Wikimedia\WrappedString;
29 use Wikimedia\WrappedStringList;
30
31 /**
32 * This class should be covered by a general architecture document which does
33 * not exist as of January 2011. This is one of the Core classes and should
34 * be read at least once by any new developers.
35 *
36 * This class is used to prepare the final rendering. A skin is then
37 * applied to the output parameters (links, javascript, html, categories ...).
38 *
39 * @todo FIXME: Another class handles sending the whole page to the client.
40 *
41 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
42 * in November 2010.
43 *
44 * @todo document
45 */
46 class OutputPage extends ContextSource {
47 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
48 protected $mMetatags = [];
49
50 /** @var array */
51 protected $mLinktags = [];
52
53 /** @var bool */
54 protected $mCanonicalUrl = false;
55
56 /**
57 * @var string The contents of <h1> */
58 private $mPageTitle = '';
59
60 /**
61 * @var string The displayed title of the page. Different from page title
62 * if overridden by display title magic word or hooks. Can contain safe
63 * HTML. Different from page title which may contain messages such as
64 * "Editing X" which is displayed in h1. This can be used for other places
65 * where the page name is referred on the page.
66 */
67 private $displayTitle;
68
69 /**
70 * @var string Contains all of the "<body>" content. Should be private we
71 * got set/get accessors and the append() method.
72 */
73 public $mBodytext = '';
74
75 /** @var string Stores contents of "<title>" tag */
76 private $mHTMLtitle = '';
77
78 /**
79 * @var bool Is the displayed content related to the source of the
80 * corresponding wiki article.
81 */
82 private $mIsArticle = false;
83
84 /** @var bool Stores "article flag" toggle. */
85 private $mIsArticleRelated = true;
86
87 /** @var bool Is the content subject to copyright */
88 private $mHasCopyright = false;
89
90 /**
91 * @var bool We have to set isPrintable(). Some pages should
92 * never be printed (ex: redirections).
93 */
94 private $mPrintable = false;
95
96 /**
97 * @var array Contains the page subtitle. Special pages usually have some
98 * links here. Don't confuse with site subtitle added by skins.
99 */
100 private $mSubtitle = [];
101
102 /** @var string */
103 public $mRedirect = '';
104
105 /** @var int */
106 protected $mStatusCode;
107
108 /**
109 * @var string Used for sending cache control.
110 * The whole caching system should probably be moved into its own class.
111 */
112 protected $mLastModified = '';
113
114 /** @var array */
115 protected $mCategoryLinks = [];
116
117 /** @var array */
118 protected $mCategories = [
119 'hidden' => [],
120 'normal' => [],
121 ];
122
123 /** @var array */
124 protected $mIndicators = [];
125
126 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
127 private $mLanguageLinks = [];
128
129 /**
130 * Used for JavaScript (predates ResourceLoader)
131 * @todo We should split JS / CSS.
132 * mScripts content is inserted as is in "<head>" by Skin. This might
133 * contain either a link to a stylesheet or inline CSS.
134 */
135 private $mScripts = '';
136
137 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
138 protected $mInlineStyles = '';
139
140 /**
141 * @var string Used by skin template.
142 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
143 */
144 public $mPageLinkTitle = '';
145
146 /** @var array Array of elements in "<head>". Parser might add its own headers! */
147 protected $mHeadItems = [];
148
149 /** @var array Additional <body> classes; there are also <body> classes from other sources */
150 protected $mAdditionalBodyClasses = [];
151
152 /** @var array */
153 protected $mModules = [];
154
155 /** @var array */
156 protected $mModuleStyles = [];
157
158 /** @var ResourceLoader */
159 protected $mResourceLoader;
160
161 /** @var ResourceLoaderClientHtml */
162 private $rlClient;
163
164 /** @var ResourceLoaderContext */
165 private $rlClientContext;
166
167 /** @var array */
168 private $rlExemptStyleModules;
169
170 /** @var array */
171 protected $mJsConfigVars = [];
172
173 /** @var array */
174 protected $mTemplateIds = [];
175
176 /** @var array */
177 protected $mImageTimeKeys = [];
178
179 /** @var string */
180 public $mRedirectCode = '';
181
182 protected $mFeedLinksAppendQuery = null;
183
184 /** @var array
185 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
186 * @see ResourceLoaderModule::$origin
187 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
188 */
189 protected $mAllowedModules = [
190 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
191 ];
192
193 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
194 protected $mDoNothing = false;
195
196 // Parser related.
197
198 /** @var int */
199 protected $mContainsNewMagic = 0;
200
201 /**
202 * lazy initialised, use parserOptions()
203 * @var ParserOptions
204 */
205 protected $mParserOptions = null;
206
207 /**
208 * Handles the Atom / RSS links.
209 * We probably only support Atom in 2011.
210 * @see $wgAdvertisedFeedTypes
211 */
212 private $mFeedLinks = [];
213
214 // Gwicke work on squid caching? Roughly from 2003.
215 protected $mEnableClientCache = true;
216
217 /** @var bool Flag if output should only contain the body of the article. */
218 private $mArticleBodyOnly = false;
219
220 /** @var bool */
221 protected $mNewSectionLink = false;
222
223 /** @var bool */
224 protected $mHideNewSectionLink = false;
225
226 /**
227 * @var bool Comes from the parser. This was probably made to load CSS/JS
228 * only if we had "<gallery>". Used directly in CategoryPage.php.
229 * Looks like ResourceLoader can replace this.
230 */
231 public $mNoGallery = false;
232
233 /** @var int Cache stuff. Looks like mEnableClientCache */
234 protected $mCdnMaxage = 0;
235 /** @var int Upper limit on mCdnMaxage */
236 protected $mCdnMaxageLimit = INF;
237
238 /**
239 * @var bool Controls if anti-clickjacking / frame-breaking headers will
240 * be sent. This should be done for pages where edit actions are possible.
241 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
242 */
243 protected $mPreventClickjacking = true;
244
245 /** @var int To include the variable {{REVISIONID}} */
246 private $mRevisionId = null;
247
248 /** @var string */
249 private $mRevisionTimestamp = null;
250
251 /** @var array */
252 protected $mFileVersion = null;
253
254 /**
255 * @var array An array of stylesheet filenames (relative from skins path),
256 * with options for CSS media, IE conditions, and RTL/LTR direction.
257 * For internal use; add settings in the skin via $this->addStyle()
258 *
259 * Style again! This seems like a code duplication since we already have
260 * mStyles. This is what makes Open Source amazing.
261 */
262 protected $styles = [];
263
264 private $mIndexPolicy = 'index';
265 private $mFollowPolicy = 'follow';
266
267 /**
268 * @var array Headers that cause the cache to vary. Key is header name,
269 * value should always be null. (Value was an array of options for
270 * the `Key` header, which was deprecated in 1.32 and removed in 1.34.)
271 */
272 private $mVaryHeader = [
273 'Accept-Encoding' => null,
274 ];
275
276 /**
277 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
278 * of the redirect.
279 *
280 * @var Title
281 */
282 private $mRedirectedFrom = null;
283
284 /**
285 * Additional key => value data
286 */
287 private $mProperties = [];
288
289 /**
290 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
291 */
292 private $mTarget = null;
293
294 /**
295 * @var bool Whether parser output contains a table of contents
296 */
297 private $mEnableTOC = false;
298
299 /**
300 * @var string|null The URL to send in a <link> element with rel=license
301 */
302 private $copyrightUrl;
303
304 /** @var array Profiling data */
305 private $limitReportJSData = [];
306
307 /** @var array Map Title to Content */
308 private $contentOverrides = [];
309
310 /** @var callable[] */
311 private $contentOverrideCallbacks = [];
312
313 /**
314 * Link: header contents
315 */
316 private $mLinkHeader = [];
317
318 /**
319 * @var string The nonce for Content-Security-Policy
320 */
321 private $CSPNonce;
322
323 /**
324 * @var array A cache of the names of the cookies that will influence the cache
325 */
326 private static $cacheVaryCookies = null;
327
328 /**
329 * Constructor for OutputPage. This should not be called directly.
330 * Instead a new RequestContext should be created and it will implicitly create
331 * a OutputPage tied to that context.
332 * @param IContextSource $context
333 */
334 function __construct( IContextSource $context ) {
335 $this->setContext( $context );
336 }
337
338 /**
339 * Redirect to $url rather than displaying the normal page
340 *
341 * @param string $url
342 * @param string $responsecode HTTP status code
343 */
344 public function redirect( $url, $responsecode = '302' ) {
345 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
346 $this->mRedirect = str_replace( "\n", '', $url );
347 $this->mRedirectCode = $responsecode;
348 }
349
350 /**
351 * Get the URL to redirect to, or an empty string if not redirect URL set
352 *
353 * @return string
354 */
355 public function getRedirect() {
356 return $this->mRedirect;
357 }
358
359 /**
360 * Set the copyright URL to send with the output.
361 * Empty string to omit, null to reset.
362 *
363 * @since 1.26
364 *
365 * @param string|null $url
366 */
367 public function setCopyrightUrl( $url ) {
368 $this->copyrightUrl = $url;
369 }
370
371 /**
372 * Set the HTTP status code to send with the output.
373 *
374 * @param int $statusCode
375 */
376 public function setStatusCode( $statusCode ) {
377 $this->mStatusCode = $statusCode;
378 }
379
380 /**
381 * Add a new "<meta>" tag
382 * To add an http-equiv meta tag, precede the name with "http:"
383 *
384 * @param string $name Name of the meta tag
385 * @param string $val Value of the meta tag
386 */
387 function addMeta( $name, $val ) {
388 array_push( $this->mMetatags, [ $name, $val ] );
389 }
390
391 /**
392 * Returns the current <meta> tags
393 *
394 * @since 1.25
395 * @return array
396 */
397 public function getMetaTags() {
398 return $this->mMetatags;
399 }
400
401 /**
402 * Add a new \<link\> tag to the page header.
403 *
404 * Note: use setCanonicalUrl() for rel=canonical.
405 *
406 * @param array $linkarr Associative array of attributes.
407 */
408 function addLink( array $linkarr ) {
409 array_push( $this->mLinktags, $linkarr );
410 }
411
412 /**
413 * Returns the current <link> tags
414 *
415 * @since 1.25
416 * @return array
417 */
418 public function getLinkTags() {
419 return $this->mLinktags;
420 }
421
422 /**
423 * Set the URL to be used for the <link rel=canonical>. This should be used
424 * in preference to addLink(), to avoid duplicate link tags.
425 * @param string $url
426 */
427 function setCanonicalUrl( $url ) {
428 $this->mCanonicalUrl = $url;
429 }
430
431 /**
432 * Returns the URL to be used for the <link rel=canonical> if
433 * one is set.
434 *
435 * @since 1.25
436 * @return bool|string
437 */
438 public function getCanonicalUrl() {
439 return $this->mCanonicalUrl;
440 }
441
442 /**
443 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
444 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
445 * if possible.
446 *
447 * @param string $script Raw HTML
448 */
449 function addScript( $script ) {
450 $this->mScripts .= $script;
451 }
452
453 /**
454 * Add a JavaScript file to be loaded as `<script>` on this page.
455 *
456 * Internal use only. Use OutputPage::addModules() if possible.
457 *
458 * @param string $file URL to file (absolute path, protocol-relative, or full url)
459 * @param string|null $unused Previously used to change the cache-busting query parameter
460 */
461 public function addScriptFile( $file, $unused = null ) {
462 $this->addScript( Html::linkedScript( $file, $this->getCSPNonce() ) );
463 }
464
465 /**
466 * Add a self-contained script tag with the given contents
467 * Internal use only. Use OutputPage::addModules() if possible.
468 *
469 * @param string $script JavaScript text, no script tags
470 */
471 public function addInlineScript( $script ) {
472 $this->mScripts .= Html::inlineScript( "\n$script\n", $this->getCSPNonce() ) . "\n";
473 }
474
475 /**
476 * Filter an array of modules to remove insufficiently trustworthy members, and modules
477 * which are no longer registered (eg a page is cached before an extension is disabled)
478 * @param array $modules
479 * @param string|null $position Unused
480 * @param string $type
481 * @return array
482 */
483 protected function filterModules( array $modules, $position = null,
484 $type = ResourceLoaderModule::TYPE_COMBINED
485 ) {
486 $resourceLoader = $this->getResourceLoader();
487 $filteredModules = [];
488 foreach ( $modules as $val ) {
489 $module = $resourceLoader->getModule( $val );
490 if ( $module instanceof ResourceLoaderModule
491 && $module->getOrigin() <= $this->getAllowedModules( $type )
492 ) {
493 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
494 $this->warnModuleTargetFilter( $module->getName() );
495 continue;
496 }
497 $filteredModules[] = $val;
498 }
499 }
500 return $filteredModules;
501 }
502
503 private function warnModuleTargetFilter( $moduleName ) {
504 static $warnings = [];
505 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
506 return;
507 }
508 $warnings[$this->mTarget][$moduleName] = true;
509 $this->getResourceLoader()->getLogger()->debug(
510 'Module "{module}" not loadable on target "{target}".',
511 [
512 'module' => $moduleName,
513 'target' => $this->mTarget,
514 ]
515 );
516 }
517
518 /**
519 * Get the list of modules to include on this page
520 *
521 * @param bool $filter Whether to filter out insufficiently trustworthy modules
522 * @param string|null $position Unused
523 * @param string $param
524 * @param string $type
525 * @return array Array of module names
526 */
527 public function getModules( $filter = false, $position = null, $param = 'mModules',
528 $type = ResourceLoaderModule::TYPE_COMBINED
529 ) {
530 $modules = array_values( array_unique( $this->$param ) );
531 return $filter
532 ? $this->filterModules( $modules, null, $type )
533 : $modules;
534 }
535
536 /**
537 * Load one or more ResourceLoader modules on this page.
538 *
539 * @param string|array $modules Module name (string) or array of module names
540 */
541 public function addModules( $modules ) {
542 $this->mModules = array_merge( $this->mModules, (array)$modules );
543 }
544
545 /**
546 * Get the list of style-only modules to load on this page.
547 *
548 * @param bool $filter
549 * @param string|null $position Unused
550 * @return array Array of module names
551 */
552 public function getModuleStyles( $filter = false, $position = null ) {
553 return $this->getModules( $filter, null, 'mModuleStyles',
554 ResourceLoaderModule::TYPE_STYLES
555 );
556 }
557
558 /**
559 * Load the styles of one or more ResourceLoader modules on this page.
560 *
561 * Module styles added through this function will be loaded as a stylesheet,
562 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
563 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
564 *
565 * @param string|array $modules Module name (string) or array of module names
566 */
567 public function addModuleStyles( $modules ) {
568 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
569 }
570
571 /**
572 * @return null|string ResourceLoader target
573 */
574 public function getTarget() {
575 return $this->mTarget;
576 }
577
578 /**
579 * Sets ResourceLoader target for load.php links. If null, will be omitted
580 *
581 * @param string|null $target
582 */
583 public function setTarget( $target ) {
584 $this->mTarget = $target;
585 }
586
587 /**
588 * Add a mapping from a LinkTarget to a Content, for things like page preview.
589 * @see self::addContentOverrideCallback()
590 * @since 1.32
591 * @param LinkTarget $target
592 * @param Content $content
593 */
594 public function addContentOverride( LinkTarget $target, Content $content ) {
595 if ( !$this->contentOverrides ) {
596 // Register a callback for $this->contentOverrides on the first call
597 $this->addContentOverrideCallback( function ( LinkTarget $target ) {
598 $key = $target->getNamespace() . ':' . $target->getDBkey();
599 return $this->contentOverrides[$key] ?? null;
600 } );
601 }
602
603 $key = $target->getNamespace() . ':' . $target->getDBkey();
604 $this->contentOverrides[$key] = $content;
605 }
606
607 /**
608 * Add a callback for mapping from a Title to a Content object, for things
609 * like page preview.
610 * @see ResourceLoaderContext::getContentOverrideCallback()
611 * @since 1.32
612 * @param callable $callback
613 */
614 public function addContentOverrideCallback( callable $callback ) {
615 $this->contentOverrideCallbacks[] = $callback;
616 }
617
618 /**
619 * Get an array of head items
620 *
621 * @return array
622 */
623 function getHeadItemsArray() {
624 return $this->mHeadItems;
625 }
626
627 /**
628 * Add or replace a head item to the output
629 *
630 * Whenever possible, use more specific options like ResourceLoader modules,
631 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
632 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
633 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
634 * This would be your very LAST fallback.
635 *
636 * @param string $name Item name
637 * @param string $value Raw HTML
638 */
639 public function addHeadItem( $name, $value ) {
640 $this->mHeadItems[$name] = $value;
641 }
642
643 /**
644 * Add one or more head items to the output
645 *
646 * @since 1.28
647 * @param string|string[] $values Raw HTML
648 */
649 public function addHeadItems( $values ) {
650 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
651 }
652
653 /**
654 * Check if the header item $name is already set
655 *
656 * @param string $name Item name
657 * @return bool
658 */
659 public function hasHeadItem( $name ) {
660 return isset( $this->mHeadItems[$name] );
661 }
662
663 /**
664 * Add a class to the <body> element
665 *
666 * @since 1.30
667 * @param string|string[] $classes One or more classes to add
668 */
669 public function addBodyClasses( $classes ) {
670 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
671 }
672
673 /**
674 * Set whether the output should only contain the body of the article,
675 * without any skin, sidebar, etc.
676 * Used e.g. when calling with "action=render".
677 *
678 * @param bool $only Whether to output only the body of the article
679 */
680 public function setArticleBodyOnly( $only ) {
681 $this->mArticleBodyOnly = $only;
682 }
683
684 /**
685 * Return whether the output will contain only the body of the article
686 *
687 * @return bool
688 */
689 public function getArticleBodyOnly() {
690 return $this->mArticleBodyOnly;
691 }
692
693 /**
694 * Set an additional output property
695 * @since 1.21
696 *
697 * @param string $name
698 * @param mixed $value
699 */
700 public function setProperty( $name, $value ) {
701 $this->mProperties[$name] = $value;
702 }
703
704 /**
705 * Get an additional output property
706 * @since 1.21
707 *
708 * @param string $name
709 * @return mixed Property value or null if not found
710 */
711 public function getProperty( $name ) {
712 return $this->mProperties[$name] ?? null;
713 }
714
715 /**
716 * checkLastModified tells the client to use the client-cached page if
717 * possible. If successful, the OutputPage is disabled so that
718 * any future call to OutputPage->output() have no effect.
719 *
720 * Side effect: sets mLastModified for Last-Modified header
721 *
722 * @param string $timestamp
723 *
724 * @return bool True if cache-ok headers was sent.
725 */
726 public function checkLastModified( $timestamp ) {
727 if ( !$timestamp || $timestamp == '19700101000000' ) {
728 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
729 return false;
730 }
731 $config = $this->getConfig();
732 if ( !$config->get( 'CachePages' ) ) {
733 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
734 return false;
735 }
736
737 $timestamp = wfTimestamp( TS_MW, $timestamp );
738 $modifiedTimes = [
739 'page' => $timestamp,
740 'user' => $this->getUser()->getTouched(),
741 'epoch' => $config->get( 'CacheEpoch' )
742 ];
743 if ( $config->get( 'UseCdn' ) ) {
744 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
745 time(),
746 $config->get( 'CdnMaxAge' )
747 ) );
748 }
749 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
750
751 $maxModified = max( $modifiedTimes );
752 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
753
754 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
755 if ( $clientHeader === false ) {
756 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
757 return false;
758 }
759
760 # IE sends sizes after the date like this:
761 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
762 # this breaks strtotime().
763 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
764
765 Wikimedia\suppressWarnings(); // E_STRICT system time warnings
766 $clientHeaderTime = strtotime( $clientHeader );
767 Wikimedia\restoreWarnings();
768 if ( !$clientHeaderTime ) {
769 wfDebug( __METHOD__
770 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
771 return false;
772 }
773 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
774
775 # Make debug info
776 $info = '';
777 foreach ( $modifiedTimes as $name => $value ) {
778 if ( $info !== '' ) {
779 $info .= ', ';
780 }
781 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
782 }
783
784 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
785 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
786 wfDebug( __METHOD__ . ": effective Last-Modified: " .
787 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
788 if ( $clientHeaderTime < $maxModified ) {
789 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
790 return false;
791 }
792
793 # Not modified
794 # Give a 304 Not Modified response code and disable body output
795 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
796 ini_set( 'zlib.output_compression', 0 );
797 $this->getRequest()->response()->statusHeader( 304 );
798 $this->sendCacheControl();
799 $this->disable();
800
801 // Don't output a compressed blob when using ob_gzhandler;
802 // it's technically against HTTP spec and seems to confuse
803 // Firefox when the response gets split over two packets.
804 wfClearOutputBuffers();
805
806 return true;
807 }
808
809 /**
810 * @param int $reqTime Time of request (eg. now)
811 * @param int $maxAge Cache TTL in seconds
812 * @return int Timestamp
813 */
814 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
815 // Ensure Last-Modified is never more than $wgCdnMaxAge in the past,
816 // because even if the wiki page content hasn't changed since, static
817 // resources may have changed (skin HTML, interface messages, urls, etc.)
818 // and must roll-over in a timely manner (T46570)
819 return $reqTime - $maxAge;
820 }
821
822 /**
823 * Override the last modified timestamp
824 *
825 * @param string $timestamp New timestamp, in a format readable by
826 * wfTimestamp()
827 */
828 public function setLastModified( $timestamp ) {
829 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
830 }
831
832 /**
833 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
834 *
835 * @param string $policy The literal string to output as the contents of
836 * the meta tag. Will be parsed according to the spec and output in
837 * standardized form.
838 * @return null
839 */
840 public function setRobotPolicy( $policy ) {
841 $policy = Article::formatRobotPolicy( $policy );
842
843 if ( isset( $policy['index'] ) ) {
844 $this->setIndexPolicy( $policy['index'] );
845 }
846 if ( isset( $policy['follow'] ) ) {
847 $this->setFollowPolicy( $policy['follow'] );
848 }
849 }
850
851 /**
852 * Set the index policy for the page, but leave the follow policy un-
853 * touched.
854 *
855 * @param string $policy Either 'index' or 'noindex'.
856 * @return null
857 */
858 public function setIndexPolicy( $policy ) {
859 $policy = trim( $policy );
860 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
861 $this->mIndexPolicy = $policy;
862 }
863 }
864
865 /**
866 * Set the follow policy for the page, but leave the index policy un-
867 * touched.
868 *
869 * @param string $policy Either 'follow' or 'nofollow'.
870 * @return null
871 */
872 public function setFollowPolicy( $policy ) {
873 $policy = trim( $policy );
874 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
875 $this->mFollowPolicy = $policy;
876 }
877 }
878
879 /**
880 * "HTML title" means the contents of "<title>".
881 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
882 *
883 * @param string|Message $name
884 */
885 public function setHTMLTitle( $name ) {
886 if ( $name instanceof Message ) {
887 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
888 } else {
889 $this->mHTMLtitle = $name;
890 }
891 }
892
893 /**
894 * Return the "HTML title", i.e. the content of the "<title>" tag.
895 *
896 * @return string
897 */
898 public function getHTMLTitle() {
899 return $this->mHTMLtitle;
900 }
901
902 /**
903 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
904 *
905 * @param Title $t
906 */
907 public function setRedirectedFrom( $t ) {
908 $this->mRedirectedFrom = $t;
909 }
910
911 /**
912 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
913 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
914 * but not bad tags like \<script\>. This function automatically sets
915 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
916 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
917 * good tags like \<i\> will be dropped entirely.
918 *
919 * @param string|Message $name
920 * @param-taint $name tainted
921 * Phan-taint-check gets very confused by $name being either a string or a Message
922 */
923 public function setPageTitle( $name ) {
924 if ( $name instanceof Message ) {
925 $name = $name->setContext( $this->getContext() )->text();
926 }
927
928 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
929 # but leave "<i>foobar</i>" alone
930 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
931 $this->mPageTitle = $nameWithTags;
932
933 # change "<i>foo&amp;bar</i>" to "foo&bar"
934 $this->setHTMLTitle(
935 $this->msg( 'pagetitle' )->plaintextParams( Sanitizer::stripAllTags( $nameWithTags ) )
936 ->inContentLanguage()
937 );
938 }
939
940 /**
941 * Return the "page title", i.e. the content of the \<h1\> tag.
942 *
943 * @return string
944 */
945 public function getPageTitle() {
946 return $this->mPageTitle;
947 }
948
949 /**
950 * Same as page title but only contains name of the page, not any other text.
951 *
952 * @since 1.32
953 * @param string $html Page title text.
954 * @see OutputPage::setPageTitle
955 */
956 public function setDisplayTitle( $html ) {
957 $this->displayTitle = $html;
958 }
959
960 /**
961 * Returns page display title.
962 *
963 * Performs some normalization, but this not as strict the magic word.
964 *
965 * @since 1.32
966 * @return string HTML
967 */
968 public function getDisplayTitle() {
969 $html = $this->displayTitle;
970 if ( $html === null ) {
971 $html = $this->getTitle()->getPrefixedText();
972 }
973
974 return Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $html ) );
975 }
976
977 /**
978 * Returns page display title without namespace prefix if possible.
979 *
980 * @since 1.32
981 * @return string HTML
982 */
983 public function getUnprefixedDisplayTitle() {
984 $text = $this->getDisplayTitle();
985 $nsPrefix = $this->getTitle()->getNsText() . ':';
986 $prefix = preg_quote( $nsPrefix, '/' );
987
988 return preg_replace( "/^$prefix/i", '', $text );
989 }
990
991 /**
992 * Set the Title object to use
993 *
994 * @param Title $t
995 */
996 public function setTitle( Title $t ) {
997 $this->getContext()->setTitle( $t );
998 }
999
1000 /**
1001 * Replace the subtitle with $str
1002 *
1003 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1004 */
1005 public function setSubtitle( $str ) {
1006 $this->clearSubtitle();
1007 $this->addSubtitle( $str );
1008 }
1009
1010 /**
1011 * Add $str to the subtitle
1012 *
1013 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1014 */
1015 public function addSubtitle( $str ) {
1016 if ( $str instanceof Message ) {
1017 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1018 } else {
1019 $this->mSubtitle[] = $str;
1020 }
1021 }
1022
1023 /**
1024 * Build message object for a subtitle containing a backlink to a page
1025 *
1026 * @param Title $title Title to link to
1027 * @param array $query Array of additional parameters to include in the link
1028 * @return Message
1029 * @since 1.25
1030 */
1031 public static function buildBacklinkSubtitle( Title $title, $query = [] ) {
1032 if ( $title->isRedirect() ) {
1033 $query['redirect'] = 'no';
1034 }
1035 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1036 return wfMessage( 'backlinksubtitle' )
1037 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1038 }
1039
1040 /**
1041 * Add a subtitle containing a backlink to a page
1042 *
1043 * @param Title $title Title to link to
1044 * @param array $query Array of additional parameters to include in the link
1045 */
1046 public function addBacklinkSubtitle( Title $title, $query = [] ) {
1047 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1048 }
1049
1050 /**
1051 * Clear the subtitles
1052 */
1053 public function clearSubtitle() {
1054 $this->mSubtitle = [];
1055 }
1056
1057 /**
1058 * Get the subtitle
1059 *
1060 * @return string
1061 */
1062 public function getSubtitle() {
1063 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1064 }
1065
1066 /**
1067 * Set the page as printable, i.e. it'll be displayed with all
1068 * print styles included
1069 */
1070 public function setPrintable() {
1071 $this->mPrintable = true;
1072 }
1073
1074 /**
1075 * Return whether the page is "printable"
1076 *
1077 * @return bool
1078 */
1079 public function isPrintable() {
1080 return $this->mPrintable;
1081 }
1082
1083 /**
1084 * Disable output completely, i.e. calling output() will have no effect
1085 */
1086 public function disable() {
1087 $this->mDoNothing = true;
1088 }
1089
1090 /**
1091 * Return whether the output will be completely disabled
1092 *
1093 * @return bool
1094 */
1095 public function isDisabled() {
1096 return $this->mDoNothing;
1097 }
1098
1099 /**
1100 * Show an "add new section" link?
1101 *
1102 * @return bool
1103 */
1104 public function showNewSectionLink() {
1105 return $this->mNewSectionLink;
1106 }
1107
1108 /**
1109 * Forcibly hide the new section link?
1110 *
1111 * @return bool
1112 */
1113 public function forceHideNewSectionLink() {
1114 return $this->mHideNewSectionLink;
1115 }
1116
1117 /**
1118 * Add or remove feed links in the page header
1119 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1120 * for the new version
1121 * @see addFeedLink()
1122 *
1123 * @param bool $show True: add default feeds, false: remove all feeds
1124 */
1125 public function setSyndicated( $show = true ) {
1126 if ( $show ) {
1127 $this->setFeedAppendQuery( false );
1128 } else {
1129 $this->mFeedLinks = [];
1130 }
1131 }
1132
1133 /**
1134 * Return effective list of advertised feed types
1135 * @see addFeedLink()
1136 *
1137 * @return array Array of feed type names ( 'rss', 'atom' )
1138 */
1139 protected function getAdvertisedFeedTypes() {
1140 if ( $this->getConfig()->get( 'Feed' ) ) {
1141 return $this->getConfig()->get( 'AdvertisedFeedTypes' );
1142 } else {
1143 return [];
1144 }
1145 }
1146
1147 /**
1148 * Add default feeds to the page header
1149 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1150 * for the new version
1151 * @see addFeedLink()
1152 *
1153 * @param string $val Query to append to feed links or false to output
1154 * default links
1155 */
1156 public function setFeedAppendQuery( $val ) {
1157 $this->mFeedLinks = [];
1158
1159 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1160 $query = "feed=$type";
1161 if ( is_string( $val ) ) {
1162 $query .= '&' . $val;
1163 }
1164 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1165 }
1166 }
1167
1168 /**
1169 * Add a feed link to the page header
1170 *
1171 * @param string $format Feed type, should be a key of $wgFeedClasses
1172 * @param string $href URL
1173 */
1174 public function addFeedLink( $format, $href ) {
1175 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1176 $this->mFeedLinks[$format] = $href;
1177 }
1178 }
1179
1180 /**
1181 * Should we output feed links for this page?
1182 * @return bool
1183 */
1184 public function isSyndicated() {
1185 return count( $this->mFeedLinks ) > 0;
1186 }
1187
1188 /**
1189 * Return URLs for each supported syndication format for this page.
1190 * @return array Associating format keys with URLs
1191 */
1192 public function getSyndicationLinks() {
1193 return $this->mFeedLinks;
1194 }
1195
1196 /**
1197 * Will currently always return null
1198 *
1199 * @return null
1200 */
1201 public function getFeedAppendQuery() {
1202 return $this->mFeedLinksAppendQuery;
1203 }
1204
1205 /**
1206 * Set whether the displayed content is related to the source of the
1207 * corresponding article on the wiki
1208 * Setting true will cause the change "article related" toggle to true
1209 *
1210 * @param bool $newVal
1211 */
1212 public function setArticleFlag( $newVal ) {
1213 $this->mIsArticle = $newVal;
1214 if ( $newVal ) {
1215 $this->mIsArticleRelated = $newVal;
1216 }
1217 }
1218
1219 /**
1220 * Return whether the content displayed page is related to the source of
1221 * the corresponding article on the wiki
1222 *
1223 * @return bool
1224 */
1225 public function isArticle() {
1226 return $this->mIsArticle;
1227 }
1228
1229 /**
1230 * Set whether this page is related an article on the wiki
1231 * Setting false will cause the change of "article flag" toggle to false
1232 *
1233 * @param bool $newVal
1234 */
1235 public function setArticleRelated( $newVal ) {
1236 $this->mIsArticleRelated = $newVal;
1237 if ( !$newVal ) {
1238 $this->mIsArticle = false;
1239 }
1240 }
1241
1242 /**
1243 * Return whether this page is related an article on the wiki
1244 *
1245 * @return bool
1246 */
1247 public function isArticleRelated() {
1248 return $this->mIsArticleRelated;
1249 }
1250
1251 /**
1252 * Set whether the standard copyright should be shown for the current page.
1253 *
1254 * @param bool $hasCopyright
1255 */
1256 public function setCopyright( $hasCopyright ) {
1257 $this->mHasCopyright = $hasCopyright;
1258 }
1259
1260 /**
1261 * Return whether the standard copyright should be shown for the current page.
1262 * By default, it is true for all articles but other pages
1263 * can signal it by using setCopyright( true ).
1264 *
1265 * Used by SkinTemplate to decided whether to show the copyright.
1266 *
1267 * @return bool
1268 */
1269 public function showsCopyright() {
1270 return $this->isArticle() || $this->mHasCopyright;
1271 }
1272
1273 /**
1274 * Add new language links
1275 *
1276 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1277 * (e.g. 'fr:Test page')
1278 */
1279 public function addLanguageLinks( array $newLinkArray ) {
1280 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $newLinkArray );
1281 }
1282
1283 /**
1284 * Reset the language links and add new language links
1285 *
1286 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1287 * (e.g. 'fr:Test page')
1288 */
1289 public function setLanguageLinks( array $newLinkArray ) {
1290 $this->mLanguageLinks = $newLinkArray;
1291 }
1292
1293 /**
1294 * Get the list of language links
1295 *
1296 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1297 */
1298 public function getLanguageLinks() {
1299 return $this->mLanguageLinks;
1300 }
1301
1302 /**
1303 * Add an array of categories, with names in the keys
1304 *
1305 * @param array $categories Mapping category name => sort key
1306 */
1307 public function addCategoryLinks( array $categories ) {
1308 if ( !$categories ) {
1309 return;
1310 }
1311
1312 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1313
1314 # Set all the values to 'normal'.
1315 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1316
1317 # Mark hidden categories
1318 foreach ( $res as $row ) {
1319 if ( isset( $row->pp_value ) ) {
1320 $categories[$row->page_title] = 'hidden';
1321 }
1322 }
1323
1324 // Avoid PHP 7.1 warning of passing $this by reference
1325 $outputPage = $this;
1326 # Add the remaining categories to the skin
1327 if ( Hooks::run(
1328 'OutputPageMakeCategoryLinks',
1329 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1330 ) {
1331 $services = MediaWikiServices::getInstance();
1332 $linkRenderer = $services->getLinkRenderer();
1333 foreach ( $categories as $category => $type ) {
1334 // array keys will cast numeric category names to ints, so cast back to string
1335 $category = (string)$category;
1336 $origcategory = $category;
1337 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1338 if ( !$title ) {
1339 continue;
1340 }
1341 $services->getContentLanguage()->findVariantLink( $category, $title, true );
1342 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1343 continue;
1344 }
1345 $text = $services->getContentLanguage()->convertHtml( $title->getText() );
1346 $this->mCategories[$type][] = $title->getText();
1347 $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1348 }
1349 }
1350 }
1351
1352 /**
1353 * @param array $categories
1354 * @return bool|IResultWrapper
1355 */
1356 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1357 # Add the links to a LinkBatch
1358 $arr = [ NS_CATEGORY => $categories ];
1359 $lb = new LinkBatch;
1360 $lb->setArray( $arr );
1361
1362 # Fetch existence plus the hiddencat property
1363 $dbr = wfGetDB( DB_REPLICA );
1364 $fields = array_merge(
1365 LinkCache::getSelectFields(),
1366 [ 'page_namespace', 'page_title', 'pp_value' ]
1367 );
1368
1369 $res = $dbr->select( [ 'page', 'page_props' ],
1370 $fields,
1371 $lb->constructSet( 'page', $dbr ),
1372 __METHOD__,
1373 [],
1374 [ 'page_props' => [ 'LEFT JOIN', [
1375 'pp_propname' => 'hiddencat',
1376 'pp_page = page_id'
1377 ] ] ]
1378 );
1379
1380 # Add the results to the link cache
1381 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1382 $lb->addResultToCache( $linkCache, $res );
1383
1384 return $res;
1385 }
1386
1387 /**
1388 * Reset the category links (but not the category list) and add $categories
1389 *
1390 * @param array $categories Mapping category name => sort key
1391 */
1392 public function setCategoryLinks( array $categories ) {
1393 $this->mCategoryLinks = [];
1394 $this->addCategoryLinks( $categories );
1395 }
1396
1397 /**
1398 * Get the list of category links, in a 2-D array with the following format:
1399 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1400 * hidden categories) and $link a HTML fragment with a link to the category
1401 * page
1402 *
1403 * @return array
1404 */
1405 public function getCategoryLinks() {
1406 return $this->mCategoryLinks;
1407 }
1408
1409 /**
1410 * Get the list of category names this page belongs to.
1411 *
1412 * @param string $type The type of categories which should be returned. Possible values:
1413 * * all: all categories of all types
1414 * * hidden: only the hidden categories
1415 * * normal: all categories, except hidden categories
1416 * @return array Array of strings
1417 */
1418 public function getCategories( $type = 'all' ) {
1419 if ( $type === 'all' ) {
1420 $allCategories = [];
1421 foreach ( $this->mCategories as $categories ) {
1422 $allCategories = array_merge( $allCategories, $categories );
1423 }
1424 return $allCategories;
1425 }
1426 if ( !isset( $this->mCategories[$type] ) ) {
1427 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1428 }
1429 return $this->mCategories[$type];
1430 }
1431
1432 /**
1433 * Add an array of indicators, with their identifiers as array
1434 * keys and HTML contents as values.
1435 *
1436 * In case of duplicate keys, existing values are overwritten.
1437 *
1438 * @param array $indicators
1439 * @since 1.25
1440 */
1441 public function setIndicators( array $indicators ) {
1442 $this->mIndicators = $indicators + $this->mIndicators;
1443 // Keep ordered by key
1444 ksort( $this->mIndicators );
1445 }
1446
1447 /**
1448 * Get the indicators associated with this page.
1449 *
1450 * The array will be internally ordered by item keys.
1451 *
1452 * @return array Keys: identifiers, values: HTML contents
1453 * @since 1.25
1454 */
1455 public function getIndicators() {
1456 return $this->mIndicators;
1457 }
1458
1459 /**
1460 * Adds help link with an icon via page indicators.
1461 * Link target can be overridden by a local message containing a wikilink:
1462 * the message key is: lowercase action or special page name + '-helppage'.
1463 * @param string $to Target MediaWiki.org page title or encoded URL.
1464 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1465 * @since 1.25
1466 */
1467 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1468 $this->addModuleStyles( 'mediawiki.helplink' );
1469 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1470
1471 if ( $overrideBaseUrl ) {
1472 $helpUrl = $to;
1473 } else {
1474 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1475 $helpUrl = "https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1476 }
1477
1478 $link = Html::rawElement(
1479 'a',
1480 [
1481 'href' => $helpUrl,
1482 'target' => '_blank',
1483 'class' => 'mw-helplink',
1484 ],
1485 $text
1486 );
1487
1488 $this->setIndicators( [ 'mw-helplink' => $link ] );
1489 }
1490
1491 /**
1492 * Do not allow scripts which can be modified by wiki users to load on this page;
1493 * only allow scripts bundled with, or generated by, the software.
1494 * Site-wide styles are controlled by a config setting, since they can be
1495 * used to create a custom skin/theme, but not user-specific ones.
1496 *
1497 * @todo this should be given a more accurate name
1498 */
1499 public function disallowUserJs() {
1500 $this->reduceAllowedModules(
1501 ResourceLoaderModule::TYPE_SCRIPTS,
1502 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1503 );
1504
1505 // Site-wide styles are controlled by a config setting, see T73621
1506 // for background on why. User styles are never allowed.
1507 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1508 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1509 } else {
1510 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1511 }
1512 $this->reduceAllowedModules(
1513 ResourceLoaderModule::TYPE_STYLES,
1514 $styleOrigin
1515 );
1516 }
1517
1518 /**
1519 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1520 * @see ResourceLoaderModule::$origin
1521 * @param string $type ResourceLoaderModule TYPE_ constant
1522 * @return int ResourceLoaderModule ORIGIN_ class constant
1523 */
1524 public function getAllowedModules( $type ) {
1525 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1526 return min( array_values( $this->mAllowedModules ) );
1527 } else {
1528 return $this->mAllowedModules[$type] ?? ResourceLoaderModule::ORIGIN_ALL;
1529 }
1530 }
1531
1532 /**
1533 * Limit the highest level of CSS/JS untrustworthiness allowed.
1534 *
1535 * If passed the same or a higher level than the current level of untrustworthiness set, the
1536 * level will remain unchanged.
1537 *
1538 * @param string $type
1539 * @param int $level ResourceLoaderModule class constant
1540 */
1541 public function reduceAllowedModules( $type, $level ) {
1542 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1543 }
1544
1545 /**
1546 * Prepend $text to the body HTML
1547 *
1548 * @param string $text HTML
1549 */
1550 public function prependHTML( $text ) {
1551 $this->mBodytext = $text . $this->mBodytext;
1552 }
1553
1554 /**
1555 * Append $text to the body HTML
1556 *
1557 * @param string $text HTML
1558 */
1559 public function addHTML( $text ) {
1560 $this->mBodytext .= $text;
1561 }
1562
1563 /**
1564 * Shortcut for adding an Html::element via addHTML.
1565 *
1566 * @since 1.19
1567 *
1568 * @param string $element
1569 * @param array $attribs
1570 * @param string $contents
1571 */
1572 public function addElement( $element, array $attribs = [], $contents = '' ) {
1573 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1574 }
1575
1576 /**
1577 * Clear the body HTML
1578 */
1579 public function clearHTML() {
1580 $this->mBodytext = '';
1581 }
1582
1583 /**
1584 * Get the body HTML
1585 *
1586 * @return string HTML
1587 */
1588 public function getHTML() {
1589 return $this->mBodytext;
1590 }
1591
1592 /**
1593 * Get/set the ParserOptions object to use for wikitext parsing
1594 *
1595 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1596 * current ParserOption object. This parameter is deprecated since 1.31.
1597 * @return ParserOptions
1598 */
1599 public function parserOptions( $options = null ) {
1600 if ( $options !== null ) {
1601 wfDeprecated( __METHOD__ . ' with non-null $options', '1.31' );
1602 }
1603
1604 if ( $options !== null && !empty( $options->isBogus ) ) {
1605 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1606 // been changed somehow, and keep it if so.
1607 $anonPO = ParserOptions::newFromAnon();
1608 $anonPO->setAllowUnsafeRawHtml( false );
1609 if ( !$options->matches( $anonPO ) ) {
1610 wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1611 $options->isBogus = false;
1612 }
1613 }
1614
1615 if ( !$this->mParserOptions ) {
1616 if ( !$this->getUser()->isSafeToLoad() ) {
1617 // $wgUser isn't unstubbable yet, so don't try to get a
1618 // ParserOptions for it. And don't cache this ParserOptions
1619 // either.
1620 $po = ParserOptions::newFromAnon();
1621 $po->setAllowUnsafeRawHtml( false );
1622 $po->isBogus = true;
1623 if ( $options !== null ) {
1624 $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
1625 }
1626 return $po;
1627 }
1628
1629 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1630 $this->mParserOptions->setAllowUnsafeRawHtml( false );
1631 }
1632
1633 if ( $options !== null && !empty( $options->isBogus ) ) {
1634 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1635 // thing.
1636 return wfSetVar( $this->mParserOptions, null, true );
1637 } else {
1638 return wfSetVar( $this->mParserOptions, $options );
1639 }
1640 }
1641
1642 /**
1643 * Set the revision ID which will be seen by the wiki text parser
1644 * for things such as embedded {{REVISIONID}} variable use.
1645 *
1646 * @param int|null $revid A positive integer, or null
1647 * @return mixed Previous value
1648 */
1649 public function setRevisionId( $revid ) {
1650 $val = is_null( $revid ) ? null : intval( $revid );
1651 return wfSetVar( $this->mRevisionId, $val, true );
1652 }
1653
1654 /**
1655 * Get the displayed revision ID
1656 *
1657 * @return int
1658 */
1659 public function getRevisionId() {
1660 return $this->mRevisionId;
1661 }
1662
1663 /**
1664 * Set the timestamp of the revision which will be displayed. This is used
1665 * to avoid a extra DB call in Skin::lastModified().
1666 *
1667 * @param string|null $timestamp
1668 * @return mixed Previous value
1669 */
1670 public function setRevisionTimestamp( $timestamp ) {
1671 return wfSetVar( $this->mRevisionTimestamp, $timestamp, true );
1672 }
1673
1674 /**
1675 * Get the timestamp of displayed revision.
1676 * This will be null if not filled by setRevisionTimestamp().
1677 *
1678 * @return string|null
1679 */
1680 public function getRevisionTimestamp() {
1681 return $this->mRevisionTimestamp;
1682 }
1683
1684 /**
1685 * Set the displayed file version
1686 *
1687 * @param File|null $file
1688 * @return mixed Previous value
1689 */
1690 public function setFileVersion( $file ) {
1691 $val = null;
1692 if ( $file instanceof File && $file->exists() ) {
1693 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1694 }
1695 return wfSetVar( $this->mFileVersion, $val, true );
1696 }
1697
1698 /**
1699 * Get the displayed file version
1700 *
1701 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1702 */
1703 public function getFileVersion() {
1704 return $this->mFileVersion;
1705 }
1706
1707 /**
1708 * Get the templates used on this page
1709 *
1710 * @return array (namespace => dbKey => revId)
1711 * @since 1.18
1712 */
1713 public function getTemplateIds() {
1714 return $this->mTemplateIds;
1715 }
1716
1717 /**
1718 * Get the files used on this page
1719 *
1720 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
1721 * @since 1.18
1722 */
1723 public function getFileSearchOptions() {
1724 return $this->mImageTimeKeys;
1725 }
1726
1727 /**
1728 * Convert wikitext *in the user interface language* to HTML and
1729 * add it to the buffer. The result will not be
1730 * language-converted, as user interface messages are already
1731 * localized into a specific variant. Assumes that the current
1732 * page title will be used if optional $title is not
1733 * provided. Output will be tidy.
1734 *
1735 * @param string $text Wikitext in the user interface language
1736 * @param bool $linestart Is this the start of a line? (Defaults to true)
1737 * @param Title|null $title Optional title to use; default of `null`
1738 * means use current page title.
1739 * @throws MWException if $title is not provided and OutputPage::getTitle()
1740 * is null
1741 * @since 1.32
1742 */
1743 public function addWikiTextAsInterface(
1744 $text, $linestart = true, Title $title = null
1745 ) {
1746 if ( $title === null ) {
1747 $title = $this->getTitle();
1748 }
1749 if ( !$title ) {
1750 throw new MWException( 'Title is null' );
1751 }
1752 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
1753 }
1754
1755 /**
1756 * Convert wikitext *in the user interface language* to HTML and
1757 * add it to the buffer with a `<div class="$wrapperClass">`
1758 * wrapper. The result will not be language-converted, as user
1759 * interface messages as already localized into a specific
1760 * variant. The $text will be parsed in start-of-line context.
1761 * Output will be tidy.
1762 *
1763 * @param string $wrapperClass The class attribute value for the <div>
1764 * wrapper in the output HTML
1765 * @param string $text Wikitext in the user interface language
1766 * @since 1.32
1767 */
1768 public function wrapWikiTextAsInterface(
1769 $wrapperClass, $text
1770 ) {
1771 $this->addWikiTextTitleInternal(
1772 $text, $this->getTitle(),
1773 /*linestart*/true, /*interface*/true,
1774 $wrapperClass
1775 );
1776 }
1777
1778 /**
1779 * Convert wikitext *in the page content language* to HTML and add
1780 * it to the buffer. The result with be language-converted to the
1781 * user's preferred variant. Assumes that the current page title
1782 * will be used if optional $title is not provided. Output will be
1783 * tidy.
1784 *
1785 * @param string $text Wikitext in the page content language
1786 * @param bool $linestart Is this the start of a line? (Defaults to true)
1787 * @param Title|null $title Optional title to use; default of `null`
1788 * means use current page title.
1789 * @throws MWException if $title is not provided and OutputPage::getTitle()
1790 * is null
1791 * @since 1.32
1792 */
1793 public function addWikiTextAsContent(
1794 $text, $linestart = true, Title $title = null
1795 ) {
1796 if ( $title === null ) {
1797 $title = $this->getTitle();
1798 }
1799 if ( !$title ) {
1800 throw new MWException( 'Title is null' );
1801 }
1802 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
1803 }
1804
1805 /**
1806 * Add wikitext with a custom Title object.
1807 * Output is unwrapped.
1808 *
1809 * @param string $text Wikitext
1810 * @param Title $title
1811 * @param bool $linestart Is this the start of a line?
1812 * @param bool $tidy Whether to use tidy.
1813 * Setting this to false (or omitting it) is deprecated
1814 * since 1.32; all wikitext should be tidied.
1815 * @param bool $interface Whether it is an interface message
1816 * (for example disables conversion)
1817 * @param string $wrapperClass if not empty, wraps the output in
1818 * a `<div class="$wrapperClass">`
1819 * @private
1820 */
1821 private function addWikiTextTitleInternal(
1822 $text, Title $title, $linestart, $interface, $wrapperClass = null
1823 ) {
1824 $parserOutput = $this->parseInternal(
1825 $text, $title, $linestart, true, $interface, /*language*/null
1826 );
1827
1828 $this->addParserOutput( $parserOutput, [
1829 'enableSectionEditLinks' => false,
1830 'wrapperDivClass' => $wrapperClass ?? '',
1831 ] );
1832 }
1833
1834 /**
1835 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1836 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1837 * and so on.
1838 *
1839 * @since 1.24
1840 * @param ParserOutput $parserOutput
1841 */
1842 public function addParserOutputMetadata( ParserOutput $parserOutput ) {
1843 $this->mLanguageLinks =
1844 array_merge( $this->mLanguageLinks, $parserOutput->getLanguageLinks() );
1845 $this->addCategoryLinks( $parserOutput->getCategories() );
1846 $this->setIndicators( $parserOutput->getIndicators() );
1847 $this->mNewSectionLink = $parserOutput->getNewSection();
1848 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1849
1850 if ( !$parserOutput->isCacheable() ) {
1851 $this->enableClientCache( false );
1852 }
1853 $this->mNoGallery = $parserOutput->getNoGallery();
1854 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1855 $this->addModules( $parserOutput->getModules() );
1856 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1857 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1858 $this->mPreventClickjacking = $this->mPreventClickjacking
1859 || $parserOutput->preventClickjacking();
1860
1861 // Template versioning...
1862 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1863 if ( isset( $this->mTemplateIds[$ns] ) ) {
1864 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1865 } else {
1866 $this->mTemplateIds[$ns] = $dbks;
1867 }
1868 }
1869 // File versioning...
1870 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1871 $this->mImageTimeKeys[$dbk] = $data;
1872 }
1873
1874 // Hooks registered in the object
1875 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1876 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1877 list( $hookName, $data ) = $hookInfo;
1878 if ( isset( $parserOutputHooks[$hookName] ) ) {
1879 $parserOutputHooks[$hookName]( $this, $parserOutput, $data );
1880 }
1881 }
1882
1883 // Enable OOUI if requested via ParserOutput
1884 if ( $parserOutput->getEnableOOUI() ) {
1885 $this->enableOOUI();
1886 }
1887
1888 // Include parser limit report
1889 if ( !$this->limitReportJSData ) {
1890 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
1891 }
1892
1893 // Link flags are ignored for now, but may in the future be
1894 // used to mark individual language links.
1895 $linkFlags = [];
1896 // Avoid PHP 7.1 warning of passing $this by reference
1897 $outputPage = $this;
1898 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1899 Hooks::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1900
1901 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1902 // so that extensions may modify ParserOutput to toggle TOC.
1903 // This cannot be moved to addParserOutputText because that is not
1904 // called by EditPage for Preview.
1905 if ( $parserOutput->getTOCHTML() ) {
1906 $this->mEnableTOC = true;
1907 }
1908 }
1909
1910 /**
1911 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1912 * ParserOutput object, without any other metadata.
1913 *
1914 * @since 1.24
1915 * @param ParserOutput $parserOutput
1916 * @param array $poOptions Options to ParserOutput::getText()
1917 */
1918 public function addParserOutputContent( ParserOutput $parserOutput, $poOptions = [] ) {
1919 $this->addParserOutputText( $parserOutput, $poOptions );
1920
1921 $this->addModules( $parserOutput->getModules() );
1922 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1923
1924 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1925 }
1926
1927 /**
1928 * Add the HTML associated with a ParserOutput object, without any metadata.
1929 *
1930 * @since 1.24
1931 * @param ParserOutput $parserOutput
1932 * @param array $poOptions Options to ParserOutput::getText()
1933 */
1934 public function addParserOutputText( ParserOutput $parserOutput, $poOptions = [] ) {
1935 $text = $parserOutput->getText( $poOptions );
1936 // Avoid PHP 7.1 warning of passing $this by reference
1937 $outputPage = $this;
1938 Hooks::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1939 $this->addHTML( $text );
1940 }
1941
1942 /**
1943 * Add everything from a ParserOutput object.
1944 *
1945 * @param ParserOutput $parserOutput
1946 * @param array $poOptions Options to ParserOutput::getText()
1947 */
1948 function addParserOutput( ParserOutput $parserOutput, $poOptions = [] ) {
1949 $this->addParserOutputMetadata( $parserOutput );
1950 $this->addParserOutputText( $parserOutput, $poOptions );
1951 }
1952
1953 /**
1954 * Add the output of a QuickTemplate to the output buffer
1955 *
1956 * @param QuickTemplate &$template
1957 */
1958 public function addTemplate( &$template ) {
1959 $this->addHTML( $template->getHTML() );
1960 }
1961
1962 /**
1963 * Parse wikitext and return the HTML.
1964 *
1965 * @todo The output is wrapped in a <div> iff $interface is false; it's
1966 * probably best to always strip the wrapper.
1967 *
1968 * @param string $text
1969 * @param bool $linestart Is this the start of a line?
1970 * @param bool $interface Use interface language (instead of content language) while parsing
1971 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
1972 * LanguageConverter.
1973 * @param Language|null $language Target language object, will override $interface
1974 * @throws MWException
1975 * @return string HTML
1976 * @deprecated since 1.32, due to untidy output and inconsistent wrapper;
1977 * use parseAsContent() if $interface is default value or false, or else
1978 * parseAsInterface() if $interface is true.
1979 */
1980 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1981 wfDeprecated( __METHOD__, '1.33' );
1982 return $this->parseInternal(
1983 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, $language
1984 )->getText( [
1985 'enableSectionEditLinks' => false,
1986 ] );
1987 }
1988
1989 /**
1990 * Parse wikitext *in the page content language* and return the HTML.
1991 * The result will be language-converted to the user's preferred variant.
1992 * Output will be tidy.
1993 *
1994 * @param string $text Wikitext in the page content language
1995 * @param bool $linestart Is this the start of a line? (Defaults to true)
1996 * @throws MWException
1997 * @return string HTML
1998 * @since 1.32
1999 */
2000 public function parseAsContent( $text, $linestart = true ) {
2001 return $this->parseInternal(
2002 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/false, /*language*/null
2003 )->getText( [
2004 'enableSectionEditLinks' => false,
2005 'wrapperDivClass' => ''
2006 ] );
2007 }
2008
2009 /**
2010 * Parse wikitext *in the user interface language* and return the HTML.
2011 * The result will not be language-converted, as user interface messages
2012 * are already localized into a specific variant.
2013 * Output will be tidy.
2014 *
2015 * @param string $text Wikitext in the user interface language
2016 * @param bool $linestart Is this the start of a line? (Defaults to true)
2017 * @throws MWException
2018 * @return string HTML
2019 * @since 1.32
2020 */
2021 public function parseAsInterface( $text, $linestart = true ) {
2022 return $this->parseInternal(
2023 $text, $this->getTitle(), $linestart, /*tidy*/true, /*interface*/true, /*language*/null
2024 )->getText( [
2025 'enableSectionEditLinks' => false,
2026 'wrapperDivClass' => ''
2027 ] );
2028 }
2029
2030 /**
2031 * Parse wikitext *in the user interface language*, strip
2032 * paragraph wrapper, and return the HTML.
2033 * The result will not be language-converted, as user interface messages
2034 * are already localized into a specific variant.
2035 * Output will be tidy. Outer paragraph wrapper will only be stripped
2036 * if the result is a single paragraph.
2037 *
2038 * @param string $text Wikitext in the user interface language
2039 * @param bool $linestart Is this the start of a line? (Defaults to true)
2040 * @throws MWException
2041 * @return string HTML
2042 * @since 1.32
2043 */
2044 public function parseInlineAsInterface( $text, $linestart = true ) {
2045 return Parser::stripOuterParagraph(
2046 $this->parseAsInterface( $text, $linestart )
2047 );
2048 }
2049
2050 /**
2051 * Parse wikitext, strip paragraph wrapper, and return the HTML.
2052 *
2053 * @param string $text
2054 * @param bool $linestart Is this the start of a line?
2055 * @param bool $interface Use interface language (instead of content language) while parsing
2056 * language sensitive magic words like GRAMMAR and PLURAL
2057 * @return string HTML
2058 * @deprecated since 1.32, due to untidy output and confusing default
2059 * for $interface. Use parseInlineAsInterface() if $interface is
2060 * the default value or false, or else use
2061 * Parser::stripOuterParagraph($outputPage->parseAsContent(...)).
2062 */
2063 public function parseInline( $text, $linestart = true, $interface = false ) {
2064 wfDeprecated( __METHOD__, '1.33' );
2065 $parsed = $this->parseInternal(
2066 $text, $this->getTitle(), $linestart, /*tidy*/false, $interface, /*language*/null
2067 )->getText( [
2068 'enableSectionEditLinks' => false,
2069 'wrapperDivClass' => '', /* no wrapper div */
2070 ] );
2071 return Parser::stripOuterParagraph( $parsed );
2072 }
2073
2074 /**
2075 * Parse wikitext and return the HTML (internal implementation helper)
2076 *
2077 * @param string $text
2078 * @param Title $title The title to use
2079 * @param bool $linestart Is this the start of a line?
2080 * @param bool $tidy Whether the output should be tidied
2081 * @param bool $interface Use interface language (instead of content language) while parsing
2082 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2083 * LanguageConverter.
2084 * @param Language|null $language Target language object, will override $interface
2085 * @throws MWException
2086 * @return ParserOutput
2087 */
2088 private function parseInternal( $text, $title, $linestart, $tidy, $interface, $language ) {
2089 if ( is_null( $title ) ) {
2090 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
2091 }
2092
2093 $popts = $this->parserOptions();
2094 $oldTidy = $popts->setTidy( $tidy );
2095 $oldInterface = $popts->setInterfaceMessage( (bool)$interface );
2096
2097 if ( $language !== null ) {
2098 $oldLang = $popts->setTargetLanguage( $language );
2099 }
2100
2101 $parserOutput = MediaWikiServices::getInstance()->getParser()->getFreshParser()->parse(
2102 $text, $title, $popts,
2103 $linestart, true, $this->mRevisionId
2104 );
2105
2106 $popts->setTidy( $oldTidy );
2107 $popts->setInterfaceMessage( $oldInterface );
2108
2109 if ( $language !== null ) {
2110 $popts->setTargetLanguage( $oldLang );
2111 }
2112
2113 return $parserOutput;
2114 }
2115
2116 /**
2117 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2118 *
2119 * @param int $maxage Maximum cache time on the CDN, in seconds.
2120 */
2121 public function setCdnMaxage( $maxage ) {
2122 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2123 }
2124
2125 /**
2126 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2127 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2128 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2129 * $maxage.
2130 *
2131 * @param int $maxage Maximum cache time on the CDN, in seconds
2132 * @since 1.27
2133 */
2134 public function lowerCdnMaxage( $maxage ) {
2135 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2136 $this->setCdnMaxage( $this->mCdnMaxage );
2137 }
2138
2139 /**
2140 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2141 *
2142 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2143 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2144 * TTL is 90% of the age of the object, subject to the min and max.
2145 *
2146 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2147 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2148 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2149 * @since 1.28
2150 */
2151 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2152 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2153 $maxTTL = $maxTTL ?: $this->getConfig()->get( 'CdnMaxAge' );
2154
2155 if ( $mtime === null || $mtime === false ) {
2156 return $minTTL; // entity does not exist
2157 }
2158
2159 $age = MWTimestamp::time() - wfTimestamp( TS_UNIX, $mtime );
2160 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2161 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2162
2163 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2164 }
2165
2166 /**
2167 * Use enableClientCache(false) to force it to send nocache headers
2168 *
2169 * @param bool|null $state New value, or null to not set the value
2170 *
2171 * @return bool Old value
2172 */
2173 public function enableClientCache( $state ) {
2174 return wfSetVar( $this->mEnableClientCache, $state );
2175 }
2176
2177 /**
2178 * Get the list of cookie names that will influence the cache
2179 *
2180 * @return array
2181 */
2182 function getCacheVaryCookies() {
2183 if ( self::$cacheVaryCookies === null ) {
2184 $config = $this->getConfig();
2185 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2186 SessionManager::singleton()->getVaryCookies(),
2187 [
2188 'forceHTTPS',
2189 ],
2190 $config->get( 'CacheVaryCookies' )
2191 ) ) );
2192 Hooks::run( 'GetCacheVaryCookies', [ $this, &self::$cacheVaryCookies ] );
2193 }
2194 return self::$cacheVaryCookies;
2195 }
2196
2197 /**
2198 * Check if the request has a cache-varying cookie header
2199 * If it does, it's very important that we don't allow public caching
2200 *
2201 * @return bool
2202 */
2203 function haveCacheVaryCookies() {
2204 $request = $this->getRequest();
2205 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2206 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2207 wfDebug( __METHOD__ . ": found $cookieName\n" );
2208 return true;
2209 }
2210 }
2211 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2212 return false;
2213 }
2214
2215 /**
2216 * Add an HTTP header that will influence on the cache
2217 *
2218 * @param string $header Header name
2219 * @param string[]|null $option Deprecated; formerly options for the
2220 * Key header, deprecated in 1.32 and removed in 1.34. See
2221 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2222 * for the list of formerly-valid options.
2223 */
2224 public function addVaryHeader( $header, array $option = null ) {
2225 if ( $option !== null && count( $option ) > 0 ) {
2226 wfDeprecated( 'addVaryHeader $option is ignored', '1.34' );
2227 }
2228 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2229 $this->mVaryHeader[$header] = null;
2230 }
2231 }
2232
2233 /**
2234 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2235 * such as Accept-Encoding or Cookie
2236 *
2237 * @return string
2238 */
2239 public function getVaryHeader() {
2240 // If we vary on cookies, let's make sure it's always included here too.
2241 if ( $this->getCacheVaryCookies() ) {
2242 $this->addVaryHeader( 'Cookie' );
2243 }
2244
2245 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2246 $this->addVaryHeader( $header, $options );
2247 }
2248 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2249 }
2250
2251 /**
2252 * Add an HTTP Link: header
2253 *
2254 * @param string $header Header value
2255 */
2256 public function addLinkHeader( $header ) {
2257 $this->mLinkHeader[] = $header;
2258 }
2259
2260 /**
2261 * Return a Link: header. Based on the values of $mLinkHeader.
2262 *
2263 * @return string
2264 */
2265 public function getLinkHeader() {
2266 if ( !$this->mLinkHeader ) {
2267 return false;
2268 }
2269
2270 return 'Link: ' . implode( ',', $this->mLinkHeader );
2271 }
2272
2273 /**
2274 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2275 *
2276 * For example:
2277 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2278 * /w/index.php?title=Main_page&variant=zh-cn will not.
2279 */
2280 private function addAcceptLanguage() {
2281 $title = $this->getTitle();
2282 if ( !$title instanceof Title ) {
2283 return;
2284 }
2285
2286 $lang = $title->getPageLanguage();
2287 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2288 $this->addVaryHeader( 'Accept-Language' );
2289 }
2290 }
2291
2292 /**
2293 * Set a flag which will cause an X-Frame-Options header appropriate for
2294 * edit pages to be sent. The header value is controlled by
2295 * $wgEditPageFrameOptions.
2296 *
2297 * This is the default for special pages. If you display a CSRF-protected
2298 * form on an ordinary view page, then you need to call this function.
2299 *
2300 * @param bool $enable
2301 */
2302 public function preventClickjacking( $enable = true ) {
2303 $this->mPreventClickjacking = $enable;
2304 }
2305
2306 /**
2307 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2308 * This can be called from pages which do not contain any CSRF-protected
2309 * HTML form.
2310 */
2311 public function allowClickjacking() {
2312 $this->mPreventClickjacking = false;
2313 }
2314
2315 /**
2316 * Get the prevent-clickjacking flag
2317 *
2318 * @since 1.24
2319 * @return bool
2320 */
2321 public function getPreventClickjacking() {
2322 return $this->mPreventClickjacking;
2323 }
2324
2325 /**
2326 * Get the X-Frame-Options header value (without the name part), or false
2327 * if there isn't one. This is used by Skin to determine whether to enable
2328 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2329 *
2330 * @return string|false
2331 */
2332 public function getFrameOptions() {
2333 $config = $this->getConfig();
2334 if ( $config->get( 'BreakFrames' ) ) {
2335 return 'DENY';
2336 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2337 return $config->get( 'EditPageFrameOptions' );
2338 }
2339 return false;
2340 }
2341
2342 /**
2343 * Get the Origin-Trial header values. This is used to enable Chrome Origin
2344 * Trials: https://github.com/GoogleChrome/OriginTrials
2345 *
2346 * @return array
2347 */
2348 private function getOriginTrials() {
2349 $config = $this->getConfig();
2350
2351 return $config->get( 'OriginTrials' );
2352 }
2353
2354 private function getReportTo() {
2355 $config = $this->getConfig();
2356
2357 $expiry = $config->get( 'ReportToExpiry' );
2358
2359 if ( !$expiry ) {
2360 return false;
2361 }
2362
2363 $endpoints = $config->get( 'ReportToEndpoints' );
2364
2365 if ( !$endpoints ) {
2366 return false;
2367 }
2368
2369 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2370
2371 foreach ( $endpoints as $endpoint ) {
2372 $output['endpoints'][] = [ 'url' => $endpoint ];
2373 }
2374
2375 return json_encode( $output, JSON_UNESCAPED_SLASHES );
2376 }
2377
2378 private function getFeaturePolicyReportOnly() {
2379 $config = $this->getConfig();
2380
2381 $features = $config->get( 'FeaturePolicyReportOnly' );
2382 return implode( ';', $features );
2383 }
2384
2385 /**
2386 * Send cache control HTTP headers
2387 */
2388 public function sendCacheControl() {
2389 $response = $this->getRequest()->response();
2390 $config = $this->getConfig();
2391
2392 $this->addVaryHeader( 'Cookie' );
2393 $this->addAcceptLanguage();
2394
2395 # don't serve compressed data to clients who can't handle it
2396 # maintain different caches for logged-in users and non-logged in ones
2397 $response->header( $this->getVaryHeader() );
2398
2399 if ( $this->mEnableClientCache ) {
2400 if (
2401 $config->get( 'UseCdn' ) &&
2402 !$response->hasCookies() &&
2403 !SessionManager::getGlobalSession()->isPersistent() &&
2404 !$this->isPrintable() &&
2405 $this->mCdnMaxage != 0 &&
2406 !$this->haveCacheVaryCookies()
2407 ) {
2408 if ( $config->get( 'UseESI' ) ) {
2409 wfDeprecated( '$wgUseESI = true', '1.33' );
2410 # We'll purge the proxy cache explicitly, but require end user agents
2411 # to revalidate against the proxy on each visit.
2412 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2413 wfDebug( __METHOD__ .
2414 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2415 # start with a shorter timeout for initial testing
2416 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2417 $response->header(
2418 "Surrogate-Control: max-age={$config->get( 'CdnMaxAge' )}" .
2419 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2420 );
2421 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2422 } else {
2423 # We'll purge the proxy cache for anons explicitly, but require end user agents
2424 # to revalidate against the proxy on each visit.
2425 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2426 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2427 wfDebug( __METHOD__ .
2428 ": local proxy caching; {$this->mLastModified} **", 'private' );
2429 # start with a shorter timeout for initial testing
2430 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2431 $response->header( "Cache-Control: " .
2432 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2433 }
2434 } else {
2435 # We do want clients to cache if they can, but they *must* check for updates
2436 # on revisiting the page.
2437 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2438 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2439 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2440 }
2441 if ( $this->mLastModified ) {
2442 $response->header( "Last-Modified: {$this->mLastModified}" );
2443 }
2444 } else {
2445 wfDebug( __METHOD__ . ": no caching **", 'private' );
2446
2447 # In general, the absence of a last modified header should be enough to prevent
2448 # the client from using its cache. We send a few other things just to make sure.
2449 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2450 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2451 $response->header( 'Pragma: no-cache' );
2452 }
2453 }
2454
2455 /**
2456 * Transfer styles and JavaScript modules from skin.
2457 *
2458 * @param Skin $sk to load modules for
2459 */
2460 public function loadSkinModules( $sk ) {
2461 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2462 if ( $group === 'styles' ) {
2463 foreach ( $modules as $key => $moduleMembers ) {
2464 $this->addModuleStyles( $moduleMembers );
2465 }
2466 } else {
2467 $this->addModules( $modules );
2468 }
2469 }
2470 }
2471
2472 /**
2473 * Finally, all the text has been munged and accumulated into
2474 * the object, let's actually output it:
2475 *
2476 * @param bool $return Set to true to get the result as a string rather than sending it
2477 * @return string|null
2478 * @throws Exception
2479 * @throws FatalError
2480 * @throws MWException
2481 */
2482 public function output( $return = false ) {
2483 if ( $this->mDoNothing ) {
2484 return $return ? '' : null;
2485 }
2486
2487 $response = $this->getRequest()->response();
2488 $config = $this->getConfig();
2489
2490 if ( $this->mRedirect != '' ) {
2491 # Standards require redirect URLs to be absolute
2492 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2493
2494 $redirect = $this->mRedirect;
2495 $code = $this->mRedirectCode;
2496
2497 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2498 if ( $code == '301' || $code == '303' ) {
2499 if ( !$config->get( 'DebugRedirects' ) ) {
2500 $response->statusHeader( $code );
2501 }
2502 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2503 }
2504 if ( $config->get( 'VaryOnXFP' ) ) {
2505 $this->addVaryHeader( 'X-Forwarded-Proto' );
2506 }
2507 $this->sendCacheControl();
2508
2509 $response->header( "Content-Type: text/html; charset=utf-8" );
2510 if ( $config->get( 'DebugRedirects' ) ) {
2511 $url = htmlspecialchars( $redirect );
2512 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2513 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2514 print "</body>\n</html>\n";
2515 } else {
2516 $response->header( 'Location: ' . $redirect );
2517 }
2518 }
2519
2520 return $return ? '' : null;
2521 } elseif ( $this->mStatusCode ) {
2522 $response->statusHeader( $this->mStatusCode );
2523 }
2524
2525 # Buffer output; final headers may depend on later processing
2526 ob_start();
2527
2528 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2529 $response->header( 'Content-language: ' .
2530 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2531
2532 $linkHeader = $this->getLinkHeader();
2533 if ( $linkHeader ) {
2534 $response->header( $linkHeader );
2535 }
2536
2537 // Prevent framing, if requested
2538 $frameOptions = $this->getFrameOptions();
2539 if ( $frameOptions ) {
2540 $response->header( "X-Frame-Options: $frameOptions" );
2541 }
2542
2543 $originTrials = $this->getOriginTrials();
2544 foreach ( $originTrials as $originTrial ) {
2545 $response->header( "Origin-Trial: $originTrial", false );
2546 }
2547
2548 $reportTo = $this->getReportTo();
2549 if ( $reportTo ) {
2550 $response->header( "Report-To: $reportTo" );
2551 }
2552
2553 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2554 if ( $featurePolicyReportOnly ) {
2555 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2556 }
2557
2558 ContentSecurityPolicy::sendHeaders( $this );
2559
2560 if ( $this->mArticleBodyOnly ) {
2561 echo $this->mBodytext;
2562 } else {
2563 // Enable safe mode if requested (T152169)
2564 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2565 $this->disallowUserJs();
2566 }
2567
2568 $sk = $this->getSkin();
2569 $this->loadSkinModules( $sk );
2570
2571 MWDebug::addModules( $this );
2572
2573 // Avoid PHP 7.1 warning of passing $this by reference
2574 $outputPage = $this;
2575 // Hook that allows last minute changes to the output page, e.g.
2576 // adding of CSS or Javascript by extensions.
2577 Hooks::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2578
2579 try {
2580 $sk->outputPage();
2581 } catch ( Exception $e ) {
2582 ob_end_clean(); // bug T129657
2583 throw $e;
2584 }
2585 }
2586
2587 try {
2588 // This hook allows last minute changes to final overall output by modifying output buffer
2589 Hooks::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2590 } catch ( Exception $e ) {
2591 ob_end_clean(); // bug T129657
2592 throw $e;
2593 }
2594
2595 $this->sendCacheControl();
2596
2597 if ( $return ) {
2598 return ob_get_clean();
2599 } else {
2600 ob_end_flush();
2601 return null;
2602 }
2603 }
2604
2605 /**
2606 * Prepare this object to display an error page; disable caching and
2607 * indexing, clear the current text and redirect, set the page's title
2608 * and optionally an custom HTML title (content of the "<title>" tag).
2609 *
2610 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2611 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2612 * optional, if not passed the "<title>" attribute will be
2613 * based on $pageTitle
2614 */
2615 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2616 $this->setPageTitle( $pageTitle );
2617 if ( $htmlTitle !== false ) {
2618 $this->setHTMLTitle( $htmlTitle );
2619 }
2620 $this->setRobotPolicy( 'noindex,nofollow' );
2621 $this->setArticleRelated( false );
2622 $this->enableClientCache( false );
2623 $this->mRedirect = '';
2624 $this->clearSubtitle();
2625 $this->clearHTML();
2626 }
2627
2628 /**
2629 * Output a standard error page
2630 *
2631 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2632 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2633 * showErrorPage( 'titlemsg', $messageObject );
2634 * showErrorPage( $titleMessageObject, $messageObject );
2635 *
2636 * @param string|Message $title Message key (string) for page title, or a Message object
2637 * @param string|Message $msg Message key (string) for page text, or a Message object
2638 * @param array $params Message parameters; ignored if $msg is a Message object
2639 */
2640 public function showErrorPage( $title, $msg, $params = [] ) {
2641 if ( !$title instanceof Message ) {
2642 $title = $this->msg( $title );
2643 }
2644
2645 $this->prepareErrorPage( $title );
2646
2647 if ( $msg instanceof Message ) {
2648 if ( $params !== [] ) {
2649 trigger_error( 'Argument ignored: $params. The message parameters argument '
2650 . 'is discarded when the $msg argument is a Message object instead of '
2651 . 'a string.', E_USER_NOTICE );
2652 }
2653 $this->addHTML( $msg->parseAsBlock() );
2654 } else {
2655 $this->addWikiMsgArray( $msg, $params );
2656 }
2657
2658 $this->returnToMain();
2659 }
2660
2661 /**
2662 * Output a standard permission error page
2663 *
2664 * @param array $errors Error message keys or [key, param...] arrays
2665 * @param string|null $action Action that was denied or null if unknown
2666 */
2667 public function showPermissionsErrorPage( array $errors, $action = null ) {
2668 foreach ( $errors as $key => $error ) {
2669 $errors[$key] = (array)$error;
2670 }
2671
2672 // For some action (read, edit, create and upload), display a "login to do this action"
2673 // error if all of the following conditions are met:
2674 // 1. the user is not logged in
2675 // 2. the only error is insufficient permissions (i.e. no block or something else)
2676 // 3. the error can be avoided simply by logging in
2677 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2678 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2679 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2680 && ( User::groupHasPermission( 'user', $action )
2681 || User::groupHasPermission( 'autoconfirmed', $action ) )
2682 ) {
2683 $displayReturnto = null;
2684
2685 # Due to T34276, if a user does not have read permissions,
2686 # $this->getTitle() will just give Special:Badtitle, which is
2687 # not especially useful as a returnto parameter. Use the title
2688 # from the request instead, if there was one.
2689 $request = $this->getRequest();
2690 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2691 if ( $action == 'edit' ) {
2692 $msg = 'whitelistedittext';
2693 $displayReturnto = $returnto;
2694 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2695 $msg = 'nocreatetext';
2696 } elseif ( $action == 'upload' ) {
2697 $msg = 'uploadnologintext';
2698 } else { # Read
2699 $msg = 'loginreqpagetext';
2700 $displayReturnto = Title::newMainPage();
2701 }
2702
2703 $query = [];
2704
2705 if ( $returnto ) {
2706 $query['returnto'] = $returnto->getPrefixedText();
2707
2708 if ( !$request->wasPosted() ) {
2709 $returntoquery = $request->getValues();
2710 unset( $returntoquery['title'] );
2711 unset( $returntoquery['returnto'] );
2712 unset( $returntoquery['returntoquery'] );
2713 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2714 }
2715 }
2716
2717 $services = MediaWikiServices::getInstance();
2718
2719 $title = SpecialPage::getTitleFor( 'Userlogin' );
2720 $linkRenderer = $services->getLinkRenderer();
2721 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE );
2722 $loginLink = $linkRenderer->makeKnownLink(
2723 $title,
2724 $this->msg( 'loginreqlink' )->text(),
2725 [],
2726 $query
2727 );
2728
2729 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2730 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2731
2732 $permissionManager = $services->getPermissionManager();
2733
2734 # Don't return to a page the user can't read otherwise
2735 # we'll end up in a pointless loop
2736 if ( $displayReturnto && $permissionManager->userCan(
2737 'read', $this->getUser(), $displayReturnto
2738 ) ) {
2739 $this->returnToMain( null, $displayReturnto );
2740 }
2741 } else {
2742 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2743 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2744 }
2745 }
2746
2747 /**
2748 * Display an error page indicating that a given version of MediaWiki is
2749 * required to use it
2750 *
2751 * @param mixed $version The version of MediaWiki needed to use the page
2752 */
2753 public function versionRequired( $version ) {
2754 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2755
2756 $this->addWikiMsg( 'versionrequiredtext', $version );
2757 $this->returnToMain();
2758 }
2759
2760 /**
2761 * Format a list of error messages
2762 *
2763 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2764 * @param string|null $action Action that was denied or null if unknown
2765 * @return string The wikitext error-messages, formatted into a list.
2766 */
2767 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2768 if ( $action == null ) {
2769 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2770 } else {
2771 $action_desc = $this->msg( "action-$action" )->plain();
2772 $text = $this->msg(
2773 'permissionserrorstext-withaction',
2774 count( $errors ),
2775 $action_desc
2776 )->plain() . "\n\n";
2777 }
2778
2779 if ( count( $errors ) > 1 ) {
2780 $text .= '<ul class="permissions-errors">' . "\n";
2781
2782 foreach ( $errors as $error ) {
2783 $text .= '<li>';
2784 $text .= $this->msg( ...$error )->plain();
2785 $text .= "</li>\n";
2786 }
2787 $text .= '</ul>';
2788 } else {
2789 $text .= "<div class=\"permissions-errors\">\n" .
2790 $this->msg( ...reset( $errors ) )->plain() .
2791 "\n</div>";
2792 }
2793
2794 return $text;
2795 }
2796
2797 /**
2798 * Show a warning about replica DB lag
2799 *
2800 * If the lag is higher than $wgSlaveLagCritical seconds,
2801 * then the warning is a bit more obvious. If the lag is
2802 * lower than $wgSlaveLagWarning, then no warning is shown.
2803 *
2804 * @param int $lag Replica lag
2805 */
2806 public function showLagWarning( $lag ) {
2807 $config = $this->getConfig();
2808 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2809 $lag = floor( $lag ); // floor to avoid nano seconds to display
2810 $message = $lag < $config->get( 'SlaveLagCritical' )
2811 ? 'lag-warn-normal'
2812 : 'lag-warn-high';
2813 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2814 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2815 }
2816 }
2817
2818 /**
2819 * Output an error page
2820 *
2821 * @note FatalError exception class provides an alternative.
2822 * @param string $message Error to output. Must be escaped for HTML.
2823 */
2824 public function showFatalError( $message ) {
2825 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2826
2827 $this->addHTML( $message );
2828 }
2829
2830 /**
2831 * Add a "return to" link pointing to a specified title
2832 *
2833 * @param Title $title Title to link
2834 * @param array $query Query string parameters
2835 * @param string|null $text Text of the link (input is not escaped)
2836 * @param array $options Options array to pass to Linker
2837 */
2838 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2839 $linkRenderer = MediaWikiServices::getInstance()
2840 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2841 $link = $this->msg( 'returnto' )->rawParams(
2842 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2843 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2844 }
2845
2846 /**
2847 * Add a "return to" link pointing to a specified title,
2848 * or the title indicated in the request, or else the main page
2849 *
2850 * @param mixed|null $unused
2851 * @param Title|string|null $returnto Title or String to return to
2852 * @param string|null $returntoquery Query string for the return to link
2853 */
2854 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2855 if ( $returnto == null ) {
2856 $returnto = $this->getRequest()->getText( 'returnto' );
2857 }
2858
2859 if ( $returntoquery == null ) {
2860 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2861 }
2862
2863 if ( $returnto === '' ) {
2864 $returnto = Title::newMainPage();
2865 }
2866
2867 if ( is_object( $returnto ) ) {
2868 $titleObj = $returnto;
2869 } else {
2870 $titleObj = Title::newFromText( $returnto );
2871 }
2872 // We don't want people to return to external interwiki. That
2873 // might potentially be used as part of a phishing scheme
2874 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
2875 $titleObj = Title::newMainPage();
2876 }
2877
2878 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2879 }
2880
2881 private function getRlClientContext() {
2882 if ( !$this->rlClientContext ) {
2883 $query = ResourceLoader::makeLoaderQuery(
2884 [], // modules; not relevant
2885 $this->getLanguage()->getCode(),
2886 $this->getSkin()->getSkinName(),
2887 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2888 null, // version; not relevant
2889 ResourceLoader::inDebugMode(),
2890 null, // only; not relevant
2891 $this->isPrintable(),
2892 $this->getRequest()->getBool( 'handheld' )
2893 );
2894 $this->rlClientContext = new ResourceLoaderContext(
2895 $this->getResourceLoader(),
2896 new FauxRequest( $query )
2897 );
2898 if ( $this->contentOverrideCallbacks ) {
2899 $this->rlClientContext = new DerivativeResourceLoaderContext( $this->rlClientContext );
2900 $this->rlClientContext->setContentOverrideCallback( function ( Title $title ) {
2901 foreach ( $this->contentOverrideCallbacks as $callback ) {
2902 $content = $callback( $title );
2903 if ( $content !== null ) {
2904 $text = ContentHandler::getContentText( $content );
2905 if ( strpos( $text, '</script>' ) !== false ) {
2906 // Proactively replace this so that we can display a message
2907 // to the user, instead of letting it go to Html::inlineScript(),
2908 // where it would be considered a server-side issue.
2909 $titleFormatted = $title->getPrefixedText();
2910 $content = new JavaScriptContent(
2911 Xml::encodeJsCall( 'mw.log.error', [
2912 "Cannot preview $titleFormatted due to script-closing tag."
2913 ] )
2914 );
2915 }
2916 return $content;
2917 }
2918 }
2919 return null;
2920 } );
2921 }
2922 }
2923 return $this->rlClientContext;
2924 }
2925
2926 /**
2927 * Call this to freeze the module queue and JS config and create a formatter.
2928 *
2929 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2930 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2931 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2932 * the module filters retroactively. Skins and extension hooks may also add modules until very
2933 * late in the request lifecycle.
2934 *
2935 * @return ResourceLoaderClientHtml
2936 */
2937 public function getRlClient() {
2938 if ( !$this->rlClient ) {
2939 $context = $this->getRlClientContext();
2940 $rl = $this->getResourceLoader();
2941 $this->addModules( [
2942 'user',
2943 'user.options',
2944 'user.tokens',
2945 ] );
2946 $this->addModuleStyles( [
2947 'site.styles',
2948 'noscript',
2949 'user.styles',
2950 ] );
2951 $this->getSkin()->setupSkinUserCss( $this );
2952
2953 // Prepare exempt modules for buildExemptModules()
2954 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2955 $exemptStates = [];
2956 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2957
2958 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2959 // Separate user-specific batch for improved cache-hit ratio.
2960 $userBatch = [ 'user.styles', 'user' ];
2961 $siteBatch = array_diff( $moduleStyles, $userBatch );
2962 $dbr = wfGetDB( DB_REPLICA );
2963 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2964 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2965
2966 // Filter out modules handled by buildExemptModules()
2967 $moduleStyles = array_filter( $moduleStyles,
2968 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2969 $module = $rl->getModule( $name );
2970 if ( $module ) {
2971 $group = $module->getGroup();
2972 if ( isset( $exemptGroups[$group] ) ) {
2973 $exemptStates[$name] = 'ready';
2974 if ( !$module->isKnownEmpty( $context ) ) {
2975 // E.g. Don't output empty <styles>
2976 $exemptGroups[$group][] = $name;
2977 }
2978 return false;
2979 }
2980 }
2981 return true;
2982 }
2983 );
2984 $this->rlExemptStyleModules = $exemptGroups;
2985
2986 $rlClient = new ResourceLoaderClientHtml( $context, [
2987 'target' => $this->getTarget(),
2988 'nonce' => $this->getCSPNonce(),
2989 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2990 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2991 // modules enqueud for loading on this page is filtered to just those.
2992 // However, to make sure we also apply the restriction to dynamic dependencies and
2993 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2994 // StartupModule so that the client-side registry will not contain any restricted
2995 // modules either. (T152169, T185303)
2996 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2997 <= ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
2998 ) ? '1' : null,
2999 ] );
3000 $rlClient->setConfig( $this->getJSVars() );
3001 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3002 $rlClient->setModuleStyles( $moduleStyles );
3003 $rlClient->setExemptStates( $exemptStates );
3004 $this->rlClient = $rlClient;
3005 }
3006 return $this->rlClient;
3007 }
3008
3009 /**
3010 * @param Skin $sk The given Skin
3011 * @param bool $includeStyle Unused
3012 * @return string The doctype, opening "<html>", and head element.
3013 */
3014 public function headElement( Skin $sk, $includeStyle = true ) {
3015 $userdir = $this->getLanguage()->getDir();
3016 $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
3017
3018 $pieces = [];
3019 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
3020 $this->getRlClient()->getDocumentAttributes(),
3021 $sk->getHtmlElementAttributes()
3022 ) );
3023 $pieces[] = Html::openElement( 'head' );
3024
3025 if ( $this->getHTMLTitle() == '' ) {
3026 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3027 }
3028
3029 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
3030 // Add <meta charset="UTF-8">
3031 // This should be before <title> since it defines the charset used by
3032 // text including the text inside <title>.
3033 // The spec recommends defining XHTML5's charset using the XML declaration
3034 // instead of meta.
3035 // Our XML declaration is output by Html::htmlHeader.
3036 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3037 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3038 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
3039 }
3040
3041 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
3042 $pieces[] = $this->getRlClient()->getHeadHtml();
3043 $pieces[] = $this->buildExemptModules();
3044 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3045 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3046
3047 // Use an IE conditional comment to serve the script only to old IE
3048 $pieces[] = '<!--[if lt IE 9]>' .
3049 ResourceLoaderClientHtml::makeLoad(
3050 new ResourceLoaderContext(
3051 $this->getResourceLoader(),
3052 new FauxRequest( [] )
3053 ),
3054 [ 'html5shiv' ],
3055 ResourceLoaderModule::TYPE_SCRIPTS,
3056 [ 'raw' => '1', 'sync' => '1' ],
3057 $this->getCSPNonce()
3058 ) .
3059 '<![endif]-->';
3060
3061 $pieces[] = Html::closeElement( 'head' );
3062
3063 $bodyClasses = $this->mAdditionalBodyClasses;
3064 $bodyClasses[] = 'mediawiki';
3065
3066 # Classes for LTR/RTL directionality support
3067 $bodyClasses[] = $userdir;
3068 $bodyClasses[] = "sitedir-$sitedir";
3069
3070 $underline = $this->getUser()->getOption( 'underline' );
3071 if ( $underline < 2 ) {
3072 // The following classes can be used here:
3073 // * mw-underline-always
3074 // * mw-underline-never
3075 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
3076 }
3077
3078 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3079 # A <body> class is probably not the best way to do this . . .
3080 $bodyClasses[] = 'capitalize-all-nouns';
3081 }
3082
3083 // Parser feature migration class
3084 // The idea is that this will eventually be removed, after the wikitext
3085 // which requires it is cleaned up.
3086 $bodyClasses[] = 'mw-hide-empty-elt';
3087
3088 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3089 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
3090 $bodyClasses[] =
3091 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
3092
3093 $bodyAttrs = [];
3094 // While the implode() is not strictly needed, it's used for backwards compatibility
3095 // (this used to be built as a string and hooks likely still expect that).
3096 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3097
3098 // Allow skins and extensions to add body attributes they need
3099 $sk->addToBodyAttributes( $this, $bodyAttrs );
3100 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3101
3102 $pieces[] = Html::openElement( 'body', $bodyAttrs );
3103
3104 return self::combineWrappedStrings( $pieces );
3105 }
3106
3107 /**
3108 * Get a ResourceLoader object associated with this OutputPage
3109 *
3110 * @return ResourceLoader
3111 */
3112 public function getResourceLoader() {
3113 if ( is_null( $this->mResourceLoader ) ) {
3114 // Lazy-initialise as needed
3115 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3116 }
3117 return $this->mResourceLoader;
3118 }
3119
3120 /**
3121 * Explicily load or embed modules on a page.
3122 *
3123 * @param array|string $modules One or more module names
3124 * @param string $only ResourceLoaderModule TYPE_ class constant
3125 * @param array $extraQuery [optional] Array with extra query parameters for the request