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