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