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