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