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