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