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