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