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