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