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