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