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