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