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