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