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