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