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