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