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