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