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