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