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