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