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