Merge "Handle missing namespace prefix in XML dumps more gracefully"
[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 if ( !$options->matches( $anonPO ) ) {
1572 wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1573 $options->isBogus = false;
1574 }
1575 }
1576
1577 if ( !$this->mParserOptions ) {
1578 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1579 // $wgUser isn't unstubbable yet, so don't try to get a
1580 // ParserOptions for it. And don't cache this ParserOptions
1581 // either.
1582 $po = ParserOptions::newFromAnon();
1583 $po->setEditSection( false );
1584 $po->isBogus = true;
1585 if ( $options !== null ) {
1586 $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
1587 }
1588 return $po;
1589 }
1590
1591 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1592 $this->mParserOptions->setEditSection( false );
1593 }
1594
1595 if ( $options !== null && !empty( $options->isBogus ) ) {
1596 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1597 // thing.
1598 return wfSetVar( $this->mParserOptions, null, true );
1599 } else {
1600 return wfSetVar( $this->mParserOptions, $options );
1601 }
1602 }
1603
1604 /**
1605 * Set the revision ID which will be seen by the wiki text parser
1606 * for things such as embedded {{REVISIONID}} variable use.
1607 *
1608 * @param int|null $revid An positive integer, or null
1609 * @return mixed Previous value
1610 */
1611 public function setRevisionId( $revid ) {
1612 $val = is_null( $revid ) ? null : intval( $revid );
1613 return wfSetVar( $this->mRevisionId, $val );
1614 }
1615
1616 /**
1617 * Get the displayed revision ID
1618 *
1619 * @return int
1620 */
1621 public function getRevisionId() {
1622 return $this->mRevisionId;
1623 }
1624
1625 /**
1626 * Set the timestamp of the revision which will be displayed. This is used
1627 * to avoid a extra DB call in Skin::lastModified().
1628 *
1629 * @param string|null $timestamp
1630 * @return mixed Previous value
1631 */
1632 public function setRevisionTimestamp( $timestamp ) {
1633 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1634 }
1635
1636 /**
1637 * Get the timestamp of displayed revision.
1638 * This will be null if not filled by setRevisionTimestamp().
1639 *
1640 * @return string|null
1641 */
1642 public function getRevisionTimestamp() {
1643 return $this->mRevisionTimestamp;
1644 }
1645
1646 /**
1647 * Set the displayed file version
1648 *
1649 * @param File|bool $file
1650 * @return mixed Previous value
1651 */
1652 public function setFileVersion( $file ) {
1653 $val = null;
1654 if ( $file instanceof File && $file->exists() ) {
1655 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1656 }
1657 return wfSetVar( $this->mFileVersion, $val, true );
1658 }
1659
1660 /**
1661 * Get the displayed file version
1662 *
1663 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1664 */
1665 public function getFileVersion() {
1666 return $this->mFileVersion;
1667 }
1668
1669 /**
1670 * Get the templates used on this page
1671 *
1672 * @return array (namespace => dbKey => revId)
1673 * @since 1.18
1674 */
1675 public function getTemplateIds() {
1676 return $this->mTemplateIds;
1677 }
1678
1679 /**
1680 * Get the files used on this page
1681 *
1682 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1683 * @since 1.18
1684 */
1685 public function getFileSearchOptions() {
1686 return $this->mImageTimeKeys;
1687 }
1688
1689 /**
1690 * Convert wikitext to HTML and add it to the buffer
1691 * Default assumes that the current page title will be used.
1692 *
1693 * @param string $text
1694 * @param bool $linestart Is this the start of a line?
1695 * @param bool $interface Is this text in the user interface language?
1696 * @throws MWException
1697 */
1698 public function addWikiText( $text, $linestart = true, $interface = true ) {
1699 $title = $this->getTitle(); // Work around E_STRICT
1700 if ( !$title ) {
1701 throw new MWException( 'Title is null' );
1702 }
1703 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1704 }
1705
1706 /**
1707 * Add wikitext with a custom Title object
1708 *
1709 * @param string $text Wikitext
1710 * @param Title $title
1711 * @param bool $linestart Is this the start of a line?
1712 */
1713 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1714 $this->addWikiTextTitle( $text, $title, $linestart );
1715 }
1716
1717 /**
1718 * Add wikitext with a custom Title object and tidy enabled.
1719 *
1720 * @param string $text Wikitext
1721 * @param Title $title
1722 * @param bool $linestart Is this the start of a line?
1723 */
1724 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1725 $this->addWikiTextTitle( $text, $title, $linestart, true );
1726 }
1727
1728 /**
1729 * Add wikitext with tidy enabled
1730 *
1731 * @param string $text Wikitext
1732 * @param bool $linestart Is this the start of a line?
1733 */
1734 public function addWikiTextTidy( $text, $linestart = true ) {
1735 $title = $this->getTitle();
1736 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1737 }
1738
1739 /**
1740 * Add wikitext with a custom Title object
1741 *
1742 * @param string $text Wikitext
1743 * @param Title $title
1744 * @param bool $linestart Is this the start of a line?
1745 * @param bool $tidy Whether to use tidy
1746 * @param bool $interface Whether it is an interface message
1747 * (for example disables conversion)
1748 */
1749 public function addWikiTextTitle( $text, Title $title, $linestart,
1750 $tidy = false, $interface = false
1751 ) {
1752 global $wgParser;
1753
1754 $popts = $this->parserOptions();
1755 $oldTidy = $popts->setTidy( $tidy );
1756 $popts->setInterfaceMessage( (bool)$interface );
1757
1758 $parserOutput = $wgParser->getFreshParser()->parse(
1759 $text, $title, $popts,
1760 $linestart, true, $this->mRevisionId
1761 );
1762
1763 $popts->setTidy( $oldTidy );
1764
1765 $this->addParserOutput( $parserOutput );
1766 }
1767
1768 /**
1769 * Add a ParserOutput object, but without Html.
1770 *
1771 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1772 * @param ParserOutput $parserOutput
1773 */
1774 public function addParserOutputNoText( $parserOutput ) {
1775 wfDeprecated( __METHOD__, '1.24' );
1776 $this->addParserOutputMetadata( $parserOutput );
1777 }
1778
1779 /**
1780 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1781 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1782 * and so on.
1783 *
1784 * @since 1.24
1785 * @param ParserOutput $parserOutput
1786 */
1787 public function addParserOutputMetadata( $parserOutput ) {
1788 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1789 $this->addCategoryLinks( $parserOutput->getCategories() );
1790 $this->setIndicators( $parserOutput->getIndicators() );
1791 $this->mNewSectionLink = $parserOutput->getNewSection();
1792 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1793
1794 if ( !$parserOutput->isCacheable() ) {
1795 $this->enableClientCache( false );
1796 }
1797 $this->mNoGallery = $parserOutput->getNoGallery();
1798 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1799 $this->addModules( $parserOutput->getModules() );
1800 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1801 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1802 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1803 $this->mPreventClickjacking = $this->mPreventClickjacking
1804 || $parserOutput->preventClickjacking();
1805
1806 // Template versioning...
1807 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1808 if ( isset( $this->mTemplateIds[$ns] ) ) {
1809 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1810 } else {
1811 $this->mTemplateIds[$ns] = $dbks;
1812 }
1813 }
1814 // File versioning...
1815 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1816 $this->mImageTimeKeys[$dbk] = $data;
1817 }
1818
1819 // Hooks registered in the object
1820 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1821 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1822 list( $hookName, $data ) = $hookInfo;
1823 if ( isset( $parserOutputHooks[$hookName] ) ) {
1824 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1825 }
1826 }
1827
1828 // Enable OOUI if requested via ParserOutput
1829 if ( $parserOutput->getEnableOOUI() ) {
1830 $this->enableOOUI();
1831 }
1832
1833 // Include parser limit report
1834 if ( !$this->limitReportJSData ) {
1835 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
1836 }
1837
1838 // Link flags are ignored for now, but may in the future be
1839 // used to mark individual language links.
1840 $linkFlags = [];
1841 // Avoid PHP 7.1 warning of passing $this by reference
1842 $outputPage = $this;
1843 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1844 Hooks::run( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1845 }
1846
1847 /**
1848 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1849 * ParserOutput object, without any other metadata.
1850 *
1851 * @since 1.24
1852 * @param ParserOutput $parserOutput
1853 */
1854 public function addParserOutputContent( $parserOutput ) {
1855 $this->addParserOutputText( $parserOutput );
1856
1857 $this->addModules( $parserOutput->getModules() );
1858 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1859 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1860
1861 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1862 }
1863
1864 /**
1865 * Add the HTML associated with a ParserOutput object, without any metadata.
1866 *
1867 * @since 1.24
1868 * @param ParserOutput $parserOutput
1869 */
1870 public function addParserOutputText( $parserOutput ) {
1871 $text = $parserOutput->getText();
1872 // Avoid PHP 7.1 warning of passing $this by reference
1873 $outputPage = $this;
1874 Hooks::run( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1875 $this->addHTML( $text );
1876 }
1877
1878 /**
1879 * Add everything from a ParserOutput object.
1880 *
1881 * @param ParserOutput $parserOutput
1882 */
1883 function addParserOutput( $parserOutput ) {
1884 $this->addParserOutputMetadata( $parserOutput );
1885 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1886
1887 // Touch section edit links only if not previously disabled
1888 if ( $parserOutput->getEditSectionTokens() ) {
1889 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1890 }
1891
1892 $this->addParserOutputText( $parserOutput );
1893 }
1894
1895 /**
1896 * Add the output of a QuickTemplate to the output buffer
1897 *
1898 * @param QuickTemplate $template
1899 */
1900 public function addTemplate( &$template ) {
1901 $this->addHTML( $template->getHTML() );
1902 }
1903
1904 /**
1905 * Parse wikitext and return the HTML.
1906 *
1907 * @param string $text
1908 * @param bool $linestart Is this the start of a line?
1909 * @param bool $interface Use interface language ($wgLang instead of
1910 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1911 * This also disables LanguageConverter.
1912 * @param Language $language Target language object, will override $interface
1913 * @throws MWException
1914 * @return string HTML
1915 */
1916 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1917 global $wgParser;
1918
1919 if ( is_null( $this->getTitle() ) ) {
1920 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1921 }
1922
1923 $popts = $this->parserOptions();
1924 if ( $interface ) {
1925 $popts->setInterfaceMessage( true );
1926 }
1927 if ( $language !== null ) {
1928 $oldLang = $popts->setTargetLanguage( $language );
1929 }
1930
1931 $parserOutput = $wgParser->getFreshParser()->parse(
1932 $text, $this->getTitle(), $popts,
1933 $linestart, true, $this->mRevisionId
1934 );
1935
1936 if ( $interface ) {
1937 $popts->setInterfaceMessage( false );
1938 }
1939 if ( $language !== null ) {
1940 $popts->setTargetLanguage( $oldLang );
1941 }
1942
1943 return $parserOutput->getText();
1944 }
1945
1946 /**
1947 * Parse wikitext, strip paragraphs, and return the HTML.
1948 *
1949 * @param string $text
1950 * @param bool $linestart Is this the start of a line?
1951 * @param bool $interface Use interface language ($wgLang instead of
1952 * $wgContLang) while parsing language sensitive magic
1953 * words like GRAMMAR and PLURAL
1954 * @return string HTML
1955 */
1956 public function parseInline( $text, $linestart = true, $interface = false ) {
1957 $parsed = $this->parse( $text, $linestart, $interface );
1958 return Parser::stripOuterParagraph( $parsed );
1959 }
1960
1961 /**
1962 * @param $maxage
1963 * @deprecated since 1.27 Use setCdnMaxage() instead
1964 */
1965 public function setSquidMaxage( $maxage ) {
1966 $this->setCdnMaxage( $maxage );
1967 }
1968
1969 /**
1970 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1971 *
1972 * @param int $maxage Maximum cache time on the CDN, in seconds.
1973 */
1974 public function setCdnMaxage( $maxage ) {
1975 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
1976 }
1977
1978 /**
1979 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1980 *
1981 * @param int $maxage Maximum cache time on the CDN, in seconds
1982 * @since 1.27
1983 */
1984 public function lowerCdnMaxage( $maxage ) {
1985 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
1986 $this->setCdnMaxage( $this->mCdnMaxage );
1987 }
1988
1989 /**
1990 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1991 *
1992 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1993 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1994 * TTL is 90% of the age of the object, subject to the min and max.
1995 *
1996 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
1997 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
1998 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1999 * @return integer TTL in seconds
2000 * @since 1.28
2001 */
2002 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2003 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2004 $maxTTL = $maxTTL ?: $this->getConfig()->get( 'SquidMaxage' );
2005
2006 if ( $mtime === null || $mtime === false ) {
2007 return $minTTL; // entity does not exist
2008 }
2009
2010 $age = time() - wfTimestamp( TS_UNIX, $mtime );
2011 $adaptiveTTL = max( .9 * $age, $minTTL );
2012 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2013
2014 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2015
2016 return $adaptiveTTL;
2017 }
2018
2019 /**
2020 * Use enableClientCache(false) to force it to send nocache headers
2021 *
2022 * @param bool $state
2023 *
2024 * @return bool
2025 */
2026 public function enableClientCache( $state ) {
2027 return wfSetVar( $this->mEnableClientCache, $state );
2028 }
2029
2030 /**
2031 * Get the list of cookies that will influence on the cache
2032 *
2033 * @return array
2034 */
2035 function getCacheVaryCookies() {
2036 static $cookies;
2037 if ( $cookies === null ) {
2038 $config = $this->getConfig();
2039 $cookies = array_merge(
2040 SessionManager::singleton()->getVaryCookies(),
2041 [
2042 'forceHTTPS',
2043 ],
2044 $config->get( 'CacheVaryCookies' )
2045 );
2046 Hooks::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2047 }
2048 return $cookies;
2049 }
2050
2051 /**
2052 * Check if the request has a cache-varying cookie header
2053 * If it does, it's very important that we don't allow public caching
2054 *
2055 * @return bool
2056 */
2057 function haveCacheVaryCookies() {
2058 $request = $this->getRequest();
2059 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2060 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2061 wfDebug( __METHOD__ . ": found $cookieName\n" );
2062 return true;
2063 }
2064 }
2065 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2066 return false;
2067 }
2068
2069 /**
2070 * Add an HTTP header that will influence on the cache
2071 *
2072 * @param string $header Header name
2073 * @param string[]|null $option Options for the Key header. See
2074 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2075 * for the list of valid options.
2076 */
2077 public function addVaryHeader( $header, array $option = null ) {
2078 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2079 $this->mVaryHeader[$header] = [];
2080 }
2081 if ( !is_array( $option ) ) {
2082 $option = [];
2083 }
2084 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2085 }
2086
2087 /**
2088 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2089 * such as Accept-Encoding or Cookie
2090 *
2091 * @return string
2092 */
2093 public function getVaryHeader() {
2094 // If we vary on cookies, let's make sure it's always included here too.
2095 if ( $this->getCacheVaryCookies() ) {
2096 $this->addVaryHeader( 'Cookie' );
2097 }
2098
2099 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2100 $this->addVaryHeader( $header, $options );
2101 }
2102 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2103 }
2104
2105 /**
2106 * Get a complete Key header
2107 *
2108 * @return string
2109 */
2110 public function getKeyHeader() {
2111 $cvCookies = $this->getCacheVaryCookies();
2112
2113 $cookiesOption = [];
2114 foreach ( $cvCookies as $cookieName ) {
2115 $cookiesOption[] = 'param=' . $cookieName;
2116 }
2117 $this->addVaryHeader( 'Cookie', $cookiesOption );
2118
2119 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2120 $this->addVaryHeader( $header, $options );
2121 }
2122
2123 $headers = [];
2124 foreach ( $this->mVaryHeader as $header => $option ) {
2125 $newheader = $header;
2126 if ( is_array( $option ) && count( $option ) > 0 ) {
2127 $newheader .= ';' . implode( ';', $option );
2128 }
2129 $headers[] = $newheader;
2130 }
2131 $key = 'Key: ' . implode( ',', $headers );
2132
2133 return $key;
2134 }
2135
2136 /**
2137 * T23672: Add Accept-Language to Vary and Key headers
2138 * if there's no 'variant' parameter existed in GET.
2139 *
2140 * For example:
2141 * /w/index.php?title=Main_page should always be served; but
2142 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2143 */
2144 function addAcceptLanguage() {
2145 $title = $this->getTitle();
2146 if ( !$title instanceof Title ) {
2147 return;
2148 }
2149
2150 $lang = $title->getPageLanguage();
2151 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2152 $variants = $lang->getVariants();
2153 $aloption = [];
2154 foreach ( $variants as $variant ) {
2155 if ( $variant === $lang->getCode() ) {
2156 continue;
2157 } else {
2158 $aloption[] = 'substr=' . $variant;
2159
2160 // IE and some other browsers use BCP 47 standards in
2161 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2162 // We should handle these too.
2163 $variantBCP47 = wfBCP47( $variant );
2164 if ( $variantBCP47 !== $variant ) {
2165 $aloption[] = 'substr=' . $variantBCP47;
2166 }
2167 }
2168 }
2169 $this->addVaryHeader( 'Accept-Language', $aloption );
2170 }
2171 }
2172
2173 /**
2174 * Set a flag which will cause an X-Frame-Options header appropriate for
2175 * edit pages to be sent. The header value is controlled by
2176 * $wgEditPageFrameOptions.
2177 *
2178 * This is the default for special pages. If you display a CSRF-protected
2179 * form on an ordinary view page, then you need to call this function.
2180 *
2181 * @param bool $enable
2182 */
2183 public function preventClickjacking( $enable = true ) {
2184 $this->mPreventClickjacking = $enable;
2185 }
2186
2187 /**
2188 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2189 * This can be called from pages which do not contain any CSRF-protected
2190 * HTML form.
2191 */
2192 public function allowClickjacking() {
2193 $this->mPreventClickjacking = false;
2194 }
2195
2196 /**
2197 * Get the prevent-clickjacking flag
2198 *
2199 * @since 1.24
2200 * @return bool
2201 */
2202 public function getPreventClickjacking() {
2203 return $this->mPreventClickjacking;
2204 }
2205
2206 /**
2207 * Get the X-Frame-Options header value (without the name part), or false
2208 * if there isn't one. This is used by Skin to determine whether to enable
2209 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2210 *
2211 * @return string|false
2212 */
2213 public function getFrameOptions() {
2214 $config = $this->getConfig();
2215 if ( $config->get( 'BreakFrames' ) ) {
2216 return 'DENY';
2217 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2218 return $config->get( 'EditPageFrameOptions' );
2219 }
2220 return false;
2221 }
2222
2223 /**
2224 * Send cache control HTTP headers
2225 */
2226 public function sendCacheControl() {
2227 $response = $this->getRequest()->response();
2228 $config = $this->getConfig();
2229
2230 $this->addVaryHeader( 'Cookie' );
2231 $this->addAcceptLanguage();
2232
2233 # don't serve compressed data to clients who can't handle it
2234 # maintain different caches for logged-in users and non-logged in ones
2235 $response->header( $this->getVaryHeader() );
2236
2237 if ( $config->get( 'UseKeyHeader' ) ) {
2238 $response->header( $this->getKeyHeader() );
2239 }
2240
2241 if ( $this->mEnableClientCache ) {
2242 if (
2243 $config->get( 'UseSquid' ) &&
2244 !$response->hasCookies() &&
2245 !SessionManager::getGlobalSession()->isPersistent() &&
2246 !$this->isPrintable() &&
2247 $this->mCdnMaxage != 0 &&
2248 !$this->haveCacheVaryCookies()
2249 ) {
2250 if ( $config->get( 'UseESI' ) ) {
2251 # We'll purge the proxy cache explicitly, but require end user agents
2252 # to revalidate against the proxy on each visit.
2253 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2254 wfDebug( __METHOD__ .
2255 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2256 # start with a shorter timeout for initial testing
2257 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2258 $response->header(
2259 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2260 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2261 );
2262 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2263 } else {
2264 # We'll purge the proxy cache for anons explicitly, but require end user agents
2265 # to revalidate against the proxy on each visit.
2266 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2267 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2268 wfDebug( __METHOD__ .
2269 ": local proxy caching; {$this->mLastModified} **", 'private' );
2270 # start with a shorter timeout for initial testing
2271 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2272 $response->header( "Cache-Control: " .
2273 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2274 }
2275 } else {
2276 # We do want clients to cache if they can, but they *must* check for updates
2277 # on revisiting the page.
2278 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2279 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2280 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2281 }
2282 if ( $this->mLastModified ) {
2283 $response->header( "Last-Modified: {$this->mLastModified}" );
2284 }
2285 } else {
2286 wfDebug( __METHOD__ . ": no caching **", 'private' );
2287
2288 # In general, the absence of a last modified header should be enough to prevent
2289 # the client from using its cache. We send a few other things just to make sure.
2290 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2291 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2292 $response->header( 'Pragma: no-cache' );
2293 }
2294 }
2295
2296 /**
2297 * Finally, all the text has been munged and accumulated into
2298 * the object, let's actually output it:
2299 *
2300 * @param bool $return Set to true to get the result as a string rather than sending it
2301 * @return string|null
2302 * @throws Exception
2303 * @throws FatalError
2304 * @throws MWException
2305 */
2306 public function output( $return = false ) {
2307 global $wgContLang;
2308
2309 if ( $this->mDoNothing ) {
2310 return $return ? '' : null;
2311 }
2312
2313 $response = $this->getRequest()->response();
2314 $config = $this->getConfig();
2315
2316 if ( $this->mRedirect != '' ) {
2317 # Standards require redirect URLs to be absolute
2318 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2319
2320 $redirect = $this->mRedirect;
2321 $code = $this->mRedirectCode;
2322
2323 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2324 if ( $code == '301' || $code == '303' ) {
2325 if ( !$config->get( 'DebugRedirects' ) ) {
2326 $response->statusHeader( $code );
2327 }
2328 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2329 }
2330 if ( $config->get( 'VaryOnXFP' ) ) {
2331 $this->addVaryHeader( 'X-Forwarded-Proto' );
2332 }
2333 $this->sendCacheControl();
2334
2335 $response->header( "Content-Type: text/html; charset=utf-8" );
2336 if ( $config->get( 'DebugRedirects' ) ) {
2337 $url = htmlspecialchars( $redirect );
2338 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2339 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2340 print "</body>\n</html>\n";
2341 } else {
2342 $response->header( 'Location: ' . $redirect );
2343 }
2344 }
2345
2346 return $return ? '' : null;
2347 } elseif ( $this->mStatusCode ) {
2348 $response->statusHeader( $this->mStatusCode );
2349 }
2350
2351 # Buffer output; final headers may depend on later processing
2352 ob_start();
2353
2354 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2355 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2356
2357 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2358 // jQuery etc. can work correctly.
2359 $response->header( 'X-UA-Compatible: IE=Edge' );
2360
2361 // Prevent framing, if requested
2362 $frameOptions = $this->getFrameOptions();
2363 if ( $frameOptions ) {
2364 $response->header( "X-Frame-Options: $frameOptions" );
2365 }
2366
2367 if ( $this->mArticleBodyOnly ) {
2368 echo $this->mBodytext;
2369 } else {
2370 $sk = $this->getSkin();
2371 // add skin specific modules
2372 $modules = $sk->getDefaultModules();
2373
2374 // Enforce various default modules for all pages and all skins
2375 $coreModules = [
2376 // Keep this list as small as possible
2377 'site',
2378 'mediawiki.page.startup',
2379 'mediawiki.user',
2380 ];
2381
2382 // Support for high-density display images if enabled
2383 if ( $config->get( 'ResponsiveImages' ) ) {
2384 $coreModules[] = 'mediawiki.hidpi';
2385 }
2386
2387 $this->addModules( $coreModules );
2388 foreach ( $modules as $group ) {
2389 $this->addModules( $group );
2390 }
2391 MWDebug::addModules( $this );
2392
2393 // Avoid PHP 7.1 warning of passing $this by reference
2394 $outputPage = $this;
2395 // Hook that allows last minute changes to the output page, e.g.
2396 // adding of CSS or Javascript by extensions.
2397 Hooks::run( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2398
2399 try {
2400 $sk->outputPage();
2401 } catch ( Exception $e ) {
2402 ob_end_clean(); // bug T129657
2403 throw $e;
2404 }
2405 }
2406
2407 try {
2408 // This hook allows last minute changes to final overall output by modifying output buffer
2409 Hooks::run( 'AfterFinalPageOutput', [ $this ] );
2410 } catch ( Exception $e ) {
2411 ob_end_clean(); // bug T129657
2412 throw $e;
2413 }
2414
2415 $this->sendCacheControl();
2416
2417 if ( $return ) {
2418 return ob_get_clean();
2419 } else {
2420 ob_end_flush();
2421 return null;
2422 }
2423 }
2424
2425 /**
2426 * Prepare this object to display an error page; disable caching and
2427 * indexing, clear the current text and redirect, set the page's title
2428 * and optionally an custom HTML title (content of the "<title>" tag).
2429 *
2430 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2431 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2432 * optional, if not passed the "<title>" attribute will be
2433 * based on $pageTitle
2434 */
2435 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2436 $this->setPageTitle( $pageTitle );
2437 if ( $htmlTitle !== false ) {
2438 $this->setHTMLTitle( $htmlTitle );
2439 }
2440 $this->setRobotPolicy( 'noindex,nofollow' );
2441 $this->setArticleRelated( false );
2442 $this->enableClientCache( false );
2443 $this->mRedirect = '';
2444 $this->clearSubtitle();
2445 $this->clearHTML();
2446 }
2447
2448 /**
2449 * Output a standard error page
2450 *
2451 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2452 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2453 * showErrorPage( 'titlemsg', $messageObject );
2454 * showErrorPage( $titleMessageObject, $messageObject );
2455 *
2456 * @param string|Message $title Message key (string) for page title, or a Message object
2457 * @param string|Message $msg Message key (string) for page text, or a Message object
2458 * @param array $params Message parameters; ignored if $msg is a Message object
2459 */
2460 public function showErrorPage( $title, $msg, $params = [] ) {
2461 if ( !$title instanceof Message ) {
2462 $title = $this->msg( $title );
2463 }
2464
2465 $this->prepareErrorPage( $title );
2466
2467 if ( $msg instanceof Message ) {
2468 if ( $params !== [] ) {
2469 trigger_error( 'Argument ignored: $params. The message parameters argument '
2470 . 'is discarded when the $msg argument is a Message object instead of '
2471 . 'a string.', E_USER_NOTICE );
2472 }
2473 $this->addHTML( $msg->parseAsBlock() );
2474 } else {
2475 $this->addWikiMsgArray( $msg, $params );
2476 }
2477
2478 $this->returnToMain();
2479 }
2480
2481 /**
2482 * Output a standard permission error page
2483 *
2484 * @param array $errors Error message keys or [key, param...] arrays
2485 * @param string $action Action that was denied or null if unknown
2486 */
2487 public function showPermissionsErrorPage( array $errors, $action = null ) {
2488 foreach ( $errors as $key => $error ) {
2489 $errors[$key] = (array)$error;
2490 }
2491
2492 // For some action (read, edit, create and upload), display a "login to do this action"
2493 // error if all of the following conditions are met:
2494 // 1. the user is not logged in
2495 // 2. the only error is insufficient permissions (i.e. no block or something else)
2496 // 3. the error can be avoided simply by logging in
2497 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2498 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2499 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2500 && ( User::groupHasPermission( 'user', $action )
2501 || User::groupHasPermission( 'autoconfirmed', $action ) )
2502 ) {
2503 $displayReturnto = null;
2504
2505 # Due to T34276, if a user does not have read permissions,
2506 # $this->getTitle() will just give Special:Badtitle, which is
2507 # not especially useful as a returnto parameter. Use the title
2508 # from the request instead, if there was one.
2509 $request = $this->getRequest();
2510 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2511 if ( $action == 'edit' ) {
2512 $msg = 'whitelistedittext';
2513 $displayReturnto = $returnto;
2514 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2515 $msg = 'nocreatetext';
2516 } elseif ( $action == 'upload' ) {
2517 $msg = 'uploadnologintext';
2518 } else { # Read
2519 $msg = 'loginreqpagetext';
2520 $displayReturnto = Title::newMainPage();
2521 }
2522
2523 $query = [];
2524
2525 if ( $returnto ) {
2526 $query['returnto'] = $returnto->getPrefixedText();
2527
2528 if ( !$request->wasPosted() ) {
2529 $returntoquery = $request->getValues();
2530 unset( $returntoquery['title'] );
2531 unset( $returntoquery['returnto'] );
2532 unset( $returntoquery['returntoquery'] );
2533 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2534 }
2535 }
2536 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
2537 $loginLink = $linkRenderer->makeKnownLink(
2538 SpecialPage::getTitleFor( 'Userlogin' ),
2539 $this->msg( 'loginreqlink' )->text(),
2540 [],
2541 $query
2542 );
2543
2544 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2545 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2546
2547 # Don't return to a page the user can't read otherwise
2548 # we'll end up in a pointless loop
2549 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2550 $this->returnToMain( null, $displayReturnto );
2551 }
2552 } else {
2553 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2554 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2555 }
2556 }
2557
2558 /**
2559 * Display an error page indicating that a given version of MediaWiki is
2560 * required to use it
2561 *
2562 * @param mixed $version The version of MediaWiki needed to use the page
2563 */
2564 public function versionRequired( $version ) {
2565 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2566
2567 $this->addWikiMsg( 'versionrequiredtext', $version );
2568 $this->returnToMain();
2569 }
2570
2571 /**
2572 * Format a list of error messages
2573 *
2574 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2575 * @param string $action Action that was denied or null if unknown
2576 * @return string The wikitext error-messages, formatted into a list.
2577 */
2578 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2579 if ( $action == null ) {
2580 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2581 } else {
2582 $action_desc = $this->msg( "action-$action" )->plain();
2583 $text = $this->msg(
2584 'permissionserrorstext-withaction',
2585 count( $errors ),
2586 $action_desc
2587 )->plain() . "\n\n";
2588 }
2589
2590 if ( count( $errors ) > 1 ) {
2591 $text .= '<ul class="permissions-errors">' . "\n";
2592
2593 foreach ( $errors as $error ) {
2594 $text .= '<li>';
2595 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2596 $text .= "</li>\n";
2597 }
2598 $text .= '</ul>';
2599 } else {
2600 $text .= "<div class=\"permissions-errors\">\n" .
2601 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2602 "\n</div>";
2603 }
2604
2605 return $text;
2606 }
2607
2608 /**
2609 * Display a page stating that the Wiki is in read-only mode.
2610 * Should only be called after wfReadOnly() has returned true.
2611 *
2612 * Historically, this function was used to show the source of the page that the user
2613 * was trying to edit and _also_ permissions error messages. The relevant code was
2614 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2615 *
2616 * @deprecated since 1.25; throw the exception directly
2617 * @throws ReadOnlyError
2618 */
2619 public function readOnlyPage() {
2620 if ( func_num_args() > 0 ) {
2621 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2622 }
2623
2624 throw new ReadOnlyError;
2625 }
2626
2627 /**
2628 * Turn off regular page output and return an error response
2629 * for when rate limiting has triggered.
2630 *
2631 * @deprecated since 1.25; throw the exception directly
2632 */
2633 public function rateLimited() {
2634 wfDeprecated( __METHOD__, '1.25' );
2635 throw new ThrottledError;
2636 }
2637
2638 /**
2639 * Show a warning about replica DB lag
2640 *
2641 * If the lag is higher than $wgSlaveLagCritical seconds,
2642 * then the warning is a bit more obvious. If the lag is
2643 * lower than $wgSlaveLagWarning, then no warning is shown.
2644 *
2645 * @param int $lag Slave lag
2646 */
2647 public function showLagWarning( $lag ) {
2648 $config = $this->getConfig();
2649 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2650 $lag = floor( $lag ); // floor to avoid nano seconds to display
2651 $message = $lag < $config->get( 'SlaveLagCritical' )
2652 ? 'lag-warn-normal'
2653 : 'lag-warn-high';
2654 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2655 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2656 }
2657 }
2658
2659 public function showFatalError( $message ) {
2660 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2661
2662 $this->addHTML( $message );
2663 }
2664
2665 public function showUnexpectedValueError( $name, $val ) {
2666 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2667 }
2668
2669 public function showFileCopyError( $old, $new ) {
2670 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2671 }
2672
2673 public function showFileRenameError( $old, $new ) {
2674 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2675 }
2676
2677 public function showFileDeleteError( $name ) {
2678 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2679 }
2680
2681 public function showFileNotFoundError( $name ) {
2682 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2683 }
2684
2685 /**
2686 * Add a "return to" link pointing to a specified title
2687 *
2688 * @param Title $title Title to link
2689 * @param array $query Query string parameters
2690 * @param string $text Text of the link (input is not escaped)
2691 * @param array $options Options array to pass to Linker
2692 */
2693 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2694 $linkRenderer = MediaWikiServices::getInstance()
2695 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2696 $link = $this->msg( 'returnto' )->rawParams(
2697 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2698 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2699 }
2700
2701 /**
2702 * Add a "return to" link pointing to a specified title,
2703 * or the title indicated in the request, or else the main page
2704 *
2705 * @param mixed $unused
2706 * @param Title|string $returnto Title or String to return to
2707 * @param string $returntoquery Query string for the return to link
2708 */
2709 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2710 if ( $returnto == null ) {
2711 $returnto = $this->getRequest()->getText( 'returnto' );
2712 }
2713
2714 if ( $returntoquery == null ) {
2715 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2716 }
2717
2718 if ( $returnto === '' ) {
2719 $returnto = Title::newMainPage();
2720 }
2721
2722 if ( is_object( $returnto ) ) {
2723 $titleObj = $returnto;
2724 } else {
2725 $titleObj = Title::newFromText( $returnto );
2726 }
2727 if ( !is_object( $titleObj ) ) {
2728 $titleObj = Title::newMainPage();
2729 }
2730
2731 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2732 }
2733
2734 private function getRlClientContext() {
2735 if ( !$this->rlClientContext ) {
2736 $query = ResourceLoader::makeLoaderQuery(
2737 [], // modules; not relevant
2738 $this->getLanguage()->getCode(),
2739 $this->getSkin()->getSkinName(),
2740 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2741 null, // version; not relevant
2742 ResourceLoader::inDebugMode(),
2743 null, // only; not relevant
2744 $this->isPrintable(),
2745 $this->getRequest()->getBool( 'handheld' )
2746 );
2747 $this->rlClientContext = new ResourceLoaderContext(
2748 $this->getResourceLoader(),
2749 new FauxRequest( $query )
2750 );
2751 }
2752 return $this->rlClientContext;
2753 }
2754
2755 /**
2756 * Call this to freeze the module queue and JS config and create a formatter.
2757 *
2758 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2759 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2760 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2761 * the module filters retroactively. Skins and extension hooks may also add modules until very
2762 * late in the request lifecycle.
2763 *
2764 * @return ResourceLoaderClientHtml
2765 */
2766 public function getRlClient() {
2767 if ( !$this->rlClient ) {
2768 $context = $this->getRlClientContext();
2769 $rl = $this->getResourceLoader();
2770 $this->addModules( [
2771 'user.options',
2772 'user.tokens',
2773 ] );
2774 $this->addModuleStyles( [
2775 'site.styles',
2776 'noscript',
2777 'user.styles',
2778 ] );
2779 $this->getSkin()->setupSkinUserCss( $this );
2780
2781 // Prepare exempt modules for buildExemptModules()
2782 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2783 $exemptStates = [];
2784 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2785
2786 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2787 // Separate user-specific batch for improved cache-hit ratio.
2788 $userBatch = [ 'user.styles', 'user' ];
2789 $siteBatch = array_diff( $moduleStyles, $userBatch );
2790 $dbr = wfGetDB( DB_REPLICA );
2791 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2792 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2793
2794 // Filter out modules handled by buildExemptModules()
2795 $moduleStyles = array_filter( $moduleStyles,
2796 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2797 $module = $rl->getModule( $name );
2798 if ( $module ) {
2799 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2800 $exemptStates[$name] = 'ready';
2801 // Special case in buildExemptModules()
2802 return false;
2803 }
2804 $group = $module->getGroup();
2805 if ( isset( $exemptGroups[$group] ) ) {
2806 $exemptStates[$name] = 'ready';
2807 if ( !$module->isKnownEmpty( $context ) ) {
2808 // E.g. Don't output empty <styles>
2809 $exemptGroups[$group][] = $name;
2810 }
2811 return false;
2812 }
2813 }
2814 return true;
2815 }
2816 );
2817 $this->rlExemptStyleModules = $exemptGroups;
2818
2819 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2820 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2821 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2822 if ( !$isUserModuleFiltered ) {
2823 // Manually handled by getBottomScripts()
2824 $userModule = $rl->getModule( 'user' );
2825 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2826 ? 'ready'
2827 : 'loading';
2828 $this->rlUserModuleState = $exemptStates['user'] = $userState;
2829 }
2830
2831 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2832 $rlClient->setConfig( $this->getJSVars() );
2833 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2834 $rlClient->setModuleStyles( $moduleStyles );
2835 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2836 $rlClient->setExemptStates( $exemptStates );
2837 $this->rlClient = $rlClient;
2838 }
2839 return $this->rlClient;
2840 }
2841
2842 /**
2843 * @param Skin $sk The given Skin
2844 * @param bool $includeStyle Unused
2845 * @return string The doctype, opening "<html>", and head element.
2846 */
2847 public function headElement( Skin $sk, $includeStyle = true ) {
2848 global $wgContLang;
2849
2850 $userdir = $this->getLanguage()->getDir();
2851 $sitedir = $wgContLang->getDir();
2852
2853 $pieces = [];
2854 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
2855 $this->getRlClient()->getDocumentAttributes(),
2856 $sk->getHtmlElementAttributes()
2857 ) );
2858 $pieces[] = Html::openElement( 'head' );
2859
2860 if ( $this->getHTMLTitle() == '' ) {
2861 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2862 }
2863
2864 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2865 // Add <meta charset="UTF-8">
2866 // This should be before <title> since it defines the charset used by
2867 // text including the text inside <title>.
2868 // The spec recommends defining XHTML5's charset using the XML declaration
2869 // instead of meta.
2870 // Our XML declaration is output by Html::htmlHeader.
2871 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2872 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2873 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
2874 }
2875
2876 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
2877 $pieces[] = $this->getRlClient()->getHeadHtml();
2878 $pieces[] = $this->buildExemptModules();
2879 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2880 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
2881 $pieces[] = Html::closeElement( 'head' );
2882
2883 $bodyClasses = [];
2884 $bodyClasses[] = 'mediawiki';
2885
2886 # Classes for LTR/RTL directionality support
2887 $bodyClasses[] = $userdir;
2888 $bodyClasses[] = "sitedir-$sitedir";
2889
2890 $underline = $this->getUser()->getOption( 'underline' );
2891 if ( $underline < 2 ) {
2892 // The following classes can be used here:
2893 // * mw-underline-always
2894 // * mw-underline-never
2895 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
2896 }
2897
2898 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2899 # A <body> class is probably not the best way to do this . . .
2900 $bodyClasses[] = 'capitalize-all-nouns';
2901 }
2902
2903 // Parser feature migration class
2904 // The idea is that this will eventually be removed, after the wikitext
2905 // which requires it is cleaned up.
2906 $bodyClasses[] = 'mw-hide-empty-elt';
2907
2908 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2909 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2910 $bodyClasses[] =
2911 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2912
2913 $bodyAttrs = [];
2914 // While the implode() is not strictly needed, it's used for backwards compatibility
2915 // (this used to be built as a string and hooks likely still expect that).
2916 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2917
2918 // Allow skins and extensions to add body attributes they need
2919 $sk->addToBodyAttributes( $this, $bodyAttrs );
2920 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2921
2922 $pieces[] = Html::openElement( 'body', $bodyAttrs );
2923
2924 return self::combineWrappedStrings( $pieces );
2925 }
2926
2927 /**
2928 * Get a ResourceLoader object associated with this OutputPage
2929 *
2930 * @return ResourceLoader
2931 */
2932 public function getResourceLoader() {
2933 if ( is_null( $this->mResourceLoader ) ) {
2934 $this->mResourceLoader = new ResourceLoader(
2935 $this->getConfig(),
2936 LoggerFactory::getInstance( 'resourceloader' )
2937 );
2938 }
2939 return $this->mResourceLoader;
2940 }
2941
2942 /**
2943 * Explicily load or embed modules on a page.
2944 *
2945 * @param array|string $modules One or more module names
2946 * @param string $only ResourceLoaderModule TYPE_ class constant
2947 * @param array $extraQuery [optional] Array with extra query parameters for the request
2948 * @return string|WrappedStringList HTML
2949 */
2950 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2951 // Apply 'target' and 'origin' filters
2952 $modules = $this->filterModules( (array)$modules, null, $only );
2953
2954 return ResourceLoaderClientHtml::makeLoad(
2955 $this->getRlClientContext(),
2956 $modules,
2957 $only,
2958 $extraQuery
2959 );
2960 }
2961
2962 /**
2963 * Combine WrappedString chunks and filter out empty ones
2964 *
2965 * @param array $chunks
2966 * @return string|WrappedStringList HTML
2967 */
2968 protected static function combineWrappedStrings( array $chunks ) {
2969 // Filter out empty values
2970 $chunks = array_filter( $chunks, 'strlen' );
2971 return WrappedString::join( "\n", $chunks );
2972 }
2973
2974 private function isUserJsPreview() {
2975 return $this->getConfig()->get( 'AllowUserJs' )
2976 && $this->getTitle()
2977 && $this->getTitle()->isJsSubpage()
2978 && $this->userCanPreview();
2979 }
2980
2981 private function isUserCssPreview() {
2982 return $this->getConfig()->get( 'AllowUserCss' )
2983 && $this->getTitle()
2984 && $this->getTitle()->isCssSubpage()
2985 && $this->userCanPreview();
2986 }
2987
2988 /**
2989 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2990 * legacy scripts ($this->mScripts), and user JS.
2991 *
2992 * @return string|WrappedStringList HTML
2993 */
2994 public function getBottomScripts() {
2995 $chunks = [];
2996 $chunks[] = $this->getRlClient()->getBodyHtml();
2997
2998 // Legacy non-ResourceLoader scripts
2999 $chunks[] = $this->mScripts;
3000
3001 // Exempt 'user' module
3002 // - May need excludepages for live preview. (T28283)
3003 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
3004 // ensures execution is scheduled after the "site" module.
3005 // - Don't load if module state is already resolved as "ready".
3006 if ( $this->rlUserModuleState === 'loading' ) {
3007 if ( $this->isUserJsPreview() ) {
3008 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3009 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3010 );
3011 $chunks[] = ResourceLoader::makeInlineScript(
3012 Xml::encodeJsCall( 'mw.loader.using', [
3013 [ 'user', 'site' ],
3014 new XmlJsCode(
3015 'function () {'
3016 . Xml::encodeJsCall( '$.globalEval', [
3017 $this->getRequest()->getText( 'wpTextbox1' )
3018 ] )
3019 . '}'
3020 )
3021 ] )
3022 );
3023 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3024 // asynchronously and may arrive *after* the inline script here. So the previewed code
3025 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3026 // Similarly, when previewing ./common.js and the user module does arrive first,
3027 // it will arrive without common.js and the inline script runs after.
3028 // Thus running common after the excluded subpage.
3029 } else {
3030 // Load normally
3031 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
3032 }
3033 }
3034
3035 if ( $this->limitReportJSData ) {
3036 $chunks[] = ResourceLoader::makeInlineScript(
3037 ResourceLoader::makeConfigSetScript(
3038 [ 'wgPageParseReport' => $this->limitReportJSData ]
3039 )
3040 );
3041 }
3042
3043 return self::combineWrappedStrings( $chunks );
3044 }
3045
3046 /**
3047 * Get the javascript config vars to include on this page
3048 *
3049 * @return array Array of javascript config vars
3050 * @since 1.23
3051 */
3052 public function getJsConfigVars() {
3053 return $this->mJsConfigVars;
3054 }
3055
3056 /**
3057 * Add one or more variables to be set in mw.config in JavaScript
3058 *
3059 * @param string|array $keys Key or array of key/value pairs
3060 * @param mixed $value [optional] Value of the configuration variable
3061 */
3062 public function addJsConfigVars( $keys, $value = null ) {
3063 if ( is_array( $keys ) ) {
3064 foreach ( $keys as $key => $value ) {
3065 $this->mJsConfigVars[$key] = $value;
3066 }
3067 return;
3068 }
3069
3070 $this->mJsConfigVars[$keys] = $value;
3071 }
3072
3073 /**
3074 * Get an array containing the variables to be set in mw.config in JavaScript.
3075 *
3076 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3077 * - in other words, page-independent/site-wide variables (without state).
3078 * You will only be adding bloat to the html page and causing page caches to
3079 * have to be purged on configuration changes.
3080 * @return array
3081 */
3082 public function getJSVars() {
3083 global $wgContLang;
3084
3085 $curRevisionId = 0;
3086 $articleId = 0;
3087 $canonicalSpecialPageName = false; # T23115
3088
3089 $title = $this->getTitle();
3090 $ns = $title->getNamespace();
3091 $canonicalNamespace = MWNamespace::exists( $ns )
3092 ? MWNamespace::getCanonicalName( $ns )
3093 : $title->getNsText();
3094
3095 $sk = $this->getSkin();
3096 // Get the relevant title so that AJAX features can use the correct page name
3097 // when making API requests from certain special pages (T36972).
3098 $relevantTitle = $sk->getRelevantTitle();
3099 $relevantUser = $sk->getRelevantUser();
3100
3101 if ( $ns == NS_SPECIAL ) {
3102 list( $canonicalSpecialPageName, /*...*/ ) =
3103 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3104 } elseif ( $this->canUseWikiPage() ) {
3105 $wikiPage = $this->getWikiPage();
3106 $curRevisionId = $wikiPage->getLatest();
3107 $articleId = $wikiPage->getId();
3108 }
3109
3110 $lang = $title->getPageViewLanguage();
3111
3112 // Pre-process information
3113 $separatorTransTable = $lang->separatorTransformTable();
3114 $separatorTransTable = $separatorTransTable ? $separatorTransTable : [];
3115 $compactSeparatorTransTable = [
3116 implode( "\t", array_keys( $separatorTransTable ) ),
3117 implode( "\t", $separatorTransTable ),
3118 ];
3119 $digitTransTable = $lang->digitTransformTable();
3120 $digitTransTable = $digitTransTable ? $digitTransTable : [];
3121 $compactDigitTransTable = [
3122 implode( "\t", array_keys( $digitTransTable ) ),
3123 implode( "\t", $digitTransTable ),
3124 ];
3125
3126 $user = $this->getUser();
3127
3128 $vars = [
3129 'wgCanonicalNamespace' => $canonicalNamespace,
3130 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3131 'wgNamespaceNumber' => $title->getNamespace(),
3132 'wgPageName' => $title->getPrefixedDBkey(),
3133 'wgTitle' => $title->getText(),
3134 'wgCurRevisionId' => $curRevisionId,
3135 'wgRevisionId' => (int)$this->getRevisionId(),
3136 'wgArticleId' => $articleId,
3137 'wgIsArticle' => $this->isArticle(),
3138 'wgIsRedirect' => $title->isRedirect(),
3139 'wgAction' => Action::getActionName( $this->getContext() ),
3140 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3141 'wgUserGroups' => $user->getEffectiveGroups(),
3142 'wgCategories' => $this->getCategories(),
3143 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3144 'wgPageContentLanguage' => $lang->getCode(),
3145 'wgPageContentModel' => $title->getContentModel(),
3146 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3147 'wgDigitTransformTable' => $compactDigitTransTable,
3148 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3149 'wgMonthNames' => $lang->getMonthNamesArray(),
3150 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3151 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3152 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3153 'wgRequestId' => WebRequest::getRequestId(),
3154 ];
3155
3156 if ( $user->isLoggedIn() ) {
3157 $vars['wgUserId'] = $user->getId();
3158 $vars['wgUserEditCount'] = $user->getEditCount();
3159 $userReg = $user->getRegistration();
3160 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3161 // Get the revision ID of the oldest new message on the user's talk
3162 // page. This can be used for constructing new message alerts on
3163 // the client side.
3164 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3165 }
3166
3167 if ( $wgContLang->hasVariants() ) {
3168 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3169 }
3170 // Same test as SkinTemplate
3171 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3172 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3173
3174 foreach ( $title->getRestrictionTypes() as $type ) {
3175 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3176 }
3177
3178 if ( $title->isMainPage() ) {
3179 $vars['wgIsMainPage'] = true;
3180 }
3181
3182 if ( $this->mRedirectedFrom ) {
3183 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3184 }
3185
3186 if ( $relevantUser ) {
3187 $vars['wgRelevantUserName'] = $relevantUser->getName();
3188 }
3189
3190 // Allow extensions to add their custom variables to the mw.config map.
3191 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3192 // page-dependant but site-wide (without state).
3193 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3194 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3195
3196 // Merge in variables from addJsConfigVars last
3197 return array_merge( $vars, $this->getJsConfigVars() );
3198 }
3199
3200 /**
3201 * To make it harder for someone to slip a user a fake
3202 * user-JavaScript or user-CSS preview, a random token
3203 * is associated with the login session. If it's not
3204 * passed back with the preview request, we won't render
3205 * the code.
3206 *
3207 * @return bool
3208 */
3209 public function userCanPreview() {
3210 $request = $this->getRequest();
3211 if (
3212 $request->getVal( 'action' ) !== 'submit' ||
3213 !$request->getCheck( 'wpPreview' ) ||
3214 !$request->wasPosted()
3215 ) {
3216 return false;
3217 }
3218
3219 $user = $this->getUser();
3220
3221 if ( !$user->isLoggedIn() ) {
3222 // Anons have predictable edit tokens
3223 return false;
3224 }
3225 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3226 return false;
3227 }
3228
3229 $title = $this->getTitle();
3230 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3231 return false;
3232 }
3233 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3234 // Don't execute another user's CSS or JS on preview (T85855)
3235 return false;
3236 }
3237
3238 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3239 if ( count( $errors ) !== 0 ) {
3240 return false;
3241 }
3242
3243 return true;
3244 }
3245
3246 /**
3247 * @return array Array in format "link name or number => 'link html'".
3248 */
3249 public function getHeadLinksArray() {
3250 global $wgVersion;
3251
3252 $tags = [];
3253 $config = $this->getConfig();
3254
3255 $canonicalUrl = $this->mCanonicalUrl;
3256
3257 $tags['meta-generator'] = Html::element( 'meta', [
3258 'name' => 'generator',
3259 'content' => "MediaWiki $wgVersion",
3260 ] );
3261
3262 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3263 $tags['meta-referrer'] = Html::element( 'meta', [
3264 'name' => 'referrer',
3265 'content' => $config->get( 'ReferrerPolicy' )
3266 ] );
3267 }
3268
3269 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3270 if ( $p !== 'index,follow' ) {
3271 // http://www.robotstxt.org/wc/meta-user.html
3272 // Only show if it's different from the default robots policy
3273 $tags['meta-robots'] = Html::element( 'meta', [
3274 'name' => 'robots',
3275 'content' => $p,
3276 ] );
3277 }
3278
3279 foreach ( $this->mMetatags as $tag ) {
3280 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3281 $a = 'http-equiv';
3282 $tag[0] = substr( $tag[0], 5 );
3283 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3284 $a = 'property';
3285 } else {
3286 $a = 'name';
3287 }
3288 $tagName = "meta-{$tag[0]}";
3289 if ( isset( $tags[$tagName] ) ) {
3290 $tagName .= $tag[1];
3291 }
3292 $tags[$tagName] = Html::element( 'meta',
3293 [
3294 $a => $tag[0],
3295 'content' => $tag[1]
3296 ]
3297 );
3298 }
3299
3300 foreach ( $this->mLinktags as $tag ) {
3301 $tags[] = Html::element( 'link', $tag );
3302 }
3303
3304 # Universal edit button
3305 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3306 $user = $this->getUser();
3307 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3308 && ( $this->getTitle()->exists() ||
3309 $this->getTitle()->quickUserCan( 'create', $user ) )
3310 ) {
3311 // Original UniversalEditButton
3312 $msg = $this->msg( 'edit' )->text();
3313 $tags['universal-edit-button'] = Html::element( 'link', [
3314 'rel' => 'alternate',
3315 'type' => 'application/x-wiki',
3316 'title' => $msg,
3317 'href' => $this->getTitle()->getEditURL(),
3318 ] );
3319 // Alternate edit link
3320 $tags['alternative-edit'] = Html::element( 'link', [
3321 'rel' => 'edit',
3322 'title' => $msg,
3323 'href' => $this->getTitle()->getEditURL(),
3324 ] );
3325 }
3326 }
3327
3328 # Generally the order of the favicon and apple-touch-icon links
3329 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3330 # uses whichever one appears later in the HTML source. Make sure
3331 # apple-touch-icon is specified first to avoid this.
3332 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3333 $tags['apple-touch-icon'] = Html::element( 'link', [
3334 'rel' => 'apple-touch-icon',
3335 'href' => $config->get( 'AppleTouchIcon' )
3336 ] );
3337 }
3338
3339 if ( $config->get( 'Favicon' ) !== false ) {
3340 $tags['favicon'] = Html::element( 'link', [
3341 'rel' => 'shortcut icon',
3342 'href' => $config->get( 'Favicon' )
3343 ] );
3344 }
3345
3346 # OpenSearch description link
3347 $tags['opensearch'] = Html::element( 'link', [
3348 'rel' => 'search',
3349 'type' => 'application/opensearchdescription+xml',
3350 'href' => wfScript( 'opensearch_desc' ),
3351 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3352 ] );
3353
3354 if ( $config->get( 'EnableAPI' ) ) {
3355 # Real Simple Discovery link, provides auto-discovery information
3356 # for the MediaWiki API (and potentially additional custom API
3357 # support such as WordPress or Twitter-compatible APIs for a
3358 # blogging extension, etc)
3359 $tags['rsd'] = Html::element( 'link', [
3360 'rel' => 'EditURI',
3361 'type' => 'application/rsd+xml',
3362 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3363 // Whether RSD accepts relative or protocol-relative URLs is completely
3364 // undocumented, though.
3365 'href' => wfExpandUrl( wfAppendQuery(
3366 wfScript( 'api' ),
3367 [ 'action' => 'rsd' ] ),
3368 PROTO_RELATIVE
3369 ),
3370 ] );
3371 }
3372
3373 # Language variants
3374 if ( !$config->get( 'DisableLangConversion' ) ) {
3375 $lang = $this->getTitle()->getPageLanguage();
3376 if ( $lang->hasVariants() ) {
3377 $variants = $lang->getVariants();
3378 foreach ( $variants as $variant ) {
3379 $tags["variant-$variant"] = Html::element( 'link', [
3380 'rel' => 'alternate',
3381 'hreflang' => wfBCP47( $variant ),
3382 'href' => $this->getTitle()->getLocalURL(
3383 [ 'variant' => $variant ] )
3384 ]
3385 );
3386 }
3387 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3388 $tags["variant-x-default"] = Html::element( 'link', [
3389 'rel' => 'alternate',
3390 'hreflang' => 'x-default',
3391 'href' => $this->getTitle()->getLocalURL() ] );
3392 }
3393 }
3394
3395 # Copyright
3396 if ( $this->copyrightUrl !== null ) {
3397 $copyright = $this->copyrightUrl;
3398 } else {
3399 $copyright = '';
3400 if ( $config->get( 'RightsPage' ) ) {
3401 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3402
3403 if ( $copy ) {
3404 $copyright = $copy->getLocalURL();
3405 }
3406 }
3407
3408 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3409 $copyright = $config->get( 'RightsUrl' );
3410 }
3411 }
3412
3413 if ( $copyright ) {
3414 $tags['copyright'] = Html::element( 'link', [
3415 'rel' => 'copyright',
3416 'href' => $copyright ]
3417 );
3418 }
3419
3420 # Feeds
3421 if ( $config->get( 'Feed' ) ) {
3422 $feedLinks = [];
3423
3424 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3425 # Use the page name for the title. In principle, this could
3426 # lead to issues with having the same name for different feeds
3427 # corresponding to the same page, but we can't avoid that at
3428 # this low a level.
3429
3430 $feedLinks[] = $this->feedLink(
3431 $format,
3432 $link,
3433 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3434 $this->msg(
3435 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3436 )->text()
3437 );
3438 }
3439
3440 # Recent changes feed should appear on every page (except recentchanges,
3441 # that would be redundant). Put it after the per-page feed to avoid
3442 # changing existing behavior. It's still available, probably via a
3443 # menu in your browser. Some sites might have a different feed they'd
3444 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3445 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3446 # If so, use it instead.
3447 $sitename = $config->get( 'Sitename' );
3448 if ( $config->get( 'OverrideSiteFeed' ) ) {
3449 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3450 // Note, this->feedLink escapes the url.
3451 $feedLinks[] = $this->feedLink(
3452 $type,
3453 $feedUrl,
3454 $this->msg( "site-{$type}-feed", $sitename )->text()
3455 );
3456 }
3457 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3458 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3459 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3460 $feedLinks[] = $this->feedLink(
3461 $format,
3462 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3463 # For grep: 'site-rss-feed', 'site-atom-feed'
3464 $this->msg( "site-{$format}-feed", $sitename )->text()
3465 );
3466 }
3467 }
3468
3469 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3470 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3471 # use OutputPage::addFeedLink() instead.
3472 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3473
3474 $tags += $feedLinks;
3475 }
3476
3477 # Canonical URL
3478 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3479 if ( $canonicalUrl !== false ) {
3480 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3481 } else {
3482 if ( $this->isArticleRelated() ) {
3483 // This affects all requests where "setArticleRelated" is true. This is
3484 // typically all requests that show content (query title, curid, oldid, diff),
3485 // and all wikipage actions (edit, delete, purge, info, history etc.).
3486 // It does not apply to File pages and Special pages.
3487 // 'history' and 'info' actions address page metadata rather than the page
3488 // content itself, so they may not be canonicalized to the view page url.
3489 // TODO: this ought to be better encapsulated in the Action class.
3490 $action = Action::getActionName( $this->getContext() );
3491 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3492 $query = "action={$action}";
3493 } else {
3494 $query = '';
3495 }
3496 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3497 } else {
3498 $reqUrl = $this->getRequest()->getRequestURL();
3499 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3500 }
3501 }
3502 }
3503 if ( $canonicalUrl !== false ) {
3504 $tags[] = Html::element( 'link', [
3505 'rel' => 'canonical',
3506 'href' => $canonicalUrl
3507 ] );
3508 }
3509
3510 return $tags;
3511 }
3512
3513 /**
3514 * @return string HTML tag links to be put in the header.
3515 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3516 * OutputPage::getHeadLinksArray directly.
3517 */
3518 public function getHeadLinks() {
3519 wfDeprecated( __METHOD__, '1.24' );
3520 return implode( "\n", $this->getHeadLinksArray() );
3521 }
3522
3523 /**
3524 * Generate a "<link rel/>" for a feed.
3525 *
3526 * @param string $type Feed type
3527 * @param string $url URL to the feed
3528 * @param string $text Value of the "title" attribute
3529 * @return string HTML fragment
3530 */
3531 private function feedLink( $type, $url, $text ) {
3532 return Html::element( 'link', [
3533 'rel' => 'alternate',
3534 'type' => "application/$type+xml",
3535 'title' => $text,
3536 'href' => $url ]
3537 );
3538 }
3539
3540 /**
3541 * Add a local or specified stylesheet, with the given media options.
3542 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3543 *
3544 * @param string $style URL to the file
3545 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3546 * @param string $condition For IE conditional comments, specifying an IE version
3547 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3548 */
3549 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3550 $options = [];
3551 if ( $media ) {
3552 $options['media'] = $media;
3553 }
3554 if ( $condition ) {
3555 $options['condition'] = $condition;
3556 }
3557 if ( $dir ) {
3558 $options['dir'] = $dir;
3559 }
3560 $this->styles[$style] = $options;
3561 }
3562
3563 /**
3564 * Adds inline CSS styles
3565 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3566 *
3567 * @param mixed $style_css Inline CSS
3568 * @param string $flip Set to 'flip' to flip the CSS if needed
3569 */
3570 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3571 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3572 # If wanted, and the interface is right-to-left, flip the CSS
3573 $style_css = CSSJanus::transform( $style_css, true, false );
3574 }
3575 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3576 }
3577
3578 /**
3579 * Build exempt modules and legacy non-ResourceLoader styles.
3580 *
3581 * @return string|WrappedStringList HTML
3582 */
3583 protected function buildExemptModules() {
3584 global $wgContLang;
3585
3586 $chunks = [];
3587 // Things that go after the ResourceLoaderDynamicStyles marker
3588 $append = [];
3589
3590 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3591 if ( $this->isUserCssPreview() ) {
3592 $append[] = $this->makeResourceLoaderLink(
3593 'user.styles',
3594 ResourceLoaderModule::TYPE_STYLES,
3595 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3596 );
3597
3598 // Load the previewed CSS. Janus it if needed.
3599 // User-supplied CSS is assumed to in the wiki's content language.
3600 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3601 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3602 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3603 }
3604 $append[] = Html::inlineStyle( $previewedCSS );
3605 }
3606
3607 // We want site, private and user styles to override dynamically added styles from
3608 // general modules, but we want dynamically added styles to override statically added
3609 // style modules. So the order has to be:
3610 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3611 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3612 // - ResourceLoaderDynamicStyles marker
3613 // - site/private/user styles
3614
3615 // Add legacy styles added through addStyle()/addInlineStyle() here
3616 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3617
3618 $chunks[] = Html::element(
3619 'meta',
3620 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3621 );
3622
3623 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3624 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3625 ResourceLoaderModule::TYPE_STYLES
3626 );
3627 }
3628
3629 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3630 }
3631
3632 /**
3633 * @return array
3634 */
3635 public function buildCssLinksArray() {
3636 $links = [];
3637
3638 // Add any extension CSS
3639 foreach ( $this->mExtStyles as $url ) {
3640 $this->addStyle( $url );
3641 }
3642 $this->mExtStyles = [];
3643
3644 foreach ( $this->styles as $file => $options ) {
3645 $link = $this->styleLink( $file, $options );
3646 if ( $link ) {
3647 $links[$file] = $link;
3648 }
3649 }
3650 return $links;
3651 }
3652
3653 /**
3654 * Generate \<link\> tags for stylesheets
3655 *
3656 * @param string $style URL to the file
3657 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3658 * @return string HTML fragment
3659 */
3660 protected function styleLink( $style, array $options ) {
3661 if ( isset( $options['dir'] ) ) {
3662 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3663 return '';
3664 }
3665 }
3666
3667 if ( isset( $options['media'] ) ) {
3668 $media = self::transformCssMedia( $options['media'] );
3669 if ( is_null( $media ) ) {
3670 return '';
3671 }
3672 } else {
3673 $media = 'all';
3674 }
3675
3676 if ( substr( $style, 0, 1 ) == '/' ||
3677 substr( $style, 0, 5 ) == 'http:' ||
3678 substr( $style, 0, 6 ) == 'https:' ) {
3679 $url = $style;
3680 } else {
3681 $config = $this->getConfig();
3682 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3683 $config->get( 'StyleVersion' );
3684 }
3685
3686 $link = Html::linkedStyle( $url, $media );
3687
3688 if ( isset( $options['condition'] ) ) {
3689 $condition = htmlspecialchars( $options['condition'] );
3690 $link = "<!--[if $condition]>$link<![endif]-->";
3691 }
3692 return $link;
3693 }
3694
3695 /**
3696 * Transform path to web-accessible static resource.
3697 *
3698 * This is used to add a validation hash as query string.
3699 * This aids various behaviors:
3700 *
3701 * - Put long Cache-Control max-age headers on responses for improved
3702 * cache performance.
3703 * - Get the correct version of a file as expected by the current page.
3704 * - Instantly get the updated version of a file after deployment.
3705 *
3706 * Avoid using this for urls included in HTML as otherwise clients may get different
3707 * versions of a resource when navigating the site depending on when the page was cached.
3708 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3709 * an external stylesheet).
3710 *
3711 * @since 1.27
3712 * @param Config $config
3713 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3714 * @return string URL
3715 */
3716 public static function transformResourcePath( Config $config, $path ) {
3717 global $IP;
3718
3719 $localDir = $IP;
3720 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3721 if ( $remotePathPrefix === '' ) {
3722 // The configured base path is required to be empty string for
3723 // wikis in the domain root
3724 $remotePath = '/';
3725 } else {
3726 $remotePath = $remotePathPrefix;
3727 }
3728 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
3729 // - Path is outside wgResourceBasePath, ignore.
3730 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3731 return $path;
3732 }
3733 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3734 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3735 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3736 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3737 $uploadPath = $config->get( 'UploadPath' );
3738 if ( strpos( $path, $uploadPath ) === 0 ) {
3739 $localDir = $config->get( 'UploadDirectory' );
3740 $remotePathPrefix = $remotePath = $uploadPath;
3741 }
3742
3743 $path = RelPath\getRelativePath( $path, $remotePath );
3744 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
3745 }
3746
3747 /**
3748 * Utility method for transformResourceFilePath().
3749 *
3750 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3751 *
3752 * @since 1.27
3753 * @param string $remotePath URL path prefix that points to $localPath
3754 * @param string $localPath File directory exposed at $remotePath
3755 * @param string $file Path to target file relative to $localPath
3756 * @return string URL
3757 */
3758 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3759 $hash = md5_file( "$localPath/$file" );
3760 if ( $hash === false ) {
3761 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3762 $hash = '';
3763 }
3764 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3765 }
3766
3767 /**
3768 * Transform "media" attribute based on request parameters
3769 *
3770 * @param string $media Current value of the "media" attribute
3771 * @return string Modified value of the "media" attribute, or null to skip
3772 * this stylesheet
3773 */
3774 public static function transformCssMedia( $media ) {
3775 global $wgRequest;
3776
3777 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3778 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3779
3780 // Switch in on-screen display for media testing
3781 $switches = [
3782 'printable' => 'print',
3783 'handheld' => 'handheld',
3784 ];
3785 foreach ( $switches as $switch => $targetMedia ) {
3786 if ( $wgRequest->getBool( $switch ) ) {
3787 if ( $media == $targetMedia ) {
3788 $media = '';
3789 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3790 /* This regex will not attempt to understand a comma-separated media_query_list
3791 *
3792 * Example supported values for $media:
3793 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3794 * Example NOT supported value for $media:
3795 * '3d-glasses, screen, print and resolution > 90dpi'
3796 *
3797 * If it's a print request, we never want any kind of screen stylesheets
3798 * If it's a handheld request (currently the only other choice with a switch),
3799 * we don't want simple 'screen' but we might want screen queries that
3800 * have a max-width or something, so we'll pass all others on and let the
3801 * client do the query.
3802 */
3803 if ( $targetMedia == 'print' || $media == 'screen' ) {
3804 return null;
3805 }
3806 }
3807 }
3808 }
3809
3810 return $media;
3811 }
3812
3813 /**
3814 * Add a wikitext-formatted message to the output.
3815 * This is equivalent to:
3816 *
3817 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3818 */
3819 public function addWikiMsg( /*...*/ ) {
3820 $args = func_get_args();
3821 $name = array_shift( $args );
3822 $this->addWikiMsgArray( $name, $args );
3823 }
3824
3825 /**
3826 * Add a wikitext-formatted message to the output.
3827 * Like addWikiMsg() except the parameters are taken as an array
3828 * instead of a variable argument list.
3829 *
3830 * @param string $name
3831 * @param array $args
3832 */
3833 public function addWikiMsgArray( $name, $args ) {
3834 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3835 }
3836
3837 /**
3838 * This function takes a number of message/argument specifications, wraps them in
3839 * some overall structure, and then parses the result and adds it to the output.
3840 *
3841 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3842 * and so on. The subsequent arguments may be either
3843 * 1) strings, in which case they are message names, or
3844 * 2) arrays, in which case, within each array, the first element is the message
3845 * name, and subsequent elements are the parameters to that message.
3846 *
3847 * Don't use this for messages that are not in the user's interface language.
3848 *
3849 * For example:
3850 *
3851 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3852 *
3853 * Is equivalent to:
3854 *
3855 * $wgOut->addWikiText( "<div class='error'>\n"
3856 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3857 *
3858 * The newline after the opening div is needed in some wikitext. See T21226.
3859 *
3860 * @param string $wrap
3861 */
3862 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3863 $msgSpecs = func_get_args();
3864 array_shift( $msgSpecs );
3865 $msgSpecs = array_values( $msgSpecs );
3866 $s = $wrap;
3867 foreach ( $msgSpecs as $n => $spec ) {
3868 if ( is_array( $spec ) ) {
3869 $args = $spec;
3870 $name = array_shift( $args );
3871 if ( isset( $args['options'] ) ) {
3872 unset( $args['options'] );
3873 wfDeprecated(
3874 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3875 '1.20'
3876 );
3877 }
3878 } else {
3879 $args = [];
3880 $name = $spec;
3881 }
3882 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3883 }
3884 $this->addWikiText( $s );
3885 }
3886
3887 /**
3888 * Enables/disables TOC, doesn't override __NOTOC__
3889 * @param bool $flag
3890 * @since 1.22
3891 */
3892 public function enableTOC( $flag = true ) {
3893 $this->mEnableTOC = $flag;
3894 }
3895
3896 /**
3897 * @return bool
3898 * @since 1.22
3899 */
3900 public function isTOCEnabled() {
3901 return $this->mEnableTOC;
3902 }
3903
3904 /**
3905 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3906 * @param bool $flag
3907 * @since 1.23
3908 */
3909 public function enableSectionEditLinks( $flag = true ) {
3910 $this->mEnableSectionEditLinks = $flag;
3911 }
3912
3913 /**
3914 * @return bool
3915 * @since 1.23
3916 */
3917 public function sectionEditLinksEnabled() {
3918 return $this->mEnableSectionEditLinks;
3919 }
3920
3921 /**
3922 * Helper function to setup the PHP implementation of OOUI to use in this request.
3923 *
3924 * @since 1.26
3925 * @param String $skinName The Skin name to determine the correct OOUI theme
3926 * @param String $dir Language direction
3927 */
3928 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3929 $themes = ExtensionRegistry::getInstance()->getAttribute( 'SkinOOUIThemes' );
3930 // Make keys (skin names) lowercase for case-insensitive matching.
3931 $themes = array_change_key_case( $themes, CASE_LOWER );
3932 $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : 'MediaWiki';
3933 // For example, 'OOUI\MediaWikiTheme'.
3934 $themeClass = "OOUI\\{$theme}Theme";
3935 OOUI\Theme::setSingleton( new $themeClass() );
3936 OOUI\Element::setDefaultDir( $dir );
3937 }
3938
3939 /**
3940 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3941 * MediaWiki and this OutputPage instance.
3942 *
3943 * @since 1.25
3944 */
3945 public function enableOOUI() {
3946 self::setupOOUI(
3947 strtolower( $this->getSkin()->getSkinName() ),
3948 $this->getLanguage()->getDir()
3949 );
3950 $this->addModuleStyles( [
3951 'oojs-ui-core.styles',
3952 'oojs-ui.styles.icons',
3953 'oojs-ui.styles.indicators',
3954 'oojs-ui.styles.textures',
3955 'mediawiki.widgets.styles',
3956 ] );
3957 }
3958 }