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