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