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