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