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