Debian Codegraph @

includes/Output/OutputPage.php

raw symbols SCIP
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 namespace MediaWiki\Output;
24
25 use Article;
26 use CSSJanus;
27 use Exception;
28 use File;
29 use HtmlArmor;
30 use InvalidArgumentException;
31 use MediaWiki\Cache\LinkCache;
32 use MediaWiki\Config\Config;
33 use MediaWiki\Content\Content;
34 use MediaWiki\Content\JavaScriptContent;
35 use MediaWiki\Content\TextContent;
36 use MediaWiki\Context\ContextSource;
37 use MediaWiki\Context\IContextSource;
38 use MediaWiki\Context\RequestContext;
39 use MediaWiki\Debug\DeprecationHelper;
40 use MediaWiki\Debug\MWDebug;
41 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
42 use MediaWiki\Html\Html;
43 use MediaWiki\Language\Language;
44 use MediaWiki\Language\LanguageCode;
45 use MediaWiki\Linker\LinkTarget;
46 use MediaWiki\MainConfigNames;
47 use MediaWiki\MediaWikiServices;
48 use MediaWiki\Message\Message;
49 use MediaWiki\Page\PageRecord;
50 use MediaWiki\Page\PageReference;
51 use MediaWiki\Parser\Parser;
52 use MediaWiki\Parser\ParserOptions;
53 use MediaWiki\Parser\ParserOutput;
54 use MediaWiki\Parser\ParserOutputFlags;
55 use MediaWiki\Parser\Sanitizer;
56 use MediaWiki\Permissions\PermissionStatus;
57 use MediaWiki\Registration\ExtensionRegistry;
58 use MediaWiki\Request\ContentSecurityPolicy;
59 use MediaWiki\Request\FauxRequest;
60 use MediaWiki\Request\WebRequest;
61 use MediaWiki\ResourceLoader as RL;
62 use MediaWiki\ResourceLoader\ResourceLoader;
63 use MediaWiki\Session\SessionManager;
64 use MediaWiki\SpecialPage\SpecialPage;
65 use MediaWiki\Title\Title;
66 use MediaWiki\Title\TitleValue;
67 use MediaWiki\Utils\MWTimestamp;
68 use OOUI\Element;
69 use OOUI\Theme;
70 use RuntimeException;
71 use Skin;
72 use Wikimedia\Assert\Assert;
73 use Wikimedia\Bcp47Code\Bcp47Code;
74 use Wikimedia\LightweightObjectStore\ExpirationAwareness;
75 use Wikimedia\Message\MessageSpecifier;
76 use Wikimedia\Parsoid\Core\LinkTarget as ParsoidLinkTarget;
77 use Wikimedia\Parsoid\Core\TOCData;
78 use Wikimedia\Rdbms\IResultWrapper;
79 use Wikimedia\RelPath;
80 use Wikimedia\WrappedString;
81 use Wikimedia\WrappedStringList;
82
83 /**
84 * This is one of the Core classes and should
85 * be read at least once by any new developers. Also documented at
86 * https://www.mediawiki.org/wiki/Manual:Architectural_modules/OutputPage
87 *
88 * This class is used to prepare the final rendering. A skin is then
89 * applied to the output parameters (links, javascript, html, categories ...).
90 *
91 * @todo FIXME: Another class handles sending the whole page to the client.
92 *
93 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
94 * in November 2010.
95 *
96 * @todo document
97 */
98 class OutputPage extends ContextSource {
99 use ProtectedHookAccessorTrait;
100 use DeprecationHelper;
101
102 /** Output CSP policies as headers */
103 public const CSP_HEADERS = 'headers';
104 /** Output CSP policies as meta tags */
105 public const CSP_META = 'meta';
106
107 // Constants for getJSVars()
108 private const JS_VAR_EARLY = 1;
109 private const JS_VAR_LATE = 2;
110
111 // Core config vars that opt-in to JS_VAR_LATE.
112 // Extensions use the 'LateJSConfigVarNames' attribute instead.
113 private const CORE_LATE_JS_CONFIG_VAR_NAMES = [];
114
115 /** @var bool Whether setupOOUI() has been called */
116 private static $oouiSetupDone = false;
117
118 /** @var string[][] Should be private. Used with addMeta() which adds "<meta>" */
119 protected $mMetatags = [];
120
121 /** @var array */
122 protected $mLinktags = [];
123
124 /** @var string|false */
125 protected $mCanonicalUrl = false;
126
127 /**
128 * @var string The contents of <h1>
129 */
130 private $mPageTitle = '';
131
132 /**
133 * @var string The displayed title of the page. Different from page title
134 * if overridden by display title magic word or hooks. Can contain safe
135 * HTML. Different from page title which may contain messages such as
136 * "Editing X" which is displayed in h1. This can be used for other places
137 * where the page name is referred on the page.
138 */
139 private $displayTitle;
140
141 /** @var bool See OutputPage::couldBePublicCached. */
142 private $cacheIsFinal = false;
143
144 /**
145 * @var string Contains all of the "<body>" content. Should be private we
146 * got set/get accessors and the append() method.
147 */
148 public $mBodytext = '';
149
150 /** @var string Stores contents of "<title>" tag */
151 private $mHTMLtitle = '';
152
153 /**
154 * @var bool Is the displayed content related to the source of the
155 * corresponding wiki article.
156 */
157 private $mIsArticle = false;
158
159 /** @var bool Stores "article flag" toggle. */
160 private $mIsArticleRelated = true;
161
162 /** @var bool Is the content subject to copyright */
163 private $mHasCopyright = false;
164
165 /**
166 * @var bool We have to set isPrintable(). Some pages should
167 * never be printed (ex: redirections).
168 */
169 private $mPrintable = false;
170
171 /**
172 * @var ?TOCData Table of Contents information from ParserOutput, or
173 * null if no TOCData was ever set.
174 */
175 private $tocData;
176
177 /**
178 * @var array Contains the page subtitle. Special pages usually have some
179 * links here. Don't confuse with site subtitle added by skins.
180 */
181 private $mSubtitle = [];
182
183 /** @var string */
184 public $mRedirect = '';
185
186 /** @var int */
187 protected $mStatusCode;
188
189 /**
190 * @var string Used for sending cache control.
191 * The whole caching system should probably be moved into its own class.
192 */
193 protected $mLastModified = '';
194
195 /**
196 * @var string[][]
197 * @deprecated since 1.38; will be made private (T301020)
198 */
199 private $mCategoryLinks = [];
200
201 /**
202 * @var string[][]
203 * @deprecated since 1.38, will be made private (T301020)
204 */
205 private $mCategories = [
206 'hidden' => [],
207 'normal' => [],
208 ];
209
210 /**
211 * Internal storage for categories on the OutputPage, stored as an array:
212 * * sortKey: category title text as a sort key,
213 * * type: category type (hidden,normal)
214 * * title: category title,
215 * * link: link string, nullable to support ::setCategoryLinks()
216 *
217 * @var list<array{sortKey:string,type:'normal'|'hidden',title:string,link:?string}>
218 */
219 private array $mCategoryData = [];
220
221 /**
222 * Keep track of whether mCategoryData has been
223 * sorted. We do this on-demand to avoid redundant sorts
224 * of incremental additions to the category list.
225 */
226 private bool $mCategoriesSorted = true;
227
228 /**
229 * @var string[]
230 * @deprecated since 1.38; will be made private (T301020)
231 */
232 private $mIndicators = [];
233
234 /**
235 * Used for JavaScript (predates ResourceLoader)
236 * @todo We should split JS / CSS.
237 * mScripts content is inserted as is in "<head>" by Skin. This might
238 * contain either a link to a stylesheet or inline CSS.
239 * @var string
240 */
241 private $mScripts = '';
242
243 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
244 protected $mInlineStyles = '';
245
246 /**
247 * Additional <html> classes; This should be rarely modified; prefer mAdditionalBodyClasses.
248 * @var array
249 */
250 protected $mAdditionalHtmlClasses = [];
251
252 /**
253 * @var string[] Array of elements in "<head>". Parser might add its own headers!
254 * @deprecated since 1.38; will be made private (T301020)
255 */
256 private $mHeadItems = [];
257
258 /** @var array Additional <body> classes; there are also <body> classes from other sources */
259 protected $mAdditionalBodyClasses = [];
260
261 /**
262 * @var array
263 * @deprecated since 1.38; will be made private (T301020)
264 */
265 private $mModules = [];
266
267 /**
268 * @var array
269 * @deprecated since 1.38; will be made private (T301020)
270 */
271 private $mModuleStyles = [];
272
273 /** @var ResourceLoader */
274 protected $mResourceLoader;
275
276 /** @var RL\ClientHtml */
277 private $rlClient;
278
279 /** @var RL\Context */
280 private $rlClientContext;
281
282 /** @var array */
283 private $rlExemptStyleModules;
284
285 /**
286 * @var array
287 * @deprecated since 1.38; will be made private (T301020)
288 */
289 private $mJsConfigVars = [];
290
291 /**
292 * @var array<int,array<string,int>>
293 * @deprecated since 1.38; will be made private (T301020)
294 */
295 private $mTemplateIds = [];
296
297 /** @var array */
298 protected $mImageTimeKeys = [];
299
300 /** @var string */
301 public $mRedirectCode = '';
302
303 /** @var null */
304 protected $mFeedLinksAppendQuery = null;
305
306 /** @var array
307 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
308 * @see RL\Module::$origin
309 * RL\Module::ORIGIN_ALL is assumed unless overridden;
310 */
311 protected $mAllowedModules = [
312 RL\Module::TYPE_COMBINED => RL\Module::ORIGIN_ALL,
313 ];
314
315 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
316 protected $mDoNothing = false;
317
318 // Parser related.
319
320 /**
321 * lazy initialised, use parserOptions()
322 * @var ParserOptions
323 */
324 protected $mParserOptions = null;
325
326 /**
327 * Handles the Atom / RSS links.
328 * We probably only support Atom in 2011.
329 * @see $wgAdvertisedFeedTypes
330 * @var array
331 */
332 private $mFeedLinks = [];
333
334 /**
335 * @var bool Set to false to send no-cache headers, disabling
336 * client-side caching. (This variable should really be named
337 * in the opposite sense; see ::disableClientCache().)
338 * @deprecated since 1.38; will be made private (T301020)
339 */
340 private $mEnableClientCache = true;
341
342 /** @var bool Flag if output should only contain the body of the article. */
343 private $mArticleBodyOnly = false;
344
345 /**
346 * @var bool
347 * @deprecated since 1.38; will be made private (T301020)
348 */
349 private $mNewSectionLink = false;
350
351 /**
352 * @var bool
353 * @deprecated since 1.38; will be made private (T301020)
354 */
355 private $mHideNewSectionLink = false;
356
357 /**
358 * @var bool Comes from the parser. This was probably made to load CSS/JS
359 * only if we had "<gallery>". Used directly in CategoryViewer.php.
360 * Looks like ResourceLoader can replace this.
361 * @deprecated since 1.38; will be made private (T301020)
362 */
363 private $mNoGallery = false;
364
365 /** @var int Cache stuff. Looks like mEnableClientCache */
366 protected $mCdnMaxage = 0;
367 /** @var int Upper limit on mCdnMaxage */
368 protected $mCdnMaxageLimit = INF;
369
370 /** @var int|null To include the variable {{REVISIONID}} */
371 private $mRevisionId = null;
372
373 /** @var bool|null */
374 private $mRevisionIsCurrent = null;
375
376 /** @var string */
377 private $mRevisionTimestamp = null;
378
379 /** @var array */
380 protected $mFileVersion = null;
381
382 /**
383 * @var array An array of stylesheet filenames (relative from skins path),
384 * with options for CSS media, IE conditions, and RTL/LTR direction.
385 * For internal use; add settings in the skin via $this->addStyle()
386 *
387 * Style again! This seems like a code duplication since we already have
388 * mStyles. This is what makes Open Source amazing.
389 */
390 protected $styles = [];
391
392 /** @var string */
393 private $mFollowPolicy = 'follow';
394
395 /** @var array */
396 private $mRobotsOptions = [ 'max-image-preview' => 'standard' ];
397
398 /**
399 * @var array Headers that cause the cache to vary. Key is header name,
400 * value should always be null. (Value was an array of options for
401 * the `Key` header, which was deprecated in 1.32 and removed in 1.34.)
402 */
403 private $mVaryHeader = [
404 'Accept-Encoding' => null,
405 ];
406
407 /**
408 * If the current page was reached through a redirect, $mRedirectedFrom contains the title
409 * of the redirect.
410 *
411 * @var PageReference
412 */
413 private $mRedirectedFrom = null;
414
415 /**
416 * Additional key => value data
417 * @var array
418 */
419 private $mProperties = [];
420
421 /**
422 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
423 */
424 private $mTarget = null;
425
426 /**
427 * @var bool Whether parser output contains a table of contents
428 */
429 private $mEnableTOC = false;
430
431 /**
432 * @var array<string,bool> Flags set in the ParserOutput
433 */
434 private $mOutputFlags = [];
435
436 /**
437 * @var string|null The URL to send in a <link> element with rel=license
438 */
439 private $copyrightUrl;
440
441 /**
442 * @var Language|null
443 */
444 private $contentLang;
445
446 /** @var array Profiling data */
447 private $limitReportJSData = [];
448
449 /** @var array Map Title to Content */
450 private $contentOverrides = [];
451
452 /** @var callable[] */
453 private $contentOverrideCallbacks = [];
454
455 /**
456 * Link: header contents
457 * @var array
458 */
459 private $mLinkHeader = [];
460
461 /**
462 * @var ContentSecurityPolicy
463 */
464 private $CSP;
465
466 private string $cspOutputMode = self::CSP_HEADERS;
467
468 /**
469 * To eliminate redundancy between information kept in OutputPage
470 * for non-article pages and metadata kept by the Parser for
471 * article pages, we create a ParserOutput for the OutputPage
472 * which will collect metadata such as categories, index policy,
473 * modules, etc, even if no parse actually occurs during the
474 * rendering of this page.
475 */
476 private ParserOutput $metadata;
477
478 /**
479 * @var array A cache of the names of the cookies that will influence the cache
480 */
481 private static $cacheVaryCookies = null;
482
483 /**
484 * Constructor for OutputPage. This should not be called directly.
485 * Instead a new RequestContext should be created and it will implicitly create
486 * a OutputPage tied to that context.
487 * @param IContextSource $context
488 */
489 public function __construct( IContextSource $context ) {
490 $this->deprecatePublicProperty( 'mCategoryLinks', '1.38', __CLASS__ );
491 $this->deprecatePublicProperty( 'mCategories', '1.38', __CLASS__ );
492 $this->deprecatePublicProperty( 'mIndicators', '1.38', __CLASS__ );
493 $this->deprecatePublicProperty( 'mHeadItems', '1.38', __CLASS__ );
494 $this->deprecatePublicProperty( 'mModules', '1.38', __CLASS__ );
495 $this->deprecatePublicProperty( 'mModuleStyles', '1.38', __CLASS__ );
496 $this->deprecatePublicProperty( 'mJsConfigVars', '1.38', __CLASS__ );
497 $this->deprecatePublicProperty( 'mTemplateIds', '1.38', __CLASS__ );
498 $this->deprecatePublicProperty( 'mEnableClientCache', '1.38', __CLASS__ );
499 $this->deprecatePublicProperty( 'mNewSectionLink', '1.38', __CLASS__ );
500 $this->deprecatePublicProperty( 'mHideNewSectionLink', '1.38', __CLASS__ );
501 $this->deprecatePublicProperty( 'mNoGallery', '1.38', __CLASS__ );
502 $this->setContext( $context );
503 $this->metadata = new ParserOutput( null );
504 $this->metadata->setPreventClickjacking( true ); // OutputPage default
505 $this->CSP = new ContentSecurityPolicy(
506 $context->getRequest()->response(),
507 $context->getConfig(),
508 $this->getHookContainer()
509 );
510 }
511
512 /**
513 * Redirect to $url rather than displaying the normal page
514 *
515 * @param string $url
516 * @param string|int $responsecode HTTP status code
517 */
518 public function redirect( $url, $responsecode = '302' ) {
519 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
520 $this->mRedirect = str_replace( "\n", '', $url );
521 $this->mRedirectCode = (string)$responsecode;
522 }
523
524 /**
525 * Get the URL to redirect to, or an empty string if not redirect URL set
526 *
527 * @return string
528 */
529 public function getRedirect() {
530 return $this->mRedirect;
531 }
532
533 /**
534 * Set the copyright URL to send with the output.
535 * Empty string to omit, null to reset.
536 *
537 * @since 1.26
538 *
539 * @param string|null $url
540 */
541 public function setCopyrightUrl( $url ) {
542 $this->copyrightUrl = $url;
543 }
544
545 /**
546 * Set the HTTP status code to send with the output.
547 *
548 * @param int $statusCode
549 */
550 public function setStatusCode( $statusCode ) {
551 $this->mStatusCode = $statusCode;
552 }
553
554 /**
555 * Return a ParserOutput that can be used to set metadata properties
556 * for the current page.
557 * @return ParserOutput
558 */
559 public function getMetadata(): ParserOutput {
560 // We can deprecate the redundant
561 // methods on OutputPage which simply turn around
562 // and invoke the corresponding method on the metadata
563 // ParserOutput.
564 return $this->metadata;
565 }
566
567 /**
568 * Add a new "<meta>" tag
569 * To add an http-equiv meta tag, precede the name with "http:"
570 *
571 * @param string $name Name of the meta tag
572 * @param string $val Value of the meta tag
573 */
574 public function addMeta( $name, $val ) {
575 $this->mMetatags[] = [ $name, $val ];
576 }
577
578 /**
579 * Returns the current <meta> tags
580 *
581 * @since 1.25
582 * @return array
583 */
584 public function getMetaTags() {
585 return $this->mMetatags;
586 }
587
588 /**
589 * Add a new \<link\> tag to the page header.
590 *
591 * Note: use setCanonicalUrl() for rel=canonical.
592 *
593 * @param array $linkarr Associative array of attributes.
594 */
595 public function addLink( array $linkarr ) {
596 $this->mLinktags[] = $linkarr;
597 }
598
599 /**
600 * Returns the current <link> tags
601 *
602 * @since 1.25
603 * @return array
604 */
605 public function getLinkTags() {
606 return $this->mLinktags;
607 }
608
609 /**
610 * Set the URL to be used for the <link rel=canonical>. This should be used
611 * in preference to addLink(), to avoid duplicate link tags.
612 * @param string $url
613 */
614 public function setCanonicalUrl( $url ) {
615 $this->mCanonicalUrl = $url;
616 }
617
618 /**
619 * Returns the URL to be used for the <link rel=canonical> if
620 * one is set.
621 *
622 * @since 1.25
623 * @return bool|string
624 */
625 public function getCanonicalUrl() {
626 return $this->mCanonicalUrl;
627 }
628
629 /**
630 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
631 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
632 * if possible.
633 *
634 * @param string $script Raw HTML
635 * @param-taint $script exec_html
636 */
637 public function addScript( $script ) {
638 $this->mScripts .= $script;
639 }
640
641 /**
642 * Add a JavaScript file to be loaded as `<script>` on this page.
643 *
644 * Internal use only. Use OutputPage::addModules() if possible.
645 *
646 * @param string $file URL to file (absolute path, protocol-relative, or full url)
647 * @param string|null $unused Previously used to change the cache-busting query parameter
648 */
649 public function addScriptFile( $file, $unused = null ) {
650 $this->addScript( Html::linkedScript( $file ) );
651 }
652
653 /**
654 * Add a self-contained script tag with the given contents
655 * Internal use only. Use OutputPage::addModules() if possible.
656 *
657 * @param string $script JavaScript text, no script tags
658 * @param-taint $script exec_html
659 */
660 public function addInlineScript( $script ) {
661 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
662 }
663
664 /**
665 * Filter an array of modules to remove insufficiently trustworthy members, and modules
666 * which are no longer registered (eg a page is cached before an extension is disabled)
667 * @param string[] $modules
668 * @param string|null $position Unused
669 * @param string $type
670 * @return string[]
671 */
672 protected function filterModules( array $modules, $position = null,
673 $type = RL\Module::TYPE_COMBINED
674 ) {
675 $resourceLoader = $this->getResourceLoader();
676 $filteredModules = [];
677 foreach ( $modules as $val ) {
678 $module = $resourceLoader->getModule( $val );
679 if ( $module instanceof RL\Module
680 && $module->getOrigin() <= $this->getAllowedModules( $type )
681 ) {
682 $filteredModules[] = $val;
683 }
684 }
685 return $filteredModules;
686 }
687
688 /**
689 * Get the list of modules to include on this page
690 *
691 * @param bool $filter Whether to filter out insufficiently trustworthy modules
692 * @param string|null $position Unused
693 * @param string $param
694 * @param string $type
695 * @return string[] Array of module names
696 */
697 public function getModules( $filter = false, $position = null, $param = 'mModules',
698 $type = RL\Module::TYPE_COMBINED
699 ) {
700 $modules = array_values( array_unique( $this->$param ) );
701 return $filter
702 ? $this->filterModules( $modules, null, $type )
703 : $modules;
704 }
705
706 /**
707 * Load one or more ResourceLoader modules on this page.
708 *
709 * @param string|array $modules Module name (string) or array of module names
710 */
711 public function addModules( $modules ) {
712 $this->mModules = array_merge( $this->mModules, (array)$modules );
713 }
714
715 /**
716 * Get the list of style-only modules to load on this page.
717 *
718 * @param bool $filter
719 * @param string|null $position Unused
720 * @return string[] Array of module names
721 */
722 public function getModuleStyles( $filter = false, $position = null ) {
723 return $this->getModules( $filter, null, 'mModuleStyles',
724 RL\Module::TYPE_STYLES
725 );
726 }
727
728 /**
729 * Load the styles of one or more style-only ResourceLoader modules on this page.
730 *
731 * Module styles added through this function will be loaded as a stylesheet,
732 * using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
733 * Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
734 *
735 * @param string|array $modules Module name (string) or array of module names
736 */
737 public function addModuleStyles( $modules ) {
738 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
739 }
740
741 /**
742 * @return null|string ResourceLoader target
743 */
744 public function getTarget() {
745 return $this->mTarget;
746 }
747
748 /**
749 * Force the given Content object for the given page, for things like page preview.
750 * @see self::addContentOverrideCallback()
751 * @since 1.32
752 * @param LinkTarget|PageReference $target
753 * @param Content $content
754 */
755 public function addContentOverride( $target, Content $content ) {
756 if ( !$this->contentOverrides ) {
757 // Register a callback for $this->contentOverrides on the first call
758 $this->addContentOverrideCallback( function ( $target ) {
759 $key = $target->getNamespace() . ':' . $target->getDBkey();
760 return $this->contentOverrides[$key] ?? null;
761 } );
762 }
763
764 $key = $target->getNamespace() . ':' . $target->getDBkey();
765 $this->contentOverrides[$key] = $content;
766 }
767
768 /**
769 * Add a callback for mapping from a Title to a Content object, for things
770 * like page preview.
771 * @see RL\Context::getContentOverrideCallback()
772 * @since 1.32
773 * @param callable $callback
774 */
775 public function addContentOverrideCallback( callable $callback ) {
776 $this->contentOverrideCallbacks[] = $callback;
777 }
778
779 /**
780 * Add a class to the <html> element. This should rarely be used.
781 * Instead use OutputPage::addBodyClasses() if possible.
782 *
783 * @unstable Experimental since 1.35. Prefer OutputPage::addBodyClasses()
784 * @param string|string[] $classes One or more classes to add
785 */
786 public function addHtmlClasses( $classes ) {
787 $this->mAdditionalHtmlClasses = array_merge( $this->mAdditionalHtmlClasses, (array)$classes );
788 }
789
790 /**
791 * Get an array of head items
792 *
793 * @return string[]
794 */
795 public function getHeadItemsArray() {
796 return $this->mHeadItems;
797 }
798
799 /**
800 * Add or replace a head item to the output
801 *
802 * Whenever possible, use more specific options like ResourceLoader modules,
803 * OutputPage::addLink(), OutputPage::addMeta() and OutputPage::addFeedLink()
804 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
805 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
806 * This would be your very LAST fallback.
807 *
808 * @param string $name Item name
809 * @param string $value Raw HTML
810 * @param-taint $value exec_html
811 */
812 public function addHeadItem( $name, $value ) {
813 $this->mHeadItems[$name] = $value;
814 }
815
816 /**
817 * Add one or more head items to the output
818 *
819 * @since 1.28
820 * @param string|string[] $values Raw HTML
821 * @param-taint $values exec_html
822 */
823 public function addHeadItems( $values ) {
824 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
825 }
826
827 /**
828 * Check if the header item $name is already set
829 *
830 * @param string $name Item name
831 * @return bool
832 */
833 public function hasHeadItem( $name ) {
834 return isset( $this->mHeadItems[$name] );
835 }
836
837 /**
838 * Add a class to the <body> element
839 *
840 * @since 1.30
841 * @param string|string[] $classes One or more classes to add
842 */
843 public function addBodyClasses( $classes ) {
844 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
845 }
846
847 /**
848 * Set whether the output should only contain the body of the article,
849 * without any skin, sidebar, etc.
850 * Used e.g. when calling with "action=render".
851 *
852 * @param bool $only Whether to output only the body of the article
853 */
854 public function setArticleBodyOnly( $only ) {
855 $this->mArticleBodyOnly = $only;
856 }
857
858 /**
859 * Return whether the output will contain only the body of the article
860 *
861 * @return bool
862 */
863 public function getArticleBodyOnly() {
864 return $this->mArticleBodyOnly;
865 }
866
867 /**
868 * Set an additional output property
869 * @since 1.21
870 *
871 * @param string $name
872 * @param mixed $value
873 */
874 public function setProperty( $name, $value ) {
875 $this->mProperties[$name] = $value;
876 }
877
878 /**
879 * Get an additional output property
880 * @since 1.21
881 *
882 * @param string $name
883 * @return mixed Property value or null if not found
884 */
885 public function getProperty( $name ) {
886 return $this->mProperties[$name] ?? null;
887 }
888
889 /**
890 * checkLastModified tells the client to use the client-cached page if
891 * possible. If successful, the OutputPage is disabled so that
892 * any future call to OutputPage->output() have no effect.
893 *
894 * Side effect: sets mLastModified for Last-Modified header
895 *
896 * @param string $timestamp
897 *
898 * @return bool True if cache-ok headers was sent.
899 */
900 public function checkLastModified( $timestamp ) {
901 if ( !$timestamp || $timestamp == '19700101000000' ) {
902 wfDebug( __METHOD__ . ': CACHE DISABLED, NO TIMESTAMP' );
903 return false;
904 }
905 $config = $this->getConfig();
906 if ( !$config->get( MainConfigNames::CachePages ) ) {
907 wfDebug( __METHOD__ . ': CACHE DISABLED' );
908 return false;
909 }
910
911 $timestamp = wfTimestamp( TS_MW, $timestamp );
912 $modifiedTimes = [
913 'page' => $timestamp,
914 'user' => $this->getUser()->getTouched(),
915 'epoch' => $config->get( MainConfigNames::CacheEpoch )
916 ];
917 if ( $config->get( MainConfigNames::UseCdn ) ) {
918 // Ensure Last-Modified is never more than "$wgCdnMaxAge" seconds in the past,
919 // because even if the wiki page hasn't been edited, other static resources may
920 // change (site configuration, default preferences, skin HTML, interface messages,
921 // URLs to other files and services) and must roll-over in a timely manner (T46570)
922 $modifiedTimes['sepoch'] = wfTimestamp(
923 TS_MW,
924 time() - $config->get( MainConfigNames::CdnMaxAge )
925 );
926 }
927 $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this );
928
929 $maxModified = max( $modifiedTimes );
930 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
931
932 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
933 if ( $clientHeader === false ) {
934 wfDebug( __METHOD__ . ': client did not send If-Modified-Since header', 'private' );
935 return false;
936 }
937
938 # IE sends sizes after the date like this:
939 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
940 # this breaks strtotime().
941 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
942
943 // Ignore timezone warning
944 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
945 $clientHeaderTime = @strtotime( $clientHeader );
946 if ( !$clientHeaderTime ) {
947 wfDebug( __METHOD__
948 . ": unable to parse the client's If-Modified-Since header: $clientHeader" );
949 return false;
950 }
951 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
952
953 # Make debug info
954 $info = '';
955 foreach ( $modifiedTimes as $name => $value ) {
956 if ( $info !== '' ) {
957 $info .= ', ';
958 }
959 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
960 }
961
962 wfDebug( __METHOD__ . ': client sent If-Modified-Since: ' .
963 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
964 wfDebug( __METHOD__ . ': effective Last-Modified: ' .
965 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
966 if ( $clientHeaderTime < $maxModified ) {
967 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
968 return false;
969 }
970
971 # Not modified
972 # Give a 304 Not Modified response code and disable body output
973 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
974 ini_set( 'zlib.output_compression', 0 );
975 $this->getRequest()->response()->statusHeader( 304 );
976 $this->sendCacheControl();
977 $this->disable();
978
979 // Don't output a compressed blob when using ob_gzhandler;
980 // it's technically against HTTP spec and seems to confuse
981 // Firefox when the response gets split over two packets.
982 wfResetOutputBuffers( false );
983
984 return true;
985 }
986
987 /**
988 * Override the last modified timestamp
989 *
990 * @param string $timestamp New timestamp, in a format readable by
991 * wfTimestamp()
992 */
993 public function setLastModified( $timestamp ) {
994 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
995 }
996
997 /**
998 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
999 *
1000 * @param string $policy The literal string to output as the contents of
1001 * the meta tag. Will be parsed according to the spec and output in
1002 * standardized form.
1003 */
1004 public function setRobotPolicy( $policy ) {
1005 $policy = Article::formatRobotPolicy( $policy );
1006
1007 if ( isset( $policy['index'] ) ) {
1008 $this->setIndexPolicy( $policy['index'] );
1009 }
1010 if ( isset( $policy['follow'] ) ) {
1011 $this->setFollowPolicy( $policy['follow'] );
1012 }
1013 }
1014
1015 /**
1016 * Get the current robot policy for the page as a string in the form
1017 * <index policy>,<follow policy>.
1018 *
1019 * @return string
1020 */
1021 public function getRobotPolicy() {
1022 $indexPolicy = $this->getIndexPolicy();
1023 return "{$indexPolicy},{$this->mFollowPolicy}";
1024 }
1025
1026 /**
1027 * Format an array of robots options as a string of directives.
1028 *
1029 * @return string The robots policy options.
1030 */
1031 private function formatRobotsOptions(): string {
1032 $options = $this->mRobotsOptions;
1033 // Check if options array has any non-integer keys.
1034 if ( count( array_filter( array_keys( $options ), 'is_string' ) ) > 0 ) {
1035 // Robots meta tags can have directives that are single strings or
1036 // have parameters that should be formatted like <directive>:<setting>.
1037 // If the options keys are strings, format them accordingly.
1038 // https://developers.google.com/search/docs/advanced/robots/robots_meta_tag
1039 array_walk( $options, static function ( &$value, $key ) {
1040 $value = is_string( $key ) ? "{$key}:{$value}" : "{$value}";
1041 } );
1042 }
1043 return implode( ',', $options );
1044 }
1045
1046 /**
1047 * Set the robots policy with options for the page.
1048 *
1049 * @since 1.38
1050 * @param array $options An array of key-value pairs or a string
1051 * to populate the robots meta tag content attribute as a string.
1052 */
1053 public function setRobotsOptions( array $options = [] ): void {
1054 $this->mRobotsOptions = array_merge( $this->mRobotsOptions, $options );
1055 }
1056
1057 /**
1058 * Get the robots policy content attribute for the page
1059 * as a string in the form <index policy>,<follow policy>,<options>.
1060 *
1061 * @return string
1062 */
1063 private function getRobotsContent(): string {
1064 $robotOptionString = $this->formatRobotsOptions();
1065 $robotArgs = ( $this->getIndexPolicy() === 'index' &&
1066 $this->mFollowPolicy === 'follow' ) ?
1067 [] :
1068 [
1069 $this->getIndexPolicy(),
1070 $this->mFollowPolicy,
1071 ];
1072 if ( $robotOptionString ) {
1073 $robotArgs[] = $robotOptionString;
1074 }
1075 return implode( ',', $robotArgs );
1076 }
1077
1078 /**
1079 * Set the index policy for the page, but leave the follow policy un-
1080 * touched.
1081 *
1082 * Since 1.43, setting 'index' after 'noindex' is deprecated. In
1083 * a future release, index policy on OutputPage will behave as
1084 * it does in ParserOutput, where 'noindex' takes precedence.
1085 *
1086 * @param string $policy Either 'index' or 'noindex'.
1087 * @deprecated since 1.43; use ->getMetadata()->setIndexPolicy()
1088 * but see note above about the change in behavior when setting
1089 * 'index' after 'noindex'.
1090 */
1091 public function setIndexPolicy( $policy ) {
1092 $policy = trim( $policy );
1093 if ( $policy === 'index' && $this->metadata->getIndexPolicy() === 'noindex' ) {
1094 wfDeprecated( __METHOD__ . ' with index after noindex', '1.43' );
1095 // ParserOutput::setIndexPolicy has noindex take precedence
1096 // (T16899) but the OutputPage version did not. Preserve
1097 // the behavior but deprecate it for future removal.
1098 $this->metadata->setOutputFlag( ParserOutputFlags::NO_INDEX_POLICY, false );
1099 }
1100 $this->metadata->setIndexPolicy( $policy );
1101 }
1102
1103 /**
1104 * Get the current index policy for the page as a string.
1105 *
1106 * @return string
1107 * @deprecated since 1.43; use ->getMetadata()->getIndexPolicy()
1108 */
1109 public function getIndexPolicy() {
1110 // Unlike ParserOutput, in OutputPage getIndexPolicy() defaults to
1111 // 'index' if unset.
1112 $policy = $this->metadata->getIndexPolicy();
1113 if ( $policy === '' ) {
1114 $policy = 'index';
1115 }
1116 return $policy;
1117 }
1118
1119 /**
1120 * Set the follow policy for the page, but leave the index policy un-
1121 * touched.
1122 *
1123 * @param string $policy Either 'follow' or 'nofollow'.
1124 */
1125 public function setFollowPolicy( $policy ) {
1126 $policy = trim( $policy );
1127 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
1128 $this->mFollowPolicy = $policy;
1129 }
1130 }
1131
1132 /**
1133 * Get the current follow policy for the page as a string.
1134 *
1135 * @return string
1136 */
1137 public function getFollowPolicy() {
1138 return $this->mFollowPolicy;
1139 }
1140
1141 /**
1142 * "HTML title" means the contents of "<title>".
1143 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
1144 *
1145 * @param string|Message $name
1146 */
1147 public function setHTMLTitle( $name ) {
1148 if ( $name instanceof Message ) {
1149 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
1150 } else {
1151 $this->mHTMLtitle = $name;
1152 }
1153 }
1154
1155 /**
1156 * Return the "HTML title", i.e. the content of the "<title>" tag.
1157 *
1158 * @return string
1159 */
1160 public function getHTMLTitle() {
1161 return $this->mHTMLtitle;
1162 }
1163
1164 /**
1165 * Set $mRedirectedFrom, the page which redirected us to the current page.
1166 *
1167 * @param PageReference $t
1168 */
1169 public function setRedirectedFrom( PageReference $t ) {
1170 $this->mRedirectedFrom = $t;
1171 }
1172
1173 /**
1174 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
1175 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
1176 * but not bad tags like \<script\>. This function automatically sets
1177 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
1178 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
1179 * good tags like \<i\> will be dropped entirely.
1180 *
1181 * @param string|Message $name The page title, either as HTML string or
1182 * as a message which will be formatted with FORMAT_TEXT to yield HTML.
1183 * Passing a Message is deprecated, since 1.41; please use
1184 * ::setPageTitleMsg() for that case instead.
1185 * @param-taint $name tainted
1186 * Phan-taint-check gets very confused by $name being either a string or a Message
1187 */
1188 public function setPageTitle( $name ) {
1189 if ( $name instanceof Message ) {
1190 // T343994: use ::setPageTitleMsg() instead (which uses ::escaped())
1191 wfDeprecated( __METHOD__ . ' with Message argument', '1.41' );
1192 $name = $name->setContext( $this->getContext() )->text();
1193 }
1194 $this->setPageTitleInternal( $name );
1195 }
1196
1197 /**
1198 * "Page title" means the contents of \<h1\>. This message takes a
1199 * Message, which will be formatted with FORMAT_ESCAPED to yield
1200 * HTML. Raw parameters to the message may contain some HTML
1201 * tags; see ::setPageTitle() and Sanitizer::removeSomeTags() for
1202 * details. This function automatically sets \<title\> to the
1203 * same content as \<h1\> but with all tags removed. Bad tags from
1204 * "raw" parameters that were escaped in \<h1\> will still be
1205 * escaped in \<title\>, and good tags like \<i\> will be dropped
1206 * entirely.
1207 *
1208 * @param Message $msg The page title, as a message which will be
1209 * formatted with FORMAT_ESCAPED to yield HTML.
1210 * @since 1.41
1211 */
1212 public function setPageTitleMsg( Message $msg ): void {
1213 $this->setPageTitleInternal(
1214 $msg->setContext( $this->getContext() )->escaped()
1215 );
1216 }
1217
1218 private function setPageTitleInternal( string $name ): void {
1219 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
1220 # but leave "<i>foobar</i>" alone
1221 $nameWithTags = Sanitizer::removeSomeTags( $name );
1222 $this->mPageTitle = $nameWithTags;
1223
1224 # change "<i>foo&amp;bar</i>" to "foo&bar"
1225 $this->setHTMLTitle(
1226 $this->msg( 'pagetitle' )->plaintextParams( Sanitizer::stripAllTags( $nameWithTags ) )
1227 ->inContentLanguage()
1228 );
1229 }
1230
1231 /**
1232 * Return the "page title", i.e. the content of the \<h1\> tag.
1233 *
1234 * @return string
1235 */
1236 public function getPageTitle() {
1237 return $this->mPageTitle;
1238 }
1239
1240 /**
1241 * Same as page title but only contains name of the page, not any other text.
1242 *
1243 * @since 1.32
1244 * @param string $html Page title text.
1245 * @see OutputPage::setPageTitle
1246 */
1247 public function setDisplayTitle( $html ) {
1248 $this->displayTitle = $html;
1249 }
1250
1251 /**
1252 * Returns page display title.
1253 *
1254 * Performs some normalization, but this not as strict the magic word.
1255 *
1256 * @since 1.32
1257 * @return string HTML
1258 */
1259 public function getDisplayTitle() {
1260 $html = $this->displayTitle;
1261 if ( $html === null ) {
1262 return htmlspecialchars( $this->getTitle()->getPrefixedText(), ENT_NOQUOTES );
1263 }
1264
1265 return Sanitizer::removeSomeTags( $html );
1266 }
1267
1268 /**
1269 * Returns page display title without namespace prefix if possible.
1270 *
1271 * This method is unreliable and best avoided. (T314399)
1272 *
1273 * @since 1.32
1274 * @return string HTML
1275 */
1276 public function getUnprefixedDisplayTitle() {
1277 $service = MediaWikiServices::getInstance();
1278 $languageConverter = $service->getLanguageConverterFactory()
1279 ->getLanguageConverter( $service->getContentLanguage() );
1280 $text = $this->getDisplayTitle();
1281
1282 // Create a regexp with matching groups as placeholders for the namespace, separator and main text
1283 $pageTitleRegexp = '/^' . str_replace(
1284 preg_quote( '(.+?)', '/' ),
1285 '(.+?)',
1286 preg_quote( Parser::formatPageTitle( '(.+?)', '(.+?)', '(.+?)' ), '/' )
1287 ) . '$/';
1288 $matches = [];
1289 if ( preg_match( $pageTitleRegexp, $text, $matches ) ) {
1290 // The regexp above could be manipulated by malicious user input,
1291 // sanitize the result just in case
1292 return Sanitizer::removeSomeTags( $matches[3] );
1293 }
1294
1295 $nsPrefix = $languageConverter->convertNamespace(
1296 $this->getTitle()->getNamespace()
1297 ) . ':';
1298 $prefix = preg_quote( $nsPrefix, '/' );
1299
1300 return preg_replace( "/^$prefix/i", '', $text );
1301 }
1302
1303 /**
1304 * Set the Title object to use
1305 *
1306 * @param PageReference $t
1307 */
1308 public function setTitle( PageReference $t ) {
1309 $t = Title::newFromPageReference( $t );
1310
1311 // @phan-suppress-next-next-line PhanUndeclaredMethod
1312 // @fixme Not all implementations of IContextSource have this method!
1313 $this->getContext()->setTitle( $t );
1314 }
1315
1316 /**
1317 * Replace the subtitle with $str
1318 *
1319 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1320 */
1321 public function setSubtitle( $str ) {
1322 $this->clearSubtitle();
1323 $this->addSubtitle( $str );
1324 }
1325
1326 /**
1327 * Add $str to the subtitle
1328 *
1329 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1330 * @param-taint $str exec_html
1331 */
1332 public function addSubtitle( $str ) {
1333 if ( $str instanceof Message ) {
1334 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1335 } else {
1336 $this->mSubtitle[] = $str;
1337 }
1338 }
1339
1340 /**
1341 * Build message object for a subtitle containing a backlink to a page
1342 *
1343 * @since 1.25
1344 * @param PageReference $page Title to link to
1345 * @param array $query Array of additional parameters to include in the link
1346 * @return Message
1347 */
1348 public static function buildBacklinkSubtitle( PageReference $page, $query = [] ) {
1349 if ( $page instanceof PageRecord || $page instanceof Title ) {
1350 // Callers will typically have a PageRecord
1351 if ( $page->isRedirect() ) {
1352 $query['redirect'] = 'no';
1353 }
1354 } elseif ( $page->getNamespace() !== NS_SPECIAL ) {
1355 // We don't know whether it's a redirect, so add the parameter, just to be sure.
1356 $query['redirect'] = 'no';
1357 }
1358
1359 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1360 return wfMessage( 'backlinksubtitle' )
1361 ->rawParams( $linkRenderer->makeLink( $page, null, [], $query ) );
1362 }
1363
1364 /**
1365 * Add a subtitle containing a backlink to a page
1366 *
1367 * @param PageReference $title Title to link to
1368 * @param array $query Array of additional parameters to include in the link
1369 */
1370 public function addBacklinkSubtitle( PageReference $title, $query = [] ) {
1371 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1372 }
1373
1374 /**
1375 * Clear the subtitles
1376 */
1377 public function clearSubtitle() {
1378 $this->mSubtitle = [];
1379 }
1380
1381 /**
1382 * @return string
1383 */
1384 public function getSubtitle() {
1385 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1386 }
1387
1388 /**
1389 * Set the page as printable, i.e. it'll be displayed with all
1390 * print styles included
1391 */
1392 public function setPrintable() {
1393 $this->mPrintable = true;
1394 }
1395
1396 /**
1397 * Return whether the page is "printable"
1398 *
1399 * @return bool
1400 */
1401 public function isPrintable() {
1402 return $this->mPrintable;
1403 }
1404
1405 /**
1406 * Disable output completely, i.e. calling output() will have no effect
1407 */
1408 public function disable() {
1409 $this->mDoNothing = true;
1410 }
1411
1412 /**
1413 * Return whether the output will be completely disabled
1414 *
1415 * @return bool
1416 */
1417 public function isDisabled() {
1418 return $this->mDoNothing;
1419 }
1420
1421 /**
1422 * Show an "add new section" link?
1423 *
1424 * @return bool
1425 */
1426 public function showNewSectionLink() {
1427 return $this->mNewSectionLink;
1428 }
1429
1430 /**
1431 * Forcibly hide the new section link?
1432 *
1433 * @return bool
1434 */
1435 public function forceHideNewSectionLink() {
1436 return $this->mHideNewSectionLink;
1437 }
1438
1439 /**
1440 * Add or remove feed links in the page header
1441 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1442 * for the new version
1443 * @see addFeedLink()
1444 *
1445 * @param bool $show True: add default feeds, false: remove all feeds
1446 */
1447 public function setSyndicated( $show = true ) {
1448 if ( $show ) {
1449 $this->setFeedAppendQuery( false );
1450 } else {
1451 $this->mFeedLinks = [];
1452 }
1453 }
1454
1455 /**
1456 * Return effective list of advertised feed types
1457 * @see addFeedLink()
1458 *
1459 * @return string[] Array of feed type names ( 'rss', 'atom' )
1460 */
1461 protected function getAdvertisedFeedTypes() {
1462 if ( $this->getConfig()->get( MainConfigNames::Feed ) ) {
1463 return $this->getConfig()->get( MainConfigNames::AdvertisedFeedTypes );
1464 } else {
1465 return [];
1466 }
1467 }
1468
1469 /**
1470 * Add default feeds to the page header
1471 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1472 * for the new version
1473 * @see addFeedLink()
1474 *
1475 * @param string|false $val Query to append to feed links or false to output
1476 * default links
1477 */
1478 public function setFeedAppendQuery( $val ) {
1479 $this->mFeedLinks = [];
1480
1481 foreach ( $this->getAdvertisedFeedTypes() as $type ) {
1482 $query = "feed=$type";
1483 if ( is_string( $val ) ) {
1484 $query .= '&' . $val;
1485 }
1486 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1487 }
1488 }
1489
1490 /**
1491 * Add a feed link to the page header
1492 *
1493 * @param string $format Feed type, should be a key of $wgFeedClasses
1494 * @param string $href URL
1495 */
1496 public function addFeedLink( $format, $href ) {
1497 if ( in_array( $format, $this->getAdvertisedFeedTypes() ) ) {
1498 $this->mFeedLinks[$format] = $href;
1499 }
1500 }
1501
1502 /**
1503 * Should we output feed links for this page?
1504 * @return bool
1505 */
1506 public function isSyndicated() {
1507 return count( $this->mFeedLinks ) > 0;
1508 }
1509
1510 /**
1511 * Return URLs for each supported syndication format for this page.
1512 * @return array Associating format keys with URLs
1513 */
1514 public function getSyndicationLinks() {
1515 return $this->mFeedLinks;
1516 }
1517
1518 /**
1519 * Will currently always return null
1520 *
1521 * @return null
1522 */
1523 public function getFeedAppendQuery() {
1524 return $this->mFeedLinksAppendQuery;
1525 }
1526
1527 /**
1528 * Set whether the displayed content is related to the source of the
1529 * corresponding article on the wiki
1530 * Setting true will cause the change "article related" toggle to true
1531 *
1532 * @param bool $newVal
1533 */
1534 public function setArticleFlag( $newVal ) {
1535 $this->mIsArticle = $newVal;
1536 if ( $newVal ) {
1537 $this->mIsArticleRelated = $newVal;
1538 }
1539 }
1540
1541 /**
1542 * Return whether the content displayed page is related to the source of
1543 * the corresponding article on the wiki
1544 *
1545 * @return bool
1546 */
1547 public function isArticle() {
1548 return $this->mIsArticle;
1549 }
1550
1551 /**
1552 * Set whether this page is related an article on the wiki
1553 * Setting false will cause the change of "article flag" toggle to false
1554 *
1555 * @param bool $newVal
1556 */
1557 public function setArticleRelated( $newVal ) {
1558 $this->mIsArticleRelated = $newVal;
1559 if ( !$newVal ) {
1560 $this->mIsArticle = false;
1561 }
1562 }
1563
1564 /**
1565 * Return whether this page is related an article on the wiki
1566 *
1567 * @return bool
1568 */
1569 public function isArticleRelated() {
1570 return $this->mIsArticleRelated;
1571 }
1572
1573 /**
1574 * Set whether the standard copyright should be shown for the current page.
1575 *
1576 * @param bool $hasCopyright
1577 */
1578 public function setCopyright( $hasCopyright ) {
1579 $this->mHasCopyright = $hasCopyright;
1580 }
1581
1582 /**
1583 * Return whether the standard copyright should be shown for the current page.
1584 * By default, it is true for all articles but other pages
1585 * can signal it by using setCopyright( true ).
1586 *
1587 * Used by SkinTemplate to decided whether to show the copyright.
1588 *
1589 * @return bool
1590 */
1591 public function showsCopyright() {
1592 return $this->isArticle() || $this->mHasCopyright;
1593 }
1594
1595 /**
1596 * Add new language links
1597 *
1598 * @param string[]|ParsoidLinkTarget[] $newLinkArray Array of
1599 * interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1600 */
1601 public function addLanguageLinks( array $newLinkArray ) {
1602 # $newLinkArray is in order of appearance on the page;
1603 # deduplicate so only the first for a given prefix is used
1604 # using code in ParserOutput (T26502)
1605 foreach ( $newLinkArray as $t ) {
1606 $this->metadata->addLanguageLink( $t );
1607 }
1608 }
1609
1610 /**
1611 * Reset the language links and add new language links
1612 *
1613 * @param string[]|ParsoidLinkTarget[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1614 * (e.g. 'fr:Test page')
1615 * @deprecated since 1.43, use ::addLanguageLinks() instead, or
1616 * use the LanguageLinksHook in the rare case that you need to remove
1617 * or replace language links from the output page.
1618 */
1619 public function setLanguageLinks( array $newLinkArray ) {
1620 $this->metadata->setLanguageLinks( $newLinkArray );
1621 }
1622
1623 /**
1624 * Get the list of language links
1625 *
1626 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1627 */
1628 public function getLanguageLinks() {
1629 return $this->metadata->getLanguageLinks();
1630 }
1631
1632 /**
1633 * Get the "no gallery" flag
1634 *
1635 * Used directly only in CategoryViewer.php
1636 * @internal
1637 */
1638 public function getNoGallery(): bool {
1639 return $this->mNoGallery;
1640 }
1641
1642 /**
1643 * Add an array of categories, with names in the keys
1644 *
1645 * @param array $categories Mapping category name => sort key
1646 */
1647 public function addCategoryLinks( array $categories ) {
1648 if ( !$categories ) {
1649 return;
1650 }
1651
1652 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1653
1654 # Set all the values to 'normal'.
1655 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1656 $pageData = [];
1657
1658 # Mark hidden categories
1659 foreach ( $res as $row ) {
1660 if ( isset( $row->pp_value ) ) {
1661 $categories[$row->page_title] = 'hidden';
1662 }
1663 // Page exists, cache results
1664 if ( isset( $row->page_id ) ) {
1665 $pageData[$row->page_title] = $row;
1666 }
1667 }
1668
1669 # Add the remaining categories to the skin
1670 if ( $this->getHookRunner()->onOutputPageMakeCategoryLinks(
1671 $this, $categories, $this->mCategoryLinks )
1672 ) {
1673 $services = MediaWikiServices::getInstance();
1674 $linkRenderer = $services->getLinkRenderer();
1675 $languageConverter = $services->getLanguageConverterFactory()
1676 ->getLanguageConverter( $services->getContentLanguage() );
1677 $collation = $services->getCollationFactory()->getCategoryCollation();
1678 foreach ( $categories as $category => $type ) {
1679 // array keys will cast numeric category names to ints, so cast back to string
1680 $category = (string)$category;
1681 $origcategory = $category;
1682 if ( array_key_exists( $category, $pageData ) ) {
1683 $title = Title::newFromRow( $pageData[$category] );
1684 } else {
1685 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1686 }
1687 if ( !$title ) {
1688 continue;
1689 }
1690 $languageConverter->findVariantLink( $category, $title, true );
1691
1692 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1693 continue;
1694 }
1695 $text = $languageConverter->convertHtml( $title->getText() );
1696 $link = null;
1697 $this->getHookRunner()->onOutputPageRenderCategoryLink( $this, $title->toPageIdentity(), $text, $link );
1698 if ( $link === null ) {
1699 $link = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1700 }
1701 $this->mCategoryData[] = [
1702 'sortKey' => $collation->getSortKey( $text ),
1703 'type' => $type,
1704 'title' => $title->getText(),
1705 'link' => $link,
1706 ];
1707 $this->mCategoriesSorted = false;
1708 // Setting mCategories and mCategoryLinks is redundant here,
1709 // but it is needed for compatibility until mCategories and
1710 // mCategoryLinks are made private (T301020)
1711 $this->mCategories[$type][] = $title->getText();
1712 $this->mCategoryLinks[$type][] = $link;
1713 }
1714 } else {
1715 // Conservatively assume the hook left the categories unsorted.
1716 $this->mCategoriesSorted = false;
1717 }
1718 }
1719
1720 /**
1721 * @param array $categories
1722 * @return IResultWrapper
1723 */
1724 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1725 # Add the links to a LinkBatch
1726 $arr = [ NS_CATEGORY => $categories ];
1727 $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
1728 $lb = $linkBatchFactory->newLinkBatch();
1729 $lb->setArray( $arr );
1730
1731 # Fetch existence plus the hiddencat property
1732 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1733 $fields = array_merge(
1734 LinkCache::getSelectFields(),
1735 [ 'pp_value' ]
1736 );
1737
1738 $res = $dbr->newSelectQueryBuilder()
1739 ->select( $fields )
1740 ->from( 'page' )
1741 ->leftJoin( 'page_props', null, [
1742 'pp_propname' => 'hiddencat',
1743 'pp_page = page_id',
1744 ] )
1745 ->where( $lb->constructSet( 'page', $dbr ) )
1746 ->caller( __METHOD__ )
1747 ->fetchResultSet();
1748
1749 # Add the results to the link cache
1750 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
1751 $lb->addResultToCache( $linkCache, $res );
1752
1753 return $res;
1754 }
1755
1756 /**
1757 * Reset the category links (but not the category list) and add $categories
1758 *
1759 * @param array $categories Mapping category name => sort key
1760 * @deprecated since 1.43, use ::addCategoryLinks()
1761 */
1762 public function setCategoryLinks( array $categories ) {
1763 wfDeprecated( __METHOD__, '1.43' );
1764 $this->mCategoryLinks = [];
1765 foreach ( $this->mCategoryData as &$arr ) {
1766 // null out the 'link' entry for existing category data
1767 $arr['link'] = null;
1768 }
1769 $this->addCategoryLinks( $categories );
1770 }
1771
1772 /**
1773 * Get the list of category links, in a 2-D array with the following format:
1774 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1775 * hidden categories) and $link a HTML fragment with a link to the category
1776 * page
1777 *
1778 * @return string[][]
1779 * @return-taint none
1780 */
1781 public function getCategoryLinks() {
1782 $this->maybeSortCategories();
1783 return $this->mCategoryLinks;
1784 }
1785
1786 /**
1787 * Get the list of category names this page belongs to.
1788 *
1789 * @param string $type The type of categories which should be returned. Possible values:
1790 * * all: all categories of all types
1791 * * hidden: only the hidden categories
1792 * * normal: all categories, except hidden categories
1793 * @return string[]
1794 */
1795 public function getCategories( $type = 'all' ) {
1796 $this->maybeSortCategories();
1797 if ( $type === 'all' ) {
1798 $allCategories = [];
1799 foreach ( $this->mCategories as $categories ) {
1800 $allCategories = array_merge( $allCategories, $categories );
1801 }
1802 return $allCategories;
1803 }
1804 if ( !isset( $this->mCategories[$type] ) ) {
1805 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1806 }
1807 return $this->mCategories[$type];
1808 }
1809
1810 /**
1811 * Ensure that the category lists are sorted, so that we don't
1812 * inadvertently depend on the exact evaluation order of various
1813 * ParserOutput fragments.
1814 */
1815 private function maybeSortCategories(): void {
1816 if ( $this->mCategoriesSorted ) {
1817 return;
1818 }
1819 // Check wiki configuration...
1820 $sortCategories = $this->getConfig()->get( MainConfigNames::SortedCategories );
1821 // ...but allow override with query parameter.
1822 $sortCategories = $this->getRequest()->getFuzzyBool( 'sortcat', $sortCategories );
1823 if ( $sortCategories ) {
1824 // Primary sort key is the first element of category data, but
1825 // break ties by looking at the other elements.
1826 usort( $this->mCategoryData, static function ( $a, $b ): int {
1827 return $a['type'] <=> $b['type'] ?:
1828 $a['sortKey'] <=> $b['sortKey'] ?:
1829 $a['title'] <=> $b['sortKey'] ?:
1830 $a['link'] <=> $b['link'];
1831 } );
1832 }
1833 // Rebuild mCategories and mCategoryLinks
1834 $this->mCategories = [
1835 'hidden' => [],
1836 'normal' => [],
1837 ];
1838 $this->mCategoryLinks = [];
1839 foreach ( $this->mCategoryData as $c ) {
1840 $this->mCategories[$c['type']][] = $c['title'];
1841 if ( $c['link'] !== null ) {
1842 // This test only needed because of ::setCategoryLinks()
1843 $this->mCategoryLinks[$c['type']][] = $c['link'];
1844 }
1845 }
1846 $this->mCategoriesSorted = true;
1847 }
1848
1849 /**
1850 * Add an array of indicators, with their identifiers as array
1851 * keys and HTML contents as values.
1852 *
1853 * In case of duplicate keys, existing values are overwritten.
1854 *
1855 * @note External code which calls this method should ensure that
1856 * any indicators sourced from parsed wikitext are wrapped with
1857 * the appropriate class; see note in ::getIndicators().
1858 *
1859 * @param string[] $indicators
1860 * @param-taint $indicators exec_html
1861 * @since 1.25
1862 */
1863 public function setIndicators( array $indicators ) {
1864 $this->mIndicators = $indicators + $this->mIndicators;
1865 // Keep ordered by key
1866 ksort( $this->mIndicators );
1867 }
1868
1869 /**
1870 * Get the indicators associated with this page.
1871 *
1872 * The array will be internally ordered by item keys.
1873 *
1874 * @return string[] Keys: identifiers, values: HTML contents
1875 * @since 1.25
1876 */
1877 public function getIndicators(): array {
1878 // Note that some -- but not all -- indicators will be wrapped
1879 // with a class appropriate for user-generated wikitext content
1880 // (usually .mw-parser-output). The exceptions would be an
1881 // indicator added via ::addHelpLink() below, which adds content
1882 // which don't come from the parser and is not user-generated;
1883 // and any indicators added by extensions which may call
1884 // OutputPage::setIndicators() directly. In the latter case the
1885 // caller is responsible for wrapping any parser-generated
1886 // indicators.
1887 return $this->mIndicators;
1888 }
1889
1890 /**
1891 * Adds help link with an icon via page indicators.
1892 * Link target can be overridden by a local message containing a wikilink:
1893 * the message key is: lowercase action or special page name + '-helppage'.
1894 * @param string $to Target MediaWiki.org page title or encoded URL.
1895 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MediaWiki.org.
1896 * @since 1.25
1897 */
1898 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1899 $this->addModuleStyles( 'mediawiki.helplink' );
1900 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1901
1902 if ( $overrideBaseUrl ) {
1903 $helpUrl = $to;
1904 } else {
1905 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1906 $helpUrl = "https://www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1907 }
1908
1909 $link = Html::rawElement(
1910 'a',
1911 [
1912 'href' => $helpUrl,
1913 'target' => '_blank',
1914 'class' => 'mw-helplink',
1915 ],
1916 Html::element( 'span', [ 'class' => 'mw-helplink-icon' ] ) . $text
1917 );
1918
1919 // See note in ::getIndicators() above -- unlike wikitext-generated
1920 // indicators which come from ParserOutput, this indicator will not
1921 // be wrapped.
1922 $this->setIndicators( [ 'mw-helplink' => $link ] );
1923 }
1924
1925 /**
1926 * Do not allow scripts which can be modified by wiki users to load on this page;
1927 * only allow scripts bundled with, or generated by, the software.
1928 * Site-wide styles are controlled by a config setting, since they can be
1929 * used to create a custom skin/theme, but not user-specific ones.
1930 *
1931 * @todo this should be given a more accurate name
1932 */
1933 public function disallowUserJs() {
1934 $this->reduceAllowedModules(
1935 RL\Module::TYPE_SCRIPTS,
1936 RL\Module::ORIGIN_CORE_INDIVIDUAL
1937 );
1938
1939 // Site-wide styles are controlled by a config setting, see T73621
1940 // for background on why. User styles are never allowed.
1941 if ( $this->getConfig()->get( MainConfigNames::AllowSiteCSSOnRestrictedPages ) ) {
1942 $styleOrigin = RL\Module::ORIGIN_USER_SITEWIDE;
1943 } else {
1944 $styleOrigin = RL\Module::ORIGIN_CORE_INDIVIDUAL;
1945 }
1946 $this->reduceAllowedModules(
1947 RL\Module::TYPE_STYLES,
1948 $styleOrigin
1949 );
1950 }
1951
1952 /**
1953 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1954 * @see RL\Module::$origin
1955 * @param string $type RL\Module TYPE_ constant
1956 * @return int Module ORIGIN_ class constant
1957 */
1958 public function getAllowedModules( $type ) {
1959 if ( $type == RL\Module::TYPE_COMBINED ) {
1960 return min( array_values( $this->mAllowedModules ) );
1961 } else {
1962 return $this->mAllowedModules[$type] ?? RL\Module::ORIGIN_ALL;
1963 }
1964 }
1965
1966 /**
1967 * Limit the highest level of CSS/JS untrustworthiness allowed.
1968 *
1969 * If passed the same or a higher level than the current level of untrustworthiness set, the
1970 * level will remain unchanged.
1971 *
1972 * @param string $type
1973 * @param int $level RL\Module class constant
1974 */
1975 public function reduceAllowedModules( $type, $level ) {
1976 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1977 }
1978
1979 /**
1980 * Prepend $text to the body HTML
1981 *
1982 * @param string $text HTML
1983 * @param-taint $text exec_html
1984 */
1985 public function prependHTML( $text ) {
1986 $this->mBodytext = $text . $this->mBodytext;
1987 }
1988
1989 /**
1990 * Append $text to the body HTML
1991 *
1992 * @param string $text HTML
1993 * @param-taint $text exec_html
1994 */
1995 public function addHTML( $text ) {
1996 $this->mBodytext .= $text;
1997 }
1998
1999 /**
2000 * Shortcut for adding an Html::element via addHTML.
2001 *
2002 * @since 1.19
2003 *
2004 * @param string $element
2005 * @param array $attribs
2006 * @param string $contents
2007 */
2008 public function addElement( $element, array $attribs = [], $contents = '' ) {
2009 $this->addHTML( Html::element( $element, $attribs, $contents ) );
2010 }
2011
2012 /**
2013 * Clear the body HTML
2014 */
2015 public function clearHTML() {
2016 $this->mBodytext = '';
2017 }
2018
2019 /**
2020 * Get the body HTML
2021 *
2022 * @return string HTML
2023 */
2024 public function getHTML() {
2025 return $this->mBodytext;
2026 }
2027
2028 /**
2029 * Get/set the ParserOptions object to use for wikitext parsing
2030 *
2031 * @return ParserOptions
2032 */
2033 public function parserOptions() {
2034 if ( !$this->mParserOptions ) {
2035 if ( !$this->getUser()->isSafeToLoad() ) {
2036 // Context user isn't unstubbable yet, so don't try to get a
2037 // ParserOptions for it. And don't cache this ParserOptions
2038 // either.
2039 $po = ParserOptions::newFromAnon();
2040 $po->setAllowUnsafeRawHtml( false );
2041 return $po;
2042 }
2043
2044 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
2045 $this->mParserOptions->setAllowUnsafeRawHtml( false );
2046 }
2047
2048 return $this->mParserOptions;
2049 }
2050
2051 /**
2052 * Set the revision ID which will be seen by the wiki text parser
2053 * for things such as embedded {{REVISIONID}} variable use.
2054 *
2055 * @param int|null $revid A positive integer, or null
2056 * @return mixed Previous value
2057 */
2058 public function setRevisionId( $revid ) {
2059 $val = $revid === null ? null : intval( $revid );
2060 return wfSetVar( $this->mRevisionId, $val, true );
2061 }
2062
2063 /**
2064 * Get the displayed revision ID
2065 *
2066 * @return int|null
2067 */
2068 public function getRevisionId() {
2069 return $this->mRevisionId;
2070 }
2071
2072 /**
2073 * Set whether the revision displayed (as set in ::setRevisionId())
2074 * is the latest revision of the page.
2075 *
2076 * @param bool $isCurrent
2077 */
2078 public function setRevisionIsCurrent( bool $isCurrent ): void {
2079 $this->mRevisionIsCurrent = $isCurrent;
2080 }
2081
2082 /**
2083 * Whether the revision displayed is the latest revision of the page
2084 *
2085 * @since 1.34
2086 * @return bool
2087 */
2088 public function isRevisionCurrent(): bool {
2089 return $this->mRevisionId == 0 || (
2090 $this->mRevisionIsCurrent ?? (
2091 $this->mRevisionId == $this->getTitle()->getLatestRevID()
2092 )
2093 );
2094 }
2095
2096 /**
2097 * Set the timestamp of the revision which will be displayed. This is used
2098 * to avoid a extra DB call in SkinComponentFooter::lastModified().
2099 *
2100 * @param string|null $timestamp
2101 * @return mixed Previous value
2102 */
2103 public function setRevisionTimestamp( $timestamp ) {
2104 return wfSetVar( $this->mRevisionTimestamp, $timestamp, true );
2105 }
2106
2107 /**
2108 * Get the timestamp of displayed revision.
2109 * This will be null if not filled by setRevisionTimestamp().
2110 *
2111 * @return string|null
2112 */
2113 public function getRevisionTimestamp() {
2114 return $this->mRevisionTimestamp;
2115 }
2116
2117 /**
2118 * Set the displayed file version
2119 *
2120 * @param File|null $file
2121 * @return mixed Previous value
2122 */
2123 public function setFileVersion( $file ) {
2124 $val = null;
2125 if ( $file instanceof File && $file->exists() ) {
2126 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
2127 }
2128 return wfSetVar( $this->mFileVersion, $val, true );
2129 }
2130
2131 /**
2132 * Get the displayed file version
2133 *
2134 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
2135 */
2136 public function getFileVersion() {
2137 return $this->mFileVersion;
2138 }
2139
2140 /**
2141 * Get the templates used on this page
2142 *
2143 * @return array<int,array<string,int>> (namespace => dbKey => revId)
2144 * @since 1.18
2145 */
2146 public function getTemplateIds() {
2147 return $this->mTemplateIds;
2148 }
2149
2150 /**
2151 * Get the files used on this page
2152 *
2153 * @return array [ dbKey => [ 'time' => MW timestamp or null, 'sha1' => sha1 or '' ] ]
2154 * @since 1.18
2155 */
2156 public function getFileSearchOptions() {
2157 return $this->mImageTimeKeys;
2158 }
2159
2160 /**
2161 * Convert wikitext *in the user interface language* to HTML and
2162 * add it to the buffer. The result will not be
2163 * language-converted, as user interface messages are already
2164 * localized into a specific variant. Assumes that the current
2165 * page title will be used if optional $title is not
2166 * provided. Output will be tidy.
2167 *
2168 * @param string $text Wikitext in the user interface language
2169 * @param bool $linestart Is this the start of a line? (Defaults to true)
2170 * @param PageReference|null $title Optional title to use; default of `null`
2171 * means use current page title.
2172 * @since 1.32
2173 */
2174 public function addWikiTextAsInterface(
2175 $text, $linestart = true, ?PageReference $title = null
2176 ) {
2177 $title ??= $this->getTitle();
2178 if ( $title === null ) {
2179 throw new RuntimeException( 'No title in ' . __METHOD__ );
2180 }
2181 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/true );
2182 }
2183
2184 /**
2185 * Convert wikitext *in the user interface language* to HTML and
2186 * add it to the buffer with a `<div class="$wrapperClass">`
2187 * wrapper. The result will not be language-converted, as user
2188 * interface messages as already localized into a specific
2189 * variant. The $text will be parsed in start-of-line context.
2190 * Output will be tidy.
2191 *
2192 * @param string $wrapperClass The class attribute value for the <div>
2193 * wrapper in the output HTML
2194 * @param string $text Wikitext in the user interface language
2195 * @since 1.32
2196 */
2197 public function wrapWikiTextAsInterface(
2198 $wrapperClass, $text
2199 ) {
2200 $title = $this->getTitle();
2201 if ( $title === null ) {
2202 throw new RuntimeException( 'No title in ' . __METHOD__ );
2203 }
2204 $this->addWikiTextTitleInternal(
2205 $text, $title,
2206 /*linestart*/true, /*interface*/true,
2207 $wrapperClass
2208 );
2209 }
2210
2211 /**
2212 * Convert wikitext *in the page content language* to HTML and add
2213 * it to the buffer. The result with be language-converted to the
2214 * user's preferred variant. Assumes that the current page title
2215 * will be used if optional $title is not provided. Output will be
2216 * tidy.
2217 *
2218 * @param string $text Wikitext in the page content language
2219 * @param bool $linestart Is this the start of a line? (Defaults to true)
2220 * @param PageReference|null $title Optional title to use; default of `null`
2221 * means use current page title.
2222 * @since 1.32
2223 */
2224 public function addWikiTextAsContent(
2225 $text, $linestart = true, ?PageReference $title = null
2226 ) {
2227 $title ??= $this->getTitle();
2228 if ( !$title ) {
2229 throw new RuntimeException( 'No title in ' . __METHOD__ );
2230 }
2231 $this->addWikiTextTitleInternal( $text, $title, $linestart, /*interface*/false );
2232 }
2233
2234 /**
2235 * Add wikitext with a custom Title object.
2236 * Output is unwrapped.
2237 *
2238 * @param string $text Wikitext
2239 * @param PageReference $title
2240 * @param bool $linestart Is this the start of a line?@param
2241 * @param bool $interface Whether it is an interface message
2242 * (for example disables conversion)
2243 * @param string|null $wrapperClass if not empty, wraps the output in
2244 * a `<div class="$wrapperClass">`
2245 */
2246 private function addWikiTextTitleInternal(
2247 string $text, PageReference $title, bool $linestart, bool $interface,
2248 ?string $wrapperClass = null
2249 ) {
2250 $parserOutput = $this->parseInternal(
2251 $text, $title, $linestart, $interface
2252 );
2253
2254 $this->addParserOutput( $parserOutput, [
2255 'enableSectionEditLinks' => false,
2256 'wrapperDivClass' => $wrapperClass ?? '',
2257 ] );
2258 }
2259
2260 /**
2261 * Adds Table of Contents data to OutputPage from ParserOutput
2262 * @param TOCData $tocData
2263 * @internal For use by Article.php
2264 */
2265 public function setTOCData( TOCData $tocData ) {
2266 $this->tocData = $tocData;
2267 }
2268
2269 /**
2270 * @internal For usage in Skin::getTOCData() only.
2271 * @return ?TOCData Table of Contents data, or
2272 * null if OutputPage::setTOCData() has not been called.
2273 */
2274 public function getTOCData(): ?TOCData {
2275 return $this->tocData;
2276 }
2277
2278 /**
2279 * @internal Will be replaced by direct access to
2280 * ParserOutput::getOutputFlag()
2281 * @param string $name A flag name from ParserOutputFlags
2282 * @return bool
2283 */
2284 public function getOutputFlag( string $name ): bool {
2285 return isset( $this->mOutputFlags[$name] );
2286 }
2287
2288 /**
2289 * @internal For use by ViewAction/Article only
2290 * @since 1.42
2291 * @param Bcp47Code $lang
2292 */
2293 public function setContentLangForJS( Bcp47Code $lang ): void {
2294 $this->contentLang = MediaWikiServices::getInstance()->getLanguageFactory()
2295 ->getLanguage( $lang );
2296 }
2297
2298 /**
2299 * Which language getJSVars should use
2300 *
2301 * Use of this is strongly discouraged in favour of ParserOutput::getLanguage(),
2302 * and should not be needed in most cases given that the OutputTransform
2303 * already takes care of 'lang' and 'dir' attributes.
2304 *
2305 * Consider whether RequestContext::getLanguage (e.g. OutputPage::getLanguage
2306 * or Skin::getLanguage) or MediaWikiServices::getContentLanguage is more
2307 * appropiate first for your use case.
2308 *
2309 * @since 1.42
2310 * @return Language
2311 */
2312 private function getContentLangForJS(): Language {
2313 if ( !$this->contentLang ) {
2314 // If this is not set, then we're likely not on in a request that renders page content
2315 // (e.g. ViewAction or ApiParse), but rather a different Action or SpecialPage.
2316 // In that case there isn't a main ParserOutput object to represent the page or output.
2317 // But, the skin and frontend code mostly don't make this distinction, and so we still
2318 // need to return something for mw.config.
2319 //
2320 // For historical reasons, the expectation is that:
2321 // * on a SpecialPage, we return the language for the content area just like on a
2322 // page view. SpecialPage content is localised, and so this is the user language.
2323 // * on an Action about a WikiPage, we return the language that content would have
2324 // been shown in, if this were a page view. This is generally the page language
2325 // as stored in the database, except adapted to the current user (e.g. in case of
2326 // translated pages or a language variant preference)
2327 //
2328 // This mess was centralised to here in 2023 (T341244).
2329 $title = $this->getTitle();
2330 if ( $title->isSpecialPage() ) {
2331 // Special pages render in the interface language, based on request context.
2332 // If the user's preference (or request parameter) specifies a variant,
2333 // the content may have been converted to the user's language variant.
2334 $pageLang = $this->getLanguage();
2335 } else {
2336 wfDebug( __METHOD__ . ' has to guess ParserOutput language' );
2337 // Guess what Article::getParserOutput and ParserOptions::optionsHash() would decide
2338 // on a page view:
2339 //
2340 // - Pages may have a custom page_lang set in the database,
2341 // via Title::getPageLanguage/Title::getDbPageLanguage
2342 //
2343 // - Interface messages (NS_MEDIAWIKI) render based on their subpage,
2344 // via Title::getPageLanguage/ContentHandler::getPageLanguage/MessageCache::figureMessage
2345 //
2346 // - Otherwise, pages are assumed to be in the wiki's default content language.
2347 // via Title::getPageLanguage/ContentHandler::getPageLanguage/MediaWikiServices::getContentLanguage
2348 $pageLang = $title->getPageLanguage();
2349 }
2350 if ( $title->getNamespace() !== NS_MEDIAWIKI ) {
2351 $services = MediaWikiServices::getInstance();
2352 $langConv = $services->getLanguageConverterFactory()->getLanguageConverter( $pageLang );
2353 // NOTE: LanguageConverter::getPreferredVariant inspects global RequestContext.
2354 // This usually returns $pageLang unchanged.
2355 $variant = $langConv->getPreferredVariant();
2356 if ( $pageLang->getCode() !== $variant ) {
2357 $pageLang = $services->getLanguageFactory()->getLanguage( $variant );
2358 }
2359 }
2360 $this->contentLang = $pageLang;
2361 }
2362 return $this->contentLang;
2363 }
2364
2365 /**
2366 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
2367 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
2368 * and so on. It does *not* include section information.
2369 *
2370 * @since 1.24
2371 * @param ParserOutput $parserOutput
2372 */
2373 public function addParserOutputMetadata( ParserOutput $parserOutput ) {
2374 // T301020 This should eventually use the standard "merge ParserOutput"
2375 // function between $parserOutput and $this->metadata.
2376 $this->addLanguageLinks( $parserOutput->getLanguageLinks() );
2377 $this->addCategoryLinks( $parserOutput->getCategoryMap() );
2378
2379 // Parser-generated indicators get wrapped like other parser output.
2380 $wrapClass = $parserOutput->getWrapperDivClass();
2381 $result = [];
2382 foreach ( $parserOutput->getIndicators() as $name => $html ) {
2383 if ( $html !== '' && $wrapClass !== '' ) {
2384 $html = Html::rawElement( 'div', [ 'class' => $wrapClass ], $html );
2385 }
2386 $result[$name] = $html;
2387 }
2388 $this->setIndicators( $result );
2389
2390 $tocData = $parserOutput->getTOCData();
2391 // Do not override existing TOC data if the new one is empty (T307256#8817705)
2392 // TODO: Invent a way to merge TOCs from multiple outputs (T327429)
2393 if ( $tocData !== null && ( $this->tocData === null || count( $tocData->getSections() ) > 0 ) ) {
2394 $this->setTOCData( $tocData );
2395 }
2396
2397 // FIXME: Best practice is for OutputPage to be an accumulator, as
2398 // addParserOutputMetadata() may be called multiple times, but the
2399 // following lines overwrite any previous data. These should
2400 // be migrated to an injection pattern. (T301020, T300979)
2401 // (Note that OutputPage::getOutputFlag() also contains this
2402 // information, with flags from each $parserOutput all OR'ed together.)
2403 $this->mNewSectionLink = $parserOutput->getNewSection();
2404 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
2405 $this->mNoGallery = $parserOutput->getNoGallery();
2406
2407 if ( !$parserOutput->isCacheable() ) {
2408 $this->disableClientCache();
2409 }
2410 $this->addHeadItems( $parserOutput->getHeadItems() );
2411 $this->addModules( $parserOutput->getModules() );
2412 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2413 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2414 if ( $parserOutput->getPreventClickjacking() ) {
2415 $this->metadata->setPreventClickjacking( true );
2416 }
2417 $scriptSrcs = $parserOutput->getExtraCSPScriptSrcs();
2418 foreach ( $scriptSrcs as $src ) {
2419 $this->getCSP()->addScriptSrc( $src );
2420 }
2421 $defaultSrcs = $parserOutput->getExtraCSPDefaultSrcs();
2422 foreach ( $defaultSrcs as $src ) {
2423 $this->getCSP()->addDefaultSrc( $src );
2424 }
2425 $styleSrcs = $parserOutput->getExtraCSPStyleSrcs();
2426 foreach ( $styleSrcs as $src ) {
2427 $this->getCSP()->addStyleSrc( $src );
2428 }
2429
2430 // If $wgImagePreconnect is true, and if the output contains images, give the user-agent
2431 // a hint about a remote hosts from which images may be served. Launched in T123582.
2432 if ( $this->getConfig()->get( MainConfigNames::ImagePreconnect ) && count( $parserOutput->getImages() ) ) {
2433 $preconnect = [];
2434 // Optimization: Instead of processing each image, assume that wikis either serve both
2435 // foreign and local from the same remote hostname (e.g. public wikis at WMF), or that
2436 // foreign images are common enough to be worth the preconnect (e.g. private wikis).
2437 $repoGroup = MediaWikiServices::getInstance()->getRepoGroup();
2438 $repoGroup->forEachForeignRepo( static function ( $repo ) use ( &$preconnect ) {
2439 $preconnect[] = $repo->getZoneUrl( 'thumb' );
2440 } );
2441 // Consider both foreign and local repos. While LocalRepo by default uses a relative
2442 // path on the same domain, wiki farms may configure it to use a dedicated hostname.
2443 $preconnect[] = $repoGroup->getLocalRepo()->getZoneUrl( 'thumb' );
2444 foreach ( $preconnect as $url ) {
2445 $host = parse_url( $url, PHP_URL_HOST );
2446 // It is expected that file URLs are often path-only, without hostname (T317329).
2447 if ( $host ) {
2448 $this->addLink( [ 'rel' => 'preconnect', 'href' => '//' . $host ] );
2449 break;
2450 }
2451 }
2452 }
2453
2454 // Template versioning...
2455 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
2456 if ( isset( $this->mTemplateIds[$ns] ) ) {
2457 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
2458 } else {
2459 $this->mTemplateIds[$ns] = $dbks;
2460 }
2461 }
2462 // File versioning...
2463 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
2464 $this->mImageTimeKeys[$dbk] = $data;
2465 }
2466
2467 // Enable OOUI if requested via ParserOutput
2468 if ( $parserOutput->getEnableOOUI() ) {
2469 $this->enableOOUI();
2470 }
2471
2472 // Include parser limit report
2473 // FIXME: This should append, rather than overwrite, or else this
2474 // data should be injected into the OutputPage like is done for the
2475 // other page-level things (like OutputPage::setTOCData()).
2476 if ( !$this->limitReportJSData ) {
2477 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
2478 }
2479
2480 // Link flags are ignored for now, but may in the future be
2481 // used to mark individual language links.
2482 $linkFlags = [];
2483 $languageLinks = $this->metadata->getLanguageLinks();
2484 // This hook can be used to remove/replace language links
2485 $this->getHookRunner()->onLanguageLinks( $this->getTitle(), $languageLinks, $linkFlags );
2486 $this->metadata->setLanguageLinks( $languageLinks );
2487
2488 $this->getHookRunner()->onOutputPageParserOutput( $this, $parserOutput );
2489
2490 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
2491 // so that extensions may modify ParserOutput to toggle TOC.
2492 // This cannot be moved to addParserOutputText because that is not
2493 // called by EditPage for Preview.
2494
2495 // ParserOutputFlags::SHOW_TOC is used to indicate whether the TOC
2496 // should be shown (or hidden) in the output.
2497 $this->mEnableTOC = $this->mEnableTOC ||
2498 $parserOutput->getOutputFlag( ParserOutputFlags::SHOW_TOC );
2499 // Uniform handling of all boolean flags: they are OR'ed together
2500 // (See ParserOutput::collectMetadata())
2501 $flags =
2502 array_flip( $parserOutput->getAllFlags() ) +
2503 array_flip( ParserOutputFlags::cases() );
2504 foreach ( $flags as $name => $ignore ) {
2505 if ( $parserOutput->getOutputFlag( $name ) ) {
2506 $this->mOutputFlags[$name] = true;
2507 }
2508 }
2509 }
2510
2511 private function getParserOutputText( ParserOutput $parserOutput, array $poOptions = [] ): string {
2512 // Add default options from the skin
2513 $skin = $this->getSkin();
2514 $skinOptions = $skin->getOptions();
2515 $oldText = $parserOutput->getRawText();
2516 $poOptions += [
2517 'allowClone' => false, // T371022
2518 'skin' => $skin,
2519 'injectTOC' => $skinOptions['toc'],
2520 ];
2521 $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
2522 // Note: this path absolutely expects the metadata of $parserOutput to be mutated by the pipeline,
2523 // but the raw text should not be, see T353257
2524 // TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
2525 $text = $pipeline->run( $parserOutput, $this->parserOptions(), $poOptions )->getContentHolderText();
2526 $parserOutput->setRawText( $oldText );
2527 return $text;
2528 }
2529
2530 /**
2531 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
2532 * ParserOutput object, without any other metadata.
2533 *
2534 * @since 1.24
2535 * @param ParserOutput $parserOutput
2536 * @param array $poOptions Options to OutputTransformPipeline::run() (to be deprecated)
2537 */
2538 public function addParserOutputContent( ParserOutput $parserOutput, $poOptions = [] ) {
2539 $text = $this->getParserOutputText( $parserOutput, $poOptions );
2540 $this->addParserOutputText( $text, $poOptions );
2541
2542 $this->addModules( $parserOutput->getModules() );
2543 $this->addModuleStyles( $parserOutput->getModuleStyles() );
2544
2545 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
2546 }
2547
2548 /**
2549 * Add the HTML associated with a ParserOutput object, without any metadata.
2550 *
2551 * @internal For local use only
2552 * @param string|ParserOutput $text
2553 * @param array $poOptions Options to OutputTransformPipeline::run() (to be deprecated)
2554 */
2555 public function addParserOutputText( $text, $poOptions = [] ) {
2556 if ( $text instanceof ParserOutput ) {
2557 wfDeprecated( __METHOD__ . ' with ParserOutput as first arg', '1.42' );
2558 $text = $this->getParserOutputText( $text, $poOptions );
2559 }
2560 $this->getHookRunner()->onOutputPageBeforeHTML( $this, $text );
2561 $this->addHTML( $text );
2562 }
2563
2564 /**
2565 * Add everything from a ParserOutput object.
2566 *
2567 * @param ParserOutput $parserOutput
2568 * @param array $poOptions Options to OutputTransformPipeline::run() (to be deprecated)
2569 */
2570 public function addParserOutput( ParserOutput $parserOutput, $poOptions = [] ) {
2571 $text = $this->getParserOutputText( $parserOutput, $poOptions );
2572 $this->addParserOutputMetadata( $parserOutput );
2573 $this->addParserOutputText( $text, $poOptions );
2574 }
2575
2576 /**
2577 * Add the output of a QuickTemplate to the output buffer
2578 *
2579 * @param \QuickTemplate &$template
2580 */
2581 public function addTemplate( &$template ) {
2582 $this->addHTML( $template->getHTML() );
2583 }
2584
2585 /**
2586 * Parse wikitext *in the page content language* and return the HTML.
2587 * The result will be language-converted to the user's preferred variant.
2588 * Output will be tidy.
2589 *
2590 * @param string $text Wikitext in the page content language
2591 * @param bool $linestart Is this the start of a line? (Defaults to true)
2592 * @return string HTML
2593 * @since 1.32
2594 */
2595 public function parseAsContent( $text, $linestart = true ) {
2596 $title = $this->getTitle();
2597 if ( $title === null ) {
2598 throw new RuntimeException( 'No title in ' . __METHOD__ );
2599 }
2600 $po = $this->parseInternal(
2601 $text, $title, $linestart, /*interface*/false
2602 );
2603 $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
2604 // TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
2605 return $pipeline->run( $po, $this->parserOptions(), [
2606 'allowTOC' => false,
2607 'enableSectionEditLinks' => false,
2608 'wrapperDivClass' => '',
2609 'userLang' => $this->getContext()->getLanguage(),
2610 ] )->getContentHolderText();
2611 }
2612
2613 /**
2614 * Parse wikitext *in the user interface language* and return the HTML.
2615 * The result will not be language-converted, as user interface messages
2616 * are already localized into a specific variant.
2617 * Output will be tidy.
2618 *
2619 * @param string $text Wikitext in the user interface language
2620 * @param bool $linestart Is this the start of a line? (Defaults to true)
2621 * @return string HTML
2622 * @since 1.32
2623 */
2624 public function parseAsInterface( $text, $linestart = true ) {
2625 $title = $this->getTitle();
2626 if ( $title === null ) {
2627 throw new RuntimeException( 'No title in ' . __METHOD__ );
2628 }
2629 $po = $this->parseInternal(
2630 $text, $title, $linestart, /*interface*/true
2631 );
2632 $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
2633 // TODO T371008 consider if using the Content framework makes sense instead of creating the pipeline
2634 return $pipeline->run( $po, $this->parserOptions(), [
2635 'allowTOC' => false,
2636 'enableSectionEditLinks' => false,
2637 'wrapperDivClass' => '',
2638 'userLang' => $this->getContext()->getLanguage(),
2639 ] )->getContentHolderText();
2640 }
2641
2642 /**
2643 * Parse wikitext *in the user interface language*, strip
2644 * paragraph wrapper, and return the HTML.
2645 * The result will not be language-converted, as user interface messages
2646 * are already localized into a specific variant.
2647 * Output will be tidy. Outer paragraph wrapper will only be stripped
2648 * if the result is a single paragraph.
2649 *
2650 * @param string $text Wikitext in the user interface language
2651 * @param bool $linestart Is this the start of a line? (Defaults to true)
2652 * @return string HTML
2653 * @since 1.32
2654 */
2655 public function parseInlineAsInterface( $text, $linestart = true ) {
2656 return Parser::stripOuterParagraph(
2657 $this->parseAsInterface( $text, $linestart )
2658 );
2659 }
2660
2661 /**
2662 * Parse wikitext and return the HTML (internal implementation helper)
2663 *
2664 * @param string $text
2665 * @param PageReference $title The title to use
2666 * @param bool $linestart Is this the start of a line?
2667 * @param bool $interface Use interface language (instead of content language) while parsing
2668 * language sensitive magic words like GRAMMAR and PLURAL. This also disables
2669 * LanguageConverter.
2670 * @return ParserOutput
2671 */
2672 private function parseInternal(
2673 string $text, PageReference $title, bool $linestart, bool $interface
2674 ) {
2675 $popts = $this->parserOptions();
2676
2677 $oldInterface = $popts->setInterfaceMessage( $interface );
2678
2679 $parserOutput = MediaWikiServices::getInstance()->getParserFactory()->getInstance()
2680 ->parse(
2681 $text, $title, $popts,
2682 $linestart, true, $this->mRevisionId
2683 );
2684
2685 $popts->setInterfaceMessage( $oldInterface );
2686
2687 return $parserOutput;
2688 }
2689
2690 /**
2691 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
2692 *
2693 * @param int $maxage Maximum cache time on the CDN, in seconds.
2694 */
2695 public function setCdnMaxage( $maxage ) {
2696 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
2697 }
2698
2699 /**
2700 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header to $maxage if that is
2701 * lower than the current s-maxage. Either way, $maxage is now an upper limit on s-maxage, so
2702 * that future calls to setCdnMaxage() will no longer be able to raise the s-maxage above
2703 * $maxage.
2704 *
2705 * @param int $maxage Maximum cache time on the CDN, in seconds
2706 * @since 1.27
2707 */
2708 public function lowerCdnMaxage( $maxage ) {
2709 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2710 $this->setCdnMaxage( $this->mCdnMaxage );
2711 }
2712
2713 /**
2714 * Get TTL in [$minTTL,$maxTTL] and pass it to lowerCdnMaxage()
2715 *
2716 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2717 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2718 * TTL is 90% of the age of the object, subject to the min and max.
2719 *
2720 * @param string|int|float|false|null $mtime Last-Modified timestamp
2721 * @param int $minTTL Minimum TTL in seconds [default: 1 minute]
2722 * @param int $maxTTL Maximum TTL in seconds [default: $wgCdnMaxAge]
2723 * @since 1.28
2724 */
2725 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2726 $minTTL = $minTTL ?: ExpirationAwareness::TTL_MINUTE;
2727 $maxTTL = $maxTTL ?: $this->getConfig()->get( MainConfigNames::CdnMaxAge );
2728
2729 if ( $mtime === null || $mtime === false ) {
2730 return; // entity does not exist
2731 }
2732
2733 $age = MWTimestamp::time() - (int)wfTimestamp( TS_UNIX, $mtime );
2734 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2735 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2736
2737 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2738 }
2739
2740 /**
2741 * Do not send nocache headers
2742 */
2743 public function enableClientCache(): void {
2744 $this->mEnableClientCache = true;
2745 }
2746
2747 /**
2748 * Force the page to send nocache headers
2749 * @since 1.38
2750 */
2751 public function disableClientCache(): void {
2752 $this->mEnableClientCache = false;
2753 }
2754
2755 /**
2756 * Whether the output might become publicly cached.
2757 *
2758 * @since 1.34
2759 * @return bool
2760 */
2761 public function couldBePublicCached() {
2762 if ( !$this->cacheIsFinal ) {
2763 // - The entry point handles its own caching and/or doesn't use OutputPage.
2764 // (such as load.php, or MediaWiki\Rest\EntryPoint).
2765 //
2766 // - Or, we haven't finished processing the main part of the request yet
2767 // (e.g. Action::show, SpecialPage::execute), and the state may still
2768 // change via enableClientCache().
2769 return true;
2770 }
2771 // e.g. various error-type pages disable all client caching
2772 return $this->mEnableClientCache;
2773 }
2774
2775 /**
2776 * Set the expectation that cache control will not change after this point.
2777 *
2778 * This should be called after the main processing logic has completed
2779 * (e.g. Action::show or SpecialPage::execute), but may be called
2780 * before Skin output has started (OutputPage::output).
2781 *
2782 * @since 1.34
2783 */
2784 public function considerCacheSettingsFinal() {
2785 $this->cacheIsFinal = true;
2786 }
2787
2788 /**
2789 * Get the list of cookie names that will influence the cache
2790 *
2791 * @return array
2792 */
2793 public function getCacheVaryCookies() {
2794 if ( self::$cacheVaryCookies === null ) {
2795 $config = $this->getConfig();
2796 self::$cacheVaryCookies = array_values( array_unique( array_merge(
2797 SessionManager::singleton()->getVaryCookies(),
2798 [
2799 'forceHTTPS',
2800 ],
2801 $config->get( MainConfigNames::CacheVaryCookies )
2802 ) ) );
2803 $this->getHookRunner()->onGetCacheVaryCookies( $this, self::$cacheVaryCookies );
2804 }
2805 return self::$cacheVaryCookies;
2806 }
2807
2808 /**
2809 * Check if the request has a cache-varying cookie header
2810 * If it does, it's very important that we don't allow public caching
2811 *
2812 * @return bool
2813 */
2814 public function haveCacheVaryCookies() {
2815 $request = $this->getRequest();
2816 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2817 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2818 wfDebug( __METHOD__ . ": found $cookieName" );
2819 return true;
2820 }
2821 }
2822 wfDebug( __METHOD__ . ': no cache-varying cookies found' );
2823 return false;
2824 }
2825
2826 /**
2827 * Add an HTTP header that will have an influence on the cache
2828 *
2829 * @param string $header Header name
2830 */
2831 public function addVaryHeader( $header ) {
2832 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2833 $this->mVaryHeader[$header] = null;
2834 }
2835 }
2836
2837 /**
2838 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2839 * such as Accept-Encoding or Cookie
2840 *
2841 * @return string
2842 */
2843 public function getVaryHeader() {
2844 // If we vary on cookies, let's make sure it's always included here too.
2845 if ( $this->getCacheVaryCookies() ) {
2846 $this->addVaryHeader( 'Cookie' );
2847 }
2848
2849 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $_ ) {
2850 $this->addVaryHeader( $header );
2851 }
2852 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2853 }
2854
2855 /**
2856 * Add an HTTP Link: header
2857 *
2858 * @param string $header Header value
2859 */
2860 public function addLinkHeader( $header ) {
2861 $this->mLinkHeader[] = $header;
2862 }
2863
2864 /**
2865 * Return a Link: header. Based on the values of $mLinkHeader.
2866 *
2867 * @return string|false
2868 */
2869 public function getLinkHeader() {
2870 if ( !$this->mLinkHeader ) {
2871 return false;
2872 }
2873
2874 return 'Link: ' . implode( ',', $this->mLinkHeader );
2875 }
2876
2877 /**
2878 * T23672: Add Accept-Language to Vary header if there's no 'variant' parameter in GET.
2879 *
2880 * For example:
2881 * /w/index.php?title=Main_page will vary based on Accept-Language; but
2882 * /w/index.php?title=Main_page&variant=zh-cn will not.
2883 */
2884 private function addAcceptLanguage() {
2885 $title = $this->getTitle();
2886 if ( !$title instanceof Title ) {
2887 return;
2888 }
2889
2890 $languageConverter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
2891 ->getLanguageConverter( $title->getPageLanguage() );
2892 if ( !$this->getRequest()->getCheck( 'variant' ) && $languageConverter->hasVariants() ) {
2893 $this->addVaryHeader( 'Accept-Language' );
2894 }
2895 }
2896
2897 /**
2898 * Set the prevent-clickjacking flag.
2899 *
2900 * If true, will cause an X-Frame-Options header appropriate for
2901 * edit pages to be sent. The header value is controlled by
2902 * $wgEditPageFrameOptions. This is the default for special
2903 * pages. If you display a CSRF-protected form on an ordinary view
2904 * page, then you need to call this function.
2905 *
2906 * Setting this flag to false will turn off frame-breaking. This
2907 * can be called from pages which do not contain any
2908 * CSRF-protected HTML form.
2909 *
2910 * @param bool $enable If true, will cause an X-Frame-Options header
2911 * appropriate for edit pages to be sent.
2912 *
2913 * @since 1.38
2914 * @deprecated since 1.43; use ->getMetadata()->setPreventClickjacking()
2915 */
2916 public function setPreventClickjacking( bool $enable ) {
2917 $this->metadata->setPreventClickjacking( $enable );
2918 }
2919
2920 /**
2921 * Get the prevent-clickjacking flag
2922 *
2923 * @since 1.24
2924 * @return bool
2925 * @deprecated since 1.43; use ->getMetadata()->getPreventClickjacking()
2926 */
2927 public function getPreventClickjacking() {
2928 return $this->metadata->getPreventClickjacking();
2929 }
2930
2931 /**
2932 * Get the X-Frame-Options header value (without the name part), or false
2933 * if there isn't one. This is used by Skin to determine whether to enable
2934 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2935 *
2936 * @return string|false
2937 */
2938 public function getFrameOptions() {
2939 $config = $this->getConfig();
2940 if ( $config->get( MainConfigNames::BreakFrames ) ) {
2941 return 'DENY';
2942 } elseif (
2943 $this->metadata->getPreventClickjacking() &&
2944 $config->get( MainConfigNames::EditPageFrameOptions )
2945 ) {
2946 return $config->get( MainConfigNames::EditPageFrameOptions );
2947 }
2948 return false;
2949 }
2950
2951 private function getReportTo() {
2952 $config = $this->getConfig();
2953
2954 $expiry = $config->get( MainConfigNames::ReportToExpiry );
2955
2956 if ( !$expiry ) {
2957 return false;
2958 }
2959
2960 $endpoints = $config->get( MainConfigNames::ReportToEndpoints );
2961
2962 if ( !$endpoints ) {
2963 return false;
2964 }
2965
2966 $output = [ 'max_age' => $expiry, 'endpoints' => [] ];
2967
2968 foreach ( $endpoints as $endpoint ) {
2969 $output['endpoints'][] = [ 'url' => $endpoint ];
2970 }
2971
2972 return json_encode( $output, JSON_UNESCAPED_SLASHES );
2973 }
2974
2975 private function getFeaturePolicyReportOnly() {
2976 $config = $this->getConfig();
2977
2978 $features = $config->get( MainConfigNames::FeaturePolicyReportOnly );
2979 return implode( ';', $features );
2980 }
2981
2982 /**
2983 * Send cache control HTTP headers
2984 */
2985 public function sendCacheControl() {
2986 $response = $this->getRequest()->response();
2987 $config = $this->getConfig();
2988
2989 $this->addVaryHeader( 'Cookie' );
2990 $this->addAcceptLanguage();
2991
2992 # don't serve compressed data to clients who can't handle it
2993 # maintain different caches for logged-in users and non-logged in ones
2994 $response->header( $this->getVaryHeader() );
2995
2996 if ( $this->mEnableClientCache ) {
2997 if ( !$config->get( MainConfigNames::UseCdn ) ) {
2998 $privateReason = 'config';
2999 } elseif ( $response->hasCookies() ) {
3000 $privateReason = 'set-cookies';
3001 // The client might use methods other than cookies to appear logged-in.
3002 // E.g. HTTP headers, or query parameter tokens, OAuth, etc.
3003 } elseif ( SessionManager::getGlobalSession()->isPersistent() ) {
3004 $privateReason = 'session';
3005 } elseif ( $this->isPrintable() ) {
3006 $privateReason = 'printable';
3007 } elseif ( $this->mCdnMaxage == 0 ) {
3008 $privateReason = 'no-maxage';
3009 } elseif ( $this->haveCacheVaryCookies() ) {
3010 $privateReason = 'cache-vary-cookies';
3011 } else {
3012 $privateReason = false;
3013 }
3014
3015 if ( $privateReason === false ) {
3016 # We'll purge the proxy cache for anons explicitly, but require end user agents
3017 # to revalidate against the proxy on each visit.
3018 # IMPORTANT! The CDN needs to replace the Cache-Control header with
3019 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
3020 wfDebug( __METHOD__ .
3021 ": local proxy caching; {$this->mLastModified} **", 'private' );
3022 # start with a shorter timeout for initial testing
3023 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
3024 $response->header( 'Cache-Control: ' .
3025 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
3026 } else {
3027 # We do want clients to cache if they can, but they *must* check for updates
3028 # on revisiting the page.
3029 wfDebug( __METHOD__ . ": private caching ($privateReason); {$this->mLastModified} **", 'private' );
3030
3031 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
3032 $response->header( 'Cache-Control: private, must-revalidate, max-age=0' );
3033 }
3034 if ( $this->mLastModified ) {
3035 $response->header( "Last-Modified: {$this->mLastModified}" );
3036 }
3037 } else {
3038 wfDebug( __METHOD__ . ': no caching **', 'private' );
3039
3040 # In general, the absence of a last modified header should be enough to prevent
3041 # the client from using its cache. We send a few other things just to make sure.
3042 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
3043 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
3044 }
3045 }
3046
3047 /**
3048 * Transfer styles and JavaScript modules from skin.
3049 *
3050 * @param Skin $sk to load modules for
3051 */
3052 public function loadSkinModules( $sk ) {
3053 foreach ( $sk->getDefaultModules() as $group => $modules ) {
3054 if ( $group === 'styles' ) {
3055 foreach ( $modules as $moduleMembers ) {
3056 $this->addModuleStyles( $moduleMembers );
3057 }
3058 } else {
3059 $this->addModules( $modules );
3060 }
3061 }
3062 }
3063
3064 /**
3065 * Finally, all the text has been munged and accumulated into
3066 * the object, let's actually output it:
3067 *
3068 * @param bool $return Set to true to get the result as a string rather than sending it
3069 * @return string|null
3070 */
3071 public function output( $return = false ) {
3072 if ( $this->mDoNothing ) {
3073 return $return ? '' : null;
3074 }
3075
3076 $request = $this->getRequest();
3077 $response = $request->response();
3078 $config = $this->getConfig();
3079
3080 if ( $this->mRedirect != '' ) {
3081 $services = MediaWikiServices::getInstance();
3082 // Modern standards don't require redirect URLs to be absolute, but make it so just in case.
3083 // Note that this doesn't actually guarantee an absolute URL: relative-path URLs are left intact.
3084 $this->mRedirect = (string)$services->getUrlUtils()->expand( $this->mRedirect, PROTO_CURRENT );
3085
3086 $redirect = $this->mRedirect;
3087 $code = $this->mRedirectCode;
3088 $content = '';
3089
3090 if ( $this->getHookRunner()->onBeforePageRedirect( $this, $redirect, $code ) ) {
3091 if ( $code == '301' || $code == '303' ) {
3092 if ( !$config->get( MainConfigNames::DebugRedirects ) ) {
3093 $response->statusHeader( (int)$code );
3094 }
3095 $this->mLastModified = wfTimestamp( TS_RFC2822 );
3096 }
3097 if ( $config->get( MainConfigNames::VaryOnXFP ) ) {
3098 $this->addVaryHeader( 'X-Forwarded-Proto' );
3099 }
3100 $this->sendCacheControl();
3101
3102 $response->header( 'Content-Type: text/html; charset=UTF-8' );
3103 if ( $config->get( MainConfigNames::DebugRedirects ) ) {
3104 $url = htmlspecialchars( $redirect );
3105 $content = "<!DOCTYPE html>\n<html>\n<head>\n"
3106 . "<title>Redirect</title>\n</head>\n<body>\n"
3107 . "<p>Location: <a href=\"$url\">$url</a></p>\n"
3108 . "</body>\n</html>\n";
3109
3110 if ( !$return ) {
3111 print $content;
3112 }
3113
3114 } else {
3115 $response->header( 'Location: ' . $redirect );
3116 }
3117 }
3118
3119 return $return ? $content : null;
3120 } elseif ( $this->mStatusCode ) {
3121 $response->statusHeader( $this->mStatusCode );
3122 }
3123
3124 # Buffer output; final headers may depend on later processing
3125 ob_start();
3126
3127 $response->header( 'Content-language: ' .
3128 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
3129
3130 $linkHeader = $this->getLinkHeader();
3131 if ( $linkHeader ) {
3132 $response->header( $linkHeader );
3133 }
3134
3135 // Prevent framing, if requested
3136 $frameOptions = $this->getFrameOptions();
3137 if ( $frameOptions ) {
3138 $response->header( "X-Frame-Options: $frameOptions" );
3139 }
3140
3141 // Get the Origin-Trial header values. This is used to enable Chrome Origin
3142 // Trials: https://github.com/GoogleChrome/OriginTrials
3143 $originTrials = $config->get( MainConfigNames::OriginTrials );
3144 foreach ( $originTrials as $originTrial ) {
3145 $response->header( "Origin-Trial: $originTrial", false );
3146 }
3147
3148 $reportTo = $this->getReportTo();
3149 if ( $reportTo ) {
3150 $response->header( "Report-To: $reportTo" );
3151 }
3152
3153 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
3154 if ( $featurePolicyReportOnly ) {
3155 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
3156 }
3157
3158 if ( $this->mArticleBodyOnly ) {
3159 $response->header( 'Content-type: ' . $config->get( MainConfigNames::MimeType ) . '; charset=UTF-8' );
3160 if ( $this->cspOutputMode === self::CSP_HEADERS ) {
3161 $this->CSP->sendHeaders();
3162 }
3163 echo $this->mBodytext;
3164 } else {
3165 // Enable safe mode if requested (T152169)
3166 if ( $this->getRequest()->getBool( 'safemode' ) ) {
3167 $this->disallowUserJs();
3168 }
3169
3170 $sk = $this->getSkin();
3171 $skinOptions = $sk->getOptions();
3172
3173 if ( $skinOptions['format'] === 'json' ) {
3174 $response->header( 'Content-type: application/json; charset=UTF-8' );
3175 return json_encode( [
3176 $this->msg( 'skin-json-warning' )->escaped() => $this->msg( 'skin-json-warning-message' )->escaped()
3177 ] + $sk->getTemplateData() );
3178 }
3179 $response->header( 'Content-type: ' . $config->get( MainConfigNames::MimeType ) . '; charset=UTF-8' );
3180 $this->loadSkinModules( $sk );
3181
3182 MWDebug::addModules( $this );
3183
3184 // Hook that allows last minute changes to the output page, e.g.
3185 // adding of CSS or Javascript by extensions, adding CSP sources.
3186 $this->getHookRunner()->onBeforePageDisplay( $this, $sk );
3187
3188 if ( $this->cspOutputMode === self::CSP_HEADERS ) {
3189 $this->CSP->sendHeaders();
3190 }
3191
3192 try {
3193 $sk->outputPageFinal( $this );
3194 } catch ( Exception $e ) {
3195 ob_end_clean(); // bug T129657
3196 throw $e;
3197 }
3198 }
3199
3200 try {
3201 // This hook allows last minute changes to final overall output by modifying output buffer
3202 $this->getHookRunner()->onAfterFinalPageOutput( $this );
3203 } catch ( Exception $e ) {
3204 ob_end_clean(); // bug T129657
3205 throw $e;
3206 }
3207
3208 $this->sendCacheControl();
3209
3210 if ( $return ) {
3211 return ob_get_clean();
3212 } else {
3213 ob_end_flush();
3214 return null;
3215 }
3216 }
3217
3218 /**
3219 * Prepare this object to display an error page; disable caching and
3220 * indexing, clear the current text and redirect, set the page's title
3221 * and optionally a custom HTML title (content of the "<title>" tag).
3222 *
3223 * @param string|Message|null $pageTitle Will be passed directly to setPageTitle()
3224 * @param string|Message|false $htmlTitle Will be passed directly to setHTMLTitle();
3225 * optional, if not passed the "<title>" attribute will be
3226 * based on $pageTitle
3227 * @note Explicitly passing $pageTitle or $htmlTitle has been deprecated
3228 * since 1.41; use ::setPageTitleMsg() and ::setHTMLTitle() instead.
3229 */
3230 public function prepareErrorPage( $pageTitle = null, $htmlTitle = false ) {
3231 if ( $pageTitle !== null || $htmlTitle !== false ) {
3232 wfDeprecated( __METHOD__ . ' with explicit arguments', '1.41' );
3233 if ( $pageTitle !== null ) {
3234 $this->setPageTitle( $pageTitle );
3235 }
3236 if ( $htmlTitle !== false ) {
3237 $this->setHTMLTitle( $htmlTitle );
3238 }
3239 }
3240 $this->setRobotPolicy( 'noindex,nofollow' );
3241 $this->setArticleRelated( false );
3242 $this->disableClientCache();
3243 $this->mRedirect = '';
3244 $this->clearSubtitle();
3245 $this->clearHTML();
3246 }
3247
3248 /**
3249 * Output a standard error page
3250 *
3251 * showErrorPage( 'titlemsg', 'pagetextmsg' );
3252 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
3253 * showErrorPage( 'titlemsg', $messageObject );
3254 * showErrorPage( $titleMessageObject, $messageObject );
3255 *
3256 * @param string|MessageSpecifier $title Message key (string) for page title, or a MessageSpecifier
3257 * @param string|MessageSpecifier $msg Message key (string) for page text, or a MessageSpecifier
3258 * @param array $params Message parameters; ignored if $msg is a Message object
3259 * @param PageReference|LinkTarget|string|null $returnto Page to show a return link to;
3260 * defaults to the 'returnto' URL parameter
3261 * @param string|null $returntoquery Query string for the return to link;
3262 * defaults to the 'returntoquery' URL parameter
3263 */
3264 public function showErrorPage(
3265 $title, $msg, $params = [], $returnto = null, $returntoquery = null
3266 ) {
3267 if ( !$title instanceof Message ) {
3268 $title = $this->msg( $title );
3269 }
3270
3271 $this->prepareErrorPage();
3272 $this->setPageTitleMsg( $title );
3273
3274 if ( $msg instanceof Message ) {
3275 if ( $params !== [] ) {
3276 trigger_error( 'Argument ignored: $params. The message parameters argument '
3277 . 'is discarded when the $msg argument is a Message object instead of '
3278 . 'a string.', E_USER_NOTICE );
3279 }
3280 $this->addHTML( $msg->parseAsBlock() );
3281 } else {
3282 $this->addWikiMsgArray( $msg, $params );
3283 }
3284
3285 $this->returnToMain( null, $returnto, $returntoquery );
3286 }
3287
3288 /**
3289 * Output a standard permission error page
3290 *
3291 * @param PermissionStatus $status
3292 * @param string|null $action Action that was denied or null if unknown
3293 */
3294 public function showPermissionStatus( PermissionStatus $status, $action = null ) {
3295 Assert::precondition( !$status->isGood(), 'Status must have errors' );
3296
3297 $this->showPermissionInternal(
3298 array_map( fn ( $msg ) => $this->msg( $msg ), $status->getMessages() ),
3299 $action
3300 );
3301 }
3302
3303 /**
3304 * Output a standard permission error page
3305 *
3306 * @deprecated since 1.43. Use ::showPermissionStatus instead
3307 * @param array $errors Error message keys or [key, param...] arrays
3308 * @param string|null $action Action that was denied or null if unknown
3309 */
3310 public function showPermissionsErrorPage( array $errors, $action = null ) {
3311 wfDeprecated( __METHOD__, '1.43' );
3312 foreach ( $errors as $key => $error ) {
3313 $errors[$key] = (array)$error;
3314 }
3315
3316 $this->showPermissionInternal(
3317 // @phan-suppress-next-line PhanParamTooFewUnpack Elements of $errors already annotated as non-empty
3318 array_map( fn ( $err ) => $this->msg( ...$err ), $errors ),
3319 $action
3320 );
3321 }
3322
3323 /**
3324 * Helper for showPermissionStatus() and deprecated showPermissionsErrorMessage(),
3325 * should be inlined when the deprecated method is removed.
3326 *
3327 * @param Message[] $messages
3328 * @param string|null $action
3329 */
3330 public function showPermissionInternal( array $messages, $action = null ) {
3331 $services = MediaWikiServices::getInstance();
3332 $groupPermissionsLookup = $services->getGroupPermissionsLookup();
3333
3334 // For some actions (read, edit, create and upload), display a "login to do this action"
3335 // error if all of the following conditions are met:
3336 // 1. the user is not logged in as a named user, and so cannot be added to groups
3337 // 2. the only error is insufficient permissions (i.e. no block or something else)
3338 // 3. the error can be avoided simply by logging in
3339
3340 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
3341 && !$this->getUser()->isNamed() && count( $messages ) == 1
3342 && ( $messages[0]->getKey() == 'badaccess-groups' || $messages[0]->getKey() == 'badaccess-group0' )
3343 && ( $groupPermissionsLookup->groupHasPermission( 'user', $action )
3344 || $groupPermissionsLookup->groupHasPermission( 'autoconfirmed', $action ) )
3345 ) {
3346 $displayReturnto = null;
3347
3348 # Due to T34276, if a user does not have read permissions,
3349 # $this->getTitle() will just give Special:Badtitle, which is
3350 # not especially useful as a returnto parameter. Use the title
3351 # from the request instead, if there was one.
3352 $request = $this->getRequest();
3353 $returnto = Title::newFromText( $request->getText( 'title' ) );
3354 if ( $action == 'edit' ) {
3355 $msg = 'whitelistedittext';
3356 $displayReturnto = $returnto;
3357 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
3358 $msg = 'nocreatetext';
3359 } elseif ( $action == 'upload' ) {
3360 $msg = 'uploadnologintext';
3361 } else { # Read
3362 $msg = 'loginreqpagetext';
3363 $displayReturnto = Title::newMainPage();
3364 }
3365
3366 $query = [];
3367
3368 if ( $returnto ) {
3369 $query['returnto'] = $returnto->getPrefixedText();
3370
3371 if ( !$request->wasPosted() ) {
3372 $returntoquery = $request->getValues();
3373 unset( $returntoquery['title'] );
3374 unset( $returntoquery['returnto'] );
3375 unset( $returntoquery['returntoquery'] );
3376 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
3377 }
3378 }
3379
3380 $title = SpecialPage::getTitleFor( 'Userlogin' );
3381 $linkRenderer = $services->getLinkRenderer();
3382 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE );
3383 $loginLink = $linkRenderer->makeKnownLink(
3384 $title,
3385 $this->msg( 'loginreqlink' )->text(),
3386 [],
3387 $query
3388 );
3389
3390 $this->prepareErrorPage();
3391 $this->setPageTitleMsg( $this->msg( 'loginreqtitle' ) );
3392 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
3393
3394 # Don't return to a page the user can't read otherwise
3395 # we'll end up in a pointless loop
3396 if ( $displayReturnto && $this->getAuthority()->probablyCan( 'read', $displayReturnto ) ) {
3397 $this->returnToMain( null, $displayReturnto );
3398 }
3399 } else {
3400 $this->prepareErrorPage();
3401 $this->setPageTitleMsg( $this->msg( 'permissionserrors' ) );
3402 $this->addWikiTextAsInterface( $this->formatPermissionInternal( $messages, $action ) );
3403 }
3404 }
3405
3406 /**
3407 * Display an error page indicating that a given version of MediaWiki is
3408 * required to use it
3409 *
3410 * @param mixed $version The version of MediaWiki needed to use the page
3411 */
3412 public function versionRequired( $version ) {
3413 $this->prepareErrorPage();
3414 $this->setPageTitleMsg(
3415 $this->msg( 'versionrequired' )->plaintextParams( $version )
3416 );
3417
3418 $this->addWikiMsg( 'versionrequiredtext', $version );
3419 $this->returnToMain();
3420 }
3421
3422 /**
3423 * Format permission $status obtained from Authority for display.
3424 *
3425 * @param PermissionStatus $status
3426 * @param-taint $status none
3427 * @param string|null $action that was denied or null if unknown
3428 * @return string
3429 * @return-taint tainted
3430 */
3431 public function formatPermissionStatus( PermissionStatus $status, ?string $action = null ): string {
3432 if ( $status->isGood() ) {
3433 return '';
3434 }
3435 return $this->formatPermissionInternal(
3436 array_map( fn ( $msg ) => $this->msg( $msg ), $status->getMessages() ),
3437 $action
3438 );
3439 }
3440
3441 /**
3442 * Format a list of error messages
3443 *
3444 * @deprecated since 1.36. Use ::formatPermissionStatus instead
3445 * @param array $errors Array of arrays returned by PermissionManager::getPermissionErrors
3446 * @param-taint $errors none
3447 * @phan-param non-empty-array[] $errors
3448 * @param string|null $action Action that was denied or null if unknown
3449 * @return string The wikitext error-messages, formatted into a list.
3450 * @return-taint tainted
3451 */
3452 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
3453 wfDeprecated( __METHOD__, '1.36' );
3454 return $this->formatPermissionInternal(
3455 // @phan-suppress-next-line PhanParamTooFewUnpack Elements of $errors already annotated as non-empty
3456 array_map( fn ( $err ) => $this->msg( ...$err ), $errors ),
3457 $action
3458 );
3459 }
3460
3461 /**
3462 * Helper for formatPermissionStatus() and deprecated formatPermissionsErrorMessage(),
3463 * should be inlined when the deprecated method is removed.
3464 *
3465 * @param Message[] $messages
3466 * @param-taint $messages none
3467 * @param string|null $action
3468 * @return string
3469 * @return-taint tainted
3470 *
3471 * @suppress SecurityCheck-DoubleEscaped Working with plain text, not HTML
3472 */
3473 private function formatPermissionInternal( array $messages, $action = null ) {
3474 if ( $action == null ) {
3475 $text = $this->msg( 'permissionserrorstext', count( $messages ) )->plain() . "\n\n";
3476 } else {
3477 $action_desc = $this->msg( "action-$action" )->plain();
3478 $text = $this->msg(
3479 'permissionserrorstext-withaction',
3480 count( $messages ),
3481 $action_desc
3482 )->plain() . "\n\n";
3483 }
3484
3485 if ( count( $messages ) > 1 ) {
3486 $text .= Html::openElement( 'ul', [ 'class' => 'permissions-errors' ] );
3487 foreach ( $messages as $message ) {
3488 $text .= Html::rawElement(
3489 'li',
3490 [ 'class' => 'mw-permissionerror-' . $message->getKey() ],
3491 $message->plain()
3492 );
3493 }
3494 $text .= Html::closeElement( 'ul' );
3495 } else {
3496 $text .= Html::openElement( 'div', [ 'class' => 'permissions-errors' ] );
3497 $text .= Html::rawElement(
3498 'div',
3499 [ 'class' => 'mw-permissionerror-' . $messages[ 0 ]->getKey() ],
3500 $messages[ 0 ]->plain()
3501 );
3502 $text .= Html::closeElement( 'div' );
3503 }
3504
3505 return $text;
3506 }
3507
3508 /**
3509 * Show a warning about replica DB lag
3510 *
3511 * If the lag is higher than $wgDatabaseReplicaLagCritical seconds,
3512 * then the warning is a bit more obvious. If the lag is
3513 * lower than $wgDatabaseReplicaLagWarning, then no warning is shown.
3514 *
3515 * @param int $lag Replica lag
3516 */
3517 public function showLagWarning( $lag ) {
3518 $config = $this->getConfig();
3519 if ( $lag >= $config->get( MainConfigNames::DatabaseReplicaLagWarning ) ) {
3520 $lag = floor( $lag ); // floor to avoid nano seconds to display
3521 $message = $lag < $config->get( MainConfigNames::DatabaseReplicaLagCritical )
3522 ? 'lag-warn-normal'
3523 : 'lag-warn-high';
3524 // For grep: mw-lag-warn-normal, mw-lag-warn-high
3525 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
3526 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
3527 }
3528 }
3529
3530 /**
3531 * Output an error page
3532 *
3533 * @deprecated since 1.43 Use showErrorPage() instead
3534 * @param string $message Error to output. Must be escaped for HTML.
3535 */
3536 public function showFatalError( $message ) {
3537 wfDeprecated( __METHOD__, '1.43' );
3538
3539 $this->prepareErrorPage();
3540 $this->setPageTitleMsg( $this->msg( 'internalerror' ) );
3541
3542 $this->addHTML( $message );
3543 }
3544
3545 /**
3546 * Add a "return to" link pointing to a specified title
3547 *
3548 * @param LinkTarget $title Title to link
3549 * @param array $query Query string parameters
3550 * @param string|null $text Text of the link (input is not escaped)
3551 * @param array $options Options array to pass to Linker
3552 */
3553 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
3554 $linkRenderer = MediaWikiServices::getInstance()
3555 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
3556 $link = $this->msg( 'returnto' )->rawParams(
3557 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
3558 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
3559 }
3560
3561 /**
3562 * Add a "return to" link pointing to a specified title,
3563 * or the title indicated in the request, or else the main page
3564 *
3565 * @param mixed|null $unused
3566 * @param PageReference|LinkTarget|string|null $returnto Page to return to
3567 * @param string|null $returntoquery Query string for the return to link
3568 */
3569 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
3570 $returnto ??= $this->getRequest()->getText( 'returnto' );
3571
3572 $returntoquery ??= $this->getRequest()->getText( 'returntoquery' );
3573
3574 if ( $returnto === '' ) {
3575 $returnto = Title::newMainPage();
3576 }
3577
3578 if ( is_object( $returnto ) ) {
3579 $linkTarget = TitleValue::castPageToLinkTarget( $returnto );
3580 } else {
3581 $linkTarget = Title::newFromText( $returnto );
3582 }
3583
3584 // We don't want people to return to external interwiki. That
3585 // might potentially be used as part of a phishing scheme
3586 if ( !is_object( $linkTarget ) || $linkTarget->isExternal() ) {
3587 $linkTarget = Title::newMainPage();
3588 }
3589
3590 $this->addReturnTo( $linkTarget, wfCgiToArray( $returntoquery ) );
3591 }
3592
3593 /**
3594 * Output a standard "wait for takeover" warning
3595 *
3596 * This is useful for extensions which are hooking an action and
3597 * suppressing its normal output so it can be taken over with JS.
3598 *
3599 * showPendingTakeover( 'url', 'pagetextmsg' );
3600 * showPendingTakeover( 'url', 'pagetextmsg', [ 'param1', 'param2' ] );
3601 * showPendingTakeover( 'url', $messageObject );
3602 *
3603 * @param string $fallbackUrl URL to redirect to if the user doesn't have JavaScript
3604 * or ResourceLoader available; this should ideally be to a page that provides similar
3605 * functionality without requiring JavaScript
3606 * @param string|MessageSpecifier $msg Message key (string) for page text, or a MessageSpecifier
3607 * @param mixed ...$params Message parameters; ignored if $msg is a Message object
3608 */
3609 public function showPendingTakeover(
3610 $fallbackUrl, $msg, ...$params
3611 ) {
3612 if ( $msg instanceof Message ) {
3613 if ( $params !== [] ) {
3614 trigger_error( 'Argument ignored: $params. The message parameters argument '
3615 . 'is discarded when the $msg argument is a Message object instead of '
3616 . 'a string.', E_USER_NOTICE );
3617 }
3618 $this->addHTML( $msg->parseAsBlock() );
3619 } else {
3620 $this->addHTML( $this->msg( $msg, ...$params )->parseAsBlock() );
3621 }
3622
3623 // Redirect if the user has no JS (<noscript>)
3624 $escapedUrl = htmlspecialchars( $fallbackUrl );
3625 $this->addHeadItem(
3626 'mw-noscript-fallback',
3627 // https://html.spec.whatwg.org/#attr-meta-http-equiv-refresh
3628 // means that if $fallbackUrl contains unencoded quotation marks
3629 // then this will behave confusingly, but shouldn't break the page
3630 "<noscript><meta http-equiv=\"refresh\" content=\"0; url=$escapedUrl\"></noscript>"
3631 );
3632 // Redirect if the user has no ResourceLoader
3633 $this->addScript( Html::inlineScript(
3634 '(window.NORLQ=window.NORLQ||[]).push(' .
3635 'function(){' .
3636 'location.href=' . json_encode( $fallbackUrl ) . ';' .
3637 '}' .
3638 ');'
3639 ) );
3640 }
3641
3642 private function getRlClientContext() {
3643 if ( !$this->rlClientContext ) {
3644 $query = ResourceLoader::makeLoaderQuery(
3645 [], // modules; not relevant
3646 $this->getLanguage()->getCode(),
3647 $this->getSkin()->getSkinName(),
3648 $this->getUser()->isRegistered() ? $this->getUser()->getName() : null,
3649 null, // version; not relevant
3650 ResourceLoader::inDebugMode(),
3651 null, // only; not relevant
3652 $this->isPrintable()
3653 );
3654 $this->rlClientContext = new RL\Context(
3655 $this->getResourceLoader(),
3656 new FauxRequest( $query )
3657 );
3658 if ( $this->contentOverrideCallbacks ) {
3659 $this->rlClientContext = new RL\DerivativeContext( $this->rlClientContext );
3660 $this->rlClientContext->setContentOverrideCallback( function ( $page ) {
3661 foreach ( $this->contentOverrideCallbacks as $callback ) {
3662 $content = $callback( $page );
3663 if ( $content !== null ) {
3664 $text = ( $content instanceof TextContent ) ? $content->getText() : '';
3665 if ( preg_match( '/<\/?script/i', $text ) ) {
3666 // Proactively replace this so that we can display a message
3667 // to the user, instead of letting it go to Html::inlineScript(),
3668 // where it would be considered a server-side issue.
3669 $content = new JavaScriptContent(
3670 Html::encodeJsCall( 'mw.log.error', [
3671 "Cannot preview $page due to suspecting script tag inside (T200506)."
3672 ] )
3673 );
3674 }
3675 return $content;
3676 }
3677 }
3678 return null;
3679 } );
3680 }
3681 }
3682 return $this->rlClientContext;
3683 }
3684
3685 /**
3686 * Call this to freeze the module queue and JS config and create a formatter.
3687 *
3688 * Depending on the Skin, this may get lazy-initialised in either headElement() or
3689 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
3690 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
3691 * the module filters retroactively. Skins and extension hooks may also add modules until very
3692 * late in the request lifecycle.
3693 *
3694 * @return RL\ClientHtml
3695 */
3696 public function getRlClient() {
3697 if ( !$this->rlClient ) {
3698 $context = $this->getRlClientContext();
3699 $rl = $this->getResourceLoader();
3700 $this->addModules( [
3701 'user',
3702 'user.options',
3703 ] );
3704 $this->addModuleStyles( [
3705 'site.styles',
3706 'noscript',
3707 'user.styles',
3708 ] );
3709
3710 // Prepare exempt modules for buildExemptModules()
3711 $exemptGroups = [
3712 RL\Module::GROUP_SITE => [],
3713 RL\Module::GROUP_NOSCRIPT => [],
3714 RL\Module::GROUP_PRIVATE => [],
3715 RL\Module::GROUP_USER => []
3716 ];
3717 $exemptStates = [];
3718 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
3719
3720 // Preload getTitleInfo for isKnownEmpty calls below and in RL\ClientHtml
3721 // Separate user-specific batch for improved cache-hit ratio.
3722 $userBatch = [ 'user.styles', 'user' ];
3723 $siteBatch = array_diff( $moduleStyles, $userBatch );
3724 RL\WikiModule::preloadTitleInfo( $context, $siteBatch );
3725 RL\WikiModule::preloadTitleInfo( $context, $userBatch );
3726
3727 // Filter out modules handled by buildExemptModules()
3728 $moduleStyles = array_filter( $moduleStyles,
3729 static function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
3730 $module = $rl->getModule( $name );
3731 if ( $module ) {
3732 $group = $module->getGroup();
3733 if ( $group !== null && isset( $exemptGroups[$group] ) ) {
3734 // The `noscript` module is excluded from the client
3735 // side registry, no need to set its state either.
3736 // But we still output it. See T291735
3737 if ( $group !== RL\Module::GROUP_NOSCRIPT ) {
3738 $exemptStates[$name] = 'ready';
3739 }
3740 if ( !$module->isKnownEmpty( $context ) ) {
3741 // E.g. Don't output empty <styles>
3742 $exemptGroups[$group][] = $name;
3743 }
3744 return false;
3745 }
3746 }
3747 return true;
3748 }
3749 );
3750 $this->rlExemptStyleModules = $exemptGroups;
3751
3752 $config = $this->getConfig();
3753 // Client preferences are controlled by the skin and specific to unregistered
3754 // users. See mw.user.clientPrefs for details on how this works and how to
3755 // handle registered users.
3756 $clientPrefEnabled = (
3757 $this->getSkin()->getOptions()['clientPrefEnabled'] &&
3758 !$this->getUser()->isNamed()
3759 );
3760 $clientPrefCookiePrefix = $config->get( MainConfigNames::CookiePrefix );
3761
3762 $rlClient = new RL\ClientHtml( $context, [
3763 'target' => $this->getTarget(),
3764 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
3765 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
3766 // modules enqueued for loading on this page is filtered to just those.
3767 // However, to make sure we also apply the restriction to dynamic dependencies and
3768 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
3769 // StartupModule so that the client-side registry will not contain any restricted
3770 // modules either. (T152169, T185303)
3771 'safemode' => ( $this->getAllowedModules( RL\Module::TYPE_COMBINED )
3772 <= RL\Module::ORIGIN_CORE_INDIVIDUAL
3773 ) ? '1' : null,
3774 'clientPrefEnabled' => $clientPrefEnabled,
3775 'clientPrefCookiePrefix' => $clientPrefCookiePrefix,
3776 ] );
3777 $rlClient->setConfig( $this->getJSVars( self::JS_VAR_EARLY ) );
3778 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
3779 $rlClient->setModuleStyles( $moduleStyles );
3780 $rlClient->setExemptStates( $exemptStates );
3781 $this->rlClient = $rlClient;
3782 }
3783 return $this->rlClient;
3784 }
3785
3786 /**
3787 * @param Skin $sk The given Skin
3788 * @param bool $includeStyle Unused
3789 * @return string The doctype, opening "<html>", and head element.
3790 */
3791 public function headElement( Skin $sk, $includeStyle = true ) {
3792 $config = $this->getConfig();
3793 $userdir = $this->getLanguage()->getDir();
3794 $services = MediaWikiServices::getInstance();
3795 $sitedir = $services->getContentLanguage()->getDir();
3796
3797 $pieces = [];
3798 $htmlAttribs = Sanitizer::mergeAttributes( Sanitizer::mergeAttributes(
3799 $this->getRlClient()->getDocumentAttributes(),
3800 $sk->getHtmlElementAttributes()
3801 ), [ 'class' => implode( ' ', $this->mAdditionalHtmlClasses ) ] );
3802 $pieces[] = Html::htmlHeader( $htmlAttribs );
3803 $pieces[] = Html::openElement( 'head' );
3804
3805 if ( $this->getHTMLTitle() == '' ) {
3806 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3807 }
3808
3809 if ( !Html::isXmlMimeType( $config->get( MainConfigNames::MimeType ) ) ) {
3810 // Add <meta charset="UTF-8">
3811 // This should be before <title> since it defines the charset used by
3812 // text including the text inside <title>.
3813 // The spec recommends defining XHTML5's charset using the XML declaration
3814 // instead of meta.
3815 // Our XML declaration is output by Html::htmlHeader.
3816 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3817 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3818 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
3819 }
3820
3821 $pieces[] = Html::element( 'title', [], $this->getHTMLTitle() );
3822 $pieces[] = $this->getRlClient()->getHeadHtml( $htmlAttribs['class'] ?? null );
3823 $pieces[] = $this->buildExemptModules();
3824 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3825 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3826
3827 $pieces[] = Html::closeElement( 'head' );
3828
3829 $skinOptions = $sk->getOptions();
3830 $bodyClasses = array_merge( $this->mAdditionalBodyClasses, $skinOptions['bodyClasses'] );
3831 $bodyClasses[] = 'mediawiki';
3832
3833 # Classes for LTR/RTL directionality support
3834 $bodyClasses[] = $userdir;
3835 $bodyClasses[] = "sitedir-$sitedir";
3836
3837 // See Article:showDiffPage for class to support article diff styling
3838
3839 $underline = $services->getUserOptionsLookup()->getOption( $this->getUser(), 'underline' );
3840 if ( $underline < 2 ) {
3841 // The following classes can be used here:
3842 // * mw-underline-always
3843 // * mw-underline-never
3844 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
3845 }
3846
3847 // Parser feature migration class
3848 // The idea is that this will eventually be removed, after the wikitext
3849 // which requires it is cleaned up.
3850 $bodyClasses[] = 'mw-hide-empty-elt';
3851
3852 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3853 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
3854 $bodyClasses[] =
3855 'action-' . Sanitizer::escapeClass( $this->getContext()->getActionName() );
3856
3857 if ( $sk->isResponsive() ) {
3858 $bodyClasses[] = 'skin--responsive';
3859 }
3860
3861 $bodyAttrs = [];
3862 // While the implode() is not strictly needed, it's used for backwards compatibility
3863 // (this used to be built as a string and hooks likely still expect that).
3864 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3865
3866 $this->getHookRunner()->onOutputPageBodyAttributes( $this, $sk, $bodyAttrs );
3867
3868 $pieces[] = Html::openElement( 'body', $bodyAttrs );
3869
3870 return self::combineWrappedStrings( $pieces );
3871 }
3872
3873 /**
3874 * Get a ResourceLoader object associated with this OutputPage
3875 *
3876 * @return ResourceLoader
3877 */
3878 public function getResourceLoader() {
3879 if ( $this->mResourceLoader === null ) {
3880 // Lazy-initialise as needed
3881 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3882 }
3883 return $this->mResourceLoader;
3884 }
3885
3886 /**
3887 * Explicitly load or embed modules on a page.
3888 *
3889 * @param array|string $modules One or more module names
3890 * @param string $only RL\Module TYPE_ class constant
3891 * @param array $extraQuery [optional] Array with extra query parameters for the request
3892 * @return string|WrappedStringList HTML
3893 */
3894 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3895 // Apply 'origin' filters
3896 $modules = $this->filterModules( (array)$modules, null, $only );
3897
3898 return RL\ClientHtml::makeLoad(
3899 $this->getRlClientContext(),
3900 $modules,
3901 $only,
3902 $extraQuery
3903 );
3904 }
3905
3906 /**
3907 * Combine WrappedString chunks and filter out empty ones
3908 *
3909 * @param array $chunks
3910 * @return string|WrappedStringList HTML
3911 */
3912 protected static function combineWrappedStrings( array $chunks ) {
3913 // Filter out empty values
3914 $chunks = array_filter( $chunks, 'strlen' );
3915 return WrappedString::join( "\n", $chunks );
3916 }
3917
3918 /**
3919 * JS stuff to put at the bottom of the `<body>`.
3920 * These are legacy scripts ($this->mScripts), and user JS.
3921 *
3922 * @return string|WrappedStringList HTML
3923 */
3924 public function getBottomScripts() {
3925 // Keep the hook appendage separate to preserve WrappedString objects.
3926 // This enables to merge them where possible.
3927 $extraHtml = '';
3928 $this->getHookRunner()->onSkinAfterBottomScripts( $this->getSkin(), $extraHtml );
3929
3930 $chunks = [];
3931 $chunks[] = $this->getRlClient()->getBodyHtml();
3932
3933 // Legacy non-ResourceLoader scripts
3934 $chunks[] = $this->mScripts;
3935
3936 // Keep hostname and backend time as the first variables for quick view-source access.
3937 // This other variables will form a very long inline blob.
3938 $vars = [];
3939 if ( $this->getConfig()->get( MainConfigNames::ShowHostnames ) ) {
3940 $vars['wgHostname'] = wfHostname();
3941 }
3942 $elapsed = $this->getRequest()->getElapsedTime();
3943 // seconds to milliseconds
3944 $vars['wgBackendResponseTime'] = round( $elapsed * 1000 );
3945
3946 $vars += $this->getJSVars( self::JS_VAR_LATE );
3947 if ( $this->limitReportJSData ) {
3948 $vars['wgPageParseReport'] = $this->limitReportJSData;
3949 }
3950
3951 $rlContext = $this->getRlClientContext();
3952 $chunks[] = ResourceLoader::makeInlineScript(
3953 'mw.config.set(' . $rlContext->encodeJson( $vars ) . ');'
3954 );
3955
3956 $chunks = [ self::combineWrappedStrings( $chunks ) ];
3957 if ( $extraHtml !== '' ) {
3958 $chunks[] = $extraHtml;
3959 }
3960
3961 return WrappedString::join( "\n", $chunks );
3962 }
3963
3964 /**
3965 * Get the javascript config vars to include on this page
3966 *
3967 * @return array Array of javascript config vars
3968 * @since 1.23
3969 */
3970 public function getJsConfigVars() {
3971 return $this->mJsConfigVars;
3972 }
3973
3974 /**
3975 * Add one or more variables to be set in mw.config in JavaScript
3976 *
3977 * @param string|array $keys Key or array of key/value pairs
3978 * @param mixed|null $value [optional] Value of the configuration variable
3979 */
3980 public function addJsConfigVars( $keys, $value = null ) {
3981 if ( is_array( $keys ) ) {
3982 foreach ( $keys as $key => $value ) {
3983 $this->mJsConfigVars[$key] = $value;
3984 }
3985 return;
3986 }
3987
3988 $this->mJsConfigVars[$keys] = $value;
3989 }
3990
3991 /**
3992 * Get an array containing the variables to be set in mw.config in JavaScript.
3993 *
3994 * Do not add things here which can be evaluated in RL\StartUpModule,
3995 * in other words, page-independent/site-wide variables (without state).
3996 * These would add a blocking HTML cost to page rendering time, and require waiting for
3997 * HTTP caches to expire before configuration changes take effect everywhere.
3998 *
3999 * By default, these are loaded in the HTML head and block page rendering.
4000 * Config variable names can be set in CORE_LATE_JS_CONFIG_VAR_NAMES, or
4001 * for extensions via the 'LateJSConfigVarNames' attribute, to opt-in to
4002 * being sent from the end of the HTML body instead, to improve page load time.
4003 * In JavaScript, late variables should be accessed via mw.hook('wikipage.content').
4004 *
4005 * @param int|null $flag Return only the specified kind of variables: self::JS_VAR_EARLY or self::JS_VAR_LATE.
4006 * For internal use only.
4007 * @return array
4008 */
4009 public function getJSVars( ?int $flag = null ) {
4010 $curRevisionId = 0;
4011 $articleId = 0;
4012 $canonicalSpecialPageName = false; # T23115
4013 $services = MediaWikiServices::getInstance();
4014
4015 $title = $this->getTitle();
4016 $ns = $title->getNamespace();
4017 $nsInfo = $services->getNamespaceInfo();
4018 $canonicalNamespace = $nsInfo->exists( $ns )
4019 ? $nsInfo->getCanonicalName( $ns )
4020 : $title->getNsText();
4021
4022 $sk = $this->getSkin();
4023 // Get the relevant title so that AJAX features can use the correct page name
4024 // when making API requests from certain special pages (T36972).
4025 $relevantTitle = $sk->getRelevantTitle();
4026
4027 if ( $ns === NS_SPECIAL ) {
4028 [ $canonicalSpecialPageName, /*...*/ ] =
4029 $services->getSpecialPageFactory()->
4030 resolveAlias( $title->getDBkey() );
4031 } elseif ( $this->canUseWikiPage() ) {
4032 $wikiPage = $this->getWikiPage();
4033 // If we already know that the latest revision ID is the same as the revision ID being viewed,
4034 // avoid fetching it again, as it may give inconsistent results (T339164).
4035 if ( $this->isRevisionCurrent() && $this->getRevisionId() ) {
4036 $curRevisionId = $this->getRevisionId();
4037 } else {
4038 $curRevisionId = $wikiPage->getLatest();
4039 }
4040 $articleId = $wikiPage->getId();
4041 }
4042
4043 // ParserOutput informs HTML/CSS via lang/dir attributes.
4044 // We inform JavaScript via mw.config from here.
4045 $lang = $this->getContentLangForJS();
4046
4047 // Pre-process information
4048 $separatorTransTable = $lang->separatorTransformTable();
4049 $separatorTransTable = $separatorTransTable ?: [];
4050 $compactSeparatorTransTable = [
4051 implode( "\t", array_keys( $separatorTransTable ) ),
4052 implode( "\t", $separatorTransTable ),
4053 ];
4054 $digitTransTable = $lang->digitTransformTable();
4055 $digitTransTable = $digitTransTable ?: [];
4056 $compactDigitTransTable = [
4057 implode( "\t", array_keys( $digitTransTable ) ),
4058 implode( "\t", $digitTransTable ),
4059 ];
4060
4061 $user = $this->getUser();
4062
4063 // Internal variables for MediaWiki core
4064 $vars = [
4065 // @internal For mediawiki.page.ready
4066 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
4067
4068 // @internal For jquery.tablesorter
4069 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
4070 'wgDigitTransformTable' => $compactDigitTransTable,
4071 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
4072 'wgMonthNames' => $lang->getMonthNamesArray(),
4073
4074 // @internal For debugging purposes
4075 'wgRequestId' => WebRequest::getRequestId(),
4076 ];
4077
4078 // Start of supported and stable config vars (for use by extensions/gadgets).
4079 $vars += [
4080 'wgCanonicalNamespace' => $canonicalNamespace,
4081 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
4082 'wgNamespaceNumber' => $title->getNamespace(),
4083 'wgPageName' => $title->getPrefixedDBkey(),
4084 'wgTitle' => $title->getText(),
4085 'wgCurRevisionId' => $curRevisionId,
4086 'wgRevisionId' => (int)$this->getRevisionId(),
4087 'wgArticleId' => $articleId,
4088 'wgIsArticle' => $this->isArticle(),
4089 'wgIsRedirect' => $title->isRedirect(),
4090 'wgAction' => $this->getContext()->getActionName(),
4091 'wgUserName' => $user->isAnon() ? null : $user->getName(),
4092 'wgUserGroups' => $services->getUserGroupManager()->getUserEffectiveGroups( $user ),
4093 'wgCategories' => $this->getCategories(),
4094 'wgPageViewLanguage' => $lang->getCode(),
4095 'wgPageContentLanguage' => $lang->getCode(),
4096 'wgPageContentModel' => $title->getContentModel(),
4097 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
4098 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
4099 ];
4100 if ( $user->isRegistered() ) {
4101 $vars['wgUserId'] = $user->getId();
4102 $vars['wgUserIsTemp'] = $user->isTemp();
4103 $vars['wgUserEditCount'] = $user->getEditCount();
4104 $userReg = $user->getRegistration();
4105 $vars['wgUserRegistration'] = $userReg ? (int)wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
4106 $userFirstReg = $services->getUserRegistrationLookup()->getFirstRegistration( $user );
4107 $vars['wgUserFirstRegistration'] = $userFirstReg ? (int)wfTimestamp( TS_UNIX, $userFirstReg ) * 1000 : null;
4108 // Get the revision ID of the oldest new message on the user's talk
4109 // page. This can be used for constructing new message alerts on
4110 // the client side.
4111 $userNewMsgRevId = $this->getLastSeenUserTalkRevId();
4112 // Only occupy precious space in the <head> when it is non-null (T53640)
4113 // mw.config.get returns null by default.
4114 if ( $userNewMsgRevId ) {
4115 $vars['wgUserNewMsgRevisionId'] = $userNewMsgRevId;
4116 }
4117 } else {
4118 $tempUserCreator = $services->getTempUserCreator();
4119 if ( $tempUserCreator->isEnabled() ) {
4120 // For logged-out users only (without a temporary account): get the user name that will
4121 // be used for their temporary account, if it has already been acquired.
4122 // This may be used in previews.
4123 $session = $this->getRequest()->getSession();
4124 $vars['wgTempUserName'] = $tempUserCreator->getStashedName( $session );
4125 }
4126 }
4127 $languageConverter = $services->getLanguageConverterFactory()
4128 ->getLanguageConverter( $title->getPageLanguage() );
4129 if ( $languageConverter->hasVariants() ) {
4130 $vars['wgUserVariant'] = $languageConverter->getPreferredVariant();
4131 }
4132 // Same test as SkinTemplate
4133 $vars['wgIsProbablyEditable'] = $this->getAuthority()->probablyCan( 'edit', $title );
4134 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle &&
4135 $this->getAuthority()->probablyCan( 'edit', $relevantTitle );
4136 $restrictionStore = $services->getRestrictionStore();
4137 foreach ( $restrictionStore->listApplicableRestrictionTypes( $title ) as $type ) {
4138 // Following keys are set in $vars:
4139 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
4140 $vars['wgRestriction' . ucfirst( $type )] = $restrictionStore->getRestrictions( $title, $type );
4141 }
4142 if ( $title->isMainPage() ) {
4143 $vars['wgIsMainPage'] = true;
4144 }
4145
4146 $relevantUser = $sk->getRelevantUser();
4147 if ( $relevantUser ) {
4148 $vars['wgRelevantUserName'] = $relevantUser->getName();
4149 }
4150 // End of stable config vars
4151
4152 $titleFormatter = $services->getTitleFormatter();
4153
4154 if ( $this->mRedirectedFrom ) {
4155 // @internal For skin JS
4156 $vars['wgRedirectedFrom'] = $titleFormatter->getPrefixedDBkey( $this->mRedirectedFrom );
4157 }
4158
4159 // Allow extensions to add their custom variables to the mw.config map.
4160 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
4161 // page-dependent but site-wide (without state).
4162 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
4163 $this->getHookRunner()->onMakeGlobalVariablesScript( $vars, $this );
4164
4165 // Merge in variables from addJsConfigVars last
4166 $vars = array_merge( $vars, $this->getJsConfigVars() );
4167
4168 // Return only early or late vars if requested
4169 if ( $flag !== null ) {
4170 $lateVarNames =
4171 array_fill_keys( self::CORE_LATE_JS_CONFIG_VAR_NAMES, true ) +
4172 array_fill_keys( ExtensionRegistry::getInstance()->getAttribute( 'LateJSConfigVarNames' ), true );
4173 foreach ( $vars as $name => $_ ) {
4174 // If the variable's late flag doesn't match the requested late flag, unset it
4175 if ( isset( $lateVarNames[ $name ] ) !== ( $flag === self::JS_VAR_LATE ) ) {
4176 unset( $vars[ $name ] );
4177 }
4178 }
4179 }
4180
4181 return $vars;
4182 }
4183
4184 /**
4185 * Get the revision ID for the last user talk page revision viewed by the talk page owner.
4186 *
4187 * @return int|null
4188 */
4189 private function getLastSeenUserTalkRevId() {
4190 $services = MediaWikiServices::getInstance();
4191 $user = $this->getUser();
4192 $userHasNewMessages = $services
4193 ->getTalkPageNotificationManager()
4194 ->userHasNewMessages( $user );
4195 if ( !$userHasNewMessages ) {
4196 return null;
4197 }
4198
4199 $timestamp = $services
4200 ->getTalkPageNotificationManager()
4201 ->getLatestSeenMessageTimestamp( $user );
4202 if ( !$timestamp ) {
4203 return null;
4204 }
4205
4206 $revRecord = $services->getRevisionLookup()->getRevisionByTimestamp(
4207 $user->getTalkPage(),
4208 $timestamp
4209 );
4210 return $revRecord ? $revRecord->getId() : null;
4211 }
4212
4213 /**
4214 * To make it harder for someone to slip a user a fake
4215 * JavaScript or CSS preview, a random token
4216 * is associated with the login session. If it's not
4217 * passed back with the preview request, we won't render
4218 * the code.
4219 *
4220 * @return bool
4221 */
4222 public function userCanPreview() {
4223 $request = $this->getRequest();
4224 if (
4225 $request->getRawVal( 'action' ) !== 'submit' ||
4226 !$request->wasPosted()
4227 ) {
4228 return false;
4229 }
4230
4231 $user = $this->getUser();
4232
4233 if ( !$user->isRegistered() ) {
4234 // Anons have predictable edit tokens
4235 return false;
4236 }
4237 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
4238 return false;
4239 }
4240
4241 $title = $this->getTitle();
4242 if ( !$this->getAuthority()->probablyCan( 'edit', $title ) ) {
4243 return false;
4244 }
4245
4246 return true;
4247 }
4248
4249 /**
4250 * @return array Array in format "link name or number => 'link html'".
4251 */
4252 public function getHeadLinksArray() {
4253 $tags = [];
4254 $config = $this->getConfig();
4255
4256 if ( $this->cspOutputMode === self::CSP_META ) {
4257 foreach ( $this->CSP->getDirectives() as $header => $directive ) {
4258 $tags["meta-csp-$header"] = Html::element( 'meta', [
4259 'http-equiv' => $header,
4260 'content' => $directive,
4261 ] );
4262 }
4263 }
4264
4265 $tags['meta-generator'] = Html::element( 'meta', [
4266 'name' => 'generator',
4267 'content' => 'MediaWiki ' . MW_VERSION,
4268 ] );
4269
4270 if ( $config->get( MainConfigNames::ReferrerPolicy ) !== false ) {
4271 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
4272 // fallbacks should come before the primary value so we need to reverse the array.
4273 foreach ( array_reverse( (array)$config->get( MainConfigNames::ReferrerPolicy ) ) as $i => $policy ) {
4274 $tags["meta-referrer-$i"] = Html::element( 'meta', [
4275 'name' => 'referrer',
4276 'content' => $policy,
4277 ] );
4278 }
4279 }
4280
4281 $p = $this->getRobotsContent();
4282 if ( $p ) {
4283 // http://www.robotstxt.org/wc/meta-user.html
4284 // Only show if it's different from the default robots policy
4285 $tags['meta-robots'] = Html::element( 'meta', [
4286 'name' => 'robots',
4287 'content' => $p,
4288 ] );
4289 }
4290
4291 # Browser based phonenumber detection
4292 if ( $config->get( MainConfigNames::BrowserFormatDetection ) !== false ) {
4293 $tags['meta-format-detection'] = Html::element( 'meta', [
4294 'name' => 'format-detection',
4295 'content' => $config->get( MainConfigNames::BrowserFormatDetection ),
4296 ] );
4297 }
4298
4299 foreach ( $this->mMetatags as [ $name, $val ] ) {
4300 $attrs = [];
4301 if ( strncasecmp( $name, 'http:', 5 ) === 0 ) {
4302 $name = substr( $name, 5 );
4303 $attrs['http-equiv'] = $name;
4304 } elseif ( strncasecmp( $name, 'og:', 3 ) === 0 ) {
4305 $attrs['property'] = $name;
4306 } else {
4307 $attrs['name'] = $name;
4308 }
4309 $attrs['content'] = $val;
4310 $tagName = "meta-$name";
4311 if ( isset( $tags[$tagName] ) ) {
4312 $tagName .= $val;
4313 }
4314 $tags[$tagName] = Html::element( 'meta', $attrs );
4315 }
4316
4317 foreach ( $this->mLinktags as $tag ) {
4318 $tags[] = Html::element( 'link', $tag );
4319 }
4320
4321 if ( $config->get( MainConfigNames::UniversalEditButton ) && $this->isArticleRelated() ) {
4322 if ( $this->getAuthority()->probablyCan( 'edit', $this->getTitle() ) ) {
4323 $msg = $this->msg( 'edit' )->text();
4324 // Use mime type per https://phabricator.wikimedia.org/T21165#6946526
4325 $tags['universal-edit-button'] = Html::element( 'link', [
4326 'rel' => 'alternate',
4327 'type' => 'application/x-wiki',
4328 'title' => $msg,
4329 'href' => $this->getTitle()->getEditURL(),
4330 ] );
4331 }
4332 }
4333
4334 # Generally the order of the favicon and apple-touch-icon links
4335 # should not matter, but Konqueror (3.5.9 at least) incorrectly
4336 # uses whichever one appears later in the HTML source. Make sure
4337 # apple-touch-icon is specified first to avoid this.
4338 $appleTouchIconHref = $config->get( MainConfigNames::AppleTouchIcon );
4339 # Browser look for those by default, unnessecary to set a link tag
4340 if (
4341 $appleTouchIconHref !== false &&
4342 $appleTouchIconHref !== '/apple-touch-icon.png' &&
4343 $appleTouchIconHref !== '/apple-touch-icon-precomposed.png'
4344 ) {
4345 $tags['apple-touch-icon'] = Html::element( 'link', [
4346 'rel' => 'apple-touch-icon',
4347 'href' => $appleTouchIconHref
4348 ] );
4349 }
4350
4351 $faviconHref = $config->get( MainConfigNames::Favicon );
4352 # Browser look for those by default, unnessecary to set a link tag
4353 if ( $faviconHref !== false && $faviconHref !== '/favicon.ico' ) {
4354 $tags['favicon'] = Html::element( 'link', [
4355 'rel' => 'icon',
4356 'href' => $faviconHref
4357 ] );
4358 }
4359
4360 # OpenSearch description link
4361 $tags['opensearch'] = Html::element( 'link', [
4362 'rel' => 'search',
4363 'type' => 'application/opensearchdescription+xml',
4364 'href' => wfScript( 'rest' ) . '/v1/search',
4365 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
4366 ] );
4367
4368 $services = MediaWikiServices::getInstance();
4369
4370 # Real Simple Discovery link, provides auto-discovery information
4371 # for the MediaWiki API (and potentially additional custom API
4372 # support such as WordPress or Twitter-compatible APIs for a
4373 # blogging extension, etc)
4374 $tags['rsd'] = Html::element( 'link', [
4375 'rel' => 'EditURI',
4376 'type' => 'application/rsd+xml',
4377 // Output a protocol-relative URL here if $wgServer is protocol-relative.
4378 // Whether RSD accepts relative or protocol-relative URLs is completely
4379 // undocumented, though.
4380 'href' => (string)$services->getUrlUtils()->expand( wfAppendQuery(
4381 wfScript( 'api' ),
4382 [ 'action' => 'rsd' ] ),
4383 PROTO_RELATIVE
4384 ),
4385 ] );
4386
4387 $tags = array_merge(
4388 $tags,
4389 $this->getHeadLinksCanonicalURLArray( $config ),
4390 $this->getHeadLinksAlternateURLsArray(),
4391 $this->getHeadLinksCopyrightArray( $config ),
4392 $this->getHeadLinksSyndicationArray( $config ),
4393 );
4394
4395 // Allow extensions to add, remove and/or otherwise manipulate these links
4396 // If you want only to *add* <head> links, please use the addHeadItem()
4397 // (or addHeadItems() for multiple items) method instead.
4398 // This hook is provided as a last resort for extensions to modify these
4399 // links before the output is sent to client.
4400 $this->getHookRunner()->onOutputPageAfterGetHeadLinksArray( $tags, $this );
4401
4402 return $tags;
4403 }
4404
4405 /**
4406 * Canonical URL and alternate URLs
4407 *
4408 * isCanonicalUrlAction affects all requests where "setArticleRelated" is true.
4409 * This is typically all requests that show content (query title, curid, oldid, diff),
4410 * and all wikipage actions (edit, delete, purge, info, history etc.).
4411 * It does not apply to file pages and special pages.
4412 * 'history' and 'info' actions address page metadata rather than the page
4413 * content itself, so they may not be canonicalized to the view page url.
4414 * TODO: this logic should be owned by Action subclasses.
4415 * See T67402
4416 */
4417
4418 /**
4419 * Get head links relating to the canonical URL
4420 * Note: There should only be one canonical URL.
4421 * @param Config $config
4422 * @return array
4423 */
4424 private function getHeadLinksCanonicalURLArray( Config $config ) {
4425 $tags = [];
4426 $canonicalUrl = $this->mCanonicalUrl;
4427
4428 if ( $config->get( MainConfigNames::EnableCanonicalServerLink ) ) {
4429 $query = [];
4430 $action = $this->getContext()->getActionName();
4431 $isCanonicalUrlAction = in_array( $action, [ 'history', 'info' ] );
4432 $services = MediaWikiServices::getInstance();
4433 $languageConverterFactory = $services->getLanguageConverterFactory();
4434 $isLangConversionDisabled = $languageConverterFactory->isConversionDisabled();
4435 $pageLang = $this->getTitle()->getPageLanguage();
4436 $pageLanguageConverter = $languageConverterFactory->getLanguageConverter( $pageLang );
4437 $urlVariant = $pageLanguageConverter->getURLVariant();
4438
4439 if ( $canonicalUrl !== false ) {
4440 $canonicalUrl = (string)$services->getUrlUtils()->expand( $canonicalUrl, PROTO_CANONICAL );
4441 } elseif ( $this->isArticleRelated() ) {
4442 if ( $isCanonicalUrlAction ) {
4443 $query['action'] = $action;
4444 } elseif ( !$isLangConversionDisabled && $urlVariant ) {
4445 # T54429, T108443: Making canonical URL language-variant-aware.
4446 $query['variant'] = $urlVariant;
4447 }
4448 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
4449 } else {
4450 $reqUrl = $this->getRequest()->getRequestURL();
4451 $canonicalUrl = (string)$services->getUrlUtils()->expand( $reqUrl, PROTO_CANONICAL );
4452 }
4453 }
4454
4455 if ( $canonicalUrl !== false ) {
4456 $tags['link-canonical'] = Html::element( 'link', [
4457 'rel' => 'canonical',
4458 'href' => $canonicalUrl
4459 ] );
4460 }
4461
4462 return $tags;
4463 }
4464
4465 /**
4466 * Get head links relating to alternate URL(s) in languages including language variants
4467 * Output fully-qualified URL since meta alternate URLs must be fully-qualified
4468 * Per https://developers.google.com/search/docs/advanced/crawling/localized-versions
4469 * See T294716
4470 *
4471 * @return array
4472 */
4473 private function getHeadLinksAlternateURLsArray() {
4474 $tags = [];
4475 $languageUrls = [];
4476 $action = $this->getContext()->getActionName();
4477 $isCanonicalUrlAction = in_array( $action, [ 'history', 'info' ] );
4478 $services = MediaWikiServices::getInstance();
4479 $languageConverterFactory = $services->getLanguageConverterFactory();
4480 $isLangConversionDisabled = $languageConverterFactory->isConversionDisabled();
4481 $pageLang = $this->getTitle()->getPageLanguage();
4482 $pageLanguageConverter = $languageConverterFactory->getLanguageConverter( $pageLang );
4483
4484 # Language variants
4485 if (
4486 $this->isArticleRelated() &&
4487 !$isCanonicalUrlAction &&
4488 $pageLanguageConverter->hasVariants() &&
4489 !$isLangConversionDisabled
4490 ) {
4491 $variants = $pageLanguageConverter->getVariants();
4492 foreach ( $variants as $variant ) {
4493 $bcp47 = LanguageCode::bcp47( $variant );
4494 $languageUrls[$bcp47] = $this->getTitle()
4495 ->getFullURL( [ 'variant' => $variant ], false, PROTO_CURRENT );
4496 }
4497 }
4498
4499 # Alternate URLs for interlanguage links would be handeled in HTML body tag instead of
4500 # head tag, see T326829.
4501
4502 if ( $languageUrls ) {
4503 # Force the alternate URL of page language code to be self.
4504 # T123901, T305540, T108443: Override mixed-variant variant link in language variant links.
4505 $currentUrl = $this->getTitle()->getFullURL( [], false, PROTO_CURRENT );
4506 $pageLangCodeBcp47 = LanguageCode::bcp47( $pageLang->getCode() );
4507 $languageUrls[$pageLangCodeBcp47] = $currentUrl;
4508
4509 ksort( $languageUrls );
4510
4511 # Also add x-default link per https://support.google.com/webmasters/answer/189077?hl=en
4512 $languageUrls['x-default'] = $currentUrl;
4513
4514 # Process all of language variants and interlanguage links
4515 foreach ( $languageUrls as $bcp47 => $languageUrl ) {
4516 $bcp47lowercase = strtolower( $bcp47 );
4517 $tags['link-alternate-language-' . $bcp47lowercase] = Html::element( 'link', [
4518 'rel' => 'alternate',
4519 'hreflang' => $bcp47,
4520 'href' => $languageUrl,
4521 ] );
4522 }
4523 }
4524
4525 return $tags;
4526 }
4527
4528 /**
4529 * Get head links relating to copyright
4530 *
4531 * @param Config $config
4532 * @return array
4533 */
4534 private function getHeadLinksCopyrightArray( Config $config ) {
4535 $tags = [];
4536
4537 if ( $this->copyrightUrl !== null ) {
4538 $copyright = $this->copyrightUrl;
4539 } else {
4540 $copyright = '';
4541 if ( $config->get( MainConfigNames::RightsPage ) ) {
4542 $copy = Title::newFromText( $config->get( MainConfigNames::RightsPage ) );
4543
4544 if ( $copy ) {
4545 $copyright = $copy->getLocalURL();
4546 }
4547 }
4548
4549 if ( !$copyright && $config->get( MainConfigNames::RightsUrl ) ) {
4550 $copyright = $config->get( MainConfigNames::RightsUrl );
4551 }
4552 }
4553
4554 if ( $copyright ) {
4555 $tags['copyright'] = Html::element( 'link', [
4556 'rel' => 'license',
4557 'href' => $copyright
4558 ] );
4559 }
4560
4561 return $tags;
4562 }
4563
4564 /**
4565 * Get head links relating to syndication feeds.
4566 *
4567 * @param Config $config
4568 * @return array
4569 */
4570 private function getHeadLinksSyndicationArray( Config $config ) {
4571 if ( !$config->get( MainConfigNames::Feed ) ) {
4572 return [];
4573 }
4574
4575 $tags = [];
4576 $feedLinks = [];
4577
4578 foreach ( $this->getSyndicationLinks() as $format => $link ) {
4579 # Use the page name for the title. In principle, this could
4580 # lead to issues with having the same name for different feeds
4581 # corresponding to the same page, but we can't avoid that at
4582 # this low a level.
4583
4584 $feedLinks[] = $this->feedLink(
4585 $format,
4586 $link,
4587 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
4588 $this->msg(
4589 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
4590 )->text()
4591 );
4592 }
4593
4594 # Recent changes feed should appear on every page (except recentchanges,
4595 # that would be redundant). Put it after the per-page feed to avoid
4596 # changing existing behavior. It's still available, probably via a
4597 # menu in your browser. Some sites might have a different feed they'd
4598 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
4599 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
4600 # If so, use it instead.
4601 $sitename = $config->get( MainConfigNames::Sitename );
4602 $overrideSiteFeed = $config->get( MainConfigNames::OverrideSiteFeed );
4603 if ( $overrideSiteFeed ) {
4604 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
4605 // Note, this->feedLink escapes the url.
4606 $feedLinks[] = $this->feedLink(
4607 $type,
4608 $feedUrl,
4609 $this->msg( "site-{$type}-feed", $sitename )->text()
4610 );
4611 }
4612 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
4613 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
4614 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
4615 $feedLinks[] = $this->feedLink(
4616 $format,
4617 $rctitle->getLocalURL( [ 'feed' => $format ] ),
4618 # For grep: 'site-rss-feed', 'site-atom-feed'
4619 $this->msg( "site-{$format}-feed", $sitename )->text()
4620 );
4621 }
4622 }
4623
4624 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
4625 # manipulating or removing existing feed tags. If you want to add new feeds, you should
4626 # use OutputPage::addFeedLink() instead.
4627 $this->getHookRunner()->onAfterBuildFeedLinks( $feedLinks );
4628
4629 $tags += $feedLinks;
4630
4631 return $tags;
4632 }
4633
4634 /**
4635 * Generate a "<link rel/>" for a feed.
4636 *
4637 * @param string $type Feed type
4638 * @param string $url URL to the feed
4639 * @param string $text Value of the "title" attribute
4640 * @return string HTML fragment
4641 */
4642 private function feedLink( $type, $url, $text ) {
4643 return Html::element( 'link', [
4644 'rel' => 'alternate',
4645 'type' => "application/$type+xml",
4646 'title' => $text,
4647 'href' => $url ]
4648 );
4649 }
4650
4651 /**
4652 * Add a local or specified stylesheet, with the given media options.
4653 * Internal use only. Use OutputPage::addModuleStyles() if possible.
4654 *
4655 * @param string $style URL to the file
4656 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
4657 * @param string $condition For IE conditional comments, specifying an IE version
4658 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
4659 */
4660 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
4661 $options = [];
4662 if ( $media ) {
4663 $options['media'] = $media;
4664 }
4665 if ( $condition ) {
4666 $options['condition'] = $condition;
4667 }
4668 if ( $dir ) {
4669 $options['dir'] = $dir;
4670 }
4671 $this->styles[$style] = $options;
4672 }
4673
4674 /**
4675 * Adds inline CSS styles
4676 * Internal use only. Use OutputPage::addModuleStyles() if possible.
4677 *
4678 * @param mixed $style_css Inline CSS
4679 * @param-taint $style_css exec_html
4680 * @param string $flip Set to 'flip' to flip the CSS if needed
4681 */
4682 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
4683 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
4684 # If wanted, and the interface is right-to-left, flip the CSS
4685 $style_css = CSSJanus::transform( $style_css, true, false );
4686 }
4687 $this->mInlineStyles .= Html::inlineStyle( $style_css );
4688 }
4689
4690 /**
4691 * Build exempt modules and legacy non-ResourceLoader styles.
4692 *
4693 * @return string|WrappedStringList HTML
4694 */
4695 protected function buildExemptModules() {
4696 $chunks = [];
4697
4698 // Requirements:
4699 // - Within modules provided by the software (core, skin, extensions),
4700 // styles from skin stylesheets should be overridden by styles
4701 // from modules dynamically loaded with JavaScript.
4702 // - Styles from site-specific, private, and user modules should override
4703 // both of the above.
4704 //
4705 // The effective order for stylesheets must thus be:
4706 // 1. Page style modules, formatted server-side by RL\ClientHtml.
4707 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
4708 // 3. Styles that are site-specific, private or from the user, formatted
4709 // server-side by this function.
4710 //
4711 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
4712 // point #2 is.
4713
4714 // Add legacy styles added through addStyle()/addInlineStyle() here
4715 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
4716
4717 // Things that go after the ResourceLoaderDynamicStyles marker
4718 $append = [];
4719 $separateReq = [ 'site.styles', 'user.styles' ];
4720 foreach ( $this->rlExemptStyleModules as $moduleNames ) {
4721 if ( $moduleNames ) {
4722 $append[] = $this->makeResourceLoaderLink(
4723 array_diff( $moduleNames, $separateReq ),
4724 RL\Module::TYPE_STYLES
4725 );
4726
4727 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
4728 // These require their own dedicated request in order to support "@import"
4729 // syntax, which is incompatible with concatenation. (T147667, T37562)
4730 $append[] = $this->makeResourceLoaderLink( $name,
4731 RL\Module::TYPE_STYLES
4732 );
4733 }
4734 }
4735 }
4736 if ( $append ) {
4737 $chunks[] = Html::element(
4738 'meta',
4739 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
4740 );
4741 $chunks = array_merge( $chunks, $append );
4742 }
4743
4744 return self::combineWrappedStrings( $chunks );
4745 }
4746
4747 /**
4748 * @return array
4749 */
4750 public function buildCssLinksArray() {
4751 $links = [];
4752
4753 foreach ( $this->styles as $file => $options ) {
4754 $link = $this->styleLink( $file, $options );
4755 if ( $link ) {
4756 $links[$file] = $link;
4757 }
4758 }
4759 return $links;
4760 }
4761
4762 /**
4763 * Generate \<link\> tags for stylesheets
4764 *
4765 * @param string $style URL to the file
4766 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
4767 * @return string HTML fragment
4768 */
4769 protected function styleLink( $style, array $options ) {
4770 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
4771 return '';
4772 }
4773
4774 if ( isset( $options['media'] ) ) {
4775 $media = self::transformCssMedia( $options['media'] );
4776 if ( $media === null ) {
4777 return '';
4778 }
4779 } else {
4780 $media = 'all';
4781 }
4782
4783 if ( str_starts_with( $style, '/' ) ||
4784 str_starts_with( $style, 'http:' ) ||
4785 str_starts_with( $style, 'https:' )
4786 ) {
4787 $url = $style;
4788 } else {
4789 $config = $this->getConfig();
4790 // Append file hash as query parameter
4791 $url = self::transformResourcePath(
4792 $config,
4793 $config->get( MainConfigNames::StylePath ) . '/' . $style
4794 );
4795 }
4796
4797 $link = Html::linkedStyle( $url, $media );
4798
4799 if ( isset( $options['condition'] ) ) {
4800 $condition = htmlspecialchars( $options['condition'] );
4801 $link = "<!--[if $condition]>$link<![endif]-->";
4802 }
4803 return $link;
4804 }
4805
4806 /**
4807 * Transform path to web-accessible static resource.
4808 *
4809 * This is used to add a validation hash as query string.
4810 * This aids various behaviors:
4811 *
4812 * - Put long Cache-Control max-age headers on responses for improved
4813 * cache performance.
4814 * - Get the correct version of a file as expected by the current page.
4815 * - Instantly get the updated version of a file after deployment.
4816 *
4817 * Avoid using this for urls included in HTML as otherwise clients may get different
4818 * versions of a resource when navigating the site depending on when the page was cached.
4819 * If changes to the url propagate, this is not a problem (e.g. if the url is in
4820 * an external stylesheet).
4821 *
4822 * @since 1.27
4823 * @param Config $config
4824 * @param string $path Path-absolute URL to file (from document root, must start with "/")
4825 * @return string URL
4826 */
4827 public static function transformResourcePath( Config $config, $path ) {
4828 $localDir = $config->get( MainConfigNames::BaseDirectory );
4829 $remotePathPrefix = $config->get( MainConfigNames::ResourceBasePath );
4830 if ( $remotePathPrefix === '' ) {
4831 // The configured base path is required to be empty string for
4832 // wikis in the domain root
4833 $remotePath = '/';
4834 } else {
4835 $remotePath = $remotePathPrefix;
4836 }
4837 if ( !str_starts_with( $path, $remotePath ) || str_starts_with( $path, '//' ) ) {
4838 // - Path is outside wgResourceBasePath, ignore.
4839 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
4840 return $path;
4841 }
4842 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
4843 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
4844 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
4845 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
4846 $uploadPath = $config->get( MainConfigNames::UploadPath );
4847 if ( strpos( $path, $uploadPath ) === 0 ) {
4848 $localDir = $config->get( MainConfigNames::UploadDirectory );
4849 $remotePathPrefix = $remotePath = $uploadPath;
4850 }
4851
4852 $path = RelPath::getRelativePath( $path, $remotePath );
4853 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
4854 }
4855
4856 /**
4857 * Utility method for transformResourceFilePath().
4858 *
4859 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
4860 *
4861 * @since 1.27
4862 * @param string $remotePathPrefix URL path prefix that points to $localPath
4863 * @param string $localPath File directory exposed at $remotePath
4864 * @param string $file Path to target file relative to $localPath
4865 * @return string URL
4866 */
4867 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
4868 // This MUST match the equivalent logic in CSSMin::remapOne()
4869 $localFile = "$localPath/$file";
4870 $url = "$remotePathPrefix/$file";
4871 if ( is_file( $localFile ) ) {
4872 $hash = md5_file( $localFile );
4873 if ( $hash === false ) {
4874 wfLogWarning( __METHOD__ . ": Failed to hash $localFile" );
4875 $hash = '';
4876 }
4877 $url .= '?' . substr( $hash, 0, 5 );
4878 }
4879 return $url;
4880 }
4881
4882 /**
4883 * Transform "media" attribute based on request parameters
4884 *
4885 * @param string $media Current value of the "media" attribute
4886 * @return string|null Modified value of the "media" attribute, or null to disable
4887 * this stylesheet
4888 */
4889 public static function transformCssMedia( $media ) {
4890 global $wgRequest;
4891
4892 if ( $wgRequest->getBool( 'printable' ) ) {
4893 // When browsing with printable=yes, apply "print" media styles
4894 // as if they are screen styles (no media, media="").
4895 if ( $media === 'print' ) {
4896 return '';
4897 }
4898
4899 // https://www.w3.org/TR/css3-mediaqueries/#syntax
4900 //
4901 // This regex will not attempt to understand a comma-separated media_query_list
4902 // Example supported values for $media:
4903 //
4904 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
4905 //
4906 // Example NOT supported value for $media:
4907 //
4908 // '3d-glasses, screen, print and resolution > 90dpi'
4909 //
4910 // If it's a "printable" request, we disable all screen stylesheets.
4911 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
4912 if ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
4913 return null;
4914 }
4915 }
4916
4917 return $media;
4918 }
4919
4920 /**
4921 * Add a wikitext-formatted message to the output.
4922 *
4923 * @param string|MessageSpecifier $name Message key
4924 * @param mixed ...$args Message parameters. Unlike wfMessage(), this method only accepts
4925 * variadic parameters (they can't be passed as a single array parameter).
4926 */
4927 public function addWikiMsg( $name, ...$args ) {
4928 $this->addWikiMsgArray( $name, $args );
4929 }
4930
4931 /**
4932 * Add a wikitext-formatted message to the output.
4933 *
4934 * @param string|MessageSpecifier $name Message key
4935 * @param array $args Message parameters. Unlike wfMessage(), this method only accepts
4936 * the parameters as an array (they can't be passed as variadic parameters),
4937 * or just a single parameter (this only works by accident, don't rely on it).
4938 */
4939 public function addWikiMsgArray( $name, $args ) {
4940 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
4941 }
4942
4943 /**
4944 * This function takes a number of message/argument specifications, wraps them in
4945 * some overall structure, and then parses the result and adds it to the output.
4946 *
4947 * In the $wrap, $1 is replaced with the first message, $2 with the second,
4948 * and so on. The subsequent arguments may be either
4949 * 1) strings, in which case they are message names, or
4950 * 2) arrays, in which case, within each array, the first element is the message
4951 * name, and subsequent elements are the parameters to that message.
4952 *
4953 * Don't use this for messages that are not in the user's interface language.
4954 *
4955 * For example:
4956 *
4957 * $wgOut->wrapWikiMsg( "<div class='customclass'>\n$1\n</div>", 'some-msg-key' );
4958 *
4959 * Is equivalent to:
4960 *
4961 * $wgOut->addWikiTextAsInterface( "<div class='customclass'>\n"
4962 * . wfMessage( 'some-msg-key' )->plain() . "\n</div>" );
4963 *
4964 * The newline after the opening div is needed in some wikitext. See T21226.
4965 *
4966 * @param string $wrap
4967 * @param mixed ...$msgSpecs
4968 */
4969 public function wrapWikiMsg( $wrap, ...$msgSpecs ) {
4970 $s = $wrap;
4971 foreach ( $msgSpecs as $n => $spec ) {
4972 if ( is_array( $spec ) ) {
4973 $args = $spec;
4974 $name = array_shift( $args );
4975 } else {
4976 $args = [];
4977 $name = $spec;
4978 }
4979 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
4980 }
4981 $this->addWikiTextAsInterface( $s );
4982 }
4983
4984 /**
4985 * Whether the output has a table of contents when the ToC is
4986 * rendered inline.
4987 * @return bool
4988 * @since 1.22
4989 */
4990 public function isTOCEnabled() {
4991 return $this->mEnableTOC;
4992 }
4993
4994 /**
4995 * Helper function to setup the PHP implementation of OOUI to use in this request.
4996 *
4997 * @since 1.26
4998 * @param string|null $skinName Ignored since 1.41
4999 * @param string|null $dir Ignored since 1.41
5000 */
5001 public static function setupOOUI( $skinName = null, $dir = null ) {
5002 if ( !self::$oouiSetupDone ) {
5003 self::$oouiSetupDone = true;
5004 $context = RequestContext::getMain();
5005 $skinName = $context->getSkinName();
5006 $dir = $context->getLanguage()->getDir();
5007 $themes = RL\OOUIFileModule::getSkinThemeMap();
5008 $theme = $themes[$skinName] ?? $themes['default'];
5009 // For example, 'OOUI\WikimediaUITheme'.
5010 $themeClass = "OOUI\\{$theme}Theme";
5011 Theme::setSingleton( new $themeClass() );
5012 Element::setDefaultDir( $dir );
5013 }
5014 }
5015
5016 /**
5017 * Notify of a change in global skin or language which would necessitate
5018 * reinitialization of OOUI global static data.
5019 * @internal
5020 */
5021 public static function resetOOUI() {
5022 if ( self::$oouiSetupDone ) {
5023 self::$oouiSetupDone = false;
5024 self::setupOOUI();
5025 }
5026 }
5027
5028 /**
5029 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
5030 * MediaWiki and this OutputPage instance.
5031 *
5032 * @since 1.25
5033 */
5034 public function enableOOUI() {
5035 self::setupOOUI();
5036 $this->addModuleStyles( [
5037 'oojs-ui-core.styles',
5038 'oojs-ui.styles.indicators',
5039 'mediawiki.widgets.styles',
5040 'oojs-ui-core.icons',
5041 ] );
5042 }
5043
5044 /**
5045 * Get the ContentSecurityPolicy object
5046 *
5047 * @since 1.35
5048 * @return ContentSecurityPolicy
5049 */
5050 public function getCSP() {
5051 return $this->CSP;
5052 }
5053
5054 /**
5055 * Sets the output mechanism for content security policies (HTTP headers or meta tags).
5056 * Defaults to HTTP headers; in most cases this should not be changed.
5057 *
5058 * Meta mode should not be used together with setArticleBodyOnly() as meta tags and other
5059 * headers are not output when that flag is set.
5060 *
5061 * @param string $mode One of the CSP_* constants
5062 * @phan-param 'headers'|'meta' $mode
5063 * @return void
5064 * @see self::CSP_HEADERS
5065 * @see self::CSP_META
5066 */
5067 public function setCspOutputMode( string $mode ): void {
5068 $this->cspOutputMode = $mode;
5069 }
5070
5071 /**
5072 * The final bits that go to the bottom of a page
5073 * HTML document including the closing tags
5074 *
5075 * @internal
5076 * @since 1.37
5077 * @param Skin $skin
5078 * @return string
5079 */
5080 public function tailElement( $skin ) {
5081 $tail = [
5082 MWDebug::getDebugHTML( $skin ),
5083 $this->getBottomScripts(),
5084 MWDebug::getHTMLDebugLog(),
5085 Html::closeElement( 'body' ),
5086 Html::closeElement( 'html' ),
5087 ];
5088
5089 return WrappedStringList::join( "\n", $tail );
5090 }
5091 }
5092
5093 /** @deprecated class alias since 1.41 */
5094 class_alias( OutputPage::class, 'OutputPage' );