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