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