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