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