Merge "Convert Special:DeletedContributions to use OOUI."
[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 ] );
2744 $this->getSkin()->setupSkinUserCss( $this );
2745
2746 // Prepare exempt modules for buildExemptModules()
2747 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2748 $exemptStates = [];
2749 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2750
2751 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2752 // Separate user-specific batch for improved cache-hit ratio.
2753 $userBatch = [ 'user.styles', 'user' ];
2754 $siteBatch = array_diff( $moduleStyles, $userBatch );
2755 $dbr = wfGetDB( DB_REPLICA );
2756 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2757 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2758
2759 // Filter out modules handled by buildExemptModules()
2760 $moduleStyles = array_filter( $moduleStyles,
2761 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2762 $module = $rl->getModule( $name );
2763 if ( $module ) {
2764 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2765 $exemptStates[$name] = 'ready';
2766 // Special case in buildExemptModules()
2767 return false;
2768 }
2769 $group = $module->getGroup();
2770 if ( isset( $exemptGroups[$group] ) ) {
2771 $exemptStates[$name] = 'ready';
2772 if ( !$module->isKnownEmpty( $context ) ) {
2773 // E.g. Don't output empty <styles>
2774 $exemptGroups[$group][] = $name;
2775 }
2776 return false;
2777 }
2778 }
2779 return true;
2780 }
2781 );
2782 $this->rlExemptStyleModules = $exemptGroups;
2783
2784 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2785 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2786 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2787 if ( !$isUserModuleFiltered ) {
2788 // Manually handled by getBottomScripts()
2789 $userModule = $rl->getModule( 'user' );
2790 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2791 ? 'ready'
2792 : 'loading';
2793 $this->rlUserModuleState = $exemptStates['user'] = $userState;
2794 }
2795
2796 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2797 $rlClient->setConfig( $this->getJSVars() );
2798 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2799 $rlClient->setModuleStyles( $moduleStyles );
2800 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2801 $rlClient->setExemptStates( $exemptStates );
2802 $this->rlClient = $rlClient;
2803 }
2804 return $this->rlClient;
2805 }
2806
2807 /**
2808 * @param Skin $sk The given Skin
2809 * @param bool $includeStyle Unused
2810 * @return string The doctype, opening "<html>", and head element.
2811 */
2812 public function headElement( Skin $sk, $includeStyle = true ) {
2813 global $wgContLang;
2814
2815 $userdir = $this->getLanguage()->getDir();
2816 $sitedir = $wgContLang->getDir();
2817
2818 $pieces = [];
2819 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
2820 $this->getRlClient()->getDocumentAttributes(),
2821 $sk->getHtmlElementAttributes()
2822 ) );
2823 $pieces[] = Html::openElement( 'head' );
2824
2825 if ( $this->getHTMLTitle() == '' ) {
2826 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2827 }
2828
2829 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2830 // Add <meta charset="UTF-8">
2831 // This should be before <title> since it defines the charset used by
2832 // text including the text inside <title>.
2833 // The spec recommends defining XHTML5's charset using the XML declaration
2834 // instead of meta.
2835 // Our XML declaration is output by Html::htmlHeader.
2836 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2837 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2838 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
2839 }
2840
2841 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
2842 $pieces[] = $this->getRlClient()->getHeadHtml();
2843 $pieces[] = $this->buildExemptModules();
2844 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2845 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
2846 $pieces[] = Html::closeElement( 'head' );
2847
2848 $bodyClasses = [];
2849 $bodyClasses[] = 'mediawiki';
2850
2851 # Classes for LTR/RTL directionality support
2852 $bodyClasses[] = $userdir;
2853 $bodyClasses[] = "sitedir-$sitedir";
2854
2855 $underline = $this->getUser()->getOption( 'underline' );
2856 if ( $underline < 2 ) {
2857 // The following classes can be used here:
2858 // * mw-underline-always
2859 // * mw-underline-never
2860 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
2861 }
2862
2863 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2864 # A <body> class is probably not the best way to do this . . .
2865 $bodyClasses[] = 'capitalize-all-nouns';
2866 }
2867
2868 // Parser feature migration class
2869 // The idea is that this will eventually be removed, after the wikitext
2870 // which requires it is cleaned up.
2871 $bodyClasses[] = 'mw-hide-empty-elt';
2872
2873 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2874 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2875 $bodyClasses[] =
2876 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2877
2878 $bodyAttrs = [];
2879 // While the implode() is not strictly needed, it's used for backwards compatibility
2880 // (this used to be built as a string and hooks likely still expect that).
2881 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2882
2883 // Allow skins and extensions to add body attributes they need
2884 $sk->addToBodyAttributes( $this, $bodyAttrs );
2885 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2886
2887 $pieces[] = Html::openElement( 'body', $bodyAttrs );
2888
2889 return self::combineWrappedStrings( $pieces );
2890 }
2891
2892 /**
2893 * Get a ResourceLoader object associated with this OutputPage
2894 *
2895 * @return ResourceLoader
2896 */
2897 public function getResourceLoader() {
2898 if ( is_null( $this->mResourceLoader ) ) {
2899 $this->mResourceLoader = new ResourceLoader(
2900 $this->getConfig(),
2901 LoggerFactory::getInstance( 'resourceloader' )
2902 );
2903 }
2904 return $this->mResourceLoader;
2905 }
2906
2907 /**
2908 * Explicily load or embed modules on a page.
2909 *
2910 * @param array|string $modules One or more module names
2911 * @param string $only ResourceLoaderModule TYPE_ class constant
2912 * @param array $extraQuery [optional] Array with extra query parameters for the request
2913 * @return string|WrappedStringList HTML
2914 */
2915 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2916 // Apply 'target' and 'origin' filters
2917 $modules = $this->filterModules( (array)$modules, null, $only );
2918
2919 return ResourceLoaderClientHtml::makeLoad(
2920 $this->getRlClientContext(),
2921 $modules,
2922 $only,
2923 $extraQuery
2924 );
2925 }
2926
2927 /**
2928 * Combine WrappedString chunks and filter out empty ones
2929 *
2930 * @param array $chunks
2931 * @return string|WrappedStringList HTML
2932 */
2933 protected static function combineWrappedStrings( array $chunks ) {
2934 // Filter out empty values
2935 $chunks = array_filter( $chunks, 'strlen' );
2936 return WrappedString::join( "\n", $chunks );
2937 }
2938
2939 private function isUserJsPreview() {
2940 return $this->getConfig()->get( 'AllowUserJs' )
2941 && $this->getTitle()
2942 && $this->getTitle()->isJsSubpage()
2943 && $this->userCanPreview();
2944 }
2945
2946 private function isUserCssPreview() {
2947 return $this->getConfig()->get( 'AllowUserCss' )
2948 && $this->getTitle()
2949 && $this->getTitle()->isCssSubpage()
2950 && $this->userCanPreview();
2951 }
2952
2953 /**
2954 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2955 * legacy scripts ($this->mScripts), and user JS.
2956 *
2957 * @return string|WrappedStringList HTML
2958 */
2959 public function getBottomScripts() {
2960 $chunks = [];
2961 $chunks[] = $this->getRlClient()->getBodyHtml();
2962
2963 // Legacy non-ResourceLoader scripts
2964 $chunks[] = $this->mScripts;
2965
2966 // Exempt 'user' module
2967 // - May need excludepages for live preview. (T28283)
2968 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2969 // ensures execution is scheduled after the "site" module.
2970 // - Don't load if module state is already resolved as "ready".
2971 if ( $this->rlUserModuleState === 'loading' ) {
2972 if ( $this->isUserJsPreview() ) {
2973 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
2974 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2975 );
2976 $chunks[] = ResourceLoader::makeInlineScript(
2977 Xml::encodeJsCall( 'mw.loader.using', [
2978 [ 'user', 'site' ],
2979 new XmlJsCode(
2980 'function () {'
2981 . Xml::encodeJsCall( '$.globalEval', [
2982 $this->getRequest()->getText( 'wpTextbox1' )
2983 ] )
2984 . '}'
2985 )
2986 ] )
2987 );
2988 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2989 // asynchronously and may arrive *after* the inline script here. So the previewed code
2990 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
2991 // Similarly, when previewing ./common.js and the user module does arrive first,
2992 // it will arrive without common.js and the inline script runs after.
2993 // Thus running common after the excluded subpage.
2994 } else {
2995 // Load normally
2996 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
2997 }
2998 }
2999
3000 return self::combineWrappedStrings( $chunks );
3001 }
3002
3003 /**
3004 * Get the javascript config vars to include on this page
3005 *
3006 * @return array Array of javascript config vars
3007 * @since 1.23
3008 */
3009 public function getJsConfigVars() {
3010 return $this->mJsConfigVars;
3011 }
3012
3013 /**
3014 * Add one or more variables to be set in mw.config in JavaScript
3015 *
3016 * @param string|array $keys Key or array of key/value pairs
3017 * @param mixed $value [optional] Value of the configuration variable
3018 */
3019 public function addJsConfigVars( $keys, $value = null ) {
3020 if ( is_array( $keys ) ) {
3021 foreach ( $keys as $key => $value ) {
3022 $this->mJsConfigVars[$key] = $value;
3023 }
3024 return;
3025 }
3026
3027 $this->mJsConfigVars[$keys] = $value;
3028 }
3029
3030 /**
3031 * Get an array containing the variables to be set in mw.config in JavaScript.
3032 *
3033 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3034 * - in other words, page-independent/site-wide variables (without state).
3035 * You will only be adding bloat to the html page and causing page caches to
3036 * have to be purged on configuration changes.
3037 * @return array
3038 */
3039 public function getJSVars() {
3040 global $wgContLang;
3041
3042 $curRevisionId = 0;
3043 $articleId = 0;
3044 $canonicalSpecialPageName = false; # bug 21115
3045
3046 $title = $this->getTitle();
3047 $ns = $title->getNamespace();
3048 $canonicalNamespace = MWNamespace::exists( $ns )
3049 ? MWNamespace::getCanonicalName( $ns )
3050 : $title->getNsText();
3051
3052 $sk = $this->getSkin();
3053 // Get the relevant title so that AJAX features can use the correct page name
3054 // when making API requests from certain special pages (bug 34972).
3055 $relevantTitle = $sk->getRelevantTitle();
3056 $relevantUser = $sk->getRelevantUser();
3057
3058 if ( $ns == NS_SPECIAL ) {
3059 list( $canonicalSpecialPageName, /*...*/ ) =
3060 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3061 } elseif ( $this->canUseWikiPage() ) {
3062 $wikiPage = $this->getWikiPage();
3063 $curRevisionId = $wikiPage->getLatest();
3064 $articleId = $wikiPage->getId();
3065 }
3066
3067 $lang = $title->getPageViewLanguage();
3068
3069 // Pre-process information
3070 $separatorTransTable = $lang->separatorTransformTable();
3071 $separatorTransTable = $separatorTransTable ? $separatorTransTable : [];
3072 $compactSeparatorTransTable = [
3073 implode( "\t", array_keys( $separatorTransTable ) ),
3074 implode( "\t", $separatorTransTable ),
3075 ];
3076 $digitTransTable = $lang->digitTransformTable();
3077 $digitTransTable = $digitTransTable ? $digitTransTable : [];
3078 $compactDigitTransTable = [
3079 implode( "\t", array_keys( $digitTransTable ) ),
3080 implode( "\t", $digitTransTable ),
3081 ];
3082
3083 $user = $this->getUser();
3084
3085 $vars = [
3086 'wgCanonicalNamespace' => $canonicalNamespace,
3087 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3088 'wgNamespaceNumber' => $title->getNamespace(),
3089 'wgPageName' => $title->getPrefixedDBkey(),
3090 'wgTitle' => $title->getText(),
3091 'wgCurRevisionId' => $curRevisionId,
3092 'wgRevisionId' => (int)$this->getRevisionId(),
3093 'wgArticleId' => $articleId,
3094 'wgIsArticle' => $this->isArticle(),
3095 'wgIsRedirect' => $title->isRedirect(),
3096 'wgAction' => Action::getActionName( $this->getContext() ),
3097 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3098 'wgUserGroups' => $user->getEffectiveGroups(),
3099 'wgCategories' => $this->getCategories(),
3100 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3101 'wgPageContentLanguage' => $lang->getCode(),
3102 'wgPageContentModel' => $title->getContentModel(),
3103 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3104 'wgDigitTransformTable' => $compactDigitTransTable,
3105 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3106 'wgMonthNames' => $lang->getMonthNamesArray(),
3107 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3108 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3109 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3110 'wgRequestId' => WebRequest::getRequestId(),
3111 ];
3112
3113 if ( $user->isLoggedIn() ) {
3114 $vars['wgUserId'] = $user->getId();
3115 $vars['wgUserEditCount'] = $user->getEditCount();
3116 $userReg = $user->getRegistration();
3117 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3118 // Get the revision ID of the oldest new message on the user's talk
3119 // page. This can be used for constructing new message alerts on
3120 // the client side.
3121 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3122 }
3123
3124 if ( $wgContLang->hasVariants() ) {
3125 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3126 }
3127 // Same test as SkinTemplate
3128 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3129 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3130
3131 foreach ( $title->getRestrictionTypes() as $type ) {
3132 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3133 }
3134
3135 if ( $title->isMainPage() ) {
3136 $vars['wgIsMainPage'] = true;
3137 }
3138
3139 if ( $this->mRedirectedFrom ) {
3140 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3141 }
3142
3143 if ( $relevantUser ) {
3144 $vars['wgRelevantUserName'] = $relevantUser->getName();
3145 }
3146
3147 // Allow extensions to add their custom variables to the mw.config map.
3148 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3149 // page-dependant but site-wide (without state).
3150 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3151 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3152
3153 // Merge in variables from addJsConfigVars last
3154 return array_merge( $vars, $this->getJsConfigVars() );
3155 }
3156
3157 /**
3158 * To make it harder for someone to slip a user a fake
3159 * user-JavaScript or user-CSS preview, a random token
3160 * is associated with the login session. If it's not
3161 * passed back with the preview request, we won't render
3162 * the code.
3163 *
3164 * @return bool
3165 */
3166 public function userCanPreview() {
3167 $request = $this->getRequest();
3168 if (
3169 $request->getVal( 'action' ) !== 'submit' ||
3170 !$request->getCheck( 'wpPreview' ) ||
3171 !$request->wasPosted()
3172 ) {
3173 return false;
3174 }
3175
3176 $user = $this->getUser();
3177
3178 if ( !$user->isLoggedIn() ) {
3179 // Anons have predictable edit tokens
3180 return false;
3181 }
3182 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3183 return false;
3184 }
3185
3186 $title = $this->getTitle();
3187 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3188 return false;
3189 }
3190 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3191 // Don't execute another user's CSS or JS on preview (T85855)
3192 return false;
3193 }
3194
3195 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3196 if ( count( $errors ) !== 0 ) {
3197 return false;
3198 }
3199
3200 return true;
3201 }
3202
3203 /**
3204 * @return array Array in format "link name or number => 'link html'".
3205 */
3206 public function getHeadLinksArray() {
3207 global $wgVersion;
3208
3209 $tags = [];
3210 $config = $this->getConfig();
3211
3212 $canonicalUrl = $this->mCanonicalUrl;
3213
3214 $tags['meta-generator'] = Html::element( 'meta', [
3215 'name' => 'generator',
3216 'content' => "MediaWiki $wgVersion",
3217 ] );
3218
3219 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3220 $tags['meta-referrer'] = Html::element( 'meta', [
3221 'name' => 'referrer',
3222 'content' => $config->get( 'ReferrerPolicy' )
3223 ] );
3224 }
3225
3226 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3227 if ( $p !== 'index,follow' ) {
3228 // http://www.robotstxt.org/wc/meta-user.html
3229 // Only show if it's different from the default robots policy
3230 $tags['meta-robots'] = Html::element( 'meta', [
3231 'name' => 'robots',
3232 'content' => $p,
3233 ] );
3234 }
3235
3236 foreach ( $this->mMetatags as $tag ) {
3237 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3238 $a = 'http-equiv';
3239 $tag[0] = substr( $tag[0], 5 );
3240 } else {
3241 $a = 'name';
3242 }
3243 $tagName = "meta-{$tag[0]}";
3244 if ( isset( $tags[$tagName] ) ) {
3245 $tagName .= $tag[1];
3246 }
3247 $tags[$tagName] = Html::element( 'meta',
3248 [
3249 $a => $tag[0],
3250 'content' => $tag[1]
3251 ]
3252 );
3253 }
3254
3255 foreach ( $this->mLinktags as $tag ) {
3256 $tags[] = Html::element( 'link', $tag );
3257 }
3258
3259 # Universal edit button
3260 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3261 $user = $this->getUser();
3262 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3263 && ( $this->getTitle()->exists() ||
3264 $this->getTitle()->quickUserCan( 'create', $user ) )
3265 ) {
3266 // Original UniversalEditButton
3267 $msg = $this->msg( 'edit' )->text();
3268 $tags['universal-edit-button'] = Html::element( 'link', [
3269 'rel' => 'alternate',
3270 'type' => 'application/x-wiki',
3271 'title' => $msg,
3272 'href' => $this->getTitle()->getEditURL(),
3273 ] );
3274 // Alternate edit link
3275 $tags['alternative-edit'] = Html::element( 'link', [
3276 'rel' => 'edit',
3277 'title' => $msg,
3278 'href' => $this->getTitle()->getEditURL(),
3279 ] );
3280 }
3281 }
3282
3283 # Generally the order of the favicon and apple-touch-icon links
3284 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3285 # uses whichever one appears later in the HTML source. Make sure
3286 # apple-touch-icon is specified first to avoid this.
3287 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3288 $tags['apple-touch-icon'] = Html::element( 'link', [
3289 'rel' => 'apple-touch-icon',
3290 'href' => $config->get( 'AppleTouchIcon' )
3291 ] );
3292 }
3293
3294 if ( $config->get( 'Favicon' ) !== false ) {
3295 $tags['favicon'] = Html::element( 'link', [
3296 'rel' => 'shortcut icon',
3297 'href' => $config->get( 'Favicon' )
3298 ] );
3299 }
3300
3301 # OpenSearch description link
3302 $tags['opensearch'] = Html::element( 'link', [
3303 'rel' => 'search',
3304 'type' => 'application/opensearchdescription+xml',
3305 'href' => wfScript( 'opensearch_desc' ),
3306 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3307 ] );
3308
3309 if ( $config->get( 'EnableAPI' ) ) {
3310 # Real Simple Discovery link, provides auto-discovery information
3311 # for the MediaWiki API (and potentially additional custom API
3312 # support such as WordPress or Twitter-compatible APIs for a
3313 # blogging extension, etc)
3314 $tags['rsd'] = Html::element( 'link', [
3315 'rel' => 'EditURI',
3316 'type' => 'application/rsd+xml',
3317 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3318 // Whether RSD accepts relative or protocol-relative URLs is completely
3319 // undocumented, though.
3320 'href' => wfExpandUrl( wfAppendQuery(
3321 wfScript( 'api' ),
3322 [ 'action' => 'rsd' ] ),
3323 PROTO_RELATIVE
3324 ),
3325 ] );
3326 }
3327
3328 # Language variants
3329 if ( !$config->get( 'DisableLangConversion' ) ) {
3330 $lang = $this->getTitle()->getPageLanguage();
3331 if ( $lang->hasVariants() ) {
3332 $variants = $lang->getVariants();
3333 foreach ( $variants as $variant ) {
3334 $tags["variant-$variant"] = Html::element( 'link', [
3335 'rel' => 'alternate',
3336 'hreflang' => wfBCP47( $variant ),
3337 'href' => $this->getTitle()->getLocalURL(
3338 [ 'variant' => $variant ] )
3339 ]
3340 );
3341 }
3342 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3343 $tags["variant-x-default"] = Html::element( 'link', [
3344 'rel' => 'alternate',
3345 'hreflang' => 'x-default',
3346 'href' => $this->getTitle()->getLocalURL() ] );
3347 }
3348 }
3349
3350 # Copyright
3351 if ( $this->copyrightUrl !== null ) {
3352 $copyright = $this->copyrightUrl;
3353 } else {
3354 $copyright = '';
3355 if ( $config->get( 'RightsPage' ) ) {
3356 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3357
3358 if ( $copy ) {
3359 $copyright = $copy->getLocalURL();
3360 }
3361 }
3362
3363 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3364 $copyright = $config->get( 'RightsUrl' );
3365 }
3366 }
3367
3368 if ( $copyright ) {
3369 $tags['copyright'] = Html::element( 'link', [
3370 'rel' => 'copyright',
3371 'href' => $copyright ]
3372 );
3373 }
3374
3375 # Feeds
3376 if ( $config->get( 'Feed' ) ) {
3377 $feedLinks = [];
3378
3379 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3380 # Use the page name for the title. In principle, this could
3381 # lead to issues with having the same name for different feeds
3382 # corresponding to the same page, but we can't avoid that at
3383 # this low a level.
3384
3385 $feedLinks[] = $this->feedLink(
3386 $format,
3387 $link,
3388 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3389 $this->msg(
3390 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3391 )->text()
3392 );
3393 }
3394
3395 # Recent changes feed should appear on every page (except recentchanges,
3396 # that would be redundant). Put it after the per-page feed to avoid
3397 # changing existing behavior. It's still available, probably via a
3398 # menu in your browser. Some sites might have a different feed they'd
3399 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3400 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3401 # If so, use it instead.
3402 $sitename = $config->get( 'Sitename' );
3403 if ( $config->get( 'OverrideSiteFeed' ) ) {
3404 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3405 // Note, this->feedLink escapes the url.
3406 $feedLinks[] = $this->feedLink(
3407 $type,
3408 $feedUrl,
3409 $this->msg( "site-{$type}-feed", $sitename )->text()
3410 );
3411 }
3412 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3413 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3414 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3415 $feedLinks[] = $this->feedLink(
3416 $format,
3417 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3418 # For grep: 'site-rss-feed', 'site-atom-feed'
3419 $this->msg( "site-{$format}-feed", $sitename )->text()
3420 );
3421 }
3422 }
3423
3424 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3425 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3426 # use OutputPage::addFeedLink() instead.
3427 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3428
3429 $tags += $feedLinks;
3430 }
3431
3432 # Canonical URL
3433 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3434 if ( $canonicalUrl !== false ) {
3435 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3436 } else {
3437 if ( $this->isArticleRelated() ) {
3438 // This affects all requests where "setArticleRelated" is true. This is
3439 // typically all requests that show content (query title, curid, oldid, diff),
3440 // and all wikipage actions (edit, delete, purge, info, history etc.).
3441 // It does not apply to File pages and Special pages.
3442 // 'history' and 'info' actions address page metadata rather than the page
3443 // content itself, so they may not be canonicalized to the view page url.
3444 // TODO: this ought to be better encapsulated in the Action class.
3445 $action = Action::getActionName( $this->getContext() );
3446 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3447 $query = "action={$action}";
3448 } else {
3449 $query = '';
3450 }
3451 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3452 } else {
3453 $reqUrl = $this->getRequest()->getRequestURL();
3454 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3455 }
3456 }
3457 }
3458 if ( $canonicalUrl !== false ) {
3459 $tags[] = Html::element( 'link', [
3460 'rel' => 'canonical',
3461 'href' => $canonicalUrl
3462 ] );
3463 }
3464
3465 return $tags;
3466 }
3467
3468 /**
3469 * @return string HTML tag links to be put in the header.
3470 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3471 * OutputPage::getHeadLinksArray directly.
3472 */
3473 public function getHeadLinks() {
3474 wfDeprecated( __METHOD__, '1.24' );
3475 return implode( "\n", $this->getHeadLinksArray() );
3476 }
3477
3478 /**
3479 * Generate a "<link rel/>" for a feed.
3480 *
3481 * @param string $type Feed type
3482 * @param string $url URL to the feed
3483 * @param string $text Value of the "title" attribute
3484 * @return string HTML fragment
3485 */
3486 private function feedLink( $type, $url, $text ) {
3487 return Html::element( 'link', [
3488 'rel' => 'alternate',
3489 'type' => "application/$type+xml",
3490 'title' => $text,
3491 'href' => $url ]
3492 );
3493 }
3494
3495 /**
3496 * Add a local or specified stylesheet, with the given media options.
3497 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3498 *
3499 * @param string $style URL to the file
3500 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3501 * @param string $condition For IE conditional comments, specifying an IE version
3502 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3503 */
3504 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3505 $options = [];
3506 if ( $media ) {
3507 $options['media'] = $media;
3508 }
3509 if ( $condition ) {
3510 $options['condition'] = $condition;
3511 }
3512 if ( $dir ) {
3513 $options['dir'] = $dir;
3514 }
3515 $this->styles[$style] = $options;
3516 }
3517
3518 /**
3519 * Adds inline CSS styles
3520 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3521 *
3522 * @param mixed $style_css Inline CSS
3523 * @param string $flip Set to 'flip' to flip the CSS if needed
3524 */
3525 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3526 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3527 # If wanted, and the interface is right-to-left, flip the CSS
3528 $style_css = CSSJanus::transform( $style_css, true, false );
3529 }
3530 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3531 }
3532
3533 /**
3534 * Build exempt modules and legacy non-ResourceLoader styles.
3535 *
3536 * @return string|WrappedStringList HTML
3537 */
3538 protected function buildExemptModules() {
3539 global $wgContLang;
3540
3541 $resourceLoader = $this->getResourceLoader();
3542 $chunks = [];
3543 // Things that go after the ResourceLoaderDynamicStyles marker
3544 $append = [];
3545
3546 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3547 if ( $this->isUserCssPreview() ) {
3548 $append[] = $this->makeResourceLoaderLink(
3549 'user.styles',
3550 ResourceLoaderModule::TYPE_STYLES,
3551 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3552 );
3553
3554 // Load the previewed CSS. Janus it if needed.
3555 // User-supplied CSS is assumed to in the wiki's content language.
3556 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3557 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3558 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3559 }
3560 $append[] = Html::inlineStyle( $previewedCSS );
3561 }
3562
3563 // We want site, private and user styles to override dynamically added styles from
3564 // general modules, but we want dynamically added styles to override statically added
3565 // style modules. So the order has to be:
3566 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3567 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3568 // - ResourceLoaderDynamicStyles marker
3569 // - site/private/user styles
3570
3571 // Add legacy styles added through addStyle()/addInlineStyle() here
3572 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3573
3574 $chunks[] = Html::element(
3575 'meta',
3576 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3577 );
3578
3579 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3580 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3581 ResourceLoaderModule::TYPE_STYLES
3582 );
3583 }
3584
3585 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3586 }
3587
3588 /**
3589 * @return array
3590 */
3591 public function buildCssLinksArray() {
3592 $links = [];
3593
3594 // Add any extension CSS
3595 foreach ( $this->mExtStyles as $url ) {
3596 $this->addStyle( $url );
3597 }
3598 $this->mExtStyles = [];
3599
3600 foreach ( $this->styles as $file => $options ) {
3601 $link = $this->styleLink( $file, $options );
3602 if ( $link ) {
3603 $links[$file] = $link;
3604 }
3605 }
3606 return $links;
3607 }
3608
3609 /**
3610 * Generate \<link\> tags for stylesheets
3611 *
3612 * @param string $style URL to the file
3613 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3614 * @return string HTML fragment
3615 */
3616 protected function styleLink( $style, array $options ) {
3617 if ( isset( $options['dir'] ) ) {
3618 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3619 return '';
3620 }
3621 }
3622
3623 if ( isset( $options['media'] ) ) {
3624 $media = self::transformCssMedia( $options['media'] );
3625 if ( is_null( $media ) ) {
3626 return '';
3627 }
3628 } else {
3629 $media = 'all';
3630 }
3631
3632 if ( substr( $style, 0, 1 ) == '/' ||
3633 substr( $style, 0, 5 ) == 'http:' ||
3634 substr( $style, 0, 6 ) == 'https:' ) {
3635 $url = $style;
3636 } else {
3637 $config = $this->getConfig();
3638 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3639 $config->get( 'StyleVersion' );
3640 }
3641
3642 $link = Html::linkedStyle( $url, $media );
3643
3644 if ( isset( $options['condition'] ) ) {
3645 $condition = htmlspecialchars( $options['condition'] );
3646 $link = "<!--[if $condition]>$link<![endif]-->";
3647 }
3648 return $link;
3649 }
3650
3651 /**
3652 * Transform path to web-accessible static resource.
3653 *
3654 * This is used to add a validation hash as query string.
3655 * This aids various behaviors:
3656 *
3657 * - Put long Cache-Control max-age headers on responses for improved
3658 * cache performance.
3659 * - Get the correct version of a file as expected by the current page.
3660 * - Instantly get the updated version of a file after deployment.
3661 *
3662 * Avoid using this for urls included in HTML as otherwise clients may get different
3663 * versions of a resource when navigating the site depending on when the page was cached.
3664 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3665 * an external stylesheet).
3666 *
3667 * @since 1.27
3668 * @param Config $config
3669 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3670 * @return string URL
3671 */
3672 public static function transformResourcePath( Config $config, $path ) {
3673 global $IP;
3674 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3675 if ( $remotePathPrefix === '' ) {
3676 // The configured base path is required to be empty string for
3677 // wikis in the domain root
3678 $remotePath = '/';
3679 } else {
3680 $remotePath = $remotePathPrefix;
3681 }
3682 if ( strpos( $path, $remotePath ) !== 0 ) {
3683 // Path is outside wgResourceBasePath, ignore.
3684 return $path;
3685 }
3686 $path = RelPath\getRelativePath( $path, $remotePath );
3687 return self::transformFilePath( $remotePathPrefix, $IP, $path );
3688 }
3689
3690 /**
3691 * Utility method for transformResourceFilePath().
3692 *
3693 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3694 *
3695 * @since 1.27
3696 * @param string $remotePath URL path prefix that points to $localPath
3697 * @param string $localPath File directory exposed at $remotePath
3698 * @param string $file Path to target file relative to $localPath
3699 * @return string URL
3700 */
3701 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3702 $hash = md5_file( "$localPath/$file" );
3703 if ( $hash === false ) {
3704 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3705 $hash = '';
3706 }
3707 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3708 }
3709
3710 /**
3711 * Transform "media" attribute based on request parameters
3712 *
3713 * @param string $media Current value of the "media" attribute
3714 * @return string Modified value of the "media" attribute, or null to skip
3715 * this stylesheet
3716 */
3717 public static function transformCssMedia( $media ) {
3718 global $wgRequest;
3719
3720 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3721 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3722
3723 // Switch in on-screen display for media testing
3724 $switches = [
3725 'printable' => 'print',
3726 'handheld' => 'handheld',
3727 ];
3728 foreach ( $switches as $switch => $targetMedia ) {
3729 if ( $wgRequest->getBool( $switch ) ) {
3730 if ( $media == $targetMedia ) {
3731 $media = '';
3732 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3733 /* This regex will not attempt to understand a comma-separated media_query_list
3734 *
3735 * Example supported values for $media:
3736 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3737 * Example NOT supported value for $media:
3738 * '3d-glasses, screen, print and resolution > 90dpi'
3739 *
3740 * If it's a print request, we never want any kind of screen stylesheets
3741 * If it's a handheld request (currently the only other choice with a switch),
3742 * we don't want simple 'screen' but we might want screen queries that
3743 * have a max-width or something, so we'll pass all others on and let the
3744 * client do the query.
3745 */
3746 if ( $targetMedia == 'print' || $media == 'screen' ) {
3747 return null;
3748 }
3749 }
3750 }
3751 }
3752
3753 return $media;
3754 }
3755
3756 /**
3757 * Add a wikitext-formatted message to the output.
3758 * This is equivalent to:
3759 *
3760 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3761 */
3762 public function addWikiMsg( /*...*/ ) {
3763 $args = func_get_args();
3764 $name = array_shift( $args );
3765 $this->addWikiMsgArray( $name, $args );
3766 }
3767
3768 /**
3769 * Add a wikitext-formatted message to the output.
3770 * Like addWikiMsg() except the parameters are taken as an array
3771 * instead of a variable argument list.
3772 *
3773 * @param string $name
3774 * @param array $args
3775 */
3776 public function addWikiMsgArray( $name, $args ) {
3777 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3778 }
3779
3780 /**
3781 * This function takes a number of message/argument specifications, wraps them in
3782 * some overall structure, and then parses the result and adds it to the output.
3783 *
3784 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3785 * and so on. The subsequent arguments may be either
3786 * 1) strings, in which case they are message names, or
3787 * 2) arrays, in which case, within each array, the first element is the message
3788 * name, and subsequent elements are the parameters to that message.
3789 *
3790 * Don't use this for messages that are not in the user's interface language.
3791 *
3792 * For example:
3793 *
3794 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3795 *
3796 * Is equivalent to:
3797 *
3798 * $wgOut->addWikiText( "<div class='error'>\n"
3799 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3800 *
3801 * The newline after the opening div is needed in some wikitext. See bug 19226.
3802 *
3803 * @param string $wrap
3804 */
3805 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3806 $msgSpecs = func_get_args();
3807 array_shift( $msgSpecs );
3808 $msgSpecs = array_values( $msgSpecs );
3809 $s = $wrap;
3810 foreach ( $msgSpecs as $n => $spec ) {
3811 if ( is_array( $spec ) ) {
3812 $args = $spec;
3813 $name = array_shift( $args );
3814 if ( isset( $args['options'] ) ) {
3815 unset( $args['options'] );
3816 wfDeprecated(
3817 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3818 '1.20'
3819 );
3820 }
3821 } else {
3822 $args = [];
3823 $name = $spec;
3824 }
3825 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3826 }
3827 $this->addWikiText( $s );
3828 }
3829
3830 /**
3831 * Enables/disables TOC, doesn't override __NOTOC__
3832 * @param bool $flag
3833 * @since 1.22
3834 */
3835 public function enableTOC( $flag = true ) {
3836 $this->mEnableTOC = $flag;
3837 }
3838
3839 /**
3840 * @return bool
3841 * @since 1.22
3842 */
3843 public function isTOCEnabled() {
3844 return $this->mEnableTOC;
3845 }
3846
3847 /**
3848 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3849 * @param bool $flag
3850 * @since 1.23
3851 */
3852 public function enableSectionEditLinks( $flag = true ) {
3853 $this->mEnableSectionEditLinks = $flag;
3854 }
3855
3856 /**
3857 * @return bool
3858 * @since 1.23
3859 */
3860 public function sectionEditLinksEnabled() {
3861 return $this->mEnableSectionEditLinks;
3862 }
3863
3864 /**
3865 * Helper function to setup the PHP implementation of OOUI to use in this request.
3866 *
3867 * @since 1.26
3868 * @param String $skinName The Skin name to determine the correct OOUI theme
3869 * @param String $dir Language direction
3870 */
3871 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3872 $themes = ExtensionRegistry::getInstance()->getAttribute( 'SkinOOUIThemes' );
3873 // Make keys (skin names) lowercase for case-insensitive matching.
3874 $themes = array_change_key_case( $themes, CASE_LOWER );
3875 $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : 'MediaWiki';
3876 // For example, 'OOUI\MediaWikiTheme'.
3877 $themeClass = "OOUI\\{$theme}Theme";
3878 OOUI\Theme::setSingleton( new $themeClass() );
3879 OOUI\Element::setDefaultDir( $dir );
3880 }
3881
3882 /**
3883 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3884 * MediaWiki and this OutputPage instance.
3885 *
3886 * @since 1.25
3887 */
3888 public function enableOOUI() {
3889 self::setupOOUI(
3890 strtolower( $this->getSkin()->getSkinName() ),
3891 $this->getLanguage()->getDir()
3892 );
3893 $this->addModuleStyles( [
3894 'oojs-ui-core.styles',
3895 'oojs-ui.styles.icons',
3896 'oojs-ui.styles.indicators',
3897 'oojs-ui.styles.textures',
3898 'mediawiki.widgets.styles',
3899 ] );
3900 }
3901 }