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