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