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