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