[FileRepo] Cleanup of URL config.
[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 * Check if the request has a cache-varying cookie header
1687 * If it does, it's very important that we don't allow public caching
1688 *
1689 * @return Boolean
1690 */
1691 function haveCacheVaryCookies() {
1692 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1693 if ( $cookieHeader === false ) {
1694 return false;
1695 }
1696 $cvCookies = $this->getCacheVaryCookies();
1697 foreach ( $cvCookies as $cookieName ) {
1698 # Check for a simple string match, like the way squid does it
1699 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1700 wfDebug( __METHOD__ . ": found $cookieName\n" );
1701 return true;
1702 }
1703 }
1704 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1705 return false;
1706 }
1707
1708 /**
1709 * Add an HTTP header that will influence on the cache
1710 *
1711 * @param $header String: header name
1712 * @param $option Array|null
1713 * @todo FIXME: Document the $option parameter; it appears to be for
1714 * X-Vary-Options but what format is acceptable?
1715 */
1716 public function addVaryHeader( $header, $option = null ) {
1717 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1718 $this->mVaryHeader[$header] = (array)$option;
1719 } elseif( is_array( $option ) ) {
1720 if( is_array( $this->mVaryHeader[$header] ) ) {
1721 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1722 } else {
1723 $this->mVaryHeader[$header] = $option;
1724 }
1725 }
1726 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1727 }
1728
1729 /**
1730 * Get a complete X-Vary-Options header
1731 *
1732 * @return String
1733 */
1734 public function getXVO() {
1735 $cvCookies = $this->getCacheVaryCookies();
1736
1737 $cookiesOption = array();
1738 foreach ( $cvCookies as $cookieName ) {
1739 $cookiesOption[] = 'string-contains=' . $cookieName;
1740 }
1741 $this->addVaryHeader( 'Cookie', $cookiesOption );
1742
1743 $headers = array();
1744 foreach( $this->mVaryHeader as $header => $option ) {
1745 $newheader = $header;
1746 if( is_array( $option ) ) {
1747 $newheader .= ';' . implode( ';', $option );
1748 }
1749 $headers[] = $newheader;
1750 }
1751 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1752
1753 return $xvo;
1754 }
1755
1756 /**
1757 * bug 21672: Add Accept-Language to Vary and XVO headers
1758 * if there's no 'variant' parameter existed in GET.
1759 *
1760 * For example:
1761 * /w/index.php?title=Main_page should always be served; but
1762 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1763 */
1764 function addAcceptLanguage() {
1765 $lang = $this->getTitle()->getPageLanguage();
1766 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1767 $variants = $lang->getVariants();
1768 $aloption = array();
1769 foreach ( $variants as $variant ) {
1770 if( $variant === $lang->getCode() ) {
1771 continue;
1772 } else {
1773 $aloption[] = 'string-contains=' . $variant;
1774
1775 // IE and some other browsers use another form of language code
1776 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1777 // We should handle these too.
1778 $ievariant = explode( '-', $variant );
1779 if ( count( $ievariant ) == 2 ) {
1780 $ievariant[1] = strtoupper( $ievariant[1] );
1781 $ievariant = implode( '-', $ievariant );
1782 $aloption[] = 'string-contains=' . $ievariant;
1783 }
1784 }
1785 }
1786 $this->addVaryHeader( 'Accept-Language', $aloption );
1787 }
1788 }
1789
1790 /**
1791 * Set a flag which will cause an X-Frame-Options header appropriate for
1792 * edit pages to be sent. The header value is controlled by
1793 * $wgEditPageFrameOptions.
1794 *
1795 * This is the default for special pages. If you display a CSRF-protected
1796 * form on an ordinary view page, then you need to call this function.
1797 *
1798 * @param $enable bool
1799 */
1800 public function preventClickjacking( $enable = true ) {
1801 $this->mPreventClickjacking = $enable;
1802 }
1803
1804 /**
1805 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1806 * This can be called from pages which do not contain any CSRF-protected
1807 * HTML form.
1808 */
1809 public function allowClickjacking() {
1810 $this->mPreventClickjacking = false;
1811 }
1812
1813 /**
1814 * Get the X-Frame-Options header value (without the name part), or false
1815 * if there isn't one. This is used by Skin to determine whether to enable
1816 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1817 *
1818 * @return string
1819 */
1820 public function getFrameOptions() {
1821 global $wgBreakFrames, $wgEditPageFrameOptions;
1822 if ( $wgBreakFrames ) {
1823 return 'DENY';
1824 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1825 return $wgEditPageFrameOptions;
1826 }
1827 return false;
1828 }
1829
1830 /**
1831 * Send cache control HTTP headers
1832 */
1833 public function sendCacheControl() {
1834 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1835
1836 $response = $this->getRequest()->response();
1837 if ( $wgUseETag && $this->mETag ) {
1838 $response->header( "ETag: $this->mETag" );
1839 }
1840
1841 $this->addAcceptLanguage();
1842
1843 # don't serve compressed data to clients who can't handle it
1844 # maintain different caches for logged-in users and non-logged in ones
1845 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1846
1847 if ( $wgUseXVO ) {
1848 # Add an X-Vary-Options header for Squid with Wikimedia patches
1849 $response->header( $this->getXVO() );
1850 }
1851
1852 if( $this->mEnableClientCache ) {
1853 if(
1854 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1855 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1856 )
1857 {
1858 if ( $wgUseESI ) {
1859 # We'll purge the proxy cache explicitly, but require end user agents
1860 # to revalidate against the proxy on each visit.
1861 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1862 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1863 # start with a shorter timeout for initial testing
1864 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1865 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1866 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1867 } else {
1868 # We'll purge the proxy cache for anons explicitly, but require end user agents
1869 # to revalidate against the proxy on each visit.
1870 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1871 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1872 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1873 # start with a shorter timeout for initial testing
1874 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1875 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1876 }
1877 } else {
1878 # We do want clients to cache if they can, but they *must* check for updates
1879 # on revisiting the page.
1880 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1881 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1882 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1883 }
1884 if($this->mLastModified) {
1885 $response->header( "Last-Modified: {$this->mLastModified}" );
1886 }
1887 } else {
1888 wfDebug( __METHOD__ . ": no caching **\n", false );
1889
1890 # In general, the absence of a last modified header should be enough to prevent
1891 # the client from using its cache. We send a few other things just to make sure.
1892 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1893 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1894 $response->header( 'Pragma: no-cache' );
1895 }
1896 }
1897
1898 /**
1899 * Get the message associed with the HTTP response code $code
1900 *
1901 * @param $code Integer: status code
1902 * @return String or null: message or null if $code is not in the list of
1903 * messages
1904 *
1905 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1906 */
1907 public static function getStatusMessage( $code ) {
1908 wfDeprecated( __METHOD__ );
1909 return HttpStatus::getMessage( $code );
1910 }
1911
1912 /**
1913 * Finally, all the text has been munged and accumulated into
1914 * the object, let's actually output it:
1915 */
1916 public function output() {
1917 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1918
1919 if( $this->mDoNothing ) {
1920 return;
1921 }
1922
1923 wfProfileIn( __METHOD__ );
1924
1925 $response = $this->getRequest()->response();
1926
1927 if ( $this->mRedirect != '' ) {
1928 # Standards require redirect URLs to be absolute
1929 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
1930
1931 $redirect = $this->mRedirect;
1932 $code = $this->mRedirectCode;
1933
1934 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1935 if( $code == '301' || $code == '303' ) {
1936 if( !$wgDebugRedirects ) {
1937 $message = HttpStatus::getMessage( $code );
1938 $response->header( "HTTP/1.1 $code $message" );
1939 }
1940 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1941 }
1942 if ( $wgVaryOnXFP ) {
1943 $this->addVaryHeader( 'X-Forwarded-Proto' );
1944 }
1945 $this->sendCacheControl();
1946
1947 $response->header( "Content-Type: text/html; charset=utf-8" );
1948 if( $wgDebugRedirects ) {
1949 $url = htmlspecialchars( $redirect );
1950 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1951 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1952 print "</body>\n</html>\n";
1953 } else {
1954 $response->header( 'Location: ' . $redirect );
1955 }
1956 }
1957
1958 wfProfileOut( __METHOD__ );
1959 return;
1960 } elseif ( $this->mStatusCode ) {
1961 $message = HttpStatus::getMessage( $this->mStatusCode );
1962 if ( $message ) {
1963 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1964 }
1965 }
1966
1967 # Buffer output; final headers may depend on later processing
1968 ob_start();
1969
1970 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1971 $response->header( 'Content-language: ' . $wgLanguageCode );
1972
1973 // Prevent framing, if requested
1974 $frameOptions = $this->getFrameOptions();
1975 if ( $frameOptions ) {
1976 $response->header( "X-Frame-Options: $frameOptions" );
1977 }
1978
1979 if ( $this->mArticleBodyOnly ) {
1980 $this->out( $this->mBodytext );
1981 } else {
1982 $this->addDefaultModules();
1983
1984 $sk = $this->getSkin();
1985
1986 // Hook that allows last minute changes to the output page, e.g.
1987 // adding of CSS or Javascript by extensions.
1988 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1989
1990 wfProfileIn( 'Output-skin' );
1991 $sk->outputPage();
1992 wfProfileOut( 'Output-skin' );
1993 }
1994
1995 $this->sendCacheControl();
1996 ob_end_flush();
1997 wfProfileOut( __METHOD__ );
1998 }
1999
2000 /**
2001 * Actually output something with print().
2002 *
2003 * @param $ins String: the string to output
2004 */
2005 public function out( $ins ) {
2006 print $ins;
2007 }
2008
2009 /**
2010 * Produce a "user is blocked" page.
2011 * @deprecated since 1.18
2012 */
2013 function blockedPage() {
2014 throw new UserBlockedError( $this->getUser()->mBlock );
2015 }
2016
2017 /**
2018 * Prepare this object to display an error page; disable caching and
2019 * indexing, clear the current text and redirect, set the page's title
2020 * and optionally an custom HTML title (content of the <title> tag).
2021 *
2022 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2023 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2024 * optional, if not passed the <title> attribute will be
2025 * based on $pageTitle
2026 */
2027 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2028 if ( $this->getTitle() ) {
2029 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
2030 }
2031
2032 $this->setPageTitle( $pageTitle );
2033 if ( $htmlTitle !== false ) {
2034 $this->setHTMLTitle( $htmlTitle );
2035 }
2036 $this->setRobotPolicy( 'noindex,nofollow' );
2037 $this->setArticleRelated( false );
2038 $this->enableClientCache( false );
2039 $this->mRedirect = '';
2040 $this->clearSubtitle();
2041 $this->clearHTML();
2042 }
2043
2044 /**
2045 * Output a standard error page
2046 *
2047 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2048 * showErrorPage( 'titlemsg', $messageObject );
2049 *
2050 * @param $title String: message key for page title
2051 * @param $msg Mixed: message key (string) for page text, or a Message object
2052 * @param $params Array: message parameters; ignored if $msg is a Message object
2053 */
2054 public function showErrorPage( $title, $msg, $params = array() ) {
2055 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2056
2057 if ( $msg instanceof Message ){
2058 $this->addHTML( $msg->parse() );
2059 } else {
2060 $this->addWikiMsgArray( $msg, $params );
2061 }
2062
2063 $this->returnToMain();
2064 }
2065
2066 /**
2067 * Output a standard permission error page
2068 *
2069 * @param $errors Array: error message keys
2070 * @param $action String: action that was denied or null if unknown
2071 */
2072 public function showPermissionsErrorPage( $errors, $action = null ) {
2073 global $wgGroupPermissions;
2074
2075 // For some action (read, edit, create and upload), display a "login to do this action"
2076 // error if all of the following conditions are met:
2077 // 1. the user is not logged in
2078 // 2. the only error is insufficient permissions (i.e. no block or something else)
2079 // 3. the error can be avoided simply by logging in
2080 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2081 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2082 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2083 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2084 || ( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2085 ) {
2086 $displayReturnto = null;
2087
2088 # Due to bug 32276, if a user does not have read permissions,
2089 # $this->getTitle() will just give Special:Badtitle, which is
2090 # not especially useful as a returnto parameter. Use the title
2091 # from the request instead, if there was one.
2092 $request = $this->getRequest();
2093 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2094 if ( $action == 'edit' ) {
2095 $msg = 'whitelistedittext';
2096 $displayReturnto = $returnto;
2097 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2098 $msg = 'nocreatetext';
2099 } elseif ( $action == 'upload' ) {
2100 $msg = 'uploadnologintext';
2101 } else { # Read
2102 $msg = 'loginreqpagetext';
2103 $displayReturnto = Title::newMainPage();
2104 }
2105
2106 $query = array();
2107
2108 if ( $returnto ) {
2109 $query['returnto'] = $returnto->getPrefixedText();
2110
2111 if ( !$request->wasPosted() ) {
2112 $returntoquery = $request->getValues();
2113 unset( $returntoquery['title'] );
2114 unset( $returntoquery['returnto'] );
2115 unset( $returntoquery['returntoquery'] );
2116 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2117 }
2118 }
2119 $loginLink = Linker::linkKnown(
2120 SpecialPage::getTitleFor( 'Userlogin' ),
2121 $this->msg( 'loginreqlink' )->escaped(),
2122 array(),
2123 $query
2124 );
2125
2126 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2127 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2128
2129 # Don't return to a page the user can't read otherwise
2130 # we'll end up in a pointless loop
2131 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2132 $this->returnToMain( null, $displayReturnto );
2133 }
2134 } else {
2135 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2136 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2137 }
2138 }
2139
2140 /**
2141 * Display an error page indicating that a given version of MediaWiki is
2142 * required to use it
2143 *
2144 * @param $version Mixed: the version of MediaWiki needed to use the page
2145 */
2146 public function versionRequired( $version ) {
2147 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2148
2149 $this->addWikiMsg( 'versionrequiredtext', $version );
2150 $this->returnToMain();
2151 }
2152
2153 /**
2154 * Display an error page noting that a given permission bit is required.
2155 * @deprecated since 1.18, just throw the exception directly
2156 * @param $permission String: key required
2157 */
2158 public function permissionRequired( $permission ) {
2159 throw new PermissionsError( $permission );
2160 }
2161
2162 /**
2163 * Produce the stock "please login to use the wiki" page
2164 *
2165 * @deprecated in 1.19; throw the exception directly
2166 */
2167 public function loginToUse() {
2168 throw new PermissionsError( 'read' );
2169 }
2170
2171 /**
2172 * Format a list of error messages
2173 *
2174 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2175 * @param $action String: action that was denied or null if unknown
2176 * @return String: the wikitext error-messages, formatted into a list.
2177 */
2178 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2179 if ( $action == null ) {
2180 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2181 } else {
2182 $action_desc = $this->msg( "action-$action" )->plain();
2183 $text = $this->msg(
2184 'permissionserrorstext-withaction',
2185 count( $errors ),
2186 $action_desc
2187 )->plain() . "\n\n";
2188 }
2189
2190 if ( count( $errors ) > 1 ) {
2191 $text .= '<ul class="permissions-errors">' . "\n";
2192
2193 foreach( $errors as $error ) {
2194 $text .= '<li>';
2195 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2196 $text .= "</li>\n";
2197 }
2198 $text .= '</ul>';
2199 } else {
2200 $text .= "<div class=\"permissions-errors\">\n" .
2201 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2202 "\n</div>";
2203 }
2204
2205 return $text;
2206 }
2207
2208 /**
2209 * Display a page stating that the Wiki is in read-only mode,
2210 * and optionally show the source of the page that the user
2211 * was trying to edit. Should only be called (for this
2212 * purpose) after wfReadOnly() has returned true.
2213 *
2214 * For historical reasons, this function is _also_ used to
2215 * show the error message when a user tries to edit a page
2216 * they are not allowed to edit. (Unless it's because they're
2217 * blocked, then we show blockedPage() instead.) In this
2218 * case, the second parameter should be set to true and a list
2219 * of reasons supplied as the third parameter.
2220 *
2221 * @todo Needs to be split into multiple functions.
2222 *
2223 * @param $source String: source code to show (or null).
2224 * @param $protected Boolean: is this a permissions error?
2225 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2226 * @param $action String: action that was denied or null if unknown
2227 */
2228 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2229 $this->setRobotPolicy( 'noindex,nofollow' );
2230 $this->setArticleRelated( false );
2231
2232 // If no reason is given, just supply a default "I can't let you do
2233 // that, Dave" message. Should only occur if called by legacy code.
2234 if ( $protected && empty( $reasons ) ) {
2235 $reasons[] = array( 'badaccess-group0' );
2236 }
2237
2238 if ( !empty( $reasons ) ) {
2239 // Permissions error
2240 if( $source ) {
2241 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2242 $this->addBacklinkSubtitle( $this->getTitle() );
2243 } else {
2244 $this->setPageTitle( $this->msg( 'badaccess' ) );
2245 }
2246 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2247 } else {
2248 // Wiki is read only
2249 throw new ReadOnlyError;
2250 }
2251
2252 // Show source, if supplied
2253 if( is_string( $source ) ) {
2254 $this->addWikiMsg( 'viewsourcetext' );
2255
2256 $pageLang = $this->getTitle()->getPageLanguage();
2257 $params = array(
2258 'id' => 'wpTextbox1',
2259 'name' => 'wpTextbox1',
2260 'cols' => $this->getUser()->getOption( 'cols' ),
2261 'rows' => $this->getUser()->getOption( 'rows' ),
2262 'readonly' => 'readonly',
2263 'lang' => $pageLang->getHtmlCode(),
2264 'dir' => $pageLang->getDir(),
2265 );
2266 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2267
2268 // Show templates used by this article
2269 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2270 $this->addHTML( "<div class='templatesUsed'>
2271 $templates
2272 </div>
2273 " );
2274 }
2275
2276 # If the title doesn't exist, it's fairly pointless to print a return
2277 # link to it. After all, you just tried editing it and couldn't, so
2278 # what's there to do there?
2279 if( $this->getTitle()->exists() ) {
2280 $this->returnToMain( null, $this->getTitle() );
2281 }
2282 }
2283
2284 /**
2285 * Turn off regular page output and return an error reponse
2286 * for when rate limiting has triggered.
2287 */
2288 public function rateLimited() {
2289 throw new ThrottledError;
2290 }
2291
2292 /**
2293 * Show a warning about slave lag
2294 *
2295 * If the lag is higher than $wgSlaveLagCritical seconds,
2296 * then the warning is a bit more obvious. If the lag is
2297 * lower than $wgSlaveLagWarning, then no warning is shown.
2298 *
2299 * @param $lag Integer: slave lag
2300 */
2301 public function showLagWarning( $lag ) {
2302 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2303 if( $lag >= $wgSlaveLagWarning ) {
2304 $message = $lag < $wgSlaveLagCritical
2305 ? 'lag-warn-normal'
2306 : 'lag-warn-high';
2307 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2308 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2309 }
2310 }
2311
2312 public function showFatalError( $message ) {
2313 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2314
2315 $this->addHTML( $message );
2316 }
2317
2318 public function showUnexpectedValueError( $name, $val ) {
2319 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2320 }
2321
2322 public function showFileCopyError( $old, $new ) {
2323 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2324 }
2325
2326 public function showFileRenameError( $old, $new ) {
2327 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2328 }
2329
2330 public function showFileDeleteError( $name ) {
2331 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2332 }
2333
2334 public function showFileNotFoundError( $name ) {
2335 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2336 }
2337
2338 /**
2339 * Add a "return to" link pointing to a specified title
2340 *
2341 * @param $title Title to link
2342 * @param $query String query string
2343 * @param $text String text of the link (input is not escaped)
2344 */
2345 public function addReturnTo( $title, $query = array(), $text = null ) {
2346 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2347 $link = $this->msg( 'returnto' )->rawParams(
2348 Linker::link( $title, $text, array(), $query ) )->escaped();
2349 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2350 }
2351
2352 /**
2353 * Add a "return to" link pointing to a specified title,
2354 * or the title indicated in the request, or else the main page
2355 *
2356 * @param $unused
2357 * @param $returnto Title or String to return to
2358 * @param $returntoquery String: query string for the return to link
2359 */
2360 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2361 if ( $returnto == null ) {
2362 $returnto = $this->getRequest()->getText( 'returnto' );
2363 }
2364
2365 if ( $returntoquery == null ) {
2366 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2367 }
2368
2369 if ( $returnto === '' ) {
2370 $returnto = Title::newMainPage();
2371 }
2372
2373 if ( is_object( $returnto ) ) {
2374 $titleObj = $returnto;
2375 } else {
2376 $titleObj = Title::newFromText( $returnto );
2377 }
2378 if ( !is_object( $titleObj ) ) {
2379 $titleObj = Title::newMainPage();
2380 }
2381
2382 $this->addReturnTo( $titleObj, $returntoquery );
2383 }
2384
2385 /**
2386 * @param $sk Skin The given Skin
2387 * @param $includeStyle Boolean: unused
2388 * @return String: The doctype, opening <html>, and head element.
2389 */
2390 public function headElement( Skin $sk, $includeStyle = true ) {
2391 global $wgContLang;
2392
2393 $userdir = $this->getLanguage()->getDir();
2394 $sitedir = $wgContLang->getDir();
2395
2396 if ( $sk->commonPrintStylesheet() ) {
2397 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2398 }
2399
2400 $ret = Html::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2401
2402 if ( $this->getHTMLTitle() == '' ) {
2403 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2404 }
2405
2406 $openHead = Html::openElement( 'head' );
2407 if ( $openHead ) {
2408 # Don't bother with the newline if $head == ''
2409 $ret .= "$openHead\n";
2410 }
2411
2412 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2413
2414 $ret .= implode( "\n", array(
2415 $this->getHeadLinks( null, true ),
2416 $this->buildCssLinks(),
2417 $this->getHeadScripts(),
2418 $this->getHeadItems()
2419 ) );
2420
2421 $closeHead = Html::closeElement( 'head' );
2422 if ( $closeHead ) {
2423 $ret .= "$closeHead\n";
2424 }
2425
2426 $bodyAttrs = array();
2427
2428 # Classes for LTR/RTL directionality support
2429 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2430
2431 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2432 # A <body> class is probably not the best way to do this . . .
2433 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2434 }
2435 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2436 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2437 $bodyAttrs['class'] .= ' action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2438
2439 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2440 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2441
2442 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2443
2444 return $ret;
2445 }
2446
2447 /**
2448 * Add the default ResourceLoader modules to this object
2449 */
2450 private function addDefaultModules() {
2451 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2452 $wgAjaxWatch, $wgEnableMWSuggest;
2453
2454 // Add base resources
2455 $this->addModules( array(
2456 'mediawiki.user',
2457 'mediawiki.page.startup',
2458 'mediawiki.page.ready',
2459 ) );
2460 if ( $wgIncludeLegacyJavaScript ){
2461 $this->addModules( 'mediawiki.legacy.wikibits' );
2462 }
2463
2464 if ( $wgPreloadJavaScriptMwUtil ) {
2465 $this->addModules( 'mediawiki.util' );
2466 }
2467
2468 MWDebug::addModules( $this );
2469
2470 // Add various resources if required
2471 if ( $wgUseAjax ) {
2472 $this->addModules( 'mediawiki.legacy.ajax' );
2473
2474 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2475
2476 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2477 $this->addModules( 'mediawiki.action.watch.ajax' );
2478 }
2479
2480 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2481 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2482 }
2483 }
2484
2485 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2486 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2487 }
2488
2489 # Crazy edit-on-double-click stuff
2490 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2491 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2492 }
2493 }
2494
2495 /**
2496 * Get a ResourceLoader object associated with this OutputPage
2497 *
2498 * @return ResourceLoader
2499 */
2500 public function getResourceLoader() {
2501 if ( is_null( $this->mResourceLoader ) ) {
2502 $this->mResourceLoader = new ResourceLoader();
2503 }
2504 return $this->mResourceLoader;
2505 }
2506
2507 /**
2508 * TODO: Document
2509 * @param $modules Array/string with the module name(s)
2510 * @param $only String ResourceLoaderModule TYPE_ class constant
2511 * @param $useESI boolean
2512 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2513 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a <script src="..."> tag
2514 * @return string html <script> and <style> tags
2515 */
2516 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2517 global $wgResourceLoaderUseESI;
2518
2519 if ( !count( $modules ) ) {
2520 return '';
2521 }
2522
2523 if ( count( $modules ) > 1 ) {
2524 // Remove duplicate module requests
2525 $modules = array_unique( (array) $modules );
2526 // Sort module names so requests are more uniform
2527 sort( $modules );
2528
2529 if ( ResourceLoader::inDebugMode() ) {
2530 // Recursively call us for every item
2531 $links = '';
2532 foreach ( $modules as $name ) {
2533 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2534 }
2535 return $links;
2536 }
2537 }
2538
2539 // Create keyed-by-group list of module objects from modules list
2540 $groups = array();
2541 $resourceLoader = $this->getResourceLoader();
2542 foreach ( (array) $modules as $name ) {
2543 $module = $resourceLoader->getModule( $name );
2544 # Check that we're allowed to include this module on this page
2545 if ( !$module
2546 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2547 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2548 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2549 && $only == ResourceLoaderModule::TYPE_STYLES )
2550 )
2551 {
2552 continue;
2553 }
2554
2555 $group = $module->getGroup();
2556 if ( !isset( $groups[$group] ) ) {
2557 $groups[$group] = array();
2558 }
2559 $groups[$group][$name] = $module;
2560 }
2561
2562 $links = '';
2563 foreach ( $groups as $group => $modules ) {
2564 // Special handling for user-specific groups
2565 $user = null;
2566 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2567 $user = $this->getUser()->getName();
2568 }
2569
2570 // Create a fake request based on the one we are about to make so modules return
2571 // correct timestamp and emptiness data
2572 $query = ResourceLoader::makeLoaderQuery(
2573 array(), // modules; not determined yet
2574 $this->getLanguage()->getCode(),
2575 $this->getSkin()->getSkinName(),
2576 $user,
2577 null, // version; not determined yet
2578 ResourceLoader::inDebugMode(),
2579 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2580 $this->isPrintable(),
2581 $this->getRequest()->getBool( 'handheld' ),
2582 $extraQuery
2583 );
2584 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2585 // Extract modules that know they're empty
2586 $emptyModules = array ();
2587 foreach ( $modules as $key => $module ) {
2588 if ( $module->isKnownEmpty( $context ) ) {
2589 $emptyModules[$key] = 'ready';
2590 unset( $modules[$key] );
2591 }
2592 }
2593 // Inline empty modules: since they're empty, just mark them as 'ready'
2594 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule::TYPE_STYLES ) {
2595 // If we're only getting the styles, we don't need to do anything for empty modules.
2596 $links .= Html::inlineScript(
2597
2598 ResourceLoader::makeLoaderConditionalScript(
2599
2600 ResourceLoader::makeLoaderStateScript( $emptyModules )
2601
2602 )
2603
2604 ) . "\n";
2605 }
2606
2607 // If there are no modules left, skip this group
2608 if ( $modules === array() ) {
2609 continue;
2610 }
2611
2612 // Inline private modules. These can't be loaded through load.php for security
2613 // reasons, see bug 34907. Note that these modules should be loaded from
2614 // getHeadScripts() before the first loader call. Otherwise other modules can't
2615 // properly use them as dependencies (bug 30914)
2616 if ( $group === 'private' ) {
2617 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2618 $links .= Html::inlineStyle(
2619 $resourceLoader->makeModuleResponse( $context, $modules )
2620 );
2621 } else {
2622 $links .= Html::inlineScript(
2623 ResourceLoader::makeLoaderConditionalScript(
2624 $resourceLoader->makeModuleResponse( $context, $modules )
2625 )
2626 );
2627 }
2628 $links .= "\n";
2629 continue;
2630 }
2631 // Special handling for the user group; because users might change their stuff
2632 // on-wiki like user pages, or user preferences; we need to find the highest
2633 // timestamp of these user-changable modules so we can ensure cache misses on change
2634 // This should NOT be done for the site group (bug 27564) because anons get that too
2635 // and we shouldn't be putting timestamps in Squid-cached HTML
2636 $version = null;
2637 if ( $group === 'user' ) {
2638 // Get the maximum timestamp
2639 $timestamp = 1;
2640 foreach ( $modules as $module ) {
2641 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2642 }
2643 // Add a version parameter so cache will break when things change
2644 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2645 }
2646
2647 $url = ResourceLoader::makeLoaderURL(
2648 array_keys( $modules ),
2649 $this->getLanguage()->getCode(),
2650 $this->getSkin()->getSkinName(),
2651 $user,
2652 $version,
2653 ResourceLoader::inDebugMode(),
2654 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2655 $this->isPrintable(),
2656 $this->getRequest()->getBool( 'handheld' ),
2657 $extraQuery
2658 );
2659 if ( $useESI && $wgResourceLoaderUseESI ) {
2660 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2661 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2662 $link = Html::inlineStyle( $esi );
2663 } else {
2664 $link = Html::inlineScript( $esi );
2665 }
2666 } else {
2667 // Automatically select style/script elements
2668 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2669 $link = Html::linkedStyle( $url );
2670 } else if ( $loadCall ) {
2671 $link = Html::inlineScript(
2672 ResourceLoader::makeLoaderConditionalScript(
2673 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2674 )
2675 );
2676 } else {
2677 $link = Html::linkedScript( $url );
2678 }
2679 }
2680
2681 if( $group == 'noscript' ){
2682 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2683 } else {
2684 $links .= $link . "\n";
2685 }
2686 }
2687 return $links;
2688 }
2689
2690 /**
2691 * JS stuff to put in the <head>. This is the startup module, config
2692 * vars and modules marked with position 'top'
2693 *
2694 * @return String: HTML fragment
2695 */
2696 function getHeadScripts() {
2697 global $wgResourceLoaderExperimentalAsyncLoading;
2698
2699 // Startup - this will immediately load jquery and mediawiki modules
2700 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2701
2702 // Load config before anything else
2703 $scripts .= Html::inlineScript(
2704 ResourceLoader::makeLoaderConditionalScript(
2705 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2706 )
2707 );
2708
2709 // Load embeddable private modules before any loader links
2710 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2711 // in mw.loader.implement() calls and deferred until mw.user is available
2712 $embedScripts = array( 'user.options', 'user.tokens' );
2713 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2714
2715 // Script and Messages "only" requests marked for top inclusion
2716 // Messages should go first
2717 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2718 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2719
2720 // Modules requests - let the client calculate dependencies and batch requests as it likes
2721 // Only load modules that have marked themselves for loading at the top
2722 $modules = $this->getModules( true, 'top' );
2723 if ( $modules ) {
2724 $scripts .= Html::inlineScript(
2725 ResourceLoader::makeLoaderConditionalScript(
2726 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2727 )
2728 );
2729 }
2730
2731 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2732 $scripts .= $this->getScriptsForBottomQueue( true );
2733 }
2734
2735 return $scripts;
2736 }
2737
2738 /**
2739 * JS stuff to put at the 'bottom', which can either be the bottom of the <body>
2740 * or the bottom of the <head> depending on $wgResourceLoaderExperimentalAsyncLoading:
2741 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2742 * user preferences, site JS and user JS
2743 *
2744 * @param $inHead boolean If true, this HTML goes into the <head>, if false it goes into the <body>
2745 * @return string
2746 */
2747 function getScriptsForBottomQueue( $inHead ) {
2748 global $wgUseSiteJs, $wgAllowUserJs;
2749
2750 // Script and Messages "only" requests marked for bottom inclusion
2751 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2752 // Messages should go first
2753 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2754 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2755 /* $loadCall = */ $inHead
2756 );
2757 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2758 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2759 /* $loadCall = */ $inHead
2760 );
2761
2762 // Modules requests - let the client calculate dependencies and batch requests as it likes
2763 // Only load modules that have marked themselves for loading at the bottom
2764 $modules = $this->getModules( true, 'bottom' );
2765 if ( $modules ) {
2766 $scripts .= Html::inlineScript(
2767 ResourceLoader::makeLoaderConditionalScript(
2768 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2769 )
2770 );
2771 }
2772
2773 // Legacy Scripts
2774 $scripts .= "\n" . $this->mScripts;
2775
2776 $defaultModules = array();
2777
2778 // Add site JS if enabled
2779 if ( $wgUseSiteJs ) {
2780 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2781 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2782 );
2783 $defaultModules['site'] = 'loading';
2784 } else {
2785 // The wiki is configured to not allow a site module.
2786 $defaultModules['site'] = 'missing';
2787 }
2788
2789 // Add user JS if enabled
2790 if ( $wgAllowUserJs ) {
2791 if ( $this->getUser()->isLoggedIn() ) {
2792 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2793 # XXX: additional security check/prompt?
2794 // We're on a preview of a JS subpage
2795 // Exclude this page from the user module in case it's in there (bug 26283)
2796 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2797 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2798 );
2799 // Load the previewed JS
2800 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2801 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2802 // asynchronously and may arrive *after* the inline script here. So the previewed code
2803 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2804 } else {
2805 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2806 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
2807 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2808 );
2809 }
2810 $defaultModules['user'] = 'loading';
2811 } else {
2812 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2813 // blocking default gadgets that might depend on it. Although arguably default-enabled
2814 // gadgets should not depend on the user module, it's harmless and less error-prone to
2815 // handle this case.
2816 $defaultModules['user'] = 'ready';
2817 }
2818 } else {
2819 // User JS disabled
2820 $defaultModules['user'] = 'missing';
2821 }
2822
2823 // Group JS is only enabled if site JS is enabled.
2824 if ( $wgUseSiteJs ) {
2825 if ( $this->getUser()->isLoggedIn() ) {
2826 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
2827 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2828 );
2829 $defaultModules['user.groups'] = 'loading';
2830 } else {
2831 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2832 // avoid blocking gadgets that might depend upon the module.
2833 $defaultModules['user.groups'] = 'ready';
2834 }
2835 } else {
2836 // Site (and group JS) disabled
2837 $defaultModules['user.groups'] = 'missing';
2838 }
2839
2840 $loaderInit = '';
2841 if ( $inHead ) {
2842 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2843 foreach ( $defaultModules as $m => $state ) {
2844 if ( $state == 'loading' ) {
2845 unset( $defaultModules[$m] );
2846 }
2847 }
2848 }
2849 if ( count( $defaultModules ) > 0 ) {
2850 $loaderInit = Html::inlineScript(
2851 ResourceLoader::makeLoaderConditionalScript(
2852 ResourceLoader::makeLoaderStateScript( $defaultModules )
2853 )
2854 ) . "\n";
2855 }
2856 return $loaderInit . $scripts;
2857 }
2858
2859 /**
2860 * JS stuff to put at the bottom of the <body>
2861 * @return string
2862 */
2863 function getBottomScripts() {
2864 global $wgResourceLoaderExperimentalAsyncLoading;
2865 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2866 return $this->getScriptsForBottomQueue( false );
2867 } else {
2868 return '';
2869 }
2870 }
2871
2872 /**
2873 * Add one or more variables to be set in mw.config in JavaScript.
2874 *
2875 * @param $key {String|Array} Key or array of key/value pars.
2876 * @param $value {Mixed} [optional] Value of the configuration variable.
2877 */
2878 public function addJsConfigVars( $keys, $value = null ) {
2879 if ( is_array( $keys ) ) {
2880 foreach ( $keys as $key => $value ) {
2881 $this->mJsConfigVars[$key] = $value;
2882 }
2883 return;
2884 }
2885
2886 $this->mJsConfigVars[$keys] = $value;
2887 }
2888
2889
2890 /**
2891 * Get an array containing the variables to be set in mw.config in JavaScript.
2892 *
2893 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2894 * This is only public until that function is removed. You have been warned.
2895 *
2896 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2897 * - in other words, page-independent/site-wide variables (without state).
2898 * You will only be adding bloat to the html page and causing page caches to
2899 * have to be purged on configuration changes.
2900 * @return array
2901 */
2902 public function getJSVars() {
2903 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2904
2905 $latestRevID = 0;
2906 $pageID = 0;
2907 $canonicalName = false; # bug 21115
2908
2909 $title = $this->getTitle();
2910 $ns = $title->getNamespace();
2911 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2912
2913 // Get the relevant title so that AJAX features can use the correct page name
2914 // when making API requests from certain special pages (bug 34972).
2915 $relevantTitle = $this->getSkin()->getRelevantTitle();
2916
2917 if ( $ns == NS_SPECIAL ) {
2918 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
2919 } elseif ( $this->canUseWikiPage() ) {
2920 $wikiPage = $this->getWikiPage();
2921 $latestRevID = $wikiPage->getLatest();
2922 $pageID = $wikiPage->getId();
2923 }
2924
2925 $lang = $title->getPageLanguage();
2926
2927 // Pre-process information
2928 $separatorTransTable = $lang->separatorTransformTable();
2929 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
2930 $compactSeparatorTransTable = array(
2931 implode( "\t", array_keys( $separatorTransTable ) ),
2932 implode( "\t", $separatorTransTable ),
2933 );
2934 $digitTransTable = $lang->digitTransformTable();
2935 $digitTransTable = $digitTransTable ? $digitTransTable : array();
2936 $compactDigitTransTable = array(
2937 implode( "\t", array_keys( $digitTransTable ) ),
2938 implode( "\t", $digitTransTable ),
2939 );
2940
2941 $vars = array(
2942 'wgCanonicalNamespace' => $nsname,
2943 'wgCanonicalSpecialPageName' => $canonicalName,
2944 'wgNamespaceNumber' => $title->getNamespace(),
2945 'wgPageName' => $title->getPrefixedDBKey(),
2946 'wgTitle' => $title->getText(),
2947 'wgCurRevisionId' => $latestRevID,
2948 'wgArticleId' => $pageID,
2949 'wgIsArticle' => $this->isArticle(),
2950 'wgAction' => Action::getActionName( $this->getContext() ),
2951 'wgUserName' => $this->getUser()->isAnon() ? null : $this->getUser()->getName(),
2952 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2953 'wgCategories' => $this->getCategories(),
2954 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2955 'wgPageContentLanguage' => $lang->getCode(),
2956 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2957 'wgDigitTransformTable' => $compactDigitTransTable,
2958 'wgRelevantPageName' => $relevantTitle->getPrefixedDBKey(),
2959 );
2960 if ( $wgContLang->hasVariants() ) {
2961 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2962 }
2963 foreach ( $title->getRestrictionTypes() as $type ) {
2964 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2965 }
2966 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2967 $vars['wgSearchNamespaces'] = SearchEngine::userNamespaces( $this->getUser() );
2968 }
2969 if ( $title->isMainPage() ) {
2970 $vars['wgIsMainPage'] = true;
2971 }
2972 if ( $this->mRedirectedFrom ) {
2973 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBKey();
2974 }
2975
2976 // Allow extensions to add their custom variables to the mw.config map.
2977 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2978 // page-dependant but site-wide (without state).
2979 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2980 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2981
2982 // Merge in variables from addJsConfigVars last
2983 return array_merge( $vars, $this->mJsConfigVars );
2984 }
2985
2986 /**
2987 * To make it harder for someone to slip a user a fake
2988 * user-JavaScript or user-CSS preview, a random token
2989 * is associated with the login session. If it's not
2990 * passed back with the preview request, we won't render
2991 * the code.
2992 *
2993 * @return bool
2994 */
2995 public function userCanPreview() {
2996 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2997 || !$this->getRequest()->wasPosted()
2998 || !$this->getUser()->matchEditToken(
2999 $this->getRequest()->getVal( 'wpEditToken' ) )
3000 ) {
3001 return false;
3002 }
3003 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3004 return false;
3005 }
3006
3007 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3008 }
3009
3010 /**
3011 * @param $addContentType bool: Whether <meta> specifying content type should be returned
3012 *
3013 * @return array in format "link name or number => 'link html'".
3014 */
3015 public function getHeadLinksArray( $addContentType = false ) {
3016 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3017 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3018 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3019 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3020 $wgRightsPage, $wgRightsUrl;
3021
3022 $tags = array();
3023
3024 if ( $addContentType ) {
3025 if ( $wgHtml5 ) {
3026 # More succinct than <meta http-equiv=Content-Type>, has the
3027 # same effect
3028 $tags['meta-charset'] = Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
3029 } else {
3030 $tags['meta-content-type'] = Html::element( 'meta', array(
3031 'http-equiv' => 'Content-Type',
3032 'content' => "$wgMimeType; charset=UTF-8"
3033 ) );
3034 $tags['meta-content-style-type'] = Html::element( 'meta', array( // bug 15835
3035 'http-equiv' => 'Content-Style-Type',
3036 'content' => 'text/css'
3037 ) );
3038 }
3039 }
3040
3041 $tags['meta-generator'] = Html::element( 'meta', array(
3042 'name' => 'generator',
3043 'content' => "MediaWiki $wgVersion",
3044 ) );
3045
3046 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3047 if( $p !== 'index,follow' ) {
3048 // http://www.robotstxt.org/wc/meta-user.html
3049 // Only show if it's different from the default robots policy
3050 $tags['meta-robots'] = Html::element( 'meta', array(
3051 'name' => 'robots',
3052 'content' => $p,
3053 ) );
3054 }
3055
3056 if ( count( $this->mKeywords ) > 0 ) {
3057 $strip = array(
3058 "/<.*?" . ">/" => '',
3059 "/_/" => ' '
3060 );
3061 $tags['meta-keywords'] = Html::element( 'meta', array(
3062 'name' => 'keywords',
3063 'content' => preg_replace(
3064 array_keys( $strip ),
3065 array_values( $strip ),
3066 implode( ',', $this->mKeywords )
3067 )
3068 ) );
3069 }
3070
3071 foreach ( $this->mMetatags as $tag ) {
3072 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3073 $a = 'http-equiv';
3074 $tag[0] = substr( $tag[0], 5 );
3075 } else {
3076 $a = 'name';
3077 }
3078 $tagName = "meta-{$tag[0]}";
3079 if ( isset( $tags[$tagName] ) ) {
3080 $tagName .= $tag[1];
3081 }
3082 $tags[$tagName] = Html::element( 'meta',
3083 array(
3084 $a => $tag[0],
3085 'content' => $tag[1]
3086 )
3087 );
3088 }
3089
3090 foreach ( $this->mLinktags as $tag ) {
3091 $tags[] = Html::element( 'link', $tag );
3092 }
3093
3094 # Universal edit button
3095 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3096 $user = $this->getUser();
3097 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3098 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3099 // Original UniversalEditButton
3100 $msg = $this->msg( 'edit' )->text();
3101 $tags['universal-edit-button'] = Html::element( 'link', array(
3102 'rel' => 'alternate',
3103 'type' => 'application/x-wiki',
3104 'title' => $msg,
3105 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3106 ) );
3107 // Alternate edit link
3108 $tags['alternative-edit'] = Html::element( 'link', array(
3109 'rel' => 'edit',
3110 'title' => $msg,
3111 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3112 ) );
3113 }
3114 }
3115
3116 # Generally the order of the favicon and apple-touch-icon links
3117 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3118 # uses whichever one appears later in the HTML source. Make sure
3119 # apple-touch-icon is specified first to avoid this.
3120 if ( $wgAppleTouchIcon !== false ) {
3121 $tags['apple-touch-icon'] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3122 }
3123
3124 if ( $wgFavicon !== false ) {
3125 $tags['favicon'] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3126 }
3127
3128 # OpenSearch description link
3129 $tags['opensearch'] = Html::element( 'link', array(
3130 'rel' => 'search',
3131 'type' => 'application/opensearchdescription+xml',
3132 'href' => wfScript( 'opensearch_desc' ),
3133 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3134 ) );
3135
3136 if ( $wgEnableAPI ) {
3137 # Real Simple Discovery link, provides auto-discovery information
3138 # for the MediaWiki API (and potentially additional custom API
3139 # support such as WordPress or Twitter-compatible APIs for a
3140 # blogging extension, etc)
3141 $tags['rsd'] = Html::element( 'link', array(
3142 'rel' => 'EditURI',
3143 'type' => 'application/rsd+xml',
3144 // Output a protocol-relative URL here if $wgServer is protocol-relative
3145 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3146 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE ),
3147 ) );
3148 }
3149
3150
3151 # Language variants
3152 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3153 $lang = $this->getTitle()->getPageLanguage();
3154 if ( $lang->hasVariants() ) {
3155
3156 $urlvar = $lang->getURLVariant();
3157
3158 if ( !$urlvar ) {
3159 $variants = $lang->getVariants();
3160 foreach ( $variants as $_v ) {
3161 $tags["variant-$_v"] = Html::element( 'link', array(
3162 'rel' => 'alternate',
3163 'hreflang' => $_v,
3164 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3165 );
3166 }
3167 } else {
3168 $tags['canonical'] = Html::element( 'link', array(
3169 'rel' => 'canonical',
3170 'href' => $this->getTitle()->getCanonicalUrl()
3171 ) );
3172 }
3173 }
3174 }
3175
3176 # Copyright
3177 $copyright = '';
3178 if ( $wgRightsPage ) {
3179 $copy = Title::newFromText( $wgRightsPage );
3180
3181 if ( $copy ) {
3182 $copyright = $copy->getLocalURL();
3183 }
3184 }
3185
3186 if ( !$copyright && $wgRightsUrl ) {
3187 $copyright = $wgRightsUrl;
3188 }
3189
3190 if ( $copyright ) {
3191 $tags['copyright'] = Html::element( 'link', array(
3192 'rel' => 'copyright',
3193 'href' => $copyright )
3194 );
3195 }
3196
3197 # Feeds
3198 if ( $wgFeed ) {
3199 foreach( $this->getSyndicationLinks() as $format => $link ) {
3200 # Use the page name for the title. In principle, this could
3201 # lead to issues with having the same name for different feeds
3202 # corresponding to the same page, but we can't avoid that at
3203 # this low a level.
3204
3205 $tags[] = $this->feedLink(
3206 $format,
3207 $link,
3208 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3209 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3210 );
3211 }
3212
3213 # Recent changes feed should appear on every page (except recentchanges,
3214 # that would be redundant). Put it after the per-page feed to avoid
3215 # changing existing behavior. It's still available, probably via a
3216 # menu in your browser. Some sites might have a different feed they'd
3217 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3218 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3219 # If so, use it instead.
3220 if ( $wgOverrideSiteFeed ) {
3221 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3222 // Note, this->feedLink escapes the url.
3223 $tags[] = $this->feedLink(
3224 $type,
3225 $feedUrl,
3226 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3227 );
3228 }
3229 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3230 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3231 foreach ( $wgAdvertisedFeedTypes as $format ) {
3232 $tags[] = $this->feedLink(
3233 $format,
3234 $rctitle->getLocalURL( "feed={$format}" ),
3235 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3236 );
3237 }
3238 }
3239 }
3240 return $tags;
3241 }
3242
3243 /**
3244 * @param $unused
3245 * @param $addContentType bool: Whether <meta> specifying content type should be returned
3246 *
3247 * @return string HTML tag links to be put in the header.
3248 */
3249 public function getHeadLinks( $unused = null, $addContentType = false ) {
3250 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3251 }
3252
3253 /**
3254 * Generate a <link rel/> for a feed.
3255 *
3256 * @param $type String: feed type
3257 * @param $url String: URL to the feed
3258 * @param $text String: value of the "title" attribute
3259 * @return String: HTML fragment
3260 */
3261 private function feedLink( $type, $url, $text ) {
3262 return Html::element( 'link', array(
3263 'rel' => 'alternate',
3264 'type' => "application/$type+xml",
3265 'title' => $text,
3266 'href' => $url )
3267 );
3268 }
3269
3270 /**
3271 * Add a local or specified stylesheet, with the given media options.
3272 * Meant primarily for internal use...
3273 *
3274 * @param $style String: URL to the file
3275 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3276 * @param $condition String: for IE conditional comments, specifying an IE version
3277 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3278 */
3279 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3280 $options = array();
3281 // Even though we expect the media type to be lowercase, but here we
3282 // force it to lowercase to be safe.
3283 if( $media ) {
3284 $options['media'] = $media;
3285 }
3286 if( $condition ) {
3287 $options['condition'] = $condition;
3288 }
3289 if( $dir ) {
3290 $options['dir'] = $dir;
3291 }
3292 $this->styles[$style] = $options;
3293 }
3294
3295 /**
3296 * Adds inline CSS styles
3297 * @param $style_css Mixed: inline CSS
3298 * @param $flip String: Set to 'flip' to flip the CSS if needed
3299 */
3300 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3301 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3302 # If wanted, and the interface is right-to-left, flip the CSS
3303 $style_css = CSSJanus::transform( $style_css, true, false );
3304 }
3305 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3306 }
3307
3308 /**
3309 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3310 * These will be applied to various media & IE conditionals.
3311 *
3312 * @return string
3313 */
3314 public function buildCssLinks() {
3315 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3316 $wgLang, $wgContLang;
3317
3318 $this->getSkin()->setupSkinUserCss( $this );
3319
3320 // Add ResourceLoader styles
3321 // Split the styles into four groups
3322 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3323 $otherTags = ''; // Tags to append after the normal <link> tags
3324 $resourceLoader = $this->getResourceLoader();
3325
3326 $moduleStyles = $this->getModuleStyles();
3327
3328 // Per-site custom styles
3329 if ( $wgUseSiteCss ) {
3330 $moduleStyles[] = 'site';
3331 $moduleStyles[] = 'noscript';
3332 if( $this->getUser()->isLoggedIn() ){
3333 $moduleStyles[] = 'user.groups';
3334 }
3335 }
3336
3337 // Per-user custom styles
3338 if ( $wgAllowUserCss ) {
3339 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3340 // We're on a preview of a CSS subpage
3341 // Exclude this page from the user module in case it's in there (bug 26283)
3342 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3343 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3344 );
3345
3346 // Load the previewed CSS
3347 // If needed, Janus it first. This is user-supplied CSS, so it's
3348 // assumed to be right for the content language directionality.
3349 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3350 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3351 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3352 }
3353 $otherTags .= Html::inlineStyle( $previewedCSS );
3354 } else {
3355 // Load the user styles normally
3356 $moduleStyles[] = 'user';
3357 }
3358 }
3359
3360 // Per-user preference styles
3361 if ( $wgAllowUserCssPrefs ) {
3362 $moduleStyles[] = 'user.cssprefs';
3363 }
3364
3365 foreach ( $moduleStyles as $name ) {
3366 $module = $resourceLoader->getModule( $name );
3367 if ( !$module ) {
3368 continue;
3369 }
3370 $group = $module->getGroup();
3371 // Modules in groups named "other" or anything different than "user", "site" or "private"
3372 // will be placed in the "other" group
3373 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3374 }
3375
3376 // We want site, private and user styles to override dynamically added styles from modules, but we want
3377 // dynamically added styles to override statically added styles from other modules. So the order
3378 // has to be other, dynamic, site, private, user
3379 // Add statically added styles for other modules
3380 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3381 // Add normal styles added through addStyle()/addInlineStyle() here
3382 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3383 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3384 // We use a <meta> tag with a made-up name for this because that's valid HTML
3385 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3386
3387 // Add site, private and user styles
3388 // 'private' at present only contains user.options, so put that before 'user'
3389 // Any future private modules will likely have a similar user-specific character
3390 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3391 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3392 ResourceLoaderModule::TYPE_STYLES
3393 );
3394 }
3395
3396 // Add stuff in $otherTags (previewed user CSS if applicable)
3397 $ret .= $otherTags;
3398 return $ret;
3399 }
3400
3401 /**
3402 * @return Array
3403 */
3404 public function buildCssLinksArray() {
3405 $links = array();
3406
3407 // Add any extension CSS
3408 foreach ( $this->mExtStyles as $url ) {
3409 $this->addStyle( $url );
3410 }
3411 $this->mExtStyles = array();
3412
3413 foreach( $this->styles as $file => $options ) {
3414 $link = $this->styleLink( $file, $options );
3415 if( $link ) {
3416 $links[$file] = $link;
3417 }
3418 }
3419 return $links;
3420 }
3421
3422 /**
3423 * Generate \<link\> tags for stylesheets
3424 *
3425 * @param $style String: URL to the file
3426 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3427 * keys
3428 * @return String: HTML fragment
3429 */
3430 protected function styleLink( $style, $options ) {
3431 if( isset( $options['dir'] ) ) {
3432 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3433 return '';
3434 }
3435 }
3436
3437 if( isset( $options['media'] ) ) {
3438 $media = self::transformCssMedia( $options['media'] );
3439 if( is_null( $media ) ) {
3440 return '';
3441 }
3442 } else {
3443 $media = 'all';
3444 }
3445
3446 if( substr( $style, 0, 1 ) == '/' ||
3447 substr( $style, 0, 5 ) == 'http:' ||
3448 substr( $style, 0, 6 ) == 'https:' ) {
3449 $url = $style;
3450 } else {
3451 global $wgStylePath, $wgStyleVersion;
3452 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3453 }
3454
3455 $link = Html::linkedStyle( $url, $media );
3456
3457 if( isset( $options['condition'] ) ) {
3458 $condition = htmlspecialchars( $options['condition'] );
3459 $link = "<!--[if $condition]>$link<![endif]-->";
3460 }
3461 return $link;
3462 }
3463
3464 /**
3465 * Transform "media" attribute based on request parameters
3466 *
3467 * @param $media String: current value of the "media" attribute
3468 * @return String: modified value of the "media" attribute
3469 */
3470 public static function transformCssMedia( $media ) {
3471 global $wgRequest, $wgHandheldForIPhone;
3472
3473 // Switch in on-screen display for media testing
3474 $switches = array(
3475 'printable' => 'print',
3476 'handheld' => 'handheld',
3477 );
3478 foreach( $switches as $switch => $targetMedia ) {
3479 if( $wgRequest->getBool( $switch ) ) {
3480 if( $media == $targetMedia ) {
3481 $media = '';
3482 } elseif( $media == 'screen' ) {
3483 return null;
3484 }
3485 }
3486 }
3487
3488 // Expand longer media queries as iPhone doesn't grok 'handheld'
3489 if( $wgHandheldForIPhone ) {
3490 $mediaAliases = array(
3491 'screen' => 'screen and (min-device-width: 481px)',
3492 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3493 );
3494
3495 if( isset( $mediaAliases[$media] ) ) {
3496 $media = $mediaAliases[$media];
3497 }
3498 }
3499
3500 return $media;
3501 }
3502
3503 /**
3504 * Add a wikitext-formatted message to the output.
3505 * This is equivalent to:
3506 *
3507 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3508 */
3509 public function addWikiMsg( /*...*/ ) {
3510 $args = func_get_args();
3511 $name = array_shift( $args );
3512 $this->addWikiMsgArray( $name, $args );
3513 }
3514
3515 /**
3516 * Add a wikitext-formatted message to the output.
3517 * Like addWikiMsg() except the parameters are taken as an array
3518 * instead of a variable argument list.
3519 *
3520 * @param $name string
3521 * @param $args array
3522 */
3523 public function addWikiMsgArray( $name, $args ) {
3524 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3525 }
3526
3527 /**
3528 * This function takes a number of message/argument specifications, wraps them in
3529 * some overall structure, and then parses the result and adds it to the output.
3530 *
3531 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3532 * on. The subsequent arguments may either be strings, in which case they are the
3533 * message names, or arrays, in which case the first element is the message name,
3534 * and subsequent elements are the parameters to that message.
3535 *
3536 * The special named parameter 'options' in a message specification array is passed
3537 * through to the $options parameter of wfMsgExt().
3538 *
3539 * Don't use this for messages that are not in users interface language.
3540 *
3541 * For example:
3542 *
3543 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3544 *
3545 * Is equivalent to:
3546 *
3547 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3548 *
3549 * The newline after opening div is needed in some wikitext. See bug 19226.
3550 *
3551 * @param $wrap string
3552 */
3553 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3554 $msgSpecs = func_get_args();
3555 array_shift( $msgSpecs );
3556 $msgSpecs = array_values( $msgSpecs );
3557 $s = $wrap;
3558 foreach ( $msgSpecs as $n => $spec ) {
3559 $options = array();
3560 if ( is_array( $spec ) ) {
3561 $args = $spec;
3562 $name = array_shift( $args );
3563 if ( isset( $args['options'] ) ) {
3564 $options = $args['options'];
3565 unset( $args['options'] );
3566 }
3567 } else {
3568 $args = array();
3569 $name = $spec;
3570 }
3571 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
3572 }
3573 $this->addWikiText( $s );
3574 }
3575
3576 /**
3577 * Include jQuery core. Use this to avoid loading it multiple times
3578 * before we get a usable script loader.
3579 *
3580 * @param $modules Array: list of jQuery modules which should be loaded
3581 * @return Array: the list of modules which were not loaded.
3582 * @since 1.16
3583 * @deprecated since 1.17
3584 */
3585 public function includeJQuery( $modules = array() ) {
3586 return array();
3587 }
3588
3589 }