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