* Replaced $wgMessageCache by MessageCache::singleton(); since we only use one instan...
[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 class 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 * Another class (fixme) handle sending the whole page to the client.
15 *
16 * Some comments comes from a pairing session between Zak Greant and Ashar Voultoiz
17 * in november 2010.
18 *
19 * @todo document
20 */
21 class OutputPage {
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 outputted 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 = true;
51
52 /**
53 * Should be private. We have to set isPrintable(). Some pages should
54 * never be printed (ex: redirections).
55 */
56 var $mPrintable = false;
57
58 /**
59 * Should be private. We have set/get/append methods.
60 *
61 * Contains the page subtitle. Special pages usually have some links here.
62 * Don't confuse with site subtitle added by skins.
63 */
64 var $mSubtitle = '';
65
66 var $mRedirect = '';
67 var $mStatusCode;
68
69 /**
70 * mLastModified and mEtag are used for sending cache control.
71 * The whole caching system should probably be moved in its own class.
72 */
73 var $mLastModified = '';
74
75 /**
76 * Should be private. No getter but used in sendCacheControl();
77 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
78 * as a unique identifier for the content. It is later used by the client
79 * to compare its cache version with the server version. Client sends
80 * headers If-Match and If-None-Match containing its local cache ETAG value.
81 *
82 * To get more information, you will have to look at HTTP1/1 protocols which
83 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
84 */
85 var $mETag = false;
86
87 var $mCategoryLinks = array();
88 var $mCategories = array();
89
90 /// Should be private. Associative array mapping language code to the page name
91 var $mLanguageLinks = array();
92
93 /**
94 * Should be private. Used for JavaScript (pre resource loader)
95 * We should split js / css.
96 * mScripts content is inserted as is in <head> by Skin. This might contains
97 * either a link to a stylesheet or inline css.
98 */
99 var $mScripts = '';
100
101 /**
102 * Inline CSS styles. Use addInlineStyle() sparsingly
103 */
104 var $mInlineStyles = '';
105
106 //
107 var $mLinkColours;
108
109 /**
110 * Used by skin template.
111 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
112 */
113 var $mPageLinkTitle = '';
114
115 /// Array of elements in <head>. Parser might add its own headers!
116 var $mHeadItems = array();
117
118 // Next variables probably comes from the resource loader @todo FIXME
119 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
120 var $mResourceLoader;
121
122 /** @fixme is this still used ?*/
123 var $mInlineMsg = array();
124
125 var $mTemplateIds = array();
126
127 /** Initialized with a global value. Let us override it.
128 * Should probably get deleted / rewritten ... */
129 var $mAllowUserJs;
130
131 /**
132 * This was for the old skins and for users with 640x480 screen.
133 * Please note old skins are still used and might prove useful for
134 * users having old computers or visually impaired.
135 */
136 var $mSuppressQuickbar = false;
137
138 /**
139 * @EasterEgg I just love the name for this self documenting variable.
140 * @todo document
141 */
142 var $mDoNothing = false;
143
144 // Parser related.
145 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
146
147 /**
148 * Should be private. Has get/set methods properly documented.
149 * Stores "article flag" toggle.
150 */
151 var $mIsArticleRelated = true;
152
153 /// lazy initialised, use parserOptions()
154 protected $mParserOptions = null;
155
156 /**
157 * Handles the atom / rss links.
158 * We probably only support atom in 2011.
159 * Looks like a private variable.
160 * @see $wgAdvertisedFeedTypes
161 */
162 var $mFeedLinks = array();
163
164 // Gwicke work on squid caching? Roughly from 2003.
165 var $mEnableClientCache = true;
166
167 /**
168 * Flag if output should only contain the body of the article.
169 * Should be private.
170 */
171 var $mArticleBodyOnly = false;
172
173 var $mNewSectionLink = false;
174 var $mHideNewSectionLink = false;
175
176 /**
177 * Comes from the parser. This was probably made to load CSS/JS only
178 * if we had <gallery>. Used directly in CategoryPage.php
179 * Looks like resource loader can replace this.
180 */
181 var $mNoGallery = false;
182
183 // should be private.
184 var $mPageTitleActionText = '';
185 var $mParseWarnings = array();
186
187 // Cache stuff. Looks like mEnableClientCache
188 var $mSquidMaxage = 0;
189
190 // @todo document
191 var $mPreventClickjacking = true;
192
193 /// should be private. To include the variable {{REVISIONID}}
194 var $mRevisionId = null;
195
196 /// Stores a Title object (of the current page).
197 protected $mTitle = null;
198
199 /**
200 * An array of stylesheet filenames (relative from skins path), with options
201 * for CSS media, IE conditions, and RTL/LTR direction.
202 * For internal use; add settings in the skin via $this->addStyle()
203 *
204 * Style again! This seems like a code duplication since we already have
205 * mStyles. This is what makes OpenSource amazing.
206 */
207 var $styles = array();
208
209 /**
210 * Whether jQuery is already handled.
211 */
212 protected $mJQueryDone = false;
213
214 private $mIndexPolicy = 'index';
215 private $mFollowPolicy = 'follow';
216 private $mVaryHeader = array(
217 'Accept-Encoding' => array( 'list-contains=gzip' ),
218 'Cookie' => null
219 );
220
221 /**
222 * Constructor
223 * Initialise private variables
224 */
225 function __construct() {
226 global $wgAllowUserJs;
227 $this->mAllowUserJs = $wgAllowUserJs;
228 }
229
230 /**
231 * Redirect to $url rather than displaying the normal page
232 *
233 * @param $url String: URL
234 * @param $responsecode String: HTTP status code
235 */
236 public function redirect( $url, $responsecode = '302' ) {
237 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
238 $this->mRedirect = str_replace( "\n", '', $url );
239 $this->mRedirectCode = $responsecode;
240 }
241
242 /**
243 * Get the URL to redirect to, or an empty string if not redirect URL set
244 *
245 * @return String
246 */
247 public function getRedirect() {
248 return $this->mRedirect;
249 }
250
251 /**
252 * Set the HTTP status code to send with the output.
253 *
254 * @param $statusCode Integer
255 */
256 public function setStatusCode( $statusCode ) {
257 $this->mStatusCode = $statusCode;
258 }
259
260 /**
261 * Add a new <meta> tag
262 * To add an http-equiv meta tag, precede the name with "http:"
263 *
264 * @param $name String tag name
265 * @param $val String tag value
266 */
267 function addMeta( $name, $val ) {
268 array_push( $this->mMetatags, array( $name, $val ) );
269 }
270
271 /**
272 * Add a keyword or a list of keywords in the page header
273 *
274 * @param $text String or array of strings
275 */
276 function addKeyword( $text ) {
277 if( is_array( $text ) ) {
278 $this->mKeywords = array_merge( $this->mKeywords, $text );
279 } else {
280 array_push( $this->mKeywords, $text );
281 }
282 }
283
284 /**
285 * Add a new \<link\> tag to the page header
286 *
287 * @param $linkarr Array: associative array of attributes.
288 */
289 function addLink( $linkarr ) {
290 array_push( $this->mLinktags, $linkarr );
291 }
292
293 /**
294 * Add a new \<link\> with "rel" attribute set to "meta"
295 *
296 * @param $linkarr Array: associative array mapping attribute names to their
297 * values, both keys and values will be escaped, and the
298 * "rel" attribute will be automatically added
299 */
300 function addMetadataLink( $linkarr ) {
301 # note: buggy CC software only reads first "meta" link
302 static $haveMeta = false;
303 $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
304 $this->addLink( $linkarr );
305 $haveMeta = true;
306 }
307
308 /**
309 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
310 *
311 * @param $script String: raw HTML
312 */
313 function addScript( $script ) {
314 $this->mScripts .= $script . "\n";
315 }
316
317 /**
318 * Register and add a stylesheet from an extension directory.
319 *
320 * @param $url String path to sheet. Provide either a full url (beginning
321 * with 'http', etc) or a relative path from the document root
322 * (beginning with '/'). Otherwise it behaves identically to
323 * addStyle() and draws from the /skins folder.
324 */
325 public function addExtensionStyle( $url ) {
326 array_push( $this->mExtStyles, $url );
327 }
328
329 /**
330 * Get all styles added by extensions
331 *
332 * @return Array
333 */
334 function getExtStyle() {
335 return $this->mExtStyles;
336 }
337
338 /**
339 * Add a JavaScript file out of skins/common, or a given relative path.
340 *
341 * @param $file String: filename in skins/common or complete on-server path
342 * (/foo/bar.js)
343 * @param $version String: style version of the file. Defaults to $wgStyleVersion
344 */
345 public function addScriptFile( $file, $version = null ) {
346 global $wgStylePath, $wgStyleVersion;
347 // See if $file parameter is an absolute URL or begins with a slash
348 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
349 $path = $file;
350 } else {
351 $path = "{$wgStylePath}/common/{$file}";
352 }
353 if ( is_null( $version ) )
354 $version = $wgStyleVersion;
355 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
356 }
357
358 /**
359 * Add a self-contained script tag with the given contents
360 *
361 * @param $script String: JavaScript text, no <script> tags
362 */
363 public function addInlineScript( $script ) {
364 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
365 }
366
367 /**
368 * Get all registered JS and CSS tags for the header.
369 *
370 * @return String
371 */
372 function getScript() {
373 return $this->mScripts . $this->getHeadItems();
374 }
375
376 /**
377 * Get the list of modules to include on this page
378 *
379 * @return Array of module names
380 */
381 public function getModules() {
382 return array_values( array_unique( $this->mModules ) );
383 }
384
385 /**
386 * Add one or more modules recognized by the resource loader. Modules added
387 * through this function will be loaded by the resource loader when the
388 * page loads.
389 *
390 * @param $modules Mixed: module name (string) or array of module names
391 */
392 public function addModules( $modules ) {
393 $this->mModules = array_merge( $this->mModules, (array)$modules );
394 }
395
396 /**
397 * Get the list of module JS to include on this page
398 * @return array of module names
399 */
400 public function getModuleScripts() {
401 return array_values( array_unique( $this->mModuleScripts ) );
402 }
403
404 /**
405 * Add only JS of one or more modules recognized by the resource loader. Module
406 * scripts added through this function will be loaded by the resource loader when
407 * the page loads.
408 *
409 * @param $modules Mixed: module name (string) or array of module names
410 */
411 public function addModuleScripts( $modules ) {
412 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
413 }
414
415 /**
416 * Get the list of module CSS to include on this page
417 *
418 * @return Array of module names
419 */
420 public function getModuleStyles() {
421 return array_values( array_unique( $this->mModuleStyles ) );
422 }
423
424 /**
425 * Add only CSS of one or more modules recognized by the resource loader. Module
426 * styles added through this function will be loaded by the resource loader when
427 * the page loads.
428 *
429 * @param $modules Mixed: module name (string) or array of module names
430 */
431 public function addModuleStyles( $modules ) {
432 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
433 }
434
435 /**
436 * Get the list of module messages to include on this page
437 *
438 * @return Array of module names
439 */
440 public function getModuleMessages() {
441 return array_values( array_unique( $this->mModuleMessages ) );
442 }
443
444 /**
445 * Add only messages of one or more modules recognized by the resource loader.
446 * Module messages added through this function will be loaded by the resource
447 * loader when the page loads.
448 *
449 * @param $modules Mixed: module name (string) or array of module names
450 */
451 public function addModuleMessages( $modules ) {
452 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
453 }
454
455 /**
456 * Get all header items in a string
457 *
458 * @return String
459 */
460 function getHeadItems() {
461 $s = '';
462 foreach ( $this->mHeadItems as $item ) {
463 $s .= $item;
464 }
465 return $s;
466 }
467
468 /**
469 * Add or replace an header item to the output
470 *
471 * @param $name String: item name
472 * @param $value String: raw HTML
473 */
474 public function addHeadItem( $name, $value ) {
475 $this->mHeadItems[$name] = $value;
476 }
477
478 /**
479 * Check if the header item $name is already set
480 *
481 * @param $name String: item name
482 * @return Boolean
483 */
484 public function hasHeadItem( $name ) {
485 return isset( $this->mHeadItems[$name] );
486 }
487
488 /**
489 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
490 *
491 * @param $tag String: value of "ETag" header
492 */
493 function setETag( $tag ) {
494 $this->mETag = $tag;
495 }
496
497 /**
498 * Set whether the output should only contain the body of the article,
499 * without any skin, sidebar, etc.
500 * Used e.g. when calling with "action=render".
501 *
502 * @param $only Boolean: whether to output only the body of the article
503 */
504 public function setArticleBodyOnly( $only ) {
505 $this->mArticleBodyOnly = $only;
506 }
507
508 /**
509 * Return whether the output will contain only the body of the article
510 *
511 * @return Boolean
512 */
513 public function getArticleBodyOnly() {
514 return $this->mArticleBodyOnly;
515 }
516
517 /**
518 * checkLastModified tells the client to use the client-cached page if
519 * possible. If sucessful, the OutputPage is disabled so that
520 * any future call to OutputPage->output() have no effect.
521 *
522 * Side effect: sets mLastModified for Last-Modified header
523 *
524 * @return Boolean: true iff cache-ok headers was sent.
525 */
526 public function checkLastModified( $timestamp ) {
527 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
528
529 if ( !$timestamp || $timestamp == '19700101000000' ) {
530 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
531 return false;
532 }
533 if( !$wgCachePages ) {
534 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
535 return false;
536 }
537 if( $wgUser->getOption( 'nocache' ) ) {
538 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
539 return false;
540 }
541
542 $timestamp = wfTimestamp( TS_MW, $timestamp );
543 $modifiedTimes = array(
544 'page' => $timestamp,
545 'user' => $wgUser->getTouched(),
546 'epoch' => $wgCacheEpoch
547 );
548 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
549
550 $maxModified = max( $modifiedTimes );
551 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
552
553 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
554 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
555 return false;
556 }
557
558 # Make debug info
559 $info = '';
560 foreach ( $modifiedTimes as $name => $value ) {
561 if ( $info !== '' ) {
562 $info .= ', ';
563 }
564 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
565 }
566
567 # IE sends sizes after the date like this:
568 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
569 # this breaks strtotime().
570 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
571
572 wfSuppressWarnings(); // E_STRICT system time bitching
573 $clientHeaderTime = strtotime( $clientHeader );
574 wfRestoreWarnings();
575 if ( !$clientHeaderTime ) {
576 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
577 return false;
578 }
579 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
580
581 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
582 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
583 wfDebug( __METHOD__ . ": effective Last-Modified: " .
584 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
585 if( $clientHeaderTime < $maxModified ) {
586 wfDebug( __METHOD__ . ": STALE, $info\n", false );
587 return false;
588 }
589
590 # Not modified
591 # Give a 304 response code and disable body output
592 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
593 ini_set( 'zlib.output_compression', 0 );
594 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
595 $this->sendCacheControl();
596 $this->disable();
597
598 // Don't output a compressed blob when using ob_gzhandler;
599 // it's technically against HTTP spec and seems to confuse
600 // Firefox when the response gets split over two packets.
601 wfClearOutputBuffers();
602
603 return true;
604 }
605
606 /**
607 * Override the last modified timestamp
608 *
609 * @param $timestamp String: new timestamp, in a format readable by
610 * wfTimestamp()
611 */
612 public function setLastModified( $timestamp ) {
613 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
614 }
615
616 /**
617 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
618 *
619 * @param $policy String: the literal string to output as the contents of
620 * the meta tag. Will be parsed according to the spec and output in
621 * standardized form.
622 * @return null
623 */
624 public function setRobotPolicy( $policy ) {
625 $policy = Article::formatRobotPolicy( $policy );
626
627 if( isset( $policy['index'] ) ) {
628 $this->setIndexPolicy( $policy['index'] );
629 }
630 if( isset( $policy['follow'] ) ) {
631 $this->setFollowPolicy( $policy['follow'] );
632 }
633 }
634
635 /**
636 * Set the index policy for the page, but leave the follow policy un-
637 * touched.
638 *
639 * @param $policy string Either 'index' or 'noindex'.
640 * @return null
641 */
642 public function setIndexPolicy( $policy ) {
643 $policy = trim( $policy );
644 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
645 $this->mIndexPolicy = $policy;
646 }
647 }
648
649 /**
650 * Set the follow policy for the page, but leave the index policy un-
651 * touched.
652 *
653 * @param $policy String: either 'follow' or 'nofollow'.
654 * @return null
655 */
656 public function setFollowPolicy( $policy ) {
657 $policy = trim( $policy );
658 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
659 $this->mFollowPolicy = $policy;
660 }
661 }
662
663 /**
664 * Set the new value of the "action text", this will be added to the
665 * "HTML title", separated from it with " - ".
666 *
667 * @param $text String: new value of the "action text"
668 */
669 public function setPageTitleActionText( $text ) {
670 $this->mPageTitleActionText = $text;
671 }
672
673 /**
674 * Get the value of the "action text"
675 *
676 * @return String
677 */
678 public function getPageTitleActionText() {
679 if ( isset( $this->mPageTitleActionText ) ) {
680 return $this->mPageTitleActionText;
681 }
682 }
683
684 /**
685 * "HTML title" means the contents of <title>.
686 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
687 */
688 public function setHTMLTitle( $name ) {
689 $this->mHTMLtitle = $name;
690 }
691
692 /**
693 * Return the "HTML title", i.e. the content of the <title> tag.
694 *
695 * @return String
696 */
697 public function getHTMLTitle() {
698 return $this->mHTMLtitle;
699 }
700
701 /**
702 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
703 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
704 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
705 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
706 */
707 public function setPageTitle( $name ) {
708 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
709 # but leave "<i>foobar</i>" alone
710 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
711 $this->mPagetitle = $nameWithTags;
712
713 # change "<i>foo&amp;bar</i>" to "foo&bar"
714 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
715 }
716
717 /**
718 * Return the "page title", i.e. the content of the \<h1\> tag.
719 *
720 * @return String
721 */
722 public function getPageTitle() {
723 return $this->mPagetitle;
724 }
725
726 /**
727 * Set the Title object to use
728 *
729 * @param $t Title object
730 */
731 public function setTitle( $t ) {
732 $this->mTitle = $t;
733 }
734
735 /**
736 * Get the Title object used in this instance
737 *
738 * @return Title
739 */
740 public function getTitle() {
741 if ( $this->mTitle instanceof Title ) {
742 return $this->mTitle;
743 } else {
744 wfDebug( __METHOD__ . " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
745 global $wgTitle;
746 return $wgTitle;
747 }
748 }
749
750 /**
751 * Replace the subtile with $str
752 *
753 * @param $str String: new value of the subtitle
754 */
755 public function setSubtitle( $str ) {
756 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
757 }
758
759 /**
760 * Add $str to the subtitle
761 *
762 * @param $str String to add to the subtitle
763 */
764 public function appendSubtitle( $str ) {
765 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
766 }
767
768 /**
769 * Get the subtitle
770 *
771 * @return String
772 */
773 public function getSubtitle() {
774 return $this->mSubtitle;
775 }
776
777 /**
778 * Set the page as printable, i.e. it'll be displayed with with all
779 * print styles included
780 */
781 public function setPrintable() {
782 $this->mPrintable = true;
783 }
784
785 /**
786 * Return whether the page is "printable"
787 *
788 * @return Boolean
789 */
790 public function isPrintable() {
791 return $this->mPrintable;
792 }
793
794 /**
795 * Disable output completely, i.e. calling output() will have no effect
796 */
797 public function disable() {
798 $this->mDoNothing = true;
799 }
800
801 /**
802 * Return whether the output will be completely disabled
803 *
804 * @return Boolean
805 */
806 public function isDisabled() {
807 return $this->mDoNothing;
808 }
809
810 /**
811 * Show an "add new section" link?
812 *
813 * @return Boolean
814 */
815 public function showNewSectionLink() {
816 return $this->mNewSectionLink;
817 }
818
819 /**
820 * Forcibly hide the new section link?
821 *
822 * @return Boolean
823 */
824 public function forceHideNewSectionLink() {
825 return $this->mHideNewSectionLink;
826 }
827
828 /**
829 * Add or remove feed links in the page header
830 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
831 * for the new version
832 * @see addFeedLink()
833 *
834 * @param $show Boolean: true: add default feeds, false: remove all feeds
835 */
836 public function setSyndicated( $show = true ) {
837 if ( $show ) {
838 $this->setFeedAppendQuery( false );
839 } else {
840 $this->mFeedLinks = array();
841 }
842 }
843
844 /**
845 * Add default feeds to the page header
846 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
847 * for the new version
848 * @see addFeedLink()
849 *
850 * @param $val String: query to append to feed links or false to output
851 * default links
852 */
853 public function setFeedAppendQuery( $val ) {
854 global $wgAdvertisedFeedTypes;
855
856 $this->mFeedLinks = array();
857
858 foreach ( $wgAdvertisedFeedTypes as $type ) {
859 $query = "feed=$type";
860 if ( is_string( $val ) ) {
861 $query .= '&' . $val;
862 }
863 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
864 }
865 }
866
867 /**
868 * Add a feed link to the page header
869 *
870 * @param $format String: feed type, should be a key of $wgFeedClasses
871 * @param $href String: URL
872 */
873 public function addFeedLink( $format, $href ) {
874 global $wgAdvertisedFeedTypes;
875
876 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
877 $this->mFeedLinks[$format] = $href;
878 }
879 }
880
881 /**
882 * Should we output feed links for this page?
883 * @return Boolean
884 */
885 public function isSyndicated() {
886 return count( $this->mFeedLinks ) > 0;
887 }
888
889 /**
890 * Return URLs for each supported syndication format for this page.
891 * @return array associating format keys with URLs
892 */
893 public function getSyndicationLinks() {
894 return $this->mFeedLinks;
895 }
896
897 /**
898 * Will currently always return null
899 *
900 * @return null
901 */
902 public function getFeedAppendQuery() {
903 return $this->mFeedLinksAppendQuery;
904 }
905
906 /**
907 * Set whether the displayed content is related to the source of the
908 * corresponding article on the wiki
909 * Setting true will cause the change "article related" toggle to true
910 *
911 * @param $v Boolean
912 */
913 public function setArticleFlag( $v ) {
914 $this->mIsarticle = $v;
915 if ( $v ) {
916 $this->mIsArticleRelated = $v;
917 }
918 }
919
920 /**
921 * Return whether the content displayed page is related to the source of
922 * the corresponding article on the wiki
923 *
924 * @return Boolean
925 */
926 public function isArticle() {
927 return $this->mIsarticle;
928 }
929
930 /**
931 * Set whether this page is related an article on the wiki
932 * Setting false will cause the change of "article flag" toggle to false
933 *
934 * @param $v Boolean
935 */
936 public function setArticleRelated( $v ) {
937 $this->mIsArticleRelated = $v;
938 if ( !$v ) {
939 $this->mIsarticle = false;
940 }
941 }
942
943 /**
944 * Return whether this page is related an article on the wiki
945 *
946 * @return Boolean
947 */
948 public function isArticleRelated() {
949 return $this->mIsArticleRelated;
950 }
951
952 /**
953 * Add new language links
954 *
955 * @param $newLinkArray Associative array mapping language code to the page
956 * name
957 */
958 public function addLanguageLinks( $newLinkArray ) {
959 $this->mLanguageLinks += $newLinkArray;
960 }
961
962 /**
963 * Reset the language links and add new language links
964 *
965 * @param $newLinkArray Associative array mapping language code to the page
966 * name
967 */
968 public function setLanguageLinks( $newLinkArray ) {
969 $this->mLanguageLinks = $newLinkArray;
970 }
971
972 /**
973 * Get the list of language links
974 *
975 * @return Associative array mapping language code to the page name
976 */
977 public function getLanguageLinks() {
978 return $this->mLanguageLinks;
979 }
980
981 /**
982 * Add an array of categories, with names in the keys
983 *
984 * @param $categories Associative array mapping category name to its sort key
985 */
986 public function addCategoryLinks( $categories ) {
987 global $wgUser, $wgContLang;
988
989 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
990 return;
991 }
992
993 # Add the links to a LinkBatch
994 $arr = array( NS_CATEGORY => $categories );
995 $lb = new LinkBatch;
996 $lb->setArray( $arr );
997
998 # Fetch existence plus the hiddencat property
999 $dbr = wfGetDB( DB_SLAVE );
1000 $res = $dbr->select( array( 'page', 'page_props' ),
1001 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1002 $lb->constructSet( 'page', $dbr ),
1003 __METHOD__,
1004 array( 'LEFT JOIN' => array( "pp_propname='hiddencat'", "pp_page=page_id" ) )
1005 );
1006
1007 # Add the results to the link cache
1008 $lb->addResultToCache( LinkCache::singleton(), $res );
1009
1010 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1011 $categories = array_combine(
1012 array_keys( $categories ),
1013 array_fill( 0, count( $categories ), 'normal' )
1014 );
1015
1016 # Mark hidden categories
1017 foreach ( $res as $row ) {
1018 if ( isset( $row->pp_value ) ) {
1019 $categories[$row->page_title] = 'hidden';
1020 }
1021 }
1022
1023 # Add the remaining categories to the skin
1024 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
1025 $sk = $wgUser->getSkin();
1026 foreach ( $categories as $category => $type ) {
1027 $origcategory = $category;
1028 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1029 $wgContLang->findVariantLink( $category, $title, true );
1030 if ( $category != $origcategory ) {
1031 if ( array_key_exists( $category, $categories ) ) {
1032 continue;
1033 }
1034 }
1035 $text = $wgContLang->convertHtml( $title->getText() );
1036 $this->mCategories[] = $title->getText();
1037 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
1038 }
1039 }
1040 }
1041
1042 /**
1043 * Reset the category links (but not the category list) and add $categories
1044 *
1045 * @param $categories Associative array mapping category name to its sort key
1046 */
1047 public function setCategoryLinks( $categories ) {
1048 $this->mCategoryLinks = array();
1049 $this->addCategoryLinks( $categories );
1050 }
1051
1052 /**
1053 * Get the list of category links, in a 2-D array with the following format:
1054 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1055 * hidden categories) and $link a HTML fragment with a link to the category
1056 * page
1057 *
1058 * @return Array
1059 */
1060 public function getCategoryLinks() {
1061 return $this->mCategoryLinks;
1062 }
1063
1064 /**
1065 * Get the list of category names this page belongs to
1066 *
1067 * @return Array of strings
1068 */
1069 public function getCategories() {
1070 return $this->mCategories;
1071 }
1072
1073 /**
1074 * Suppress the quickbar from the output, only for skin supporting
1075 * the quickbar
1076 */
1077 public function suppressQuickbar() {
1078 $this->mSuppressQuickbar = true;
1079 }
1080
1081 /**
1082 * Return whether the quickbar should be suppressed from the output
1083 *
1084 * @return Boolean
1085 */
1086 public function isQuickbarSuppressed() {
1087 return $this->mSuppressQuickbar;
1088 }
1089
1090 /**
1091 * Remove user JavaScript from scripts to load
1092 */
1093 public function disallowUserJs() {
1094 $this->mAllowUserJs = false;
1095 }
1096
1097 /**
1098 * Return whether user JavaScript is allowed for this page
1099 *
1100 * @return Boolean
1101 */
1102 public function isUserJsAllowed() {
1103 return $this->mAllowUserJs;
1104 }
1105
1106 /**
1107 * Prepend $text to the body HTML
1108 *
1109 * @param $text String: HTML
1110 */
1111 public function prependHTML( $text ) {
1112 $this->mBodytext = $text . $this->mBodytext;
1113 }
1114
1115 /**
1116 * Append $text to the body HTML
1117 *
1118 * @param $text String: HTML
1119 */
1120 public function addHTML( $text ) {
1121 $this->mBodytext .= $text;
1122 }
1123
1124 /**
1125 * Clear the body HTML
1126 */
1127 public function clearHTML() {
1128 $this->mBodytext = '';
1129 }
1130
1131 /**
1132 * Get the body HTML
1133 *
1134 * @return String: HTML
1135 */
1136 public function getHTML() {
1137 return $this->mBodytext;
1138 }
1139
1140 /**
1141 * Add $text to the debug output
1142 *
1143 * @param $text String: debug text
1144 */
1145 public function debug( $text ) {
1146 $this->mDebugtext .= $text;
1147 }
1148
1149 /**
1150 * Get/set the ParserOptions object to use for wikitext parsing
1151 *
1152 * @param $options either the ParserOption to use or null to only get the
1153 * current ParserOption object
1154 * @return current ParserOption object
1155 */
1156 public function parserOptions( $options = null ) {
1157 if ( !$this->mParserOptions ) {
1158 $this->mParserOptions = new ParserOptions;
1159 }
1160 return wfSetVar( $this->mParserOptions, $options );
1161 }
1162
1163 /**
1164 * Set the revision ID which will be seen by the wiki text parser
1165 * for things such as embedded {{REVISIONID}} variable use.
1166 *
1167 * @param $revid Mixed: an positive integer, or null
1168 * @return Mixed: previous value
1169 */
1170 public function setRevisionId( $revid ) {
1171 $val = is_null( $revid ) ? null : intval( $revid );
1172 return wfSetVar( $this->mRevisionId, $val );
1173 }
1174
1175 /**
1176 * Get the current revision ID
1177 *
1178 * @return Integer
1179 */
1180 public function getRevisionId() {
1181 return $this->mRevisionId;
1182 }
1183
1184 /**
1185 * Convert wikitext to HTML and add it to the buffer
1186 * Default assumes that the current page title will be used.
1187 *
1188 * @param $text String
1189 * @param $linestart Boolean: is this the start of a line?
1190 */
1191 public function addWikiText( $text, $linestart = true ) {
1192 $title = $this->getTitle(); // Work arround E_STRICT
1193 $this->addWikiTextTitle( $text, $title, $linestart );
1194 }
1195
1196 /**
1197 * Add wikitext with a custom Title object
1198 *
1199 * @param $text String: wikitext
1200 * @param $title Title object
1201 * @param $linestart Boolean: is this the start of a line?
1202 */
1203 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1204 $this->addWikiTextTitle( $text, $title, $linestart );
1205 }
1206
1207 /**
1208 * Add wikitext with a custom Title object and
1209 *
1210 * @param $text String: wikitext
1211 * @param $title Title object
1212 * @param $linestart Boolean: is this the start of a line?
1213 */
1214 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1215 $this->addWikiTextTitle( $text, $title, $linestart, true );
1216 }
1217
1218 /**
1219 * Add wikitext with tidy enabled
1220 *
1221 * @param $text String: wikitext
1222 * @param $linestart Boolean: is this the start of a line?
1223 */
1224 public function addWikiTextTidy( $text, $linestart = true ) {
1225 $title = $this->getTitle();
1226 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1227 }
1228
1229 /**
1230 * Add wikitext with a custom Title object
1231 *
1232 * @param $text String: wikitext
1233 * @param $title Title object
1234 * @param $linestart Boolean: is this the start of a line?
1235 * @param $tidy Boolean: whether to use tidy
1236 */
1237 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1238 global $wgParser;
1239
1240 wfProfileIn( __METHOD__ );
1241
1242 wfIncrStats( 'pcache_not_possible' );
1243
1244 $popts = $this->parserOptions();
1245 $oldTidy = $popts->setTidy( $tidy );
1246
1247 $parserOutput = $wgParser->parse(
1248 $text, $title, $popts,
1249 $linestart, true, $this->mRevisionId
1250 );
1251
1252 $popts->setTidy( $oldTidy );
1253
1254 $this->addParserOutput( $parserOutput );
1255
1256 wfProfileOut( __METHOD__ );
1257 }
1258
1259 /**
1260 * Add a ParserOutput object, but without Html
1261 *
1262 * @param $parserOutput ParserOutput object
1263 */
1264 public function addParserOutputNoText( &$parserOutput ) {
1265 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1266 $this->addCategoryLinks( $parserOutput->getCategories() );
1267 $this->mNewSectionLink = $parserOutput->getNewSection();
1268 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1269
1270 $this->mParseWarnings = $parserOutput->getWarnings();
1271 if ( !$parserOutput->isCacheable() ) {
1272 $this->enableClientCache( false );
1273 }
1274 $this->mNoGallery = $parserOutput->getNoGallery();
1275 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1276 $this->addModules( $parserOutput->getModules() );
1277 // Versioning...
1278 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
1279 if ( isset( $this->mTemplateIds[$ns] ) ) {
1280 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1281 } else {
1282 $this->mTemplateIds[$ns] = $dbks;
1283 }
1284 }
1285
1286 // Hooks registered in the object
1287 global $wgParserOutputHooks;
1288 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1289 list( $hookName, $data ) = $hookInfo;
1290 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1291 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1292 }
1293 }
1294
1295 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1296 }
1297
1298 /**
1299 * Add a ParserOutput object
1300 *
1301 * @param $parserOutput ParserOutput
1302 */
1303 function addParserOutput( &$parserOutput ) {
1304 $this->addParserOutputNoText( $parserOutput );
1305 $text = $parserOutput->getText();
1306 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1307 $this->addHTML( $text );
1308 }
1309
1310
1311 /**
1312 * Add the output of a QuickTemplate to the output buffer
1313 *
1314 * @param $template QuickTemplate
1315 */
1316 public function addTemplate( &$template ) {
1317 ob_start();
1318 $template->execute();
1319 $this->addHTML( ob_get_contents() );
1320 ob_end_clean();
1321 }
1322
1323 /**
1324 * Parse wikitext and return the HTML.
1325 *
1326 * @param $text String
1327 * @param $linestart Boolean: is this the start of a line?
1328 * @param $interface Boolean: use interface language ($wgLang instead of
1329 * $wgContLang) while parsing language sensitive magic
1330 * words like GRAMMAR and PLURAL
1331 * @param $language Language object: target language object, will override
1332 * $interface
1333 * @return String: HTML
1334 */
1335 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1336 // Check one for one common cause for parser state resetting
1337 $callers = wfGetAllCallers( 10 );
1338 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1339 throw new MWException( "wfMsg* function with parsing cannot be used " .
1340 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1341 }
1342
1343 global $wgParser;
1344
1345 if( is_null( $this->getTitle() ) ) {
1346 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1347 }
1348
1349 $popts = $this->parserOptions();
1350 if ( $interface ) {
1351 $popts->setInterfaceMessage( true );
1352 }
1353 if ( $language !== null ) {
1354 $oldLang = $popts->setTargetLanguage( $language );
1355 }
1356
1357 $parserOutput = $wgParser->parse(
1358 $text, $this->getTitle(), $popts,
1359 $linestart, true, $this->mRevisionId
1360 );
1361
1362 if ( $interface ) {
1363 $popts->setInterfaceMessage( false );
1364 }
1365 if ( $language !== null ) {
1366 $popts->setTargetLanguage( $oldLang );
1367 }
1368
1369 return $parserOutput->getText();
1370 }
1371
1372 /**
1373 * Parse wikitext, strip paragraphs, and return the HTML.
1374 *
1375 * @param $text String
1376 * @param $linestart Boolean: is this the start of a line?
1377 * @param $interface Boolean: use interface language ($wgLang instead of
1378 * $wgContLang) while parsing language sensitive magic
1379 * words like GRAMMAR and PLURAL
1380 * @return String: HTML
1381 */
1382 public function parseInline( $text, $linestart = true, $interface = false ) {
1383 $parsed = $this->parse( $text, $linestart, $interface );
1384
1385 $m = array();
1386 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1387 $parsed = $m[1];
1388 }
1389
1390 return $parsed;
1391 }
1392
1393 /**
1394 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1395 *
1396 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1397 */
1398 public function setSquidMaxage( $maxage ) {
1399 $this->mSquidMaxage = $maxage;
1400 }
1401
1402 /**
1403 * Use enableClientCache(false) to force it to send nocache headers
1404 *
1405 * @param $state ??
1406 */
1407 public function enableClientCache( $state ) {
1408 return wfSetVar( $this->mEnableClientCache, $state );
1409 }
1410
1411 /**
1412 * Get the list of cookies that will influence on the cache
1413 *
1414 * @return Array
1415 */
1416 function getCacheVaryCookies() {
1417 global $wgCookiePrefix, $wgCacheVaryCookies;
1418 static $cookies;
1419 if ( $cookies === null ) {
1420 $cookies = array_merge(
1421 array(
1422 "{$wgCookiePrefix}Token",
1423 "{$wgCookiePrefix}LoggedOut",
1424 session_name()
1425 ),
1426 $wgCacheVaryCookies
1427 );
1428 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1429 }
1430 return $cookies;
1431 }
1432
1433 /**
1434 * Return whether this page is not cacheable because "useskin" or "uselang"
1435 * URL parameters were passed.
1436 *
1437 * @return Boolean
1438 */
1439 function uncacheableBecauseRequestVars() {
1440 global $wgRequest;
1441 return $wgRequest->getText( 'useskin', false ) === false
1442 && $wgRequest->getText( 'uselang', false ) === false;
1443 }
1444
1445 /**
1446 * Check if the request has a cache-varying cookie header
1447 * If it does, it's very important that we don't allow public caching
1448 *
1449 * @return Boolean
1450 */
1451 function haveCacheVaryCookies() {
1452 global $wgRequest;
1453 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1454 if ( $cookieHeader === false ) {
1455 return false;
1456 }
1457 $cvCookies = $this->getCacheVaryCookies();
1458 foreach ( $cvCookies as $cookieName ) {
1459 # Check for a simple string match, like the way squid does it
1460 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1461 wfDebug( __METHOD__ . ": found $cookieName\n" );
1462 return true;
1463 }
1464 }
1465 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1466 return false;
1467 }
1468
1469 /**
1470 * Add an HTTP header that will influence on the cache
1471 *
1472 * @param $header String: header name
1473 * @param $option either an Array or null
1474 * @fixme Document the $option parameter; it appears to be for
1475 * X-Vary-Options but what format is acceptable?
1476 */
1477 public function addVaryHeader( $header, $option = null ) {
1478 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1479 $this->mVaryHeader[$header] = (array)$option;
1480 } elseif( is_array( $option ) ) {
1481 if( is_array( $this->mVaryHeader[$header] ) ) {
1482 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1483 } else {
1484 $this->mVaryHeader[$header] = $option;
1485 }
1486 }
1487 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1488 }
1489
1490 /**
1491 * Get a complete X-Vary-Options header
1492 *
1493 * @return String
1494 */
1495 public function getXVO() {
1496 $cvCookies = $this->getCacheVaryCookies();
1497
1498 $cookiesOption = array();
1499 foreach ( $cvCookies as $cookieName ) {
1500 $cookiesOption[] = 'string-contains=' . $cookieName;
1501 }
1502 $this->addVaryHeader( 'Cookie', $cookiesOption );
1503
1504 $headers = array();
1505 foreach( $this->mVaryHeader as $header => $option ) {
1506 $newheader = $header;
1507 if( is_array( $option ) ) {
1508 $newheader .= ';' . implode( ';', $option );
1509 }
1510 $headers[] = $newheader;
1511 }
1512 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1513
1514 return $xvo;
1515 }
1516
1517 /**
1518 * bug 21672: Add Accept-Language to Vary and XVO headers
1519 * if there's no 'variant' parameter existed in GET.
1520 *
1521 * For example:
1522 * /w/index.php?title=Main_page should always be served; but
1523 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1524 */
1525 function addAcceptLanguage() {
1526 global $wgRequest, $wgContLang;
1527 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1528 $variants = $wgContLang->getVariants();
1529 $aloption = array();
1530 foreach ( $variants as $variant ) {
1531 if( $variant === $wgContLang->getCode() ) {
1532 continue;
1533 } else {
1534 $aloption[] = 'string-contains=' . $variant;
1535
1536 // IE and some other browsers use another form of language code
1537 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1538 // We should handle these too.
1539 $ievariant = explode( '-', $variant );
1540 if ( count( $ievariant ) == 2 ) {
1541 $ievariant[1] = strtoupper( $ievariant[1] );
1542 $ievariant = implode( '-', $ievariant );
1543 $aloption[] = 'string-contains=' . $ievariant;
1544 }
1545 }
1546 }
1547 $this->addVaryHeader( 'Accept-Language', $aloption );
1548 }
1549 }
1550
1551 /**
1552 * Set a flag which will cause an X-Frame-Options header appropriate for
1553 * edit pages to be sent. The header value is controlled by
1554 * $wgEditPageFrameOptions.
1555 *
1556 * This is the default for special pages. If you display a CSRF-protected
1557 * form on an ordinary view page, then you need to call this function.
1558 */
1559 public function preventClickjacking( $enable = true ) {
1560 $this->mPreventClickjacking = $enable;
1561 }
1562
1563 /**
1564 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1565 * This can be called from pages which do not contain any CSRF-protected
1566 * HTML form.
1567 */
1568 public function allowClickjacking() {
1569 $this->mPreventClickjacking = false;
1570 }
1571
1572 /**
1573 * Get the X-Frame-Options header value (without the name part), or false
1574 * if there isn't one. This is used by Skin to determine whether to enable
1575 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1576 */
1577 public function getFrameOptions() {
1578 global $wgBreakFrames, $wgEditPageFrameOptions;
1579 if ( $wgBreakFrames ) {
1580 return 'DENY';
1581 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1582 return $wgEditPageFrameOptions;
1583 }
1584 }
1585
1586 /**
1587 * Send cache control HTTP headers
1588 */
1589 public function sendCacheControl() {
1590 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1591
1592 $response = $wgRequest->response();
1593 if ( $wgUseETag && $this->mETag ) {
1594 $response->header( "ETag: $this->mETag" );
1595 }
1596
1597 $this->addAcceptLanguage();
1598
1599 # don't serve compressed data to clients who can't handle it
1600 # maintain different caches for logged-in users and non-logged in ones
1601 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1602
1603 if ( $wgUseXVO ) {
1604 # Add an X-Vary-Options header for Squid with Wikimedia patches
1605 $response->header( $this->getXVO() );
1606 }
1607
1608 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1609 if(
1610 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1611 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1612 )
1613 {
1614 if ( $wgUseESI ) {
1615 # We'll purge the proxy cache explicitly, but require end user agents
1616 # to revalidate against the proxy on each visit.
1617 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1618 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1619 # start with a shorter timeout for initial testing
1620 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1621 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1622 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1623 } else {
1624 # We'll purge the proxy cache for anons explicitly, but require end user agents
1625 # to revalidate against the proxy on each visit.
1626 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1627 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1628 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1629 # start with a shorter timeout for initial testing
1630 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1631 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1632 }
1633 } else {
1634 # We do want clients to cache if they can, but they *must* check for updates
1635 # on revisiting the page.
1636 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1637 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1638 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1639 }
1640 if($this->mLastModified) {
1641 $response->header( "Last-Modified: {$this->mLastModified}" );
1642 }
1643 } else {
1644 wfDebug( __METHOD__ . ": no caching **\n", false );
1645
1646 # In general, the absence of a last modified header should be enough to prevent
1647 # the client from using its cache. We send a few other things just to make sure.
1648 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1649 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1650 $response->header( 'Pragma: no-cache' );
1651 }
1652 }
1653
1654 /**
1655 * Get the message associed with the HTTP response code $code
1656 *
1657 * @param $code Integer: status code
1658 * @return String or null: message or null if $code is not in the list of
1659 * messages
1660 */
1661 public static function getStatusMessage( $code ) {
1662 static $statusMessage = array(
1663 100 => 'Continue',
1664 101 => 'Switching Protocols',
1665 102 => 'Processing',
1666 200 => 'OK',
1667 201 => 'Created',
1668 202 => 'Accepted',
1669 203 => 'Non-Authoritative Information',
1670 204 => 'No Content',
1671 205 => 'Reset Content',
1672 206 => 'Partial Content',
1673 207 => 'Multi-Status',
1674 300 => 'Multiple Choices',
1675 301 => 'Moved Permanently',
1676 302 => 'Found',
1677 303 => 'See Other',
1678 304 => 'Not Modified',
1679 305 => 'Use Proxy',
1680 307 => 'Temporary Redirect',
1681 400 => 'Bad Request',
1682 401 => 'Unauthorized',
1683 402 => 'Payment Required',
1684 403 => 'Forbidden',
1685 404 => 'Not Found',
1686 405 => 'Method Not Allowed',
1687 406 => 'Not Acceptable',
1688 407 => 'Proxy Authentication Required',
1689 408 => 'Request Timeout',
1690 409 => 'Conflict',
1691 410 => 'Gone',
1692 411 => 'Length Required',
1693 412 => 'Precondition Failed',
1694 413 => 'Request Entity Too Large',
1695 414 => 'Request-URI Too Large',
1696 415 => 'Unsupported Media Type',
1697 416 => 'Request Range Not Satisfiable',
1698 417 => 'Expectation Failed',
1699 422 => 'Unprocessable Entity',
1700 423 => 'Locked',
1701 424 => 'Failed Dependency',
1702 500 => 'Internal Server Error',
1703 501 => 'Not Implemented',
1704 502 => 'Bad Gateway',
1705 503 => 'Service Unavailable',
1706 504 => 'Gateway Timeout',
1707 505 => 'HTTP Version Not Supported',
1708 507 => 'Insufficient Storage'
1709 );
1710 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1711 }
1712
1713 /**
1714 * Finally, all the text has been munged and accumulated into
1715 * the object, let's actually output it:
1716 */
1717 public function output() {
1718 global $wgUser, $wgOutputEncoding, $wgRequest;
1719 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1720 global $wgUseAjax, $wgAjaxWatch;
1721 global $wgEnableMWSuggest, $wgUniversalEditButton;
1722
1723 if( $this->mDoNothing ) {
1724 return;
1725 }
1726 wfProfileIn( __METHOD__ );
1727 if ( $this->mRedirect != '' ) {
1728 # Standards require redirect URLs to be absolute
1729 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1730 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1731 if( !$wgDebugRedirects ) {
1732 $message = self::getStatusMessage( $this->mRedirectCode );
1733 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1734 }
1735 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1736 }
1737 $this->sendCacheControl();
1738
1739 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1740 if( $wgDebugRedirects ) {
1741 $url = htmlspecialchars( $this->mRedirect );
1742 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1743 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1744 print "</body>\n</html>\n";
1745 } else {
1746 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1747 }
1748 wfProfileOut( __METHOD__ );
1749 return;
1750 } elseif ( $this->mStatusCode ) {
1751 $message = self::getStatusMessage( $this->mStatusCode );
1752 if ( $message ) {
1753 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1754 }
1755 }
1756
1757 $sk = $wgUser->getSkin();
1758
1759 // Add base resources
1760 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1761
1762 // Add various resources if required
1763 if ( $wgUseAjax ) {
1764 $this->addModules( 'mediawiki.legacy.ajax' );
1765
1766 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1767
1768 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1769 $this->addModules( 'mediawiki.action.watch.ajax' );
1770 }
1771
1772 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1773 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1774 }
1775 }
1776
1777 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1778 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1779 }
1780
1781 if( $wgUniversalEditButton ) {
1782 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1783 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1784 // Original UniversalEditButton
1785 $msg = wfMsg( 'edit' );
1786 $this->addLink( array(
1787 'rel' => 'alternate',
1788 'type' => 'application/x-wiki',
1789 'title' => $msg,
1790 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1791 ) );
1792 // Alternate edit link
1793 $this->addLink( array(
1794 'rel' => 'edit',
1795 'title' => $msg,
1796 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1797 ) );
1798 }
1799 }
1800
1801
1802 # Buffer output; final headers may depend on later processing
1803 ob_start();
1804
1805 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1806 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1807
1808 // Prevent framing, if requested
1809 $frameOptions = $this->getFrameOptions();
1810 if ( $frameOptions ) {
1811 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1812 }
1813
1814 if ( $this->mArticleBodyOnly ) {
1815 $this->out( $this->mBodytext );
1816 } else {
1817 // Hook that allows last minute changes to the output page, e.g.
1818 // adding of CSS or Javascript by extensions.
1819 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1820
1821 wfProfileIn( 'Output-skin' );
1822 $sk->outputPage( $this );
1823 wfProfileOut( 'Output-skin' );
1824 }
1825
1826 $this->sendCacheControl();
1827 ob_end_flush();
1828 wfProfileOut( __METHOD__ );
1829 }
1830
1831 /**
1832 * Actually output something with print(). Performs an iconv to the
1833 * output encoding, if needed.
1834 *
1835 * @param $ins String: the string to output
1836 */
1837 public function out( $ins ) {
1838 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1839 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1840 $outs = $ins;
1841 } else {
1842 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1843 if ( false === $outs ) {
1844 $outs = $ins;
1845 }
1846 }
1847 print $outs;
1848 }
1849
1850 /**
1851 * Produce a "user is blocked" page.
1852 *
1853 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1854 * @return nothing
1855 */
1856 function blockedPage( $return = true ) {
1857 global $wgUser, $wgContLang, $wgLang;
1858
1859 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1860 $this->setRobotPolicy( 'noindex,nofollow' );
1861 $this->setArticleRelated( false );
1862
1863 $name = User::whoIs( $wgUser->blockedBy() );
1864 $reason = $wgUser->blockedFor();
1865 if( $reason == '' ) {
1866 $reason = wfMsg( 'blockednoreason' );
1867 }
1868 $blockTimestamp = $wgLang->timeanddate(
1869 wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true
1870 );
1871 $ip = wfGetIP();
1872
1873 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1874
1875 $blockid = $wgUser->mBlock->mId;
1876
1877 $blockExpiry = $wgUser->mBlock->mExpiry;
1878 if ( $blockExpiry == 'infinity' ) {
1879 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1880 // Search for localization in 'ipboptions'
1881 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1882 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1883 if ( strpos( $option, ':' ) === false ) {
1884 continue;
1885 }
1886 list( $show, $value ) = explode( ':', $option );
1887 if ( $value == 'infinite' || $value == 'indefinite' ) {
1888 $blockExpiry = $show;
1889 break;
1890 }
1891 }
1892 } else {
1893 $blockExpiry = $wgLang->timeanddate(
1894 wfTimestamp( TS_MW, $blockExpiry ),
1895 true
1896 );
1897 }
1898
1899 if ( $wgUser->mBlock->mAuto ) {
1900 $msg = 'autoblockedtext';
1901 } else {
1902 $msg = 'blockedtext';
1903 }
1904
1905 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1906 * This could be a username, an IP range, or a single IP. */
1907 $intended = $wgUser->mBlock->mAddress;
1908
1909 $this->addWikiMsg(
1910 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1911 $intended, $blockTimestamp
1912 );
1913
1914 # Don't auto-return to special pages
1915 if( $return ) {
1916 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1917 $this->returnToMain( null, $return );
1918 }
1919 }
1920
1921 /**
1922 * Output a standard error page
1923 *
1924 * @param $title String: message key for page title
1925 * @param $msg String: message key for page text
1926 * @param $params Array: message parameters
1927 */
1928 public function showErrorPage( $title, $msg, $params = array() ) {
1929 if ( $this->getTitle() ) {
1930 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1931 }
1932 $this->setPageTitle( wfMsg( $title ) );
1933 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1934 $this->setRobotPolicy( 'noindex,nofollow' );
1935 $this->setArticleRelated( false );
1936 $this->enableClientCache( false );
1937 $this->mRedirect = '';
1938 $this->mBodytext = '';
1939
1940 $this->addWikiMsgArray( $msg, $params );
1941
1942 $this->returnToMain();
1943 }
1944
1945 /**
1946 * Output a standard permission error page
1947 *
1948 * @param $errors Array: error message keys
1949 * @param $action String: action that was denied or null if unknown
1950 */
1951 public function showPermissionsErrorPage( $errors, $action = null ) {
1952 $this->mDebugtext .= 'Original title: ' .
1953 $this->getTitle()->getPrefixedText() . "\n";
1954 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1955 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1956 $this->setRobotPolicy( 'noindex,nofollow' );
1957 $this->setArticleRelated( false );
1958 $this->enableClientCache( false );
1959 $this->mRedirect = '';
1960 $this->mBodytext = '';
1961 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1962 }
1963
1964 /**
1965 * Display an error page indicating that a given version of MediaWiki is
1966 * required to use it
1967 *
1968 * @param $version Mixed: the version of MediaWiki needed to use the page
1969 */
1970 public function versionRequired( $version ) {
1971 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1972 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1973 $this->setRobotPolicy( 'noindex,nofollow' );
1974 $this->setArticleRelated( false );
1975 $this->mBodytext = '';
1976
1977 $this->addWikiMsg( 'versionrequiredtext', $version );
1978 $this->returnToMain();
1979 }
1980
1981 /**
1982 * Display an error page noting that a given permission bit is required.
1983 *
1984 * @param $permission String: key required
1985 */
1986 public function permissionRequired( $permission ) {
1987 global $wgLang;
1988
1989 $this->setPageTitle( wfMsg( 'badaccess' ) );
1990 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1991 $this->setRobotPolicy( 'noindex,nofollow' );
1992 $this->setArticleRelated( false );
1993 $this->mBodytext = '';
1994
1995 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1996 User::getGroupsWithPermission( $permission ) );
1997 if( $groups ) {
1998 $this->addWikiMsg(
1999 'badaccess-groups',
2000 $wgLang->commaList( $groups ),
2001 count( $groups )
2002 );
2003 } else {
2004 $this->addWikiMsg( 'badaccess-group0' );
2005 }
2006 $this->returnToMain();
2007 }
2008
2009 /**
2010 * Produce the stock "please login to use the wiki" page
2011 */
2012 public function loginToUse() {
2013 global $wgUser;
2014
2015 if( $wgUser->isLoggedIn() ) {
2016 $this->permissionRequired( 'read' );
2017 return;
2018 }
2019
2020 $skin = $wgUser->getSkin();
2021
2022 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2023 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2024 $this->setRobotPolicy( 'noindex,nofollow' );
2025 $this->setArticleRelated( false );
2026
2027 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2028 $loginLink = $skin->link(
2029 $loginTitle,
2030 wfMsgHtml( 'loginreqlink' ),
2031 array(),
2032 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2033 array( 'known', 'noclasses' )
2034 );
2035 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
2036 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2037
2038 # Don't return to the main page if the user can't read it
2039 # otherwise we'll end up in a pointless loop
2040 $mainPage = Title::newMainPage();
2041 if( $mainPage->userCanRead() ) {
2042 $this->returnToMain( null, $mainPage );
2043 }
2044 }
2045
2046 /**
2047 * Format a list of error messages
2048 *
2049 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
2050 * @param $action String: action that was denied or null if unknown
2051 * @return String: the wikitext error-messages, formatted into a list.
2052 */
2053 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2054 if ( $action == null ) {
2055 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2056 } else {
2057 $action_desc = wfMsgNoTrans( "action-$action" );
2058 $text = wfMsgNoTrans(
2059 'permissionserrorstext-withaction',
2060 count( $errors ),
2061 $action_desc
2062 ) . "\n\n";
2063 }
2064
2065 if ( count( $errors ) > 1 ) {
2066 $text .= '<ul class="permissions-errors">' . "\n";
2067
2068 foreach( $errors as $error ) {
2069 $text .= '<li>';
2070 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2071 $text .= "</li>\n";
2072 }
2073 $text .= '</ul>';
2074 } else {
2075 $text .= "<div class=\"permissions-errors\">\n" .
2076 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2077 "\n</div>";
2078 }
2079
2080 return $text;
2081 }
2082
2083 /**
2084 * Display a page stating that the Wiki is in read-only mode,
2085 * and optionally show the source of the page that the user
2086 * was trying to edit. Should only be called (for this
2087 * purpose) after wfReadOnly() has returned true.
2088 *
2089 * For historical reasons, this function is _also_ used to
2090 * show the error message when a user tries to edit a page
2091 * they are not allowed to edit. (Unless it's because they're
2092 * blocked, then we show blockedPage() instead.) In this
2093 * case, the second parameter should be set to true and a list
2094 * of reasons supplied as the third parameter.
2095 *
2096 * @todo Needs to be split into multiple functions.
2097 *
2098 * @param $source String: source code to show (or null).
2099 * @param $protected Boolean: is this a permissions error?
2100 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2101 * @param $action String: action that was denied or null if unknown
2102 */
2103 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2104 global $wgUser;
2105 $skin = $wgUser->getSkin();
2106
2107 $this->setRobotPolicy( 'noindex,nofollow' );
2108 $this->setArticleRelated( false );
2109
2110 // If no reason is given, just supply a default "I can't let you do
2111 // that, Dave" message. Should only occur if called by legacy code.
2112 if ( $protected && empty( $reasons ) ) {
2113 $reasons[] = array( 'badaccess-group0' );
2114 }
2115
2116 if ( !empty( $reasons ) ) {
2117 // Permissions error
2118 if( $source ) {
2119 $this->setPageTitle( wfMsg( 'viewsource' ) );
2120 $this->setSubtitle(
2121 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2122 );
2123 } else {
2124 $this->setPageTitle( wfMsg( 'badaccess' ) );
2125 }
2126 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2127 } else {
2128 // Wiki is read only
2129 $this->setPageTitle( wfMsg( 'readonly' ) );
2130 $reason = wfReadOnlyReason();
2131 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2132 }
2133
2134 // Show source, if supplied
2135 if( is_string( $source ) ) {
2136 $this->addWikiMsg( 'viewsourcetext' );
2137
2138 $params = array(
2139 'id' => 'wpTextbox1',
2140 'name' => 'wpTextbox1',
2141 'cols' => $wgUser->getOption( 'cols' ),
2142 'rows' => $wgUser->getOption( 'rows' ),
2143 'readonly' => 'readonly'
2144 );
2145 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2146
2147 // Show templates used by this article
2148 $skin = $wgUser->getSkin();
2149 $article = new Article( $this->getTitle() );
2150 $this->addHTML( "<div class='templatesUsed'>
2151 {$skin->formatTemplates( $article->getUsedTemplates() )}
2152 </div>
2153 " );
2154 }
2155
2156 # If the title doesn't exist, it's fairly pointless to print a return
2157 # link to it. After all, you just tried editing it and couldn't, so
2158 # what's there to do there?
2159 if( $this->getTitle()->exists() ) {
2160 $this->returnToMain( null, $this->getTitle() );
2161 }
2162 }
2163
2164 /**
2165 * Adds JS-based password security checker
2166 * @param $passwordId String ID of input box containing password
2167 * @param $retypeId String ID of input box containing retyped password
2168 * @return none
2169 */
2170 public function addPasswordSecurity( $passwordId, $retypeId ) {
2171 $data = array(
2172 'password' => '#' . $passwordId,
2173 'retype' => '#' . $retypeId,
2174 'messages' => array(),
2175 );
2176 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2177 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2178 ) as $message ) {
2179 $data['messages'][$message] = wfMsg( $message );
2180 }
2181 $this->addScript( Html::inlineScript( 'var passwordSecurity=' . FormatJson::encode( $data ) ) );
2182 $this->addModules( 'mediawiki.legacy.password' );
2183 }
2184
2185 public function showFatalError( $message ) {
2186 $this->setPageTitle( wfMsg( 'internalerror' ) );
2187 $this->setRobotPolicy( 'noindex,nofollow' );
2188 $this->setArticleRelated( false );
2189 $this->enableClientCache( false );
2190 $this->mRedirect = '';
2191 $this->mBodytext = $message;
2192 }
2193
2194 public function showUnexpectedValueError( $name, $val ) {
2195 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2196 }
2197
2198 public function showFileCopyError( $old, $new ) {
2199 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2200 }
2201
2202 public function showFileRenameError( $old, $new ) {
2203 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2204 }
2205
2206 public function showFileDeleteError( $name ) {
2207 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2208 }
2209
2210 public function showFileNotFoundError( $name ) {
2211 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2212 }
2213
2214 /**
2215 * Add a "return to" link pointing to a specified title
2216 *
2217 * @param $title Title to link
2218 * @param $query String: query string
2219 * @param $text String text of the link (input is not escaped)
2220 */
2221 public function addReturnTo( $title, $query = array(), $text = null ) {
2222 global $wgUser;
2223 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2224 $link = wfMsgHtml(
2225 'returnto',
2226 $wgUser->getSkin()->link( $title, $text, array(), $query )
2227 );
2228 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2229 }
2230
2231 /**
2232 * Add a "return to" link pointing to a specified title,
2233 * or the title indicated in the request, or else the main page
2234 *
2235 * @param $unused No longer used
2236 * @param $returnto Title or String to return to
2237 * @param $returntoquery String: query string for the return to link
2238 */
2239 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2240 global $wgRequest;
2241
2242 if ( $returnto == null ) {
2243 $returnto = $wgRequest->getText( 'returnto' );
2244 }
2245
2246 if ( $returntoquery == null ) {
2247 $returntoquery = $wgRequest->getText( 'returntoquery' );
2248 }
2249
2250 if ( $returnto === '' ) {
2251 $returnto = Title::newMainPage();
2252 }
2253
2254 if ( is_object( $returnto ) ) {
2255 $titleObj = $returnto;
2256 } else {
2257 $titleObj = Title::newFromText( $returnto );
2258 }
2259 if ( !is_object( $titleObj ) ) {
2260 $titleObj = Title::newMainPage();
2261 }
2262
2263 $this->addReturnTo( $titleObj, $returntoquery );
2264 }
2265
2266 /**
2267 * @param $sk Skin The given Skin
2268 * @param $includeStyle Boolean: unused
2269 * @return String: The doctype, opening <html>, and head element.
2270 */
2271 public function headElement( Skin $sk, $includeStyle = true ) {
2272 global $wgOutputEncoding, $wgMimeType;
2273 global $wgUseTrackbacks, $wgHtml5;
2274 global $wgUser, $wgRequest, $wgLang;
2275
2276 if ( $sk->commonPrintStylesheet() ) {
2277 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2278 }
2279 $sk->setupUserCss( $this );
2280
2281 $ret = Html::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2282
2283 if ( $this->getHTMLTitle() == '' ) {
2284 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2285 }
2286
2287 $openHead = Html::openElement( 'head' );
2288 if ( $openHead ) {
2289 # Don't bother with the newline if $head == ''
2290 $ret .= "$openHead\n";
2291 }
2292
2293 if ( $wgHtml5 ) {
2294 # More succinct than <meta http-equiv=Content-Type>, has the
2295 # same effect
2296 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2297 } else {
2298 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2299 }
2300
2301 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2302
2303 $ret .= implode( "\n", array(
2304 $this->getHeadLinks( $sk ),
2305 $this->buildCssLinks( $sk ),
2306 $this->getHeadItems()
2307 ) );
2308
2309 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2310 $ret .= $this->getTitle()->trackbackRDF();
2311 }
2312
2313 $closeHead = Html::closeElement( 'head' );
2314 if ( $closeHead ) {
2315 $ret .= "$closeHead\n";
2316 }
2317
2318 $bodyAttrs = array();
2319
2320 # Crazy edit-on-double-click stuff
2321 $action = $wgRequest->getVal( 'action', 'view' );
2322
2323 if (
2324 $this->getTitle()->getNamespace() != NS_SPECIAL &&
2325 !in_array( $action, array( 'edit', 'submit' ) ) &&
2326 $wgUser->getOption( 'editondblclick' )
2327 )
2328 {
2329 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2330 }
2331
2332 # Class bloat
2333 $dir = wfUILang()->getDir();
2334 $bodyAttrs['class'] = "mediawiki $dir";
2335
2336 if ( $wgLang->capitalizeAllNouns() ) {
2337 # A <body> class is probably not the best way to do this . . .
2338 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2339 }
2340 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2341 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2342 $bodyAttrs['class'] .= ' ns-special';
2343 } elseif ( $this->getTitle()->isTalkPage() ) {
2344 $bodyAttrs['class'] .= ' ns-talk';
2345 } else {
2346 $bodyAttrs['class'] .= ' ns-subject';
2347 }
2348 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2349 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2350
2351 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2352 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2353
2354 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2355
2356 return $ret;
2357 }
2358
2359 /**
2360 * Get a ResourceLoader object associated with this OutputPage
2361 */
2362 public function getResourceLoader() {
2363 if ( is_null( $this->mResourceLoader ) ) {
2364 $this->mResourceLoader = new ResourceLoader();
2365 }
2366 return $this->mResourceLoader;
2367 }
2368
2369 /**
2370 * TODO: Document
2371 * @param $skin Skin
2372 * @param $modules Array/string with the module name
2373 * @param $only string May be styles, messages or scripts
2374 * @param $useESI boolean
2375 * @return string html <script> and <style> tags
2376 */
2377 protected function makeResourceLoaderLink( Skin $skin, $modules, $only, $useESI = false ) {
2378 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2379 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2380 // Lazy-load ResourceLoader
2381 // TODO: Should this be a static function of ResourceLoader instead?
2382 // TODO: Divide off modules starting with "user", and add the user parameter to them
2383 $query = array(
2384 'lang' => $wgLang->getCode(),
2385 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
2386 'skin' => $skin->getSkinName(),
2387 'only' => $only,
2388 );
2389 // Propagate printable and handheld parameters if present
2390 if ( $wgRequest->getBool( 'printable' ) ) {
2391 $query['printable'] = 1;
2392 }
2393 if ( $wgRequest->getBool( 'handheld' ) ) {
2394 $query['handheld'] = 1;
2395 }
2396
2397 if ( !count( $modules ) ) {
2398 return '';
2399 }
2400
2401 if ( count( $modules ) > 1 ) {
2402 // Remove duplicate module requests
2403 $modules = array_unique( (array) $modules );
2404 // Sort module names so requests are more uniform
2405 sort( $modules );
2406
2407 if ( ResourceLoader::inDebugMode() ) {
2408 // Recursively call us for every item
2409 $links = '';
2410 foreach ( $modules as $name ) {
2411 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2412 }
2413 return $links;
2414 }
2415 }
2416
2417 // Create keyed-by-group list of module objects from modules list
2418 $groups = array();
2419 $resourceLoader = $this->getResourceLoader();
2420 foreach ( (array) $modules as $name ) {
2421 $module = $resourceLoader->getModule( $name );
2422 $group = $module->getGroup();
2423 if ( !isset( $groups[$group] ) ) {
2424 $groups[$group] = array();
2425 }
2426 $groups[$group][$name] = $module;
2427 }
2428 $links = '';
2429 foreach ( $groups as $group => $modules ) {
2430 $query['modules'] = implode( '|', array_keys( $modules ) );
2431 // Special handling for user-specific groups
2432 if ( ( $group === 'user' || $group === 'private' ) && $wgUser->isLoggedIn() ) {
2433 $query['user'] = $wgUser->getName();
2434 }
2435 // Support inlining of private modules if configured as such
2436 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2437 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2438 if ( $only == 'styles' ) {
2439 $links .= Html::inlineStyle(
2440 $resourceLoader->makeModuleResponse( $context, $modules )
2441 );
2442 } else {
2443 $links .= Html::inlineScript(
2444 ResourceLoader::makeLoaderConditionalScript(
2445 $resourceLoader->makeModuleResponse( $context, $modules )
2446 )
2447 );
2448 }
2449 continue;
2450 }
2451 // Special handling for user and site groups; because users might change their stuff
2452 // on-wiki like site or user pages, or user preferences; we need to find the highest
2453 // timestamp of these user-changable modules so we can ensure cache misses on change
2454 if ( $group === 'user' || $group === 'site' ) {
2455 // Create a fake request based on the one we are about to make so modules return
2456 // correct times
2457 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2458 // Get the maximum timestamp
2459 $timestamp = 1;
2460 foreach ( $modules as $module ) {
2461 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2462 }
2463 // Add a version parameter so cache will break when things change
2464 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, round( $timestamp, -2 ) );
2465 }
2466 // Make queries uniform in order
2467 ksort( $query );
2468
2469 $url = wfAppendQuery( $wgLoadScript, $query );
2470 if ( $useESI && $wgResourceLoaderUseESI ) {
2471 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2472 if ( $only == 'styles' ) {
2473 $links .= Html::inlineStyle( $esi );
2474 } else {
2475 $links .= Html::inlineScript( $esi );
2476 }
2477 } else {
2478 // Automatically select style/script elements
2479 if ( $only === 'styles' ) {
2480 $links .= Html::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2481 } else {
2482 $links .= Html::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2483 }
2484 }
2485 }
2486 return $links;
2487 }
2488
2489 /**
2490 * Gets the global variables and mScripts; also adds userjs to the end if
2491 * enabled. Despite the name, these scripts are no longer put in the
2492 * <head> but at the bottom of the <body>
2493 *
2494 * @param $sk Skin object to use
2495 * @return String: HTML fragment
2496 */
2497 function getHeadScripts( Skin $sk ) {
2498 global $wgUser, $wgRequest, $wgUseSiteJs;
2499
2500 // Startup - this will immediately load jquery and mediawiki modules
2501 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
2502
2503 // Configuration -- This could be merged together with the load and go, but
2504 // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
2505 $scripts .= Skin::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2506
2507 // Script and Messages "only" requests
2508 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2509 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2510
2511 // Modules requests - let the client calculate dependencies and batch requests as it likes
2512 if ( $this->getModules() ) {
2513 $scripts .= Html::inlineScript(
2514 ResourceLoader::makeLoaderConditionalScript(
2515 Xml::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
2516 Xml::encodeJsCall( 'mediaWiki.loader.go', array() )
2517 )
2518 ) . "\n";
2519 }
2520
2521 // Legacy Scripts
2522 $scripts .= "\n" . $this->mScripts;
2523
2524 // Add site JS if enabled
2525 if ( $wgUseSiteJs ) {
2526 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
2527 }
2528
2529 // Add user JS if enabled - trying to load user.options as a bundle if possible
2530 $userOptionsAdded = false;
2531 if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2532 $action = $wgRequest->getVal( 'action', 'view' );
2533 if( $this->mTitle && $this->mTitle->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2534 # XXX: additional security check/prompt?
2535 $scripts .= Html::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2536 } else {
2537 $scripts .= $this->makeResourceLoaderLink(
2538 $sk, array( 'user', 'user.options' ), 'scripts'
2539 );
2540 $userOptionsAdded = true;
2541 }
2542 }
2543 if ( !$userOptionsAdded ) {
2544 $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
2545 }
2546
2547 return $scripts;
2548 }
2549
2550 /**
2551 * Add default \<meta\> tags
2552 */
2553 protected function addDefaultMeta() {
2554 global $wgVersion, $wgHtml5;
2555
2556 static $called = false;
2557 if ( $called ) {
2558 # Don't run this twice
2559 return;
2560 }
2561 $called = true;
2562
2563 if ( !$wgHtml5 ) {
2564 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2565 }
2566 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2567
2568 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2569 if( $p !== 'index,follow' ) {
2570 // http://www.robotstxt.org/wc/meta-user.html
2571 // Only show if it's different from the default robots policy
2572 $this->addMeta( 'robots', $p );
2573 }
2574
2575 if ( count( $this->mKeywords ) > 0 ) {
2576 $strip = array(
2577 "/<.*?" . ">/" => '',
2578 "/_/" => ' '
2579 );
2580 $this->addMeta(
2581 'keywords',
2582 preg_replace(
2583 array_keys( $strip ),
2584 array_values( $strip ),
2585 implode( ',', $this->mKeywords )
2586 )
2587 );
2588 }
2589 }
2590
2591 /**
2592 * @return string HTML tag links to be put in the header.
2593 */
2594 public function getHeadLinks( Skin $sk ) {
2595 global $wgFeed;
2596
2597 // Ideally this should happen earlier, somewhere. :P
2598 $this->addDefaultMeta();
2599
2600 $tags = array();
2601
2602 foreach ( $this->mMetatags as $tag ) {
2603 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2604 $a = 'http-equiv';
2605 $tag[0] = substr( $tag[0], 5 );
2606 } else {
2607 $a = 'name';
2608 }
2609 $tags[] = Html::element( 'meta',
2610 array(
2611 $a => $tag[0],
2612 'content' => $tag[1]
2613 )
2614 );
2615 }
2616 foreach ( $this->mLinktags as $tag ) {
2617 $tags[] = Html::element( 'link', $tag );
2618 }
2619
2620 if( $wgFeed ) {
2621 foreach( $this->getSyndicationLinks() as $format => $link ) {
2622 # Use the page name for the title (accessed through $wgTitle since
2623 # there's no other way). In principle, this could lead to issues
2624 # with having the same name for different feeds corresponding to
2625 # the same page, but we can't avoid that at this low a level.
2626
2627 $tags[] = $this->feedLink(
2628 $format,
2629 $link,
2630 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2631 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2632 );
2633 }
2634
2635 # Recent changes feed should appear on every page (except recentchanges,
2636 # that would be redundant). Put it after the per-page feed to avoid
2637 # changing existing behavior. It's still available, probably via a
2638 # menu in your browser. Some sites might have a different feed they'd
2639 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2640 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2641 # If so, use it instead.
2642
2643 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2644 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2645
2646 if ( $wgOverrideSiteFeed ) {
2647 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2648 $tags[] = $this->feedLink(
2649 $type,
2650 htmlspecialchars( $feedUrl ),
2651 wfMsg( "site-{$type}-feed", $wgSitename )
2652 );
2653 }
2654 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2655 foreach ( $wgAdvertisedFeedTypes as $format ) {
2656 $tags[] = $this->feedLink(
2657 $format,
2658 $rctitle->getLocalURL( "feed={$format}" ),
2659 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2660 );
2661 }
2662 }
2663 }
2664 return implode( "\n", $tags );
2665 }
2666
2667 /**
2668 * Generate a <link rel/> for a feed.
2669 *
2670 * @param $type String: feed type
2671 * @param $url String: URL to the feed
2672 * @param $text String: value of the "title" attribute
2673 * @return String: HTML fragment
2674 */
2675 private function feedLink( $type, $url, $text ) {
2676 return Html::element( 'link', array(
2677 'rel' => 'alternate',
2678 'type' => "application/$type+xml",
2679 'title' => $text,
2680 'href' => $url )
2681 );
2682 }
2683
2684 /**
2685 * Add a local or specified stylesheet, with the given media options.
2686 * Meant primarily for internal use...
2687 *
2688 * @param $style String: URL to the file
2689 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2690 * @param $condition String: for IE conditional comments, specifying an IE version
2691 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2692 */
2693 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2694 $options = array();
2695 // Even though we expect the media type to be lowercase, but here we
2696 // force it to lowercase to be safe.
2697 if( $media ) {
2698 $options['media'] = $media;
2699 }
2700 if( $condition ) {
2701 $options['condition'] = $condition;
2702 }
2703 if( $dir ) {
2704 $options['dir'] = $dir;
2705 }
2706 $this->styles[$style] = $options;
2707 }
2708
2709 /**
2710 * Adds inline CSS styles
2711 * @param $style_css Mixed: inline CSS
2712 */
2713 public function addInlineStyle( $style_css ){
2714 $this->mInlineStyles .= Html::inlineStyle( $style_css );
2715 }
2716
2717 /**
2718 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2719 * These will be applied to various media & IE conditionals.
2720 * @param $sk Skin object
2721 */
2722 public function buildCssLinks( $sk ) {
2723 $ret = '';
2724 // Add ResourceLoader styles
2725 // Split the styles into three groups
2726 $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
2727 $resourceLoader = $this->getResourceLoader();
2728 foreach ( $this->getModuleStyles() as $name ) {
2729 $group = $resourceLoader->getModule( $name )->getGroup();
2730 // Modules in groups named "other" or anything different than "user" or "site" will
2731 // be placed in the "other" group
2732 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
2733 }
2734
2735 // We want site and user styles to override dynamically added styles from modules, but we want
2736 // dynamically added styles to override statically added styles from other modules. So the order
2737 // has to be other, dynamic, site, user
2738 // Add statically added styles for other modules
2739 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
2740 // Add normal styles added through addStyle()/addInlineStyle() here
2741 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
2742 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2743 // We use a <meta> tag with a made-up name for this because that's valid HTML
2744 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2745 // Add site and user styles
2746 $ret .= $this->makeResourceLoaderLink(
2747 $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
2748 );
2749 return $ret;
2750 }
2751
2752 public function buildCssLinksArray() {
2753 $links = array();
2754 foreach( $this->styles as $file => $options ) {
2755 $link = $this->styleLink( $file, $options );
2756 if( $link ) {
2757 $links[$file] = $link;
2758 }
2759 }
2760 return $links;
2761 }
2762
2763 /**
2764 * Generate \<link\> tags for stylesheets
2765 *
2766 * @param $style String: URL to the file
2767 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2768 * keys
2769 * @return String: HTML fragment
2770 */
2771 protected function styleLink( $style, $options ) {
2772 if( isset( $options['dir'] ) ) {
2773 $siteDir = wfUILang()->getDir();
2774 if( $siteDir != $options['dir'] ) {
2775 return '';
2776 }
2777 }
2778
2779 if( isset( $options['media'] ) ) {
2780 $media = self::transformCssMedia( $options['media'] );
2781 if( is_null( $media ) ) {
2782 return '';
2783 }
2784 } else {
2785 $media = 'all';
2786 }
2787
2788 if( substr( $style, 0, 1 ) == '/' ||
2789 substr( $style, 0, 5 ) == 'http:' ||
2790 substr( $style, 0, 6 ) == 'https:' ) {
2791 $url = $style;
2792 } else {
2793 global $wgStylePath, $wgStyleVersion;
2794 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2795 }
2796
2797 $link = Html::linkedStyle( $url, $media );
2798
2799 if( isset( $options['condition'] ) ) {
2800 $condition = htmlspecialchars( $options['condition'] );
2801 $link = "<!--[if $condition]>$link<![endif]-->";
2802 }
2803 return $link;
2804 }
2805
2806 /**
2807 * Transform "media" attribute based on request parameters
2808 *
2809 * @param $media String: current value of the "media" attribute
2810 * @return String: modified value of the "media" attribute
2811 */
2812 public static function transformCssMedia( $media ) {
2813 global $wgRequest, $wgHandheldForIPhone;
2814
2815 // Switch in on-screen display for media testing
2816 $switches = array(
2817 'printable' => 'print',
2818 'handheld' => 'handheld',
2819 );
2820 foreach( $switches as $switch => $targetMedia ) {
2821 if( $wgRequest->getBool( $switch ) ) {
2822 if( $media == $targetMedia ) {
2823 $media = '';
2824 } elseif( $media == 'screen' ) {
2825 return null;
2826 }
2827 }
2828 }
2829
2830 // Expand longer media queries as iPhone doesn't grok 'handheld'
2831 if( $wgHandheldForIPhone ) {
2832 $mediaAliases = array(
2833 'screen' => 'screen and (min-device-width: 481px)',
2834 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2835 );
2836
2837 if( isset( $mediaAliases[$media] ) ) {
2838 $media = $mediaAliases[$media];
2839 }
2840 }
2841
2842 return $media;
2843 }
2844
2845 /**
2846 * Turn off regular page output and return an error reponse
2847 * for when rate limiting has triggered.
2848 */
2849 public function rateLimited() {
2850 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2851 $this->setRobotPolicy( 'noindex,follow' );
2852 $this->setArticleRelated( false );
2853 $this->enableClientCache( false );
2854 $this->mRedirect = '';
2855 $this->clearHTML();
2856 $this->setStatusCode( 503 );
2857 $this->addWikiMsg( 'actionthrottledtext' );
2858
2859 $this->returnToMain( null, $this->getTitle() );
2860 }
2861
2862 /**
2863 * Show a warning about slave lag
2864 *
2865 * If the lag is higher than $wgSlaveLagCritical seconds,
2866 * then the warning is a bit more obvious. If the lag is
2867 * lower than $wgSlaveLagWarning, then no warning is shown.
2868 *
2869 * @param $lag Integer: slave lag
2870 */
2871 public function showLagWarning( $lag ) {
2872 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2873 if( $lag >= $wgSlaveLagWarning ) {
2874 $message = $lag < $wgSlaveLagCritical
2875 ? 'lag-warn-normal'
2876 : 'lag-warn-high';
2877 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2878 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2879 }
2880 }
2881
2882 /**
2883 * Add a wikitext-formatted message to the output.
2884 * This is equivalent to:
2885 *
2886 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2887 */
2888 public function addWikiMsg( /*...*/ ) {
2889 $args = func_get_args();
2890 $name = array_shift( $args );
2891 $this->addWikiMsgArray( $name, $args );
2892 }
2893
2894 /**
2895 * Add a wikitext-formatted message to the output.
2896 * Like addWikiMsg() except the parameters are taken as an array
2897 * instead of a variable argument list.
2898 *
2899 * $options is passed through to wfMsgExt(), see that function for details.
2900 */
2901 public function addWikiMsgArray( $name, $args, $options = array() ) {
2902 $options[] = 'parse';
2903 $text = wfMsgExt( $name, $options, $args );
2904 $this->addHTML( $text );
2905 }
2906
2907 /**
2908 * This function takes a number of message/argument specifications, wraps them in
2909 * some overall structure, and then parses the result and adds it to the output.
2910 *
2911 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2912 * on. The subsequent arguments may either be strings, in which case they are the
2913 * message names, or arrays, in which case the first element is the message name,
2914 * and subsequent elements are the parameters to that message.
2915 *
2916 * The special named parameter 'options' in a message specification array is passed
2917 * through to the $options parameter of wfMsgExt().
2918 *
2919 * Don't use this for messages that are not in users interface language.
2920 *
2921 * For example:
2922 *
2923 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2924 *
2925 * Is equivalent to:
2926 *
2927 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2928 *
2929 * The newline after opening div is needed in some wikitext. See bug 19226.
2930 */
2931 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2932 $msgSpecs = func_get_args();
2933 array_shift( $msgSpecs );
2934 $msgSpecs = array_values( $msgSpecs );
2935 $s = $wrap;
2936 foreach ( $msgSpecs as $n => $spec ) {
2937 $options = array();
2938 if ( is_array( $spec ) ) {
2939 $args = $spec;
2940 $name = array_shift( $args );
2941 if ( isset( $args['options'] ) ) {
2942 $options = $args['options'];
2943 unset( $args['options'] );
2944 }
2945 } else {
2946 $args = array();
2947 $name = $spec;
2948 }
2949 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2950 }
2951 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2952 }
2953
2954 /**
2955 * Include jQuery core. Use this to avoid loading it multiple times
2956 * before we get a usable script loader.
2957 *
2958 * @param $modules Array: list of jQuery modules which should be loaded
2959 * @return Array: the list of modules which were not loaded.
2960 * @since 1.16
2961 * @deprecated @since 1.17
2962 */
2963 public function includeJQuery( $modules = array() ) {
2964 return array();
2965 }
2966
2967 }