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