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