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