Merge "Declare dynamic properties"
[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 # We'll purge the proxy cache for anons explicitly, but require end user agents
2418 # to revalidate against the proxy on each visit.
2419 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2420 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2421 wfDebug( __METHOD__ .
2422 ": local proxy caching; {$this->mLastModified} **", 'private' );
2423 # start with a shorter timeout for initial testing
2424 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2425 $response->header( "Cache-Control: " .
2426 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2427 } else {
2428 # We do want clients to cache if they can, but they *must* check for updates
2429 # on revisiting the page.
2430 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2431 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2432 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2433 }
2434 if ( $this->mLastModified ) {
2435 $response->header( "Last-Modified: {$this->mLastModified}" );
2436 }
2437 } else {
2438 wfDebug( __METHOD__ . ": no caching **", 'private' );
2439
2440 # In general, the absence of a last modified header should be enough to prevent
2441 # the client from using its cache. We send a few other things just to make sure.
2442 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2443 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2444 $response->header( 'Pragma: no-cache' );
2445 }
2446 }
2447
2448 /**
2449 * Transfer styles and JavaScript modules from skin.
2450 *
2451 * @param Skin $sk to load modules for
2452 */
2453 public function loadSkinModules( $sk ) {
2454 foreach ( $sk->getDefaultModules() as $group => $modules ) {
2455 if ( $group === 'styles' ) {
2456 foreach ( $modules as $key => $moduleMembers ) {
2457 $this->addModuleStyles( $moduleMembers );
2458 }
2459 } else {
2460 $this->addModules( $modules );
2461 }
2462 }
2463 }
2464
2465 /**
2466 * Finally, all the text has been munged and accumulated into
2467 * the object, let's actually output it:
2468 *
2469 * @param bool $return Set to true to get the result as a string rather than sending it
2470 * @return string|null
2471 * @throws Exception
2472 * @throws FatalError
2473 * @throws MWException
2474 */
2475 public function output( $return = false ) {
2476 if ( $this->mDoNothing ) {
2477 return $return ? '' : null;
2478 }
2479
2480 $response = $this->getRequest()->response();
2481 $config = $this->getConfig();
2482
2483 if ( $this->mRedirect != '' ) {
2484 # Standards require redirect URLs to be absolute
2485 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2486
2487 $redirect = $this->mRedirect;
2488 $code = $this->mRedirectCode;
2489
2490 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2491 if ( $code == '301' || $code == '303' ) {
2492 if ( !$config->get( 'DebugRedirects' ) ) {
2493 $response->statusHeader( $code );
2494 }
2495 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2496 }
2497 if ( $config->get( 'VaryOnXFP' ) ) {
2498 $this->addVaryHeader( 'X-Forwarded-Proto' );
2499 }
2500 $this->sendCacheControl();
2501
2502 $response->header( "Content-Type: text/html; charset=utf-8" );
2503 if ( $config->get( 'DebugRedirects' ) ) {
2504 $url = htmlspecialchars( $redirect );
2505 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2506 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2507 print "</body>\n</html>\n";
2508 } else {
2509 $response->header( 'Location: ' . $redirect );
2510 }
2511 }
2512
2513 return $return ? '' : null;
2514 } elseif ( $this->mStatusCode ) {
2515 $response->statusHeader( $this->mStatusCode );
2516 }
2517
2518 # Buffer output; final headers may depend on later processing
2519 ob_start();
2520
2521 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2522 $response->header( 'Content-language: ' .
2523 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
2524
2525 $linkHeader = $this->getLinkHeader();
2526 if ( $linkHeader ) {
2527 $response->header( $linkHeader );
2528 }
2529
2530 // Prevent framing, if requested
2531 $frameOptions = $this->getFrameOptions();
2532 if ( $frameOptions ) {
2533 $response->header( "X-Frame-Options: $frameOptions" );
2534 }
2535
2536 $originTrials = $this->getOriginTrials();
2537 foreach ( $originTrials as $originTrial ) {
2538 $response->header( "Origin-Trial: $originTrial", false );
2539 }
2540
2541 $reportTo = $this->getReportTo();
2542 if ( $reportTo ) {
2543 $response->header( "Report-To: $reportTo" );
2544 }
2545
2546 $featurePolicyReportOnly = $this->getFeaturePolicyReportOnly();
2547 if ( $featurePolicyReportOnly ) {
2548 $response->header( "Feature-Policy-Report-Only: $featurePolicyReportOnly" );
2549 }
2550
2551 ContentSecurityPolicy::sendHeaders( $this );
2552
2553 if ( $this->mArticleBodyOnly ) {
2554 echo $this->mBodytext;
2555 } else {
2556 // Enable safe mode if requested (T152169)
2557 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2558 $this->disallowUserJs();
2559 }
2560
2561 $sk = $this->getSkin();
2562 $this->loadSkinModules( $sk );
2563
2564 MWDebug::addModules( $this );
2565
2566 // Avoid PHP 7.1 warning of passing $this by reference
2567 $outputPage = $this;
2568 // Hook that allows last minute changes to the output page, e.g.
2569 // adding of CSS or Javascript by extensions.
2570 Hooks::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2571
2572 try {
2573 $sk->outputPage();
2574 } catch ( Exception $e ) {
2575 ob_end_clean(); // bug T129657
2576 throw $e;
2577 }
2578 }
2579
2580 try {
2581 // This hook allows last minute changes to final overall output by modifying output buffer
2582 Hooks::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2583 } catch ( Exception $e ) {
2584 ob_end_clean(); // bug T129657
2585 throw $e;
2586 }
2587
2588 $this->sendCacheControl();
2589
2590 if ( $return ) {
2591 return ob_get_clean();
2592 } else {
2593 ob_end_flush();
2594 return null;
2595 }
2596 }
2597
2598 /**
2599 * Prepare this object to display an error page; disable caching and
2600 * indexing, clear the current text and redirect, set the page's title
2601 * and optionally an custom HTML title (content of the "<title>" tag).
2602 *
2603 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2604 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2605 * optional, if not passed the "<title>" attribute will be
2606 * based on $pageTitle
2607 */
2608 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2609 $this->setPageTitle( $pageTitle );
2610 if ( $htmlTitle !== false ) {
2611 $this->setHTMLTitle( $htmlTitle );
2612 }
2613 $this->setRobotPolicy( 'noindex,nofollow' );
2614 $this->setArticleRelated( false );
2615 $this->enableClientCache( false );
2616 $this->mRedirect = '';
2617 $this->clearSubtitle();
2618 $this->clearHTML();
2619 }
2620
2621 /**
2622 * Output a standard error page
2623 *
2624 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2625 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2626 * showErrorPage( 'titlemsg', $messageObject );
2627 * showErrorPage( $titleMessageObject, $messageObject );
2628 *
2629 * @param string|Message $title Message key (string) for page title, or a Message object
2630 * @param string|Message $msg Message key (string) for page text, or a Message object
2631 * @param array $params Message parameters; ignored if $msg is a Message object
2632 */
2633 public function showErrorPage( $title, $msg, $params = [] ) {
2634 if ( !$title instanceof Message ) {
2635 $title = $this->msg( $title );
2636 }
2637
2638 $this->prepareErrorPage( $title );
2639
2640 if ( $msg instanceof Message ) {
2641 if ( $params !== [] ) {
2642 trigger_error( 'Argument ignored: $params. The message parameters argument '
2643 . 'is discarded when the $msg argument is a Message object instead of '
2644 . 'a string.', E_USER_NOTICE );
2645 }
2646 $this->addHTML( $msg->parseAsBlock() );
2647 } else {
2648 $this->addWikiMsgArray( $msg, $params );
2649 }
2650
2651 $this->returnToMain();
2652 }
2653
2654 /**
2655 * Output a standard permission error page
2656 *
2657 * @param array $errors Error message keys or [key, param...] arrays
2658 * @param string|null $action Action that was denied or null if unknown
2659 */
2660 public function showPermissionsErrorPage( array $errors, $action = null ) {
2661 $services = MediaWikiServices::getInstance();
2662 $permissionManager = $services->getPermissionManager();
2663 foreach ( $errors as $key => $error ) {
2664 $errors[$key] = (array)$error;
2665 }
2666
2667 // For some action (read, edit, create and upload), display a "login to do this action"
2668 // error if all of the following conditions are met:
2669 // 1. the user is not logged in
2670 // 2. the only error is insufficient permissions (i.e. no block or something else)
2671 // 3. the error can be avoided simply by logging in
2672
2673 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2674 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2675 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2676 && ( $permissionManager->groupHasPermission( 'user', $action )
2677 || $permissionManager->groupHasPermission( 'autoconfirmed', $action ) )
2678 ) {
2679 $displayReturnto = null;
2680
2681 # Due to T34276, if a user does not have read permissions,
2682 # $this->getTitle() will just give Special:Badtitle, which is
2683 # not especially useful as a returnto parameter. Use the title
2684 # from the request instead, if there was one.
2685 $request = $this->getRequest();
2686 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2687 if ( $action == 'edit' ) {
2688 $msg = 'whitelistedittext';
2689 $displayReturnto = $returnto;
2690 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2691 $msg = 'nocreatetext';
2692 } elseif ( $action == 'upload' ) {
2693 $msg = 'uploadnologintext';
2694 } else { # Read
2695 $msg = 'loginreqpagetext';
2696 $displayReturnto = Title::newMainPage();
2697 }
2698
2699 $query = [];
2700
2701 if ( $returnto ) {
2702 $query['returnto'] = $returnto->getPrefixedText();
2703
2704 if ( !$request->wasPosted() ) {
2705 $returntoquery = $request->getValues();
2706 unset( $returntoquery['title'] );
2707 unset( $returntoquery['returnto'] );
2708 unset( $returntoquery['returntoquery'] );
2709 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2710 }
2711 }
2712
2713 $title = SpecialPage::getTitleFor( 'Userlogin' );
2714 $linkRenderer = $services->getLinkRenderer();
2715 $loginUrl = $title->getLinkURL( $query, false, PROTO_RELATIVE );
2716 $loginLink = $linkRenderer->makeKnownLink(
2717 $title,
2718 $this->msg( 'loginreqlink' )->text(),
2719 [],
2720 $query
2721 );
2722
2723 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2724 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->params( $loginUrl )->parse() );
2725
2726 # Don't return to a page the user can't read otherwise
2727 # we'll end up in a pointless loop
2728 if ( $displayReturnto && $permissionManager->userCan(
2729 'read', $this->getUser(), $displayReturnto
2730 ) ) {
2731 $this->returnToMain( null, $displayReturnto );
2732 }
2733 } else {
2734 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2735 $this->addWikiTextAsInterface( $this->formatPermissionsErrorMessage( $errors, $action ) );
2736 }
2737 }
2738
2739 /**
2740 * Display an error page indicating that a given version of MediaWiki is
2741 * required to use it
2742 *
2743 * @param mixed $version The version of MediaWiki needed to use the page
2744 */
2745 public function versionRequired( $version ) {
2746 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2747
2748 $this->addWikiMsg( 'versionrequiredtext', $version );
2749 $this->returnToMain();
2750 }
2751
2752 /**
2753 * Format a list of error messages
2754 *
2755 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2756 * @param string|null $action Action that was denied or null if unknown
2757 * @return string The wikitext error-messages, formatted into a list.
2758 */
2759 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2760 if ( $action == null ) {
2761 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2762 } else {
2763 $action_desc = $this->msg( "action-$action" )->plain();
2764 $text = $this->msg(
2765 'permissionserrorstext-withaction',
2766 count( $errors ),
2767 $action_desc
2768 )->plain() . "\n\n";
2769 }
2770
2771 if ( count( $errors ) > 1 ) {
2772 $text .= '<ul class="permissions-errors">' . "\n";
2773
2774 foreach ( $errors as $error ) {
2775 $text .= '<li>';
2776 $text .= $this->msg( ...$error )->plain();
2777 $text .= "</li>\n";
2778 }
2779 $text .= '</ul>';
2780 } else {
2781 $text .= "<div class=\"permissions-errors\">\n" .
2782 $this->msg( ...reset( $errors ) )->plain() .
2783 "\n</div>";
2784 }
2785
2786 return $text;
2787 }
2788
2789 /**
2790 * Show a warning about replica DB lag
2791 *
2792 * If the lag is higher than $wgSlaveLagCritical seconds,
2793 * then the warning is a bit more obvious. If the lag is
2794 * lower than $wgSlaveLagWarning, then no warning is shown.
2795 *
2796 * @param int $lag Replica lag
2797 */
2798 public function showLagWarning( $lag ) {
2799 $config = $this->getConfig();
2800 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2801 $lag = floor( $lag ); // floor to avoid nano seconds to display
2802 $message = $lag < $config->get( 'SlaveLagCritical' )
2803 ? 'lag-warn-normal'
2804 : 'lag-warn-high';
2805 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2806 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2807 }
2808 }
2809
2810 /**
2811 * Output an error page
2812 *
2813 * @note FatalError exception class provides an alternative.
2814 * @param string $message Error to output. Must be escaped for HTML.
2815 */
2816 public function showFatalError( $message ) {
2817 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2818
2819 $this->addHTML( $message );
2820 }
2821
2822 /**
2823 * Add a "return to" link pointing to a specified title
2824 *
2825 * @param LinkTarget $title Title to link
2826 * @param array $query Query string parameters
2827 * @param string|null $text Text of the link (input is not escaped)
2828 * @param array $options Options array to pass to Linker
2829 */
2830 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2831 $linkRenderer = MediaWikiServices::getInstance()
2832 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2833 $link = $this->msg( 'returnto' )->rawParams(
2834 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2835 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2836 }
2837
2838 /**
2839 * Add a "return to" link pointing to a specified title,
2840 * or the title indicated in the request, or else the main page
2841 *
2842 * @param mixed|null $unused
2843 * @param Title|string|null $returnto Title or String to return to
2844 * @param string|null $returntoquery Query string for the return to link
2845 */
2846 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2847 if ( $returnto == null ) {
2848 $returnto = $this->getRequest()->getText( 'returnto' );
2849 }
2850
2851 if ( $returntoquery == null ) {
2852 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2853 }
2854
2855 if ( $returnto === '' ) {
2856 $returnto = Title::newMainPage();
2857 }
2858
2859 if ( is_object( $returnto ) ) {
2860 $titleObj = $returnto;
2861 } else {
2862 $titleObj = Title::newFromText( $returnto );
2863 }
2864 // We don't want people to return to external interwiki. That
2865 // might potentially be used as part of a phishing scheme
2866 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
2867 $titleObj = Title::newMainPage();
2868 }
2869
2870 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2871 }
2872
2873 private function getRlClientContext() {
2874 if ( !$this->rlClientContext ) {
2875 $query = ResourceLoader::makeLoaderQuery(
2876 [], // modules; not relevant
2877 $this->getLanguage()->getCode(),
2878 $this->getSkin()->getSkinName(),
2879 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2880 null, // version; not relevant
2881 ResourceLoader::inDebugMode(),
2882 null, // only; not relevant
2883 $this->isPrintable(),
2884 $this->getRequest()->getBool( 'handheld' )
2885 );
2886 $this->rlClientContext = new ResourceLoaderContext(
2887 $this->getResourceLoader(),
2888 new FauxRequest( $query )
2889 );
2890 if ( $this->contentOverrideCallbacks ) {
2891 $this->rlClientContext = new DerivativeResourceLoaderContext( $this->rlClientContext );
2892 $this->rlClientContext->setContentOverrideCallback( function ( Title $title ) {
2893 foreach ( $this->contentOverrideCallbacks as $callback ) {
2894 $content = $callback( $title );
2895 if ( $content !== null ) {
2896 $text = ContentHandler::getContentText( $content );
2897 if ( strpos( $text, '</script>' ) !== false ) {
2898 // Proactively replace this so that we can display a message
2899 // to the user, instead of letting it go to Html::inlineScript(),
2900 // where it would be considered a server-side issue.
2901 $titleFormatted = $title->getPrefixedText();
2902 $content = new JavaScriptContent(
2903 Xml::encodeJsCall( 'mw.log.error', [
2904 "Cannot preview $titleFormatted due to script-closing tag."
2905 ] )
2906 );
2907 }
2908 return $content;
2909 }
2910 }
2911 return null;
2912 } );
2913 }
2914 }
2915 return $this->rlClientContext;
2916 }
2917
2918 /**
2919 * Call this to freeze the module queue and JS config and create a formatter.
2920 *
2921 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2922 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2923 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2924 * the module filters retroactively. Skins and extension hooks may also add modules until very
2925 * late in the request lifecycle.
2926 *
2927 * @return ResourceLoaderClientHtml
2928 */
2929 public function getRlClient() {
2930 if ( !$this->rlClient ) {
2931 $context = $this->getRlClientContext();
2932 $rl = $this->getResourceLoader();
2933 $this->addModules( [
2934 'user',
2935 'user.options',
2936 'user.tokens',
2937 ] );
2938 $this->addModuleStyles( [
2939 'site.styles',
2940 'noscript',
2941 'user.styles',
2942 ] );
2943 $this->getSkin()->setupSkinUserCss( $this );
2944
2945 // Prepare exempt modules for buildExemptModules()
2946 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2947 $exemptStates = [];
2948 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2949
2950 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2951 // Separate user-specific batch for improved cache-hit ratio.
2952 $userBatch = [ 'user.styles', 'user' ];
2953 $siteBatch = array_diff( $moduleStyles, $userBatch );
2954 $dbr = wfGetDB( DB_REPLICA );
2955 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2956 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2957
2958 // Filter out modules handled by buildExemptModules()
2959 $moduleStyles = array_filter( $moduleStyles,
2960 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2961 $module = $rl->getModule( $name );
2962 if ( $module ) {
2963 $group = $module->getGroup();
2964 if ( isset( $exemptGroups[$group] ) ) {
2965 $exemptStates[$name] = 'ready';
2966 if ( !$module->isKnownEmpty( $context ) ) {
2967 // E.g. Don't output empty <styles>
2968 $exemptGroups[$group][] = $name;
2969 }
2970 return false;
2971 }
2972 }
2973 return true;
2974 }
2975 );
2976 $this->rlExemptStyleModules = $exemptGroups;
2977
2978 $rlClient = new ResourceLoaderClientHtml( $context, [
2979 'target' => $this->getTarget(),
2980 'nonce' => $this->getCSPNonce(),
2981 // When 'safemode', disallowUserJs(), or reduceAllowedModules() is used
2982 // to only restrict modules to ORIGIN_CORE (ie. disallow ORIGIN_USER), the list of
2983 // modules enqueud for loading on this page is filtered to just those.
2984 // However, to make sure we also apply the restriction to dynamic dependencies and
2985 // lazy-loaded modules at run-time on the client-side, pass 'safemode' down to the
2986 // StartupModule so that the client-side registry will not contain any restricted
2987 // modules either. (T152169, T185303)
2988 'safemode' => ( $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2989 <= ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
2990 ) ? '1' : null,
2991 ] );
2992 $rlClient->setConfig( $this->getJSVars() );
2993 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2994 $rlClient->setModuleStyles( $moduleStyles );
2995 $rlClient->setExemptStates( $exemptStates );
2996 $this->rlClient = $rlClient;
2997 }
2998 return $this->rlClient;
2999 }
3000
3001 /**
3002 * @param Skin $sk The given Skin
3003 * @param bool $includeStyle Unused
3004 * @return string The doctype, opening "<html>", and head element.
3005 */
3006 public function headElement( Skin $sk, $includeStyle = true ) {
3007 $config = $this->getConfig();
3008 $userdir = $this->getLanguage()->getDir();
3009 $sitedir = MediaWikiServices::getInstance()->getContentLanguage()->getDir();
3010
3011 $pieces = [];
3012 $htmlAttribs = Sanitizer::mergeAttributes(
3013 $this->getRlClient()->getDocumentAttributes(),
3014 $sk->getHtmlElementAttributes()
3015 );
3016 $pieces[] = Html::htmlHeader( $htmlAttribs );
3017 $pieces[] = Html::openElement( 'head' );
3018
3019 if ( $this->getHTMLTitle() == '' ) {
3020 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
3021 }
3022
3023 if ( !Html::isXmlMimeType( $config->get( 'MimeType' ) ) ) {
3024 // Add <meta charset="UTF-8">
3025 // This should be before <title> since it defines the charset used by
3026 // text including the text inside <title>.
3027 // The spec recommends defining XHTML5's charset using the XML declaration
3028 // instead of meta.
3029 // Our XML declaration is output by Html::htmlHeader.
3030 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
3031 // https://html.spec.whatwg.org/multipage/semantics.html#charset
3032 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
3033 }
3034
3035 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
3036 $pieces[] = $this->getRlClient()->getHeadHtml( $htmlAttribs['class'] ?? null );
3037 $pieces[] = $this->buildExemptModules();
3038 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
3039 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
3040
3041 // This library is intended to run on older browsers that MediaWiki no longer
3042 // supports as Grade A. For these Grade C browsers, we provide an experience
3043 // using only HTML and CSS. But, where standards-compliant browsers are able to
3044 // style unknown HTML elements without issue, old IE ignores these styles.
3045 // The html5shiv library fixes that.
3046 // Use an IE conditional comment to serve the script only to old IE
3047 $shivUrl = $config->get( 'ResourceBasePath' ) . '/resources/lib/html5shiv/html5shiv.js';
3048 $pieces[] = '<!--[if lt IE 9]>' .
3049 Html::linkedScript( $shivUrl, $this->getCSPNonce() ) .
3050 '<![endif]-->';
3051
3052 $pieces[] = Html::closeElement( 'head' );
3053
3054 $bodyClasses = $this->mAdditionalBodyClasses;
3055 $bodyClasses[] = 'mediawiki';
3056
3057 # Classes for LTR/RTL directionality support
3058 $bodyClasses[] = $userdir;
3059 $bodyClasses[] = "sitedir-$sitedir";
3060
3061 $underline = $this->getUser()->getOption( 'underline' );
3062 if ( $underline < 2 ) {
3063 // The following classes can be used here:
3064 // * mw-underline-always
3065 // * mw-underline-never
3066 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
3067 }
3068
3069 if ( $this->getLanguage()->capitalizeAllNouns() ) {
3070 # A <body> class is probably not the best way to do this . . .
3071 $bodyClasses[] = 'capitalize-all-nouns';
3072 }
3073
3074 // Parser feature migration class
3075 // The idea is that this will eventually be removed, after the wikitext
3076 // which requires it is cleaned up.
3077 $bodyClasses[] = 'mw-hide-empty-elt';
3078
3079 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
3080 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
3081 $bodyClasses[] =
3082 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
3083
3084 $bodyAttrs = [];
3085 // While the implode() is not strictly needed, it's used for backwards compatibility
3086 // (this used to be built as a string and hooks likely still expect that).
3087 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
3088
3089 // Allow skins and extensions to add body attributes they need
3090 $sk->addToBodyAttributes( $this, $bodyAttrs );
3091 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
3092
3093 $pieces[] = Html::openElement( 'body', $bodyAttrs );
3094
3095 return self::combineWrappedStrings( $pieces );
3096 }
3097
3098 /**
3099 * Get a ResourceLoader object associated with this OutputPage
3100 *
3101 * @return ResourceLoader
3102 */
3103 public function getResourceLoader() {
3104 if ( is_null( $this->mResourceLoader ) ) {
3105 // Lazy-initialise as needed
3106 $this->mResourceLoader = MediaWikiServices::getInstance()->getResourceLoader();
3107 }
3108 return $this->mResourceLoader;
3109 }
3110
3111 /**
3112 * Explicily load or embed modules on a page.
3113 *
3114 * @param array|string $modules One or more module names
3115 * @param string $only ResourceLoaderModule TYPE_ class constant
3116 * @param array $extraQuery [optional] Array with extra query parameters for the request
3117 * @return string|WrappedStringList HTML
3118 */
3119 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3120 // Apply 'target' and 'origin' filters
3121 $modules = $this->filterModules( (array)$modules, null, $only );
3122
3123 return ResourceLoaderClientHtml::makeLoad(
3124 $this->getRlClientContext(),
3125 $modules,
3126 $only,
3127 $extraQuery,
3128 $this->getCSPNonce()
3129 );
3130 }
3131
3132 /**
3133 * Combine WrappedString chunks and filter out empty ones
3134 *
3135 * @param array $chunks
3136 * @return string|WrappedStringList HTML
3137 */
3138 protected static function combineWrappedStrings( array $chunks ) {
3139 // Filter out empty values
3140 $chunks = array_filter( $chunks, 'strlen' );
3141 return WrappedString::join( "\n", $chunks );
3142 }
3143
3144 /**
3145 * JS stuff to put at the bottom of the `<body>`.
3146 * These are legacy scripts ($this->mScripts), and user JS.
3147 *
3148 * @return string|WrappedStringList HTML
3149 */
3150 public function getBottomScripts() {
3151 $chunks = [];
3152 $chunks[] = $this->getRlClient()->getBodyHtml();
3153
3154 // Legacy non-ResourceLoader scripts
3155 $chunks[] = $this->mScripts;
3156
3157 if ( $this->limitReportJSData ) {
3158 $chunks[] = ResourceLoader::makeInlineScript(
3159 ResourceLoader::makeConfigSetScript(
3160 [ 'wgPageParseReport' => $this->limitReportJSData ]
3161 ),
3162 $this->getCSPNonce()
3163 );
3164 }
3165
3166 return self::combineWrappedStrings( $chunks );
3167 }
3168
3169 /**
3170 * Get the javascript config vars to include on this page
3171 *
3172 * @return array Array of javascript config vars
3173 * @since 1.23
3174 */
3175 public function getJsConfigVars() {
3176 return $this->mJsConfigVars;
3177 }
3178
3179 /**
3180 * Add one or more variables to be set in mw.config in JavaScript
3181 *
3182 * @param string|array $keys Key or array of key/value pairs
3183 * @param mixed|null $value [optional] Value of the configuration variable
3184 */
3185 public function addJsConfigVars( $keys, $value = null ) {
3186 if ( is_array( $keys ) ) {
3187 foreach ( $keys as $key => $value ) {
3188 $this->mJsConfigVars[$key] = $value;
3189 }
3190 return;
3191 }
3192
3193 $this->mJsConfigVars[$keys] = $value;
3194 }
3195
3196 /**
3197 * Get an array containing the variables to be set in mw.config in JavaScript.
3198 *
3199 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3200 * - in other words, page-independent/site-wide variables (without state).
3201 * You will only be adding bloat to the html page and causing page caches to
3202 * have to be purged on configuration changes.
3203 * @return array
3204 */
3205 public function getJSVars() {
3206 $curRevisionId = 0;
3207 $articleId = 0;
3208 $canonicalSpecialPageName = false; # T23115
3209 $services = MediaWikiServices::getInstance();
3210
3211 $title = $this->getTitle();
3212 $ns = $title->getNamespace();
3213 $nsInfo = $services->getNamespaceInfo();
3214 $canonicalNamespace = $nsInfo->exists( $ns )
3215 ? $nsInfo->getCanonicalName( $ns )
3216 : $title->getNsText();
3217
3218 $sk = $this->getSkin();
3219 // Get the relevant title so that AJAX features can use the correct page name
3220 // when making API requests from certain special pages (T36972).
3221 $relevantTitle = $sk->getRelevantTitle();
3222 $relevantUser = $sk->getRelevantUser();
3223
3224 if ( $ns == NS_SPECIAL ) {
3225 list( $canonicalSpecialPageName, /*...*/ ) =
3226 $services->getSpecialPageFactory()->
3227 resolveAlias( $title->getDBkey() );
3228 } elseif ( $this->canUseWikiPage() ) {
3229 $wikiPage = $this->getWikiPage();
3230 $curRevisionId = $wikiPage->getLatest();
3231 $articleId = $wikiPage->getId();
3232 }
3233
3234 $lang = $title->getPageViewLanguage();
3235
3236 // Pre-process information
3237 $separatorTransTable = $lang->separatorTransformTable();
3238 $separatorTransTable = $separatorTransTable ?: [];
3239 $compactSeparatorTransTable = [
3240 implode( "\t", array_keys( $separatorTransTable ) ),
3241 implode( "\t", $separatorTransTable ),
3242 ];
3243 $digitTransTable = $lang->digitTransformTable();
3244 $digitTransTable = $digitTransTable ?: [];
3245 $compactDigitTransTable = [
3246 implode( "\t", array_keys( $digitTransTable ) ),
3247 implode( "\t", $digitTransTable ),
3248 ];
3249
3250 $user = $this->getUser();
3251
3252 $vars = [
3253 'wgCanonicalNamespace' => $canonicalNamespace,
3254 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3255 'wgNamespaceNumber' => $title->getNamespace(),
3256 'wgPageName' => $title->getPrefixedDBkey(),
3257 'wgTitle' => $title->getText(),
3258 'wgCurRevisionId' => $curRevisionId,
3259 'wgRevisionId' => (int)$this->getRevisionId(),
3260 'wgArticleId' => $articleId,
3261 'wgIsArticle' => $this->isArticle(),
3262 'wgIsRedirect' => $title->isRedirect(),
3263 'wgAction' => Action::getActionName( $this->getContext() ),
3264 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3265 'wgUserGroups' => $user->getEffectiveGroups(),
3266 'wgCategories' => $this->getCategories(),
3267 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3268 'wgPageContentLanguage' => $lang->getCode(),
3269 'wgPageContentModel' => $title->getContentModel(),
3270 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3271 'wgDigitTransformTable' => $compactDigitTransTable,
3272 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3273 'wgMonthNames' => $lang->getMonthNamesArray(),
3274 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3275 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3276 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3277 'wgRequestId' => WebRequest::getRequestId(),
3278 'wgCSPNonce' => $this->getCSPNonce(),
3279 ];
3280
3281 if ( $user->isLoggedIn() ) {
3282 $vars['wgUserId'] = $user->getId();
3283 $vars['wgUserEditCount'] = $user->getEditCount();
3284 $userReg = $user->getRegistration();
3285 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3286 // Get the revision ID of the oldest new message on the user's talk
3287 // page. This can be used for constructing new message alerts on
3288 // the client side.
3289 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3290 }
3291
3292 $contLang = $services->getContentLanguage();
3293 if ( $contLang->hasVariants() ) {
3294 $vars['wgUserVariant'] = $contLang->getPreferredVariant();
3295 }
3296 // Same test as SkinTemplate
3297 $vars['wgIsProbablyEditable'] = $this->userCanEditOrCreate( $user, $title );
3298
3299 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle &&
3300 $this->userCanEditOrCreate( $user, $relevantTitle );
3301
3302 foreach ( $title->getRestrictionTypes() as $type ) {
3303 // Following keys are set in $vars:
3304 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3305 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3306 }
3307
3308 if ( $title->isMainPage() ) {
3309 $vars['wgIsMainPage'] = true;
3310 }
3311
3312 if ( $this->mRedirectedFrom ) {
3313 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3314 }
3315
3316 if ( $relevantUser ) {
3317 $vars['wgRelevantUserName'] = $relevantUser->getName();
3318 }
3319
3320 // Allow extensions to add their custom variables to the mw.config map.
3321 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3322 // page-dependant but site-wide (without state).
3323 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3324 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3325
3326 // Merge in variables from addJsConfigVars last
3327 return array_merge( $vars, $this->getJsConfigVars() );
3328 }
3329
3330 /**
3331 * To make it harder for someone to slip a user a fake
3332 * JavaScript or CSS preview, a random token
3333 * is associated with the login session. If it's not
3334 * passed back with the preview request, we won't render
3335 * the code.
3336 *
3337 * @return bool
3338 */
3339 public function userCanPreview() {
3340 $request = $this->getRequest();
3341 if (
3342 $request->getVal( 'action' ) !== 'submit' ||
3343 !$request->wasPosted()
3344 ) {
3345 return false;
3346 }
3347
3348 $user = $this->getUser();
3349
3350 if ( !$user->isLoggedIn() ) {
3351 // Anons have predictable edit tokens
3352 return false;
3353 }
3354 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3355 return false;
3356 }
3357
3358 $title = $this->getTitle();
3359 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3360 if ( count( $errors ) !== 0 ) {
3361 return false;
3362 }
3363
3364 return true;
3365 }
3366
3367 /**
3368 * @param User $user
3369 * @param LinkTarget $title
3370 * @return bool
3371 */
3372 private function userCanEditOrCreate(
3373 User $user,
3374 LinkTarget $title
3375 ) {
3376 $pm = MediaWikiServices::getInstance()->getPermissionManager();
3377 return $pm->quickUserCan( 'edit', $user, $title )
3378 && ( $this->getTitle()->exists() ||
3379 $pm->quickUserCan( 'create', $user, $title ) );
3380 }
3381
3382 /**
3383 * @return array Array in format "link name or number => 'link html'".
3384 */
3385 public function getHeadLinksArray() {
3386 global $wgVersion;
3387
3388 $tags = [];
3389 $config = $this->getConfig();
3390
3391 $canonicalUrl = $this->mCanonicalUrl;
3392
3393 $tags['meta-generator'] = Html::element( 'meta', [
3394 'name' => 'generator',
3395 'content' => "MediaWiki $wgVersion",
3396 ] );
3397
3398 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3399 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3400 // fallbacks should come before the primary value so we need to reverse the array.
3401 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3402 $tags["meta-referrer-$i"] = Html::element( 'meta', [
3403 'name' => 'referrer',
3404 'content' => $policy,
3405 ] );
3406 }
3407 }
3408
3409 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3410 if ( $p !== 'index,follow' ) {
3411 // http://www.robotstxt.org/wc/meta-user.html
3412 // Only show if it's different from the default robots policy
3413 $tags['meta-robots'] = Html::element( 'meta', [
3414 'name' => 'robots',
3415 'content' => $p,
3416 ] );
3417 }
3418
3419 foreach ( $this->mMetatags as $tag ) {
3420 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3421 $a = 'http-equiv';
3422 $tag[0] = substr( $tag[0], 5 );
3423 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3424 $a = 'property';
3425 } else {
3426 $a = 'name';
3427 }
3428 $tagName = "meta-{$tag[0]}";
3429 if ( isset( $tags[$tagName] ) ) {
3430 $tagName .= $tag[1];
3431 }
3432 $tags[$tagName] = Html::element( 'meta',
3433 [
3434 $a => $tag[0],
3435 'content' => $tag[1]
3436 ]
3437 );
3438 }
3439
3440 foreach ( $this->mLinktags as $tag ) {
3441 $tags[] = Html::element( 'link', $tag );
3442 }
3443
3444 # Universal edit button
3445 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3446 if ( $this->userCanEditOrCreate( $this->getUser(), $this->getTitle() ) ) {
3447 // Original UniversalEditButton
3448 $msg = $this->msg( 'edit' )->text();
3449 $tags['universal-edit-button'] = Html::element( 'link', [
3450 'rel' => 'alternate',
3451 'type' => 'application/x-wiki',
3452 'title' => $msg,
3453 'href' => $this->getTitle()->getEditURL(),
3454 ] );
3455 // Alternate edit link
3456 $tags['alternative-edit'] = Html::element( 'link', [
3457 'rel' => 'edit',
3458 'title' => $msg,
3459 'href' => $this->getTitle()->getEditURL(),
3460 ] );
3461 }
3462 }
3463
3464 # Generally the order of the favicon and apple-touch-icon links
3465 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3466 # uses whichever one appears later in the HTML source. Make sure
3467 # apple-touch-icon is specified first to avoid this.
3468 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3469 $tags['apple-touch-icon'] = Html::element( 'link', [
3470 'rel' => 'apple-touch-icon',
3471 'href' => $config->get( 'AppleTouchIcon' )
3472 ] );
3473 }
3474
3475 if ( $config->get( 'Favicon' ) !== false ) {
3476 $tags['favicon'] = Html::element( 'link', [
3477 'rel' => 'shortcut icon',
3478 'href' => $config->get( 'Favicon' )
3479 ] );
3480 }
3481
3482 # OpenSearch description link
3483 $tags['opensearch'] = Html::element( 'link', [
3484 'rel' => 'search',
3485 'type' => 'application/opensearchdescription+xml',
3486 'href' => wfScript( 'opensearch_desc' ),
3487 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3488 ] );
3489
3490 # Real Simple Discovery link, provides auto-discovery information
3491 # for the MediaWiki API (and potentially additional custom API
3492 # support such as WordPress or Twitter-compatible APIs for a
3493 # blogging extension, etc)
3494 $tags['rsd'] = Html::element( 'link', [
3495 'rel' => 'EditURI',
3496 'type' => 'application/rsd+xml',
3497 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3498 // Whether RSD accepts relative or protocol-relative URLs is completely
3499 // undocumented, though.
3500 'href' => wfExpandUrl( wfAppendQuery(
3501 wfScript( 'api' ),
3502 [ 'action' => 'rsd' ] ),
3503 PROTO_RELATIVE
3504 ),
3505 ] );
3506
3507 # Language variants
3508 if ( !$config->get( 'DisableLangConversion' ) ) {
3509 $lang = $this->getTitle()->getPageLanguage();
3510 if ( $lang->hasVariants() ) {
3511 $variants = $lang->getVariants();
3512 foreach ( $variants as $variant ) {
3513 $tags["variant-$variant"] = Html::element( 'link', [
3514 'rel' => 'alternate',
3515 'hreflang' => LanguageCode::bcp47( $variant ),
3516 'href' => $this->getTitle()->getLocalURL(
3517 [ 'variant' => $variant ] )
3518 ]
3519 );
3520 }
3521 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3522 $tags["variant-x-default"] = Html::element( 'link', [
3523 'rel' => 'alternate',
3524 'hreflang' => 'x-default',
3525 'href' => $this->getTitle()->getLocalURL() ] );
3526 }
3527 }
3528
3529 # Copyright
3530 if ( $this->copyrightUrl !== null ) {
3531 $copyright = $this->copyrightUrl;
3532 } else {
3533 $copyright = '';
3534 if ( $config->get( 'RightsPage' ) ) {
3535 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3536
3537 if ( $copy ) {
3538 $copyright = $copy->getLocalURL();
3539 }
3540 }
3541
3542 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3543 $copyright = $config->get( 'RightsUrl' );
3544 }
3545 }
3546
3547 if ( $copyright ) {
3548 $tags['copyright'] = Html::element( 'link', [
3549 'rel' => 'license',
3550 'href' => $copyright ]
3551 );
3552 }
3553
3554 # Feeds
3555 if ( $config->get( 'Feed' ) ) {
3556 $feedLinks = [];
3557
3558 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3559 # Use the page name for the title. In principle, this could
3560 # lead to issues with having the same name for different feeds
3561 # corresponding to the same page, but we can't avoid that at
3562 # this low a level.
3563
3564 $feedLinks[] = $this->feedLink(
3565 $format,
3566 $link,
3567 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3568 $this->msg(
3569 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3570 )->text()
3571 );
3572 }
3573
3574 # Recent changes feed should appear on every page (except recentchanges,
3575 # that would be redundant). Put it after the per-page feed to avoid
3576 # changing existing behavior. It's still available, probably via a
3577 # menu in your browser. Some sites might have a different feed they'd
3578 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3579 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3580 # If so, use it instead.
3581 $sitename = $config->get( 'Sitename' );
3582 $overrideSiteFeed = $config->get( 'OverrideSiteFeed' );
3583 if ( $overrideSiteFeed ) {
3584 foreach ( $overrideSiteFeed as $type => $feedUrl ) {
3585 // Note, this->feedLink escapes the url.
3586 $feedLinks[] = $this->feedLink(
3587 $type,
3588 $feedUrl,
3589 $this->msg( "site-{$type}-feed", $sitename )->text()
3590 );
3591 }
3592 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3593 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3594 foreach ( $this->getAdvertisedFeedTypes() as $format ) {
3595 $feedLinks[] = $this->feedLink(
3596 $format,
3597 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3598 # For grep: 'site-rss-feed', 'site-atom-feed'
3599 $this->msg( "site-{$format}-feed", $sitename )->text()
3600 );
3601 }
3602 }
3603
3604 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3605 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3606 # use OutputPage::addFeedLink() instead.
3607 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3608
3609 $tags += $feedLinks;
3610 }
3611
3612 # Canonical URL
3613 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3614 if ( $canonicalUrl !== false ) {
3615 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3616 } elseif ( $this->isArticleRelated() ) {
3617 // This affects all requests where "setArticleRelated" is true. This is
3618 // typically all requests that show content (query title, curid, oldid, diff),
3619 // and all wikipage actions (edit, delete, purge, info, history etc.).
3620 // It does not apply to File pages and Special pages.
3621 // 'history' and 'info' actions address page metadata rather than the page
3622 // content itself, so they may not be canonicalized to the view page url.
3623 // TODO: this ought to be better encapsulated in the Action class.
3624 $action = Action::getActionName( $this->getContext() );
3625 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3626 $query = "action={$action}";
3627 } else {
3628 $query = '';
3629 }
3630 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3631 } else {
3632 $reqUrl = $this->getRequest()->getRequestURL();
3633 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3634 }
3635 }
3636 if ( $canonicalUrl !== false ) {
3637 $tags[] = Html::element( 'link', [
3638 'rel' => 'canonical',
3639 'href' => $canonicalUrl
3640 ] );
3641 }
3642
3643 // Allow extensions to add, remove and/or otherwise manipulate these links
3644 // If you want only to *add* <head> links, please use the addHeadItem()
3645 // (or addHeadItems() for multiple items) method instead.
3646 // This hook is provided as a last resort for extensions to modify these
3647 // links before the output is sent to client.
3648 Hooks::run( 'OutputPageAfterGetHeadLinksArray', [ &$tags, $this ] );
3649
3650 return $tags;
3651 }
3652
3653 /**
3654 * Generate a "<link rel/>" for a feed.
3655 *
3656 * @param string $type Feed type
3657 * @param string $url URL to the feed
3658 * @param string $text Value of the "title" attribute
3659 * @return string HTML fragment
3660 */
3661 private function feedLink( $type, $url, $text ) {
3662 return Html::element( 'link', [
3663 'rel' => 'alternate',
3664 'type' => "application/$type+xml",
3665 'title' => $text,
3666 'href' => $url ]
3667 );
3668 }
3669
3670 /**
3671 * Add a local or specified stylesheet, with the given media options.
3672 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3673 *
3674 * @param string $style URL to the file
3675 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3676 * @param string $condition For IE conditional comments, specifying an IE version
3677 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3678 */
3679 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3680 $options = [];
3681 if ( $media ) {
3682 $options['media'] = $media;
3683 }
3684 if ( $condition ) {
3685 $options['condition'] = $condition;
3686 }
3687 if ( $dir ) {
3688 $options['dir'] = $dir;
3689 }
3690 $this->styles[$style] = $options;
3691 }
3692
3693 /**
3694 * Adds inline CSS styles
3695 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3696 *
3697 * @param mixed $style_css Inline CSS
3698 * @param string $flip Set to 'flip' to flip the CSS if needed
3699 */
3700 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3701 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3702 # If wanted, and the interface is right-to-left, flip the CSS
3703 $style_css = CSSJanus::transform( $style_css, true, false );
3704 }
3705 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3706 }
3707
3708 /**
3709 * Build exempt modules and legacy non-ResourceLoader styles.
3710 *
3711 * @return string|WrappedStringList HTML
3712 */
3713 protected function buildExemptModules() {
3714 $chunks = [];
3715
3716 // Requirements:
3717 // - Within modules provided by the software (core, skin, extensions),
3718 // styles from skin stylesheets should be overridden by styles
3719 // from modules dynamically loaded with JavaScript.
3720 // - Styles from site-specific, private, and user modules should override
3721 // both of the above.
3722 //
3723 // The effective order for stylesheets must thus be:
3724 // 1. Page style modules, formatted server-side by ResourceLoaderClientHtml.
3725 // 2. Dynamically-loaded styles, inserted client-side by mw.loader.
3726 // 3. Styles that are site-specific, private or from the user, formatted
3727 // server-side by this function.
3728 //
3729 // The 'ResourceLoaderDynamicStyles' marker helps JavaScript know where
3730 // point #2 is.
3731
3732 // Add legacy styles added through addStyle()/addInlineStyle() here
3733 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3734
3735 // Things that go after the ResourceLoaderDynamicStyles marker
3736 $append = [];
3737 $separateReq = [ 'site.styles', 'user.styles' ];
3738 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3739 if ( $moduleNames ) {
3740 $append[] = $this->makeResourceLoaderLink(
3741 array_diff( $moduleNames, $separateReq ),
3742 ResourceLoaderModule::TYPE_STYLES
3743 );
3744
3745 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3746 // These require their own dedicated request in order to support "@import"
3747 // syntax, which is incompatible with concatenation. (T147667, T37562)
3748 $append[] = $this->makeResourceLoaderLink( $name,
3749 ResourceLoaderModule::TYPE_STYLES
3750 );
3751 }
3752 }
3753 }
3754 if ( $append ) {
3755 $chunks[] = Html::element(
3756 'meta',
3757 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3758 );
3759 $chunks = array_merge( $chunks, $append );
3760 }
3761
3762 return self::combineWrappedStrings( $chunks );
3763 }
3764
3765 /**
3766 * @return array
3767 */
3768 public function buildCssLinksArray() {
3769 $links = [];
3770
3771 foreach ( $this->styles as $file => $options ) {
3772 $link = $this->styleLink( $file, $options );
3773 if ( $link ) {
3774 $links[$file] = $link;
3775 }
3776 }
3777 return $links;
3778 }
3779
3780 /**
3781 * Generate \<link\> tags for stylesheets
3782 *
3783 * @param string $style URL to the file
3784 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3785 * @return string HTML fragment
3786 */
3787 protected function styleLink( $style, array $options ) {
3788 if ( isset( $options['dir'] ) && $this->getLanguage()->getDir() != $options['dir'] ) {
3789 return '';
3790 }
3791
3792 if ( isset( $options['media'] ) ) {
3793 $media = self::transformCssMedia( $options['media'] );
3794 if ( is_null( $media ) ) {
3795 return '';
3796 }
3797 } else {
3798 $media = 'all';
3799 }
3800
3801 if ( substr( $style, 0, 1 ) == '/' ||
3802 substr( $style, 0, 5 ) == 'http:' ||
3803 substr( $style, 0, 6 ) == 'https:' ) {
3804 $url = $style;
3805 } else {
3806 $config = $this->getConfig();
3807 // Append file hash as query parameter
3808 $url = self::transformResourcePath(
3809 $config,
3810 $config->get( 'StylePath' ) . '/' . $style
3811 );
3812 }
3813
3814 $link = Html::linkedStyle( $url, $media );
3815
3816 if ( isset( $options['condition'] ) ) {
3817 $condition = htmlspecialchars( $options['condition'] );
3818 $link = "<!--[if $condition]>$link<![endif]-->";
3819 }
3820 return $link;
3821 }
3822
3823 /**
3824 * Transform path to web-accessible static resource.
3825 *
3826 * This is used to add a validation hash as query string.
3827 * This aids various behaviors:
3828 *
3829 * - Put long Cache-Control max-age headers on responses for improved
3830 * cache performance.
3831 * - Get the correct version of a file as expected by the current page.
3832 * - Instantly get the updated version of a file after deployment.
3833 *
3834 * Avoid using this for urls included in HTML as otherwise clients may get different
3835 * versions of a resource when navigating the site depending on when the page was cached.
3836 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3837 * an external stylesheet).
3838 *
3839 * @since 1.27
3840 * @param Config $config
3841 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3842 * @return string URL
3843 */
3844 public static function transformResourcePath( Config $config, $path ) {
3845 global $IP;
3846
3847 $localDir = $IP;
3848 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3849 if ( $remotePathPrefix === '' ) {
3850 // The configured base path is required to be empty string for
3851 // wikis in the domain root
3852 $remotePath = '/';
3853 } else {
3854 $remotePath = $remotePathPrefix;
3855 }
3856 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
3857 // - Path is outside wgResourceBasePath, ignore.
3858 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3859 return $path;
3860 }
3861 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3862 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3863 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3864 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3865 $uploadPath = $config->get( 'UploadPath' );
3866 if ( strpos( $path, $uploadPath ) === 0 ) {
3867 $localDir = $config->get( 'UploadDirectory' );
3868 $remotePathPrefix = $remotePath = $uploadPath;
3869 }
3870
3871 $path = RelPath::getRelativePath( $path, $remotePath );
3872 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
3873 }
3874
3875 /**
3876 * Utility method for transformResourceFilePath().
3877 *
3878 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3879 *
3880 * @since 1.27
3881 * @param string $remotePathPrefix URL path prefix that points to $localPath
3882 * @param string $localPath File directory exposed at $remotePath
3883 * @param string $file Path to target file relative to $localPath
3884 * @return string URL
3885 */
3886 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3887 $hash = md5_file( "$localPath/$file" );
3888 if ( $hash === false ) {
3889 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3890 $hash = '';
3891 }
3892 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3893 }
3894
3895 /**
3896 * Transform "media" attribute based on request parameters
3897 *
3898 * @param string $media Current value of the "media" attribute
3899 * @return string Modified value of the "media" attribute, or null to skip
3900 * this stylesheet
3901 */
3902 public static function transformCssMedia( $media ) {
3903 global $wgRequest;
3904
3905 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3906 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3907
3908 // Switch in on-screen display for media testing
3909 $switches = [
3910 'printable' => 'print',
3911 'handheld' => 'handheld',
3912 ];
3913 foreach ( $switches as $switch => $targetMedia ) {
3914 if ( $wgRequest->getBool( $switch ) ) {
3915 if ( $media == $targetMedia ) {
3916 $media = '';
3917 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3918 /* This regex will not attempt to understand a comma-separated media_query_list
3919 *
3920 * Example supported values for $media:
3921 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3922 * Example NOT supported value for $media:
3923 * '3d-glasses, screen, print and resolution > 90dpi'
3924 *
3925 * If it's a print request, we never want any kind of screen stylesheets
3926 * If it's a handheld request (currently the only other choice with a switch),
3927 * we don't want simple 'screen' but we might want screen queries that
3928 * have a max-width or something, so we'll pass all others on and let the
3929 * client do the query.
3930 */
3931 if ( $targetMedia == 'print' || $media == 'screen' ) {
3932 return null;
3933 }
3934 }
3935 }
3936 }
3937
3938 return $media;
3939 }
3940
3941 /**
3942 * Add a wikitext-formatted message to the output.
3943 * This is equivalent to:
3944 *
3945 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3946 */
3947 public function addWikiMsg( /*...*/ ) {
3948 $args = func_get_args();
3949 $name = array_shift( $args );
3950 $this->addWikiMsgArray( $name, $args );
3951 }
3952
3953 /**
3954 * Add a wikitext-formatted message to the output.
3955 * Like addWikiMsg() except the parameters are taken as an array
3956 * instead of a variable argument list.
3957 *
3958 * @param string $name
3959 * @param array $args
3960 */
3961 public function addWikiMsgArray( $name, $args ) {
3962 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3963 }
3964
3965 /**
3966 * This function takes a number of message/argument specifications, wraps them in
3967 * some overall structure, and then parses the result and adds it to the output.
3968 *
3969 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3970 * and so on. The subsequent arguments may be either
3971 * 1) strings, in which case they are message names, or
3972 * 2) arrays, in which case, within each array, the first element is the message
3973 * name, and subsequent elements are the parameters to that message.
3974 *
3975 * Don't use this for messages that are not in the user's interface language.
3976 *
3977 * For example:
3978 *
3979 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3980 *
3981 * Is equivalent to:
3982 *
3983 * $wgOut->addWikiTextAsInterface( "<div class='error'>\n"
3984 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3985 *
3986 * The newline after the opening div is needed in some wikitext. See T21226.
3987 *
3988 * @param string $wrap
3989 */
3990 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3991 $msgSpecs = func_get_args();
3992 array_shift( $msgSpecs );
3993 $msgSpecs = array_values( $msgSpecs );
3994 $s = $wrap;
3995 foreach ( $msgSpecs as $n => $spec ) {
3996 if ( is_array( $spec ) ) {
3997 $args = $spec;
3998 $name = array_shift( $args );
3999 } else {
4000 $args = [];
4001 $name = $spec;
4002 }
4003 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
4004 }
4005 $this->addWikiTextAsInterface( $s );
4006 }
4007
4008 /**
4009 * Whether the output has a table of contents
4010 * @return bool
4011 * @since 1.22
4012 */
4013 public function isTOCEnabled() {
4014 return $this->mEnableTOC;
4015 }
4016
4017 /**
4018 * Helper function to setup the PHP implementation of OOUI to use in this request.
4019 *
4020 * @since 1.26
4021 * @param string $skinName The Skin name to determine the correct OOUI theme
4022 * @param string $dir Language direction
4023 */
4024 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
4025 $themes = ResourceLoaderOOUIModule::getSkinThemeMap();
4026 $theme = $themes[$skinName] ?? $themes['default'];
4027 // For example, 'OOUI\WikimediaUITheme'.
4028 $themeClass = "OOUI\\{$theme}Theme";
4029 OOUI\Theme::setSingleton( new $themeClass() );
4030 OOUI\Element::setDefaultDir( $dir );
4031 }
4032
4033 /**
4034 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4035 * MediaWiki and this OutputPage instance.
4036 *
4037 * @since 1.25
4038 */
4039 public function enableOOUI() {
4040 self::setupOOUI(
4041 strtolower( $this->getSkin()->getSkinName() ),
4042 $this->getLanguage()->getDir()
4043 );
4044 $this->addModuleStyles( [
4045 'oojs-ui-core.styles',
4046 'oojs-ui.styles.indicators',
4047 'mediawiki.widgets.styles',
4048 'oojs-ui-core.icons',
4049 ] );
4050 }
4051
4052 /**
4053 * Get (and set if not yet set) the CSP nonce.
4054 *
4055 * This value needs to be included in any <script> tags on the
4056 * page.
4057 *
4058 * @return string|bool Nonce or false to mean don't output nonce
4059 * @since 1.32
4060 */
4061 public function getCSPNonce() {
4062 if ( !ContentSecurityPolicy::isNonceRequired( $this->getConfig() ) ) {
4063 return false;
4064 }
4065 if ( $this->CSPNonce === null ) {
4066 // XXX It might be expensive to generate randomness
4067 // on every request, on Windows.
4068 $rand = random_bytes( 15 );
4069 $this->CSPNonce = base64_encode( $rand );
4070 }
4071 return $this->CSPNonce;
4072 }
4073
4074 }