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