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