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