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