f87a6d90ce3bd8d638718868b1e2ff49ff4425f1
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 if ( ! defined( 'MEDIAWIKI' ) )
3 die( 1 );
4
5 /**
6 * @todo document
7 */
8 class OutputPage {
9 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
10 var $mExtStyles = array();
11 var $mPagetitle = '', $mBodytext = '', $mDebugtext = '';
12 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
13 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14 var $mLastModified = '', $mETag = false;
15 var $mCategoryLinks = array(), $mCategories = array(), $mLanguageLinks = array();
16
17 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
18 var $mInlineMsg = array();
19
20 var $mTemplateIds = array();
21
22 var $mAllowUserJs;
23 var $mSuppressQuickbar = false;
24 var $mDoNothing = false;
25 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
26 var $mIsArticleRelated = true;
27 protected $mParserOptions = null; // lazy initialised, use parserOptions()
28
29 var $mFeedLinks = array();
30
31 var $mEnableClientCache = true;
32 var $mArticleBodyOnly = false;
33
34 var $mNewSectionLink = false;
35 var $mHideNewSectionLink = false;
36 var $mNoGallery = false;
37 var $mPageTitleActionText = '';
38 var $mParseWarnings = array();
39 var $mSquidMaxage = 0;
40 var $mRevisionId = null;
41 protected $mTitle = null;
42
43 /**
44 * An array of stylesheet filenames (relative from skins path), with options
45 * for CSS media, IE conditions, and RTL/LTR direction.
46 * For internal use; add settings in the skin via $this->addStyle()
47 */
48 var $styles = array();
49
50 /**
51 * Whether to load jQuery core.
52 */
53 protected $mJQueryDone = false;
54
55 private $mIndexPolicy = 'index';
56 private $mFollowPolicy = 'follow';
57 private $mVaryHeader = array( 'Accept-Encoding' => array('list-contains=gzip'),
58 'Cookie' => null );
59
60
61 /**
62 * Constructor
63 * Initialise private variables
64 */
65 function __construct() {
66 global $wgAllowUserJs;
67 $this->mAllowUserJs = $wgAllowUserJs;
68 }
69
70 /**
71 * Redirect to $url rather than displaying the normal page
72 *
73 * @param $url String: URL
74 * @param $responsecode String: HTTP status code
75 */
76 public function redirect( $url, $responsecode = '302' ) {
77 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
78 $this->mRedirect = str_replace( "\n", '', $url );
79 $this->mRedirectCode = $responsecode;
80 }
81
82 /**
83 * Get the URL to redirect to, or an empty string if not redirect URL set
84 *
85 * @return String
86 */
87 public function getRedirect() {
88 return $this->mRedirect;
89 }
90
91 /**
92 * Set the HTTP status code to send with the output.
93 *
94 * @param $statusCode Integer
95 * @return nothing
96 */
97 public function setStatusCode( $statusCode ) {
98 $this->mStatusCode = $statusCode;
99 }
100
101
102 /**
103 * Add a new <meta> tag
104 * To add an http-equiv meta tag, precede the name with "http:"
105 *
106 * @param $name tag name
107 * @param $val tag value
108 */
109 function addMeta( $name, $val ) {
110 array_push( $this->mMetatags, array( $name, $val ) );
111 }
112
113 /**
114 * Add a keyword or a list of keywords in the page header
115 *
116 * @param $text String or array of strings
117 */
118 function addKeyword( $text ) {
119 if( is_array( $text ) ) {
120 $this->mKeywords = array_merge( $this->mKeywords, $text );
121 } else {
122 array_push( $this->mKeywords, $text );
123 }
124 }
125
126 /**
127 * Add a new \<link\> tag to the page header
128 *
129 * @param $linkarr Array: associative array of attributes.
130 */
131 function addLink( $linkarr ) {
132 array_push( $this->mLinktags, $linkarr );
133 }
134
135 /**
136 * Add a new \<link\> with "rel" attribute set to "meta"
137 *
138 * @param $linkarr Array: associative array mapping attribute names to their
139 * values, both keys and values will be escaped, and the
140 * "rel" attribute will be automatically added
141 */
142 function addMetadataLink( $linkarr ) {
143 # note: buggy CC software only reads first "meta" link
144 static $haveMeta = false;
145 $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
146 $this->addLink( $linkarr );
147 $haveMeta = true;
148 }
149
150
151 /**
152 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
153 *
154 * @param $script String: raw HTML
155 */
156 function addScript( $script ) {
157 $this->mScripts .= $script . "\n";
158 }
159
160 /**
161 * Register and add a stylesheet from an extension directory.
162 *
163 * @param $url String path to sheet. Provide either a full url (beginning
164 * with 'http', etc) or a relative path from the document root
165 * (beginning with '/'). Otherwise it behaves identically to
166 * addStyle() and draws from the /skins folder.
167 */
168 public function addExtensionStyle( $url ) {
169 array_push( $this->mExtStyles, $url );
170 }
171
172 /**
173 * Get all links added by extensions
174 *
175 * @return Array
176 */
177 function getExtStyle() {
178 return $this->mExtStyles;
179 }
180
181 /**
182 * Add a JavaScript file out of skins/common, or a given relative path.
183 *
184 * @param $file String: filename in skins/common or complete on-server path
185 * (/foo/bar.js)
186 */
187 public function addScriptFile( $file ) {
188 global $wgStylePath, $wgStyleVersion;
189 if( substr( $file, 0, 1 ) == '/' ) {
190 $path = $file;
191 } else {
192 $path = "{$wgStylePath}/common/{$file}";
193 }
194 $this->addScript( Html::linkedScript( "$path?$wgStyleVersion" ) );
195 }
196
197 /**
198 * Add a self-contained script tag with the given contents
199 *
200 * @param $script String: JavaScript text, no <script> tags
201 */
202 public function addInlineScript( $script ) {
203 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
204 }
205
206 /**
207 * Get all registered JS and CSS tags for the header.
208 *
209 * @return String
210 */
211 function getScript() {
212 return $this->mScripts . $this->getHeadItems();
213 }
214
215 /**
216 * Get all header items in a string
217 *
218 * @return String
219 */
220 function getHeadItems() {
221 $s = '';
222 foreach ( $this->mHeadItems as $item ) {
223 $s .= $item;
224 }
225 return $s;
226 }
227
228 /**
229 * Add or replace an header item to the output
230 *
231 * @param $name String: item name
232 * @param $value String: raw HTML
233 */
234 public function addHeadItem( $name, $value ) {
235 $this->mHeadItems[$name] = $value;
236 }
237
238 /**
239 * Check if the header item $name is already set
240 *
241 * @param $name String: item name
242 * @return Boolean
243 */
244 public function hasHeadItem( $name ) {
245 return isset( $this->mHeadItems[$name] );
246 }
247
248 /**
249 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
250 *
251 * @param $tag String: value of "ETag" header
252 */
253 function setETag( $tag ) {
254 $this->mETag = $tag;
255 }
256
257 /**
258 * Set whether the output should only contain the body of the article,
259 * without any skin, sidebar, etc.
260 * Used e.g. when calling with "action=raw".
261 *
262 * @param $only Boolean: whether to output only the body of the article
263 */
264 public function setArticleBodyOnly( $only ) {
265 $this->mArticleBodyOnly = $only;
266 }
267
268 /**
269 * Return whether the output will contain only the body of the article
270 *
271 * @return Boolean
272 */
273 public function getArticleBodyOnly() {
274 return $this->mArticleBodyOnly;
275 }
276
277
278 /**
279 * checkLastModified tells the client to use the client-cached page if
280 * possible. If sucessful, the OutputPage is disabled so that
281 * any future call to OutputPage->output() have no effect.
282 *
283 * Side effect: sets mLastModified for Last-Modified header
284 *
285 * @return Boolean: true iff cache-ok headers was sent.
286 */
287 public function checkLastModified( $timestamp ) {
288 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
289
290 if ( !$timestamp || $timestamp == '19700101000000' ) {
291 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
292 return false;
293 }
294 if( !$wgCachePages ) {
295 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
296 return false;
297 }
298 if( $wgUser->getOption( 'nocache' ) ) {
299 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
300 return false;
301 }
302
303 $timestamp = wfTimestamp( TS_MW, $timestamp );
304 $modifiedTimes = array(
305 'page' => $timestamp,
306 'user' => $wgUser->getTouched(),
307 'epoch' => $wgCacheEpoch
308 );
309 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
310
311 $maxModified = max( $modifiedTimes );
312 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
313
314 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
315 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
316 return false;
317 }
318
319 # Make debug info
320 $info = '';
321 foreach ( $modifiedTimes as $name => $value ) {
322 if ( $info !== '' ) {
323 $info .= ', ';
324 }
325 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
326 }
327
328 # IE sends sizes after the date like this:
329 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
330 # this breaks strtotime().
331 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
332
333 wfSuppressWarnings(); // E_STRICT system time bitching
334 $clientHeaderTime = strtotime( $clientHeader );
335 wfRestoreWarnings();
336 if ( !$clientHeaderTime ) {
337 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
338 return false;
339 }
340 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
341
342 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
343 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
344 wfDebug( __METHOD__ . ": effective Last-Modified: " .
345 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
346 if( $clientHeaderTime < $maxModified ) {
347 wfDebug( __METHOD__ . ": STALE, $info\n", false );
348 return false;
349 }
350
351 # Not modified
352 # Give a 304 response code and disable body output
353 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
354 ini_set('zlib.output_compression', 0);
355 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
356 $this->sendCacheControl();
357 $this->disable();
358
359 // Don't output a compressed blob when using ob_gzhandler;
360 // it's technically against HTTP spec and seems to confuse
361 // Firefox when the response gets split over two packets.
362 wfClearOutputBuffers();
363
364 return true;
365 }
366
367
368 /**
369 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
370 *
371 * @param $policy String: the literal string to output as the contents of
372 * the meta tag. Will be parsed according to the spec and output in
373 * standardized form.
374 * @return null
375 */
376 public function setRobotPolicy( $policy ) {
377 $policy = Article::formatRobotPolicy( $policy );
378
379 if( isset( $policy['index'] ) ){
380 $this->setIndexPolicy( $policy['index'] );
381 }
382 if( isset( $policy['follow'] ) ){
383 $this->setFollowPolicy( $policy['follow'] );
384 }
385 }
386
387 /**
388 * Set the index policy for the page, but leave the follow policy un-
389 * touched.
390 *
391 * @param $policy string Either 'index' or 'noindex'.
392 * @return null
393 */
394 public function setIndexPolicy( $policy ) {
395 $policy = trim( $policy );
396 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
397 $this->mIndexPolicy = $policy;
398 }
399 }
400
401 /**
402 * Set the follow policy for the page, but leave the index policy un-
403 * touched.
404 *
405 * @param $policy String: either 'follow' or 'nofollow'.
406 * @return null
407 */
408 public function setFollowPolicy( $policy ) {
409 $policy = trim( $policy );
410 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
411 $this->mFollowPolicy = $policy;
412 }
413 }
414
415
416 /**
417 * Set the new value of the "action text", this will be added to the
418 * "HTML title", separated from it with " - ".
419 *
420 * @param $text String: new value of the "action text"
421 */
422 public function setPageTitleActionText( $text ) {
423 $this->mPageTitleActionText = $text;
424 }
425
426 /**
427 * Get the value of the "action text"
428 *
429 * @return String
430 */
431 public function getPageTitleActionText() {
432 if ( isset( $this->mPageTitleActionText ) ) {
433 return $this->mPageTitleActionText;
434 }
435 }
436
437 /**
438 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
439 */
440 public function setHTMLTitle( $name ) {
441 $this->mHTMLtitle = $name;
442 }
443
444 /**
445 * Return the "HTML title", i.e. the content of the <title> tag.
446 *
447 * @return String
448 */
449 public function getHTMLTitle() {
450 return $this->mHTMLtitle;
451 }
452
453 /**
454 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
455 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
456 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
457 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
458 */
459 public function setPageTitle( $name ) {
460 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
461 # but leave "<i>foobar</i>" alone
462 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
463 $this->mPagetitle = $nameWithTags;
464
465 $taction = $this->getPageTitleActionText();
466 if( !empty( $taction ) ) {
467 $name .= ' - '.$taction;
468 }
469
470 # change "<i>foo&amp;bar</i>" to "foo&bar"
471 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
472 }
473
474 /**
475 * Return the "page title", i.e. the content of the <h1> tag.
476 *
477 * @return String
478 */
479 public function getPageTitle() {
480 return $this->mPagetitle;
481 }
482
483 /**
484 * Set the Title object to use
485 *
486 * @param $t Title object
487 */
488 public function setTitle( $t ) {
489 $this->mTitle = $t;
490 }
491
492 /**
493 * Get the Title object used in this instance
494 *
495 * @return Title
496 */
497 public function getTitle() {
498 if ( $this->mTitle instanceof Title ) {
499 return $this->mTitle;
500 } else {
501 wfDebug( __METHOD__ . ' called and $mTitle is null. Return $wgTitle for sanity' );
502 global $wgTitle;
503 return $wgTitle;
504 }
505 }
506
507 /**
508 * Replace the subtile with $str
509 *
510 * @param $str String: new value of the subtitle
511 */
512 public function setSubtitle( $str ) {
513 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
514 }
515
516 /**
517 * Add $str to the subtitle
518 *
519 * @param $str String to add to the subtitle
520 */
521 public function appendSubtitle( $str ) {
522 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
523 }
524
525 /**
526 * Get the subtitle
527 *
528 * @return String
529 */
530 public function getSubtitle() {
531 return $this->mSubtitle;
532 }
533
534
535 /**
536 * Set the page as printable, i.e. it'll be displayed with with all
537 * print styles included
538 */
539 public function setPrintable() {
540 $this->mPrintable = true;
541 }
542
543 /**
544 * Return whether the page is "printable"
545 *
546 * @return Boolean
547 */
548 public function isPrintable() {
549 return $this->mPrintable;
550 }
551
552
553 /**
554 * Disable output completely, i.e. calling output() will have no effect
555 */
556 public function disable() {
557 $this->mDoNothing = true;
558 }
559
560 /**
561 * Return whether the output will be completely disabled
562 *
563 * @return Boolean
564 */
565 public function isDisabled() {
566 return $this->mDoNothing;
567 }
568
569
570 /**
571 * Add or remove feed links in the page header
572 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
573 * for the new version
574 * @see addFeedLink()
575 *
576 * @param $show Boolean: true: add default feeds, false: remove all feeds
577 */
578 public function setSyndicated( $show = true ) {
579 if ( $show ) {
580 $this->setFeedAppendQuery( false );
581 } else {
582 $this->mFeedLinks = array();
583 }
584 }
585
586 /**
587 * Add default feeds to the page header
588 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
589 * for the new version
590 * @see addFeedLink()
591 *
592 * @param $val String: query to append to feed links or false to output
593 * default links
594 */
595 public function setFeedAppendQuery( $val ) {
596 global $wgAdvertisedFeedTypes;
597
598 $this->mFeedLinks = array();
599
600 foreach ( $wgAdvertisedFeedTypes as $type ) {
601 $query = "feed=$type";
602 if ( is_string( $val ) ) {
603 $query .= '&' . $val;
604 }
605 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
606 }
607 }
608
609 /**
610 * Add a feed link to the page header
611 *
612 * @param $format String: feed type, should be a key of $wgFeedClasses
613 * @param $href String: URL
614 */
615 public function addFeedLink( $format, $href ) {
616 $this->mFeedLinks[$format] = $href;
617 }
618
619 /**
620 * Should we output feed links for this page?
621 * @return Boolean
622 */
623 public function isSyndicated() {
624 return count( $this->mFeedLinks ) > 0;
625 }
626
627 /**
628 * Will currently always return null
629 *
630 * @return null
631 */
632 public function getFeedAppendQuery() {
633 return $this->mFeedLinksAppendQuery;
634 }
635
636 /**
637 * Set whether the displayed content is related to the source of the
638 * corresponding article on the wiki
639 * Setting true will cause the change "article related" toggle to true
640 *
641 * @param $v Boolean
642 */
643 public function setArticleFlag( $v ) {
644 $this->mIsarticle = $v;
645 if ( $v ) {
646 $this->mIsArticleRelated = $v;
647 }
648 }
649
650 /**
651 * Return whether the content displayed page is related to the source of
652 * the corresponding article on the wiki
653 *
654 * @return Boolean
655 */
656 public function isArticle() {
657 return $this->mIsarticle;
658 }
659
660 /**
661 * Set whether this page is related an article on the wiki
662 * Setting false will cause the change of "article flag" toggle to false
663 *
664 * @param $v Boolean
665 */
666 public function setArticleRelated( $v ) {
667 $this->mIsArticleRelated = $v;
668 if ( !$v ) {
669 $this->mIsarticle = false;
670 }
671 }
672
673 /**
674 * Return whether this page is related an article on the wiki
675 *
676 * @return Boolean
677 */
678 public function isArticleRelated() {
679 return $this->mIsArticleRelated;
680 }
681
682
683 /**
684 * Add new language links
685 *
686 * @param $newLinkArray Associative array mapping language code to the page
687 * name
688 */
689 public function addLanguageLinks( $newLinkArray ) {
690 $this->mLanguageLinks += $newLinkArray;
691 }
692
693 /**
694 * Reset the language links and add new language links
695 *
696 * @param $newLinkArray Associative array mapping language code to the page
697 * name
698 */
699 public function setLanguageLinks( $newLinkArray ) {
700 $this->mLanguageLinks = $newLinkArray;
701 }
702
703 /**
704 * Get the list of language links
705 *
706 * @return Associative array mapping language code to the page name
707 */
708 public function getLanguageLinks() {
709 return $this->mLanguageLinks;
710 }
711
712
713 /**
714 * Add an array of categories, with names in the keys
715 *
716 * @param $categories Associative array mapping category name to its sort key
717 */
718 public function addCategoryLinks( $categories ) {
719 global $wgUser, $wgContLang;
720
721 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
722 return;
723 }
724
725 # Add the links to a LinkBatch
726 $arr = array( NS_CATEGORY => $categories );
727 $lb = new LinkBatch;
728 $lb->setArray( $arr );
729
730 # Fetch existence plus the hiddencat property
731 $dbr = wfGetDB( DB_SLAVE );
732 $pageTable = $dbr->tableName( 'page' );
733 $where = $lb->constructSet( 'page', $dbr );
734 $propsTable = $dbr->tableName( 'page_props' );
735 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
736 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
737 $res = $dbr->query( $sql, __METHOD__ );
738
739 # Add the results to the link cache
740 $lb->addResultToCache( LinkCache::singleton(), $res );
741
742 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
743 $categories = array_combine( array_keys( $categories ),
744 array_fill( 0, count( $categories ), 'normal' ) );
745
746 # Mark hidden categories
747 foreach ( $res as $row ) {
748 if ( isset( $row->pp_value ) ) {
749 $categories[$row->page_title] = 'hidden';
750 }
751 }
752
753 # Add the remaining categories to the skin
754 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
755 $sk = $wgUser->getSkin();
756 foreach ( $categories as $category => $type ) {
757 $origcategory = $category;
758 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
759 $wgContLang->findVariantLink( $category, $title, true );
760 if ( $category != $origcategory )
761 if ( array_key_exists( $category, $categories ) )
762 continue;
763 $text = $wgContLang->convertHtml( $title->getText() );
764 $this->mCategories[] = $title->getText();
765 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
766 }
767 }
768 }
769
770 /**
771 * Reset the category links (but not the category list) and add $categories
772 *
773 * @param $categories Associative array mapping category name to its sort key
774 */
775 public function setCategoryLinks( $categories ) {
776 $this->mCategoryLinks = array();
777 $this->addCategoryLinks( $categories );
778 }
779
780 /**
781 * Get the list of category links, in a 2-D array with the following format:
782 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
783 * hidden categories) and $link a HTML fragment with a link to the category
784 * page
785 *
786 * @return Array
787 */
788 public function getCategoryLinks() {
789 return $this->mCategoryLinks;
790 }
791
792 /**
793 * Get the list of category names this page belongs to
794 *
795 * @return Array of strings
796 */
797 public function getCategories() {
798 return $this->mCategories;
799 }
800
801 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
802 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
803
804 public function disallowUserJs() { $this->mAllowUserJs = false; }
805 public function isUserJsAllowed() { return $this->mAllowUserJs; }
806
807 public function prependHTML( $text ) { $this->mBodytext = $text . $this->mBodytext; }
808 public function addHTML( $text ) { $this->mBodytext .= $text; }
809 public function clearHTML() { $this->mBodytext = ''; }
810 public function getHTML() { return $this->mBodytext; }
811 public function debug( $text ) { $this->mDebugtext .= $text; }
812
813 /* @deprecated */
814 public function setParserOptions( $options ) {
815 wfDeprecated( __METHOD__ );
816 return $this->parserOptions( $options );
817 }
818
819 public function parserOptions( $options = null ) {
820 if ( !$this->mParserOptions ) {
821 $this->mParserOptions = new ParserOptions;
822 }
823 return wfSetVar( $this->mParserOptions, $options );
824 }
825
826 /**
827 * Set the revision ID which will be seen by the wiki text parser
828 * for things such as embedded {{REVISIONID}} variable use.
829 * @param mixed $revid an integer, or NULL
830 * @return mixed previous value
831 */
832 public function setRevisionId( $revid ) {
833 $val = is_null( $revid ) ? null : intval( $revid );
834 return wfSetVar( $this->mRevisionId, $val );
835 }
836
837 public function getRevisionId() {
838 return $this->mRevisionId;
839 }
840
841 /**
842 * Convert wikitext to HTML and add it to the buffer
843 * Default assumes that the current page title will
844 * be used.
845 *
846 * @param string $text
847 * @param bool $linestart
848 */
849 public function addWikiText( $text, $linestart = true ) {
850 $title = $this->getTitle(); // Work arround E_STRICT
851 $this->addWikiTextTitle( $text, $title, $linestart );
852 }
853
854 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
855 $this->addWikiTextTitle($text, $title, $linestart);
856 }
857
858 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
859 $this->addWikiTextTitle( $text, $title, $linestart, true );
860 }
861
862 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
863 global $wgParser;
864
865 wfProfileIn( __METHOD__ );
866
867 wfIncrStats( 'pcache_not_possible' );
868
869 $popts = $this->parserOptions();
870 $oldTidy = $popts->setTidy( $tidy );
871
872 $parserOutput = $wgParser->parse( $text, $title, $popts,
873 $linestart, true, $this->mRevisionId );
874
875 $popts->setTidy( $oldTidy );
876
877 $this->addParserOutput( $parserOutput );
878
879 wfProfileOut( __METHOD__ );
880 }
881
882 /**
883 * @todo document
884 * @param ParserOutput object &$parserOutput
885 */
886 public function addParserOutputNoText( &$parserOutput ) {
887 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
888
889 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
890 $this->addCategoryLinks( $parserOutput->getCategories() );
891 $this->mNewSectionLink = $parserOutput->getNewSection();
892 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
893
894 $this->mParseWarnings = $parserOutput->getWarnings();
895 if ( $parserOutput->getCacheTime() == -1 ) {
896 $this->enableClientCache( false );
897 }
898 $this->mNoGallery = $parserOutput->getNoGallery();
899 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
900 // Versioning...
901 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
902 if ( isset( $this->mTemplateIds[$ns] ) ) {
903 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
904 } else {
905 $this->mTemplateIds[$ns] = $dbks;
906 }
907 }
908 // Page title
909 $title = $parserOutput->getTitleText();
910 if ( $title != '' ) {
911 $this->setPageTitle( $title );
912 }
913
914 // Hooks registered in the object
915 global $wgParserOutputHooks;
916 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
917 list( $hookName, $data ) = $hookInfo;
918 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
919 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
920 }
921 }
922
923 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
924 }
925
926 /**
927 * @todo document
928 * @param ParserOutput &$parserOutput
929 */
930 function addParserOutput( &$parserOutput ) {
931 $this->addParserOutputNoText( $parserOutput );
932 $text = $parserOutput->getText();
933 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
934 $this->addHTML( $text );
935 }
936
937 /**
938 * Add wikitext to the buffer, assuming that this is the primary text for a page view
939 * Saves the text into the parser cache if possible.
940 *
941 * @param string $text
942 * @param Article $article
943 * @param bool $cache
944 * @deprecated Use Article::outputWikitext
945 */
946 public function addPrimaryWikiText( $text, $article, $cache = true ) {
947 global $wgParser;
948
949 wfDeprecated( __METHOD__ );
950
951 $popts = $this->parserOptions();
952 $popts->setTidy(true);
953 $parserOutput = $wgParser->parse( $text, $article->mTitle,
954 $popts, true, true, $this->mRevisionId );
955 $popts->setTidy(false);
956 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
957 $parserCache = ParserCache::singleton();
958 $parserCache->save( $parserOutput, $article, $popts);
959 }
960
961 $this->addParserOutput( $parserOutput );
962 }
963
964 /**
965 * @deprecated use addWikiTextTidy()
966 */
967 public function addSecondaryWikiText( $text, $linestart = true ) {
968 wfDeprecated( __METHOD__ );
969 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
970 }
971
972 /**
973 * Add wikitext with tidy enabled
974 */
975 public function addWikiTextTidy( $text, $linestart = true ) {
976 $title = $this->getTitle();
977 $this->addWikiTextTitleTidy($text, $title, $linestart);
978 }
979
980
981 /**
982 * Add the output of a QuickTemplate to the output buffer
983 *
984 * @param QuickTemplate $template
985 */
986 public function addTemplate( &$template ) {
987 ob_start();
988 $template->execute();
989 $this->addHTML( ob_get_contents() );
990 ob_end_clean();
991 }
992
993 /**
994 * Parse wikitext and return the HTML.
995 *
996 * @param string $text
997 * @param bool $linestart Is this the start of a line?
998 * @param bool $interface ??
999 */
1000 public function parse( $text, $linestart = true, $interface = false ) {
1001 global $wgParser;
1002 if( is_null( $this->getTitle() ) ) {
1003 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1004 }
1005 $popts = $this->parserOptions();
1006 if ( $interface) { $popts->setInterfaceMessage(true); }
1007 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
1008 $linestart, true, $this->mRevisionId );
1009 if ( $interface) { $popts->setInterfaceMessage(false); }
1010 return $parserOutput->getText();
1011 }
1012
1013 /** Parse wikitext, strip paragraphs, and return the HTML. */
1014 public function parseInline( $text, $linestart = true, $interface = false ) {
1015 $parsed = $this->parse( $text, $linestart, $interface );
1016
1017 $m = array();
1018 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1019 $parsed = $m[1];
1020 }
1021
1022 return $parsed;
1023 }
1024
1025 /**
1026 * @param Article $article
1027 * @param User $user
1028 *
1029 * @deprecated
1030 *
1031 * @return bool True if successful, else false.
1032 */
1033 public function tryParserCache( &$article ) {
1034 wfDeprecated( __METHOD__ );
1035 $parserOutput = ParserCache::singleton()->get( $article, $article->getParserOptions() );
1036
1037 if ($parserOutput !== false) {
1038 $this->addParserOutput( $parserOutput );
1039 return true;
1040 } else {
1041 return false;
1042 }
1043 }
1044
1045 /**
1046 * @param int $maxage Maximum cache time on the Squid, in seconds.
1047 */
1048 public function setSquidMaxage( $maxage ) {
1049 $this->mSquidMaxage = $maxage;
1050 }
1051
1052 /**
1053 * Use enableClientCache(false) to force it to send nocache headers
1054 * @param $state ??
1055 */
1056 public function enableClientCache( $state ) {
1057 return wfSetVar( $this->mEnableClientCache, $state );
1058 }
1059
1060 function getCacheVaryCookies() {
1061 global $wgCookiePrefix, $wgCacheVaryCookies;
1062 static $cookies;
1063 if ( $cookies === null ) {
1064 $cookies = array_merge(
1065 array(
1066 "{$wgCookiePrefix}Token",
1067 "{$wgCookiePrefix}LoggedOut",
1068 session_name()
1069 ),
1070 $wgCacheVaryCookies
1071 );
1072 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
1073 }
1074 return $cookies;
1075 }
1076
1077 function uncacheableBecauseRequestVars() {
1078 global $wgRequest;
1079 return $wgRequest->getText('useskin', false) === false
1080 && $wgRequest->getText('uselang', false) === false;
1081 }
1082
1083 /**
1084 * Check if the request has a cache-varying cookie header
1085 * If it does, it's very important that we don't allow public caching
1086 */
1087 function haveCacheVaryCookies() {
1088 global $wgRequest;
1089 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1090 if ( $cookieHeader === false ) {
1091 return false;
1092 }
1093 $cvCookies = $this->getCacheVaryCookies();
1094 foreach ( $cvCookies as $cookieName ) {
1095 # Check for a simple string match, like the way squid does it
1096 if ( strpos( $cookieHeader, $cookieName ) ) {
1097 wfDebug( __METHOD__.": found $cookieName\n" );
1098 return true;
1099 }
1100 }
1101 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
1102 return false;
1103 }
1104
1105 public function addVaryHeader( $header, $option = null ) {
1106 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1107 $this->mVaryHeader[$header] = $option;
1108 }
1109 elseif( is_array( $option ) ) {
1110 if( is_array( $this->mVaryHeader[$header] ) ) {
1111 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1112 }
1113 else {
1114 $this->mVaryHeader[$header] = $option;
1115 }
1116 }
1117 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1118 }
1119
1120 /** Get a complete X-Vary-Options header */
1121 public function getXVO() {
1122 $cvCookies = $this->getCacheVaryCookies();
1123
1124 $cookiesOption = array();
1125 foreach ( $cvCookies as $cookieName ) {
1126 $cookiesOption[] = 'string-contains=' . $cookieName;
1127 }
1128 $this->addVaryHeader( 'Cookie', $cookiesOption );
1129
1130 $headers = array();
1131 foreach( $this->mVaryHeader as $header => $option ) {
1132 $newheader = $header;
1133 if( is_array( $option ) )
1134 $newheader .= ';' . implode( ';', $option );
1135 $headers[] = $newheader;
1136 }
1137 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1138
1139 return $xvo;
1140 }
1141
1142 /** bug 21672: Add Accept-Language to Vary and XVO headers
1143 if there's no 'variant' parameter existed in GET.
1144
1145 For example:
1146 /w/index.php?title=Main_page should always be served; but
1147 /w/index.php?title=Main_page&variant=zh-cn should never be served.
1148
1149 patched by Liangent and Philip */
1150 function addAcceptLanguage() {
1151 global $wgRequest, $wgContLang;
1152 if( !$wgRequest->getCheck('variant') && $wgContLang->hasVariants() ) {
1153 $variants = $wgContLang->getVariants();
1154 $aloption = array();
1155 foreach ( $variants as $variant ) {
1156 if( $variant === $wgContLang->getCode() )
1157 continue;
1158 else
1159 $aloption[] = "string-contains=$variant";
1160 }
1161 $this->addVaryHeader( 'Accept-Language', $aloption );
1162 }
1163 }
1164
1165 public function sendCacheControl() {
1166 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1167
1168 $response = $wgRequest->response();
1169 if ($wgUseETag && $this->mETag)
1170 $response->header("ETag: $this->mETag");
1171
1172 $this->addAcceptLanguage();
1173
1174 # don't serve compressed data to clients who can't handle it
1175 # maintain different caches for logged-in users and non-logged in ones
1176 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1177
1178 if ( $wgUseXVO ) {
1179 # Add an X-Vary-Options header for Squid with Wikimedia patches
1180 $response->header( $this->getXVO() );
1181 }
1182
1183 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1184 if( $wgUseSquid && session_id() == '' &&
1185 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
1186 {
1187 if ( $wgUseESI ) {
1188 # We'll purge the proxy cache explicitly, but require end user agents
1189 # to revalidate against the proxy on each visit.
1190 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1191 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1192 # start with a shorter timeout for initial testing
1193 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1194 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1195 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1196 } else {
1197 # We'll purge the proxy cache for anons explicitly, but require end user agents
1198 # to revalidate against the proxy on each visit.
1199 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1200 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1201 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1202 # start with a shorter timeout for initial testing
1203 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1204 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1205 }
1206 } else {
1207 # We do want clients to cache if they can, but they *must* check for updates
1208 # on revisiting the page.
1209 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1210 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1211 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1212 }
1213 if($this->mLastModified) {
1214 $response->header( "Last-Modified: {$this->mLastModified}" );
1215 }
1216 } else {
1217 wfDebug( __METHOD__ . ": no caching **\n", false );
1218
1219 # In general, the absence of a last modified header should be enough to prevent
1220 # the client from using its cache. We send a few other things just to make sure.
1221 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1222 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1223 $response->header( 'Pragma: no-cache' );
1224 }
1225 wfRunHooks('CacheHeadersAfterSet', array( $this ) );
1226 }
1227
1228 /**
1229 * Get the message associed with the HTTP response code $code
1230 *
1231 * @param $code Integer: status code
1232 * @return String or null: message or null if $code is not in the list of
1233 * messages
1234 */
1235 public static function getStatusMessage( $code ) {
1236 static $statusMessage = array(
1237 100 => 'Continue',
1238 101 => 'Switching Protocols',
1239 102 => 'Processing',
1240 200 => 'OK',
1241 201 => 'Created',
1242 202 => 'Accepted',
1243 203 => 'Non-Authoritative Information',
1244 204 => 'No Content',
1245 205 => 'Reset Content',
1246 206 => 'Partial Content',
1247 207 => 'Multi-Status',
1248 300 => 'Multiple Choices',
1249 301 => 'Moved Permanently',
1250 302 => 'Found',
1251 303 => 'See Other',
1252 304 => 'Not Modified',
1253 305 => 'Use Proxy',
1254 307 => 'Temporary Redirect',
1255 400 => 'Bad Request',
1256 401 => 'Unauthorized',
1257 402 => 'Payment Required',
1258 403 => 'Forbidden',
1259 404 => 'Not Found',
1260 405 => 'Method Not Allowed',
1261 406 => 'Not Acceptable',
1262 407 => 'Proxy Authentication Required',
1263 408 => 'Request Timeout',
1264 409 => 'Conflict',
1265 410 => 'Gone',
1266 411 => 'Length Required',
1267 412 => 'Precondition Failed',
1268 413 => 'Request Entity Too Large',
1269 414 => 'Request-URI Too Large',
1270 415 => 'Unsupported Media Type',
1271 416 => 'Request Range Not Satisfiable',
1272 417 => 'Expectation Failed',
1273 422 => 'Unprocessable Entity',
1274 423 => 'Locked',
1275 424 => 'Failed Dependency',
1276 500 => 'Internal Server Error',
1277 501 => 'Not Implemented',
1278 502 => 'Bad Gateway',
1279 503 => 'Service Unavailable',
1280 504 => 'Gateway Timeout',
1281 505 => 'HTTP Version Not Supported',
1282 507 => 'Insufficient Storage'
1283 );
1284 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1285 }
1286
1287 /**
1288 * Finally, all the text has been munged and accumulated into
1289 * the object, let's actually output it:
1290 */
1291 public function output() {
1292 global $wgUser, $wgOutputEncoding, $wgRequest;
1293 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1294 global $wgUseAjax, $wgAjaxWatch;
1295 global $wgEnableMWSuggest, $wgUniversalEditButton;
1296 global $wgArticle;
1297
1298 if( $this->mDoNothing ){
1299 return;
1300 }
1301 wfProfileIn( __METHOD__ );
1302 if ( $this->mRedirect != '' ) {
1303 # Standards require redirect URLs to be absolute
1304 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1305 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1306 if( !$wgDebugRedirects ) {
1307 $message = self::getStatusMessage( $this->mRedirectCode );
1308 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1309 }
1310 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1311 }
1312 $this->sendCacheControl();
1313
1314 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1315 if( $wgDebugRedirects ) {
1316 $url = htmlspecialchars( $this->mRedirect );
1317 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1318 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1319 print "</body>\n</html>\n";
1320 } else {
1321 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1322 }
1323 wfProfileOut( __METHOD__ );
1324 return;
1325 } elseif ( $this->mStatusCode ) {
1326 $message = self::getStatusMessage( $this->mStatusCode );
1327 if ( $message )
1328 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1329 }
1330
1331 $sk = $wgUser->getSkin();
1332
1333 if ( $wgUseAjax ) {
1334 $this->addScriptFile( 'ajax.js' );
1335
1336 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1337
1338 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1339 $this->addScriptFile( 'ajaxwatch.js' );
1340 }
1341
1342 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1343 $this->addScriptFile( 'mwsuggest.js' );
1344 }
1345 }
1346
1347 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1348 $this->addScriptFile( 'rightclickedit.js' );
1349 }
1350
1351 if( $wgUniversalEditButton ) {
1352 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1353 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1354 // Original UniversalEditButton
1355 $msg = wfMsg('edit');
1356 $this->addLink( array(
1357 'rel' => 'alternate',
1358 'type' => 'application/x-wiki',
1359 'title' => $msg,
1360 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1361 ) );
1362 // Alternate edit link
1363 $this->addLink( array(
1364 'rel' => 'edit',
1365 'title' => $msg,
1366 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1367 ) );
1368 }
1369 }
1370
1371 # Buffer output; final headers may depend on later processing
1372 ob_start();
1373
1374 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1375 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1376
1377 if ($this->mArticleBodyOnly) {
1378 $this->out($this->mBodytext);
1379 } else {
1380 // Hook that allows last minute changes to the output page, e.g.
1381 // adding of CSS or Javascript by extensions.
1382 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1383
1384 wfProfileIn( 'Output-skin' );
1385 $sk->outputPage( $this );
1386 wfProfileOut( 'Output-skin' );
1387 }
1388
1389 $this->sendCacheControl();
1390 ob_end_flush();
1391 wfProfileOut( __METHOD__ );
1392 }
1393
1394 /**
1395 * Actually output something with print(). Performs an iconv to the
1396 * output encoding, if needed.
1397 * @param string $ins The string to output
1398 */
1399 public function out( $ins ) {
1400 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1401 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1402 $outs = $ins;
1403 } else {
1404 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1405 if ( false === $outs ) { $outs = $ins; }
1406 }
1407 print $outs;
1408 }
1409
1410 /**
1411 * @todo document
1412 */
1413 public static function setEncodings() {
1414 global $wgInputEncoding, $wgOutputEncoding;
1415 global $wgContLang;
1416
1417 $wgInputEncoding = strtolower( $wgInputEncoding );
1418
1419 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1420 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1421 return;
1422 }
1423 $wgOutputEncoding = $wgInputEncoding;
1424 }
1425
1426 /**
1427 * Deprecated, use wfReportTime() instead.
1428 * @return string
1429 * @deprecated
1430 */
1431 public function reportTime() {
1432 wfDeprecated( __METHOD__ );
1433 $time = wfReportTime();
1434 return $time;
1435 }
1436
1437 /**
1438 * Produce a "user is blocked" page.
1439 *
1440 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1441 * @return nothing
1442 */
1443 function blockedPage( $return = true ) {
1444 global $wgUser, $wgContLang, $wgLang;
1445
1446 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1447 $this->setRobotPolicy( 'noindex,nofollow' );
1448 $this->setArticleRelated( false );
1449
1450 $name = User::whoIs( $wgUser->blockedBy() );
1451 $reason = $wgUser->blockedFor();
1452 if( $reason == '' ) {
1453 $reason = wfMsg( 'blockednoreason' );
1454 }
1455 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1456 $ip = wfGetIP();
1457
1458 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1459
1460 $blockid = $wgUser->mBlock->mId;
1461
1462 $blockExpiry = $wgUser->mBlock->mExpiry;
1463 if ( $blockExpiry == 'infinity' ) {
1464 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1465 // Search for localization in 'ipboptions'
1466 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1467 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1468 if ( strpos( $option, ":" ) === false )
1469 continue;
1470 list( $show, $value ) = explode( ":", $option );
1471 if ( $value == 'infinite' || $value == 'indefinite' ) {
1472 $blockExpiry = $show;
1473 break;
1474 }
1475 }
1476 } else {
1477 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1478 }
1479
1480 if ( $wgUser->mBlock->mAuto ) {
1481 $msg = 'autoblockedtext';
1482 } else {
1483 $msg = 'blockedtext';
1484 }
1485
1486 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1487 * This could be a username, an ip range, or a single ip. */
1488 $intended = $wgUser->mBlock->mAddress;
1489
1490 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1491
1492 # Don't auto-return to special pages
1493 if( $return ) {
1494 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1495 $this->returnToMain( null, $return );
1496 }
1497 }
1498
1499 /**
1500 * Output a standard error page
1501 *
1502 * @param string $title Message key for page title
1503 * @param string $msg Message key for page text
1504 * @param array $params Message parameters
1505 */
1506 public function showErrorPage( $title, $msg, $params = array() ) {
1507 if ( $this->getTitle() ) {
1508 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1509 }
1510 $this->setPageTitle( wfMsg( $title ) );
1511 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1512 $this->setRobotPolicy( 'noindex,nofollow' );
1513 $this->setArticleRelated( false );
1514 $this->enableClientCache( false );
1515 $this->mRedirect = '';
1516 $this->mBodytext = '';
1517
1518 array_unshift( $params, 'parse' );
1519 array_unshift( $params, $msg );
1520 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1521
1522 $this->returnToMain();
1523 }
1524
1525 /**
1526 * Output a standard permission error page
1527 *
1528 * @param array $errors Error message keys
1529 */
1530 public function showPermissionsErrorPage( $errors, $action = null )
1531 {
1532 $this->mDebugtext .= 'Original title: ' .
1533 $this->getTitle()->getPrefixedText() . "\n";
1534 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1535 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1536 $this->setRobotPolicy( 'noindex,nofollow' );
1537 $this->setArticleRelated( false );
1538 $this->enableClientCache( false );
1539 $this->mRedirect = '';
1540 $this->mBodytext = '';
1541 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1542 }
1543
1544 /** @deprecated */
1545 public function errorpage( $title, $msg ) {
1546 wfDeprecated( __METHOD__ );
1547 throw new ErrorPageError( $title, $msg );
1548 }
1549
1550 /**
1551 * Display an error page indicating that a given version of MediaWiki is
1552 * required to use it
1553 *
1554 * @param mixed $version The version of MediaWiki needed to use the page
1555 */
1556 public function versionRequired( $version ) {
1557 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1558 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1559 $this->setRobotPolicy( 'noindex,nofollow' );
1560 $this->setArticleRelated( false );
1561 $this->mBodytext = '';
1562
1563 $this->addWikiMsg( 'versionrequiredtext', $version );
1564 $this->returnToMain();
1565 }
1566
1567 /**
1568 * Display an error page noting that a given permission bit is required.
1569 *
1570 * @param string $permission key required
1571 */
1572 public function permissionRequired( $permission ) {
1573 global $wgLang;
1574
1575 $this->setPageTitle( wfMsg( 'badaccess' ) );
1576 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1577 $this->setRobotPolicy( 'noindex,nofollow' );
1578 $this->setArticleRelated( false );
1579 $this->mBodytext = '';
1580
1581 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1582 User::getGroupsWithPermission( $permission ) );
1583 if( $groups ) {
1584 $this->addWikiMsg( 'badaccess-groups',
1585 $wgLang->commaList( $groups ),
1586 count( $groups) );
1587 } else {
1588 $this->addWikiMsg( 'badaccess-group0' );
1589 }
1590 $this->returnToMain();
1591 }
1592
1593 /**
1594 * Use permissionRequired.
1595 * @deprecated
1596 */
1597 public function sysopRequired() {
1598 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1599 }
1600
1601 /**
1602 * Use permissionRequired.
1603 * @deprecated
1604 */
1605 public function developerRequired() {
1606 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1607 }
1608
1609 /**
1610 * Produce the stock "please login to use the wiki" page
1611 */
1612 public function loginToUse() {
1613 global $wgUser, $wgContLang;
1614
1615 if( $wgUser->isLoggedIn() ) {
1616 $this->permissionRequired( 'read' );
1617 return;
1618 }
1619
1620 $skin = $wgUser->getSkin();
1621
1622 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1623 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1624 $this->setRobotPolicy( 'noindex,nofollow' );
1625 $this->setArticleFlag( false );
1626
1627 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1628 $loginLink = $skin->link(
1629 $loginTitle,
1630 wfMsgHtml( 'loginreqlink' ),
1631 array(),
1632 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1633 array( 'known', 'noclasses' )
1634 );
1635 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1636 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1637
1638 # Don't return to the main page if the user can't read it
1639 # otherwise we'll end up in a pointless loop
1640 $mainPage = Title::newMainPage();
1641 if( $mainPage->userCanRead() )
1642 $this->returnToMain( null, $mainPage );
1643 }
1644
1645 /** @deprecated */
1646 public function databaseError( $fname, $sql, $error, $errno ) {
1647 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1648 }
1649
1650 /**
1651 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1652 * @return string The wikitext error-messages, formatted into a list.
1653 */
1654 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1655 if ($action == null) {
1656 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1657 } else {
1658 global $wgLang;
1659 $action_desc = wfMsgNoTrans( "action-$action" );
1660 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1661 }
1662
1663 if (count( $errors ) > 1) {
1664 $text .= '<ul class="permissions-errors">' . "\n";
1665
1666 foreach( $errors as $error )
1667 {
1668 $text .= '<li>';
1669 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1670 $text .= "</li>\n";
1671 }
1672 $text .= '</ul>';
1673 } else {
1674 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1675 }
1676
1677 return $text;
1678 }
1679
1680 /**
1681 * Display a page stating that the Wiki is in read-only mode,
1682 * and optionally show the source of the page that the user
1683 * was trying to edit. Should only be called (for this
1684 * purpose) after wfReadOnly() has returned true.
1685 *
1686 * For historical reasons, this function is _also_ used to
1687 * show the error message when a user tries to edit a page
1688 * they are not allowed to edit. (Unless it's because they're
1689 * blocked, then we show blockedPage() instead.) In this
1690 * case, the second parameter should be set to true and a list
1691 * of reasons supplied as the third parameter.
1692 *
1693 * @todo Needs to be split into multiple functions.
1694 *
1695 * @param string $source Source code to show (or null).
1696 * @param bool $protected Is this a permissions error?
1697 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1698 */
1699 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1700 global $wgUser;
1701 $skin = $wgUser->getSkin();
1702
1703 $this->setRobotPolicy( 'noindex,nofollow' );
1704 $this->setArticleRelated( false );
1705
1706 // If no reason is given, just supply a default "I can't let you do
1707 // that, Dave" message. Should only occur if called by legacy code.
1708 if ( $protected && empty($reasons) ) {
1709 $reasons[] = array( 'badaccess-group0' );
1710 }
1711
1712 if ( !empty($reasons) ) {
1713 // Permissions error
1714 if( $source ) {
1715 $this->setPageTitle( wfMsg( 'viewsource' ) );
1716 $this->setSubtitle(
1717 wfMsg(
1718 'viewsourcefor',
1719 $skin->link(
1720 $this->getTitle(),
1721 null,
1722 array(),
1723 array(),
1724 array( 'known', 'noclasses' )
1725 )
1726 )
1727 );
1728 } else {
1729 $this->setPageTitle( wfMsg( 'badaccess' ) );
1730 }
1731 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1732 } else {
1733 // Wiki is read only
1734 $this->setPageTitle( wfMsg( 'readonly' ) );
1735 $reason = wfReadOnlyReason();
1736 $this->wrapWikiMsg( '<div class="mw-readonly-error">\n$1</div>', array( 'readonlytext', $reason ) );
1737 }
1738
1739 // Show source, if supplied
1740 if( is_string( $source ) ) {
1741 $this->addWikiMsg( 'viewsourcetext' );
1742
1743 $params = array(
1744 'id' => 'wpTextbox1',
1745 'name' => 'wpTextbox1',
1746 'cols' => $wgUser->getOption( 'cols' ),
1747 'rows' => $wgUser->getOption( 'rows' ),
1748 'readonly' => 'readonly'
1749 );
1750 $this->addHTML( Html::element( 'textarea', $params, $source ) );
1751
1752 // Show templates used by this article
1753 $skin = $wgUser->getSkin();
1754 $article = new Article( $this->getTitle() );
1755 $this->addHTML( "<div class='templatesUsed'>
1756 {$skin->formatTemplates( $article->getUsedTemplates() )}
1757 </div>
1758 " );
1759 }
1760
1761 # If the title doesn't exist, it's fairly pointless to print a return
1762 # link to it. After all, you just tried editing it and couldn't, so
1763 # what's there to do there?
1764 if( $this->getTitle()->exists() ) {
1765 $this->returnToMain( null, $this->getTitle() );
1766 }
1767 }
1768
1769 /** @deprecated */
1770 public function fatalError( $message ) {
1771 wfDeprecated( __METHOD__ );
1772 throw new FatalError( $message );
1773 }
1774
1775 /** @deprecated */
1776 public function unexpectedValueError( $name, $val ) {
1777 wfDeprecated( __METHOD__ );
1778 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1779 }
1780
1781 /** @deprecated */
1782 public function fileCopyError( $old, $new ) {
1783 wfDeprecated( __METHOD__ );
1784 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1785 }
1786
1787 /** @deprecated */
1788 public function fileRenameError( $old, $new ) {
1789 wfDeprecated( __METHOD__ );
1790 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1791 }
1792
1793 /** @deprecated */
1794 public function fileDeleteError( $name ) {
1795 wfDeprecated( __METHOD__ );
1796 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1797 }
1798
1799 /** @deprecated */
1800 public function fileNotFoundError( $name ) {
1801 wfDeprecated( __METHOD__ );
1802 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1803 }
1804
1805 public function showFatalError( $message ) {
1806 $this->setPageTitle( wfMsg( "internalerror" ) );
1807 $this->setRobotPolicy( "noindex,nofollow" );
1808 $this->setArticleRelated( false );
1809 $this->enableClientCache( false );
1810 $this->mRedirect = '';
1811 $this->mBodytext = $message;
1812 }
1813
1814 public function showUnexpectedValueError( $name, $val ) {
1815 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1816 }
1817
1818 public function showFileCopyError( $old, $new ) {
1819 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1820 }
1821
1822 public function showFileRenameError( $old, $new ) {
1823 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1824 }
1825
1826 public function showFileDeleteError( $name ) {
1827 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1828 }
1829
1830 public function showFileNotFoundError( $name ) {
1831 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1832 }
1833
1834 /**
1835 * Add a "return to" link pointing to a specified title
1836 *
1837 * @param $title Title to link
1838 * @param $query String: query string
1839 */
1840 public function addReturnTo( $title, $query = array() ) {
1841 global $wgUser;
1842 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1843 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1844 $title, null, array(), $query ) );
1845 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1846 }
1847
1848 /**
1849 * Add a "return to" link pointing to a specified title,
1850 * or the title indicated in the request, or else the main page
1851 *
1852 * @param $unused No longer used
1853 * @param $returnto Title or String to return to
1854 * @param $returntoquery String: query string for the return to link
1855 */
1856 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1857 global $wgRequest;
1858
1859 if ( $returnto == null ) {
1860 $returnto = $wgRequest->getText( 'returnto' );
1861 }
1862
1863 if ( $returntoquery == null ) {
1864 $returntoquery = $wgRequest->getText( 'returntoquery' );
1865 }
1866
1867 if ( $returnto === '' ) {
1868 $returnto = Title::newMainPage();
1869 }
1870
1871 if ( is_object( $returnto ) ) {
1872 $titleObj = $returnto;
1873 } else {
1874 $titleObj = Title::newFromText( $returnto );
1875 }
1876 if ( !is_object( $titleObj ) ) {
1877 $titleObj = Title::newMainPage();
1878 }
1879
1880 $this->addReturnTo( $titleObj, $returntoquery );
1881 }
1882
1883 /**
1884 * @return string The doctype, opening <html>, and head element.
1885 *
1886 * @param $sk Skin The given Skin
1887 */
1888 public function headElement( Skin $sk, $includeStyle = true ) {
1889 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1890 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces, $wgHtml5Version;
1891 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgHtml5, $wgWellFormedXml;
1892 global $wgUser, $wgRequest, $wgLang;
1893
1894 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1895 if ( $sk->commonPrintStylesheet() ) {
1896 $this->addStyle( 'common/wikiprintable.css', 'print' );
1897 }
1898 $sk->setupUserCss( $this );
1899
1900 $ret = '';
1901
1902 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1903 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1904 }
1905
1906 if ( $this->getHTMLTitle() == '' ) {
1907 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1908 }
1909
1910 $dir = $wgContLang->getDir();
1911
1912 if ( $wgHtml5 ) {
1913 if ( $wgWellFormedXml ) {
1914 # Unknown elements and attributes are okay in XML, but unknown
1915 # named entities are well-formedness errors and will break XML
1916 # parsers. Thus we need a doctype that gives us appropriate
1917 # entity definitions. The HTML5 spec permits four legacy
1918 # doctypes as obsolete but conforming, so let's pick one of
1919 # those, although it makes our pages look like XHTML1 Strict.
1920 # Isn't compatibility great?
1921 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1922 } else {
1923 # Much saner.
1924 $ret .= "<!doctype html>\n";
1925 }
1926 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\" ";
1927 if ( $wgHtml5Version ) $ret .= " version=\"$wgHtml5Version\" ";
1928 $ret .= ">\n";
1929 } else {
1930 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1931 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1932 foreach($wgXhtmlNamespaces as $tag => $ns) {
1933 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1934 }
1935 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1936 }
1937
1938 $ret .= "<head>\n";
1939 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1940 $ret .= implode( "\n", array(
1941 $this->getHeadLinks(),
1942 $this->buildCssLinks(),
1943 $this->getHeadScripts( $sk ),
1944 $this->getHeadItems(),
1945 ));
1946 if( $sk->usercss ){
1947 $ret .= Html::inlineStyle( $sk->usercss );
1948 }
1949
1950 if ($wgUseTrackbacks && $this->isArticleRelated())
1951 $ret .= $this->getTitle()->trackbackRDF();
1952
1953 $ret .= "</head>\n";
1954
1955 $bodyAttrs = array();
1956
1957 # Crazy edit-on-double-click stuff
1958 $action = $wgRequest->getVal( 'action', 'view' );
1959
1960 if ( $this->getTitle()->getNamespace() != NS_SPECIAL
1961 && !in_array( $action, array( 'edit', 'submit' ) )
1962 && $wgUser->getOption( 'editondblclick' ) ) {
1963 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
1964 }
1965
1966 # Class bloat
1967 $bodyAttrs['class'] = "mediawiki $dir";
1968
1969 if ( $wgLang->capitalizeAllNouns() ) {
1970 # A <body> class is probably not the best way to do this . . .
1971 $bodyAttrs['class'] .= ' capitalize-all-nouns';
1972 }
1973 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
1974 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
1975 $bodyAttrs['class'] .= ' ns-special';
1976 } elseif ( $this->getTitle()->isTalkPage() ) {
1977 $bodyAttrs['class'] .= ' ns-talk';
1978 } else {
1979 $bodyAttrs['class'] .= ' ns-subject';
1980 }
1981 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
1982 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
1983
1984 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
1985
1986 return $ret;
1987 }
1988
1989 /*
1990 * gets the global variables and mScripts
1991 *
1992 * also adds userjs to the end if enabled:
1993 */
1994 function getHeadScripts( Skin $sk ) {
1995 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1996 global $wgStylePath, $wgStyleVersion;
1997
1998 $scripts = Skin::makeGlobalVariablesScript( $sk->getSkinName() );
1999 $scripts .= Html::linkedScript( "{$wgStylePath}/common/wikibits.js?$wgStyleVersion" );
2000
2001 //add site JS if enabled:
2002 if( $wgUseSiteJs ) {
2003 $jsCache = $wgUser->isLoggedIn() ? '&smaxage=0' : '';
2004 $this->addScriptFile( Skin::makeUrl( '-',
2005 "action=raw$jsCache&gen=js&useskin=" .
2006 urlencode( $sk->getSkinName() )
2007 )
2008 );
2009 }
2010
2011 //add user js if enabled:
2012 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2013 $action = $wgRequest->getVal( 'action', 'view' );
2014 if( $this->mTitle && $this->mTitle->isJsSubpage() and $sk->userCanPreview( $action ) ) {
2015 # XXX: additional security check/prompt?
2016 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
2017 } else {
2018 $userpage = $wgUser->getUserPage();
2019 $scriptpage = Title::makeTitleSafe(
2020 NS_USER,
2021 $userpage->getDBkey() . '/' . $sk->getSkinName() . '.js'
2022 );
2023 if ( $scriptpage && $scriptpage->exists() ) {
2024 $userjs = Skin::makeUrl( $scriptpage->getPrefixedText(), 'action=raw&ctype=' . $wgJsMimeType );
2025 $this->addScriptFile( $userjs );
2026 }
2027 }
2028 }
2029
2030 $scripts .= "\n" . $this->mScripts;
2031 return $scripts;
2032 }
2033
2034 protected function addDefaultMeta() {
2035 global $wgVersion, $wgHtml5;
2036
2037 static $called = false;
2038 if ( $called ) {
2039 # Don't run this twice
2040 return;
2041 }
2042 $called = true;
2043
2044 if ( !$wgHtml5 ) {
2045 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
2046 }
2047 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2048
2049 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2050 if( $p !== 'index,follow' ) {
2051 // http://www.robotstxt.org/wc/meta-user.html
2052 // Only show if it's different from the default robots policy
2053 $this->addMeta( 'robots', $p );
2054 }
2055
2056 if ( count( $this->mKeywords ) > 0 ) {
2057 $strip = array(
2058 "/<.*?" . ">/" => '',
2059 "/_/" => ' '
2060 );
2061 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
2062 }
2063 }
2064
2065 /**
2066 * @return string HTML tag links to be put in the header.
2067 */
2068 public function getHeadLinks() {
2069 global $wgRequest, $wgFeed;
2070
2071 // Ideally this should happen earlier, somewhere. :P
2072 $this->addDefaultMeta();
2073
2074 $tags = array();
2075
2076 foreach ( $this->mMetatags as $tag ) {
2077 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2078 $a = 'http-equiv';
2079 $tag[0] = substr( $tag[0], 5 );
2080 } else {
2081 $a = 'name';
2082 }
2083 $tags[] = Html::element( 'meta',
2084 array(
2085 $a => $tag[0],
2086 'content' => $tag[1] ) );
2087 }
2088 foreach ( $this->mLinktags as $tag ) {
2089 $tags[] = Html::element( 'link', $tag );
2090 }
2091
2092 if( $wgFeed ) {
2093 foreach( $this->getSyndicationLinks() as $format => $link ) {
2094 # Use the page name for the title (accessed through $wgTitle since
2095 # there's no other way). In principle, this could lead to issues
2096 # with having the same name for different feeds corresponding to
2097 # the same page, but we can't avoid that at this low a level.
2098
2099 $tags[] = $this->feedLink(
2100 $format,
2101 $link,
2102 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2103 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) );
2104 }
2105
2106 # Recent changes feed should appear on every page (except recentchanges,
2107 # that would be redundant). Put it after the per-page feed to avoid
2108 # changing existing behavior. It's still available, probably via a
2109 # menu in your browser. Some sites might have a different feed they'd
2110 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2111 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2112 # If so, use it instead.
2113
2114 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2115 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2116
2117 if ( $wgOverrideSiteFeed ) {
2118 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2119 $tags[] = $this->feedLink (
2120 $type,
2121 htmlspecialchars( $feedUrl ),
2122 wfMsg( "site-{$type}-feed", $wgSitename ) );
2123 }
2124 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2125 foreach ( $wgAdvertisedFeedTypes as $format ) {
2126 $tags[] = $this->feedLink(
2127 $format,
2128 $rctitle->getLocalURL( "feed={$format}" ),
2129 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
2130 }
2131 }
2132 }
2133
2134 return implode( "\n", $tags );
2135 }
2136
2137 /**
2138 * Return URLs for each supported syndication format for this page.
2139 * @return array associating format keys with URLs
2140 */
2141 public function getSyndicationLinks() {
2142 return $this->mFeedLinks;
2143 }
2144
2145 /**
2146 * Generate a <link rel/> for an RSS feed.
2147 */
2148 private function feedLink( $type, $url, $text ) {
2149 return Html::element( 'link', array(
2150 'rel' => 'alternate',
2151 'type' => "application/$type+xml",
2152 'title' => $text,
2153 'href' => $url ) );
2154 }
2155
2156 /**
2157 * Add a local or specified stylesheet, with the given media options.
2158 * Meant primarily for internal use...
2159 *
2160 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
2161 * @param $conditional -- for IE conditional comments, specifying an IE version
2162 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
2163 */
2164 public function addStyle( $style, $media='', $condition='', $dir='' ) {
2165 $options = array();
2166 // Even though we expect the media type to be lowercase, but here we
2167 // force it to lowercase to be safe.
2168 if( $media )
2169 $options['media'] = $media;
2170 if( $condition )
2171 $options['condition'] = $condition;
2172 if( $dir )
2173 $options['dir'] = $dir;
2174 $this->styles[$style] = $options;
2175 }
2176
2177 /**
2178 * Adds inline CSS styles
2179 * @param $style_css Mixed: inline CSS
2180 */
2181 public function addInlineStyle( $style_css ){
2182 $this->mScripts .= Html::inlineStyle( $style_css );
2183 }
2184
2185 /**
2186 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2187 * These will be applied to various media & IE conditionals.
2188 */
2189 public function buildCssLinks() {
2190 $links = array();
2191 foreach( $this->styles as $file => $options ) {
2192 $link = $this->styleLink( $file, $options );
2193 if( $link )
2194 $links[] = $link;
2195 }
2196
2197 return implode( "\n", $links );
2198 }
2199
2200 protected function styleLink( $style, $options ) {
2201 global $wgRequest;
2202
2203 if( isset( $options['dir'] ) ) {
2204 global $wgContLang;
2205 $siteDir = $wgContLang->getDir();
2206 if( $siteDir != $options['dir'] )
2207 return '';
2208 }
2209
2210 if( isset( $options['media'] ) ) {
2211 $media = $this->transformCssMedia( $options['media'] );
2212 if( is_null( $media ) ) {
2213 return '';
2214 }
2215 } else {
2216 $media = 'all';
2217 }
2218
2219 if( substr( $style, 0, 1 ) == '/' ||
2220 substr( $style, 0, 5 ) == 'http:' ||
2221 substr( $style, 0, 6 ) == 'https:' ) {
2222 $url = $style;
2223 } else {
2224 global $wgStylePath, $wgStyleVersion;
2225 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2226 }
2227
2228 $link = Html::linkedStyle( $url, $media );
2229
2230 if( isset( $options['condition'] ) ) {
2231 $condition = htmlspecialchars( $options['condition'] );
2232 $link = "<!--[if $condition]>$link<![endif]-->";
2233 }
2234 return $link;
2235 }
2236
2237 function transformCssMedia( $media ) {
2238 global $wgRequest, $wgHandheldForIPhone;
2239
2240 // Switch in on-screen display for media testing
2241 $switches = array(
2242 'printable' => 'print',
2243 'handheld' => 'handheld',
2244 );
2245 foreach( $switches as $switch => $targetMedia ) {
2246 if( $wgRequest->getBool( $switch ) ) {
2247 if( $media == $targetMedia ) {
2248 $media = '';
2249 } elseif( $media == 'screen' ) {
2250 return null;
2251 }
2252 }
2253 }
2254
2255 // Expand longer media queries as iPhone doesn't grok 'handheld'
2256 if( $wgHandheldForIPhone ) {
2257 $mediaAliases = array(
2258 'screen' => 'screen and (min-device-width: 481px)',
2259 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2260 );
2261
2262 if( isset( $mediaAliases[$media] ) ) {
2263 $media = $mediaAliases[$media];
2264 }
2265 }
2266
2267 return $media;
2268 }
2269
2270 /**
2271 * Turn off regular page output and return an error reponse
2272 * for when rate limiting has triggered.
2273 */
2274 public function rateLimited() {
2275
2276 $this->setPageTitle(wfMsg('actionthrottled'));
2277 $this->setRobotPolicy( 'noindex,follow' );
2278 $this->setArticleRelated( false );
2279 $this->enableClientCache( false );
2280 $this->mRedirect = '';
2281 $this->clearHTML();
2282 $this->setStatusCode(503);
2283 $this->addWikiMsg( 'actionthrottledtext' );
2284
2285 $this->returnToMain( null, $this->getTitle() );
2286 }
2287
2288 /**
2289 * Show an "add new section" link?
2290 *
2291 * @return bool
2292 */
2293 public function showNewSectionLink() {
2294 return $this->mNewSectionLink;
2295 }
2296
2297 /**
2298 * Forcibly hide the new section link?
2299 *
2300 * @return bool
2301 */
2302 public function forceHideNewSectionLink() {
2303 return $this->mHideNewSectionLink;
2304 }
2305
2306 /**
2307 * Show a warning about slave lag
2308 *
2309 * If the lag is higher than $wgSlaveLagCritical seconds,
2310 * then the warning is a bit more obvious. If the lag is
2311 * lower than $wgSlaveLagWarning, then no warning is shown.
2312 *
2313 * @param int $lag Slave lag
2314 */
2315 public function showLagWarning( $lag ) {
2316 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2317 if( $lag >= $wgSlaveLagWarning ) {
2318 $message = $lag < $wgSlaveLagCritical
2319 ? 'lag-warn-normal'
2320 : 'lag-warn-high';
2321 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2322 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2323 }
2324 }
2325
2326 /**
2327 * Add a wikitext-formatted message to the output.
2328 * This is equivalent to:
2329 *
2330 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2331 */
2332 public function addWikiMsg( /*...*/ ) {
2333 $args = func_get_args();
2334 $name = array_shift( $args );
2335 $this->addWikiMsgArray( $name, $args );
2336 }
2337
2338 /**
2339 * Add a wikitext-formatted message to the output.
2340 * Like addWikiMsg() except the parameters are taken as an array
2341 * instead of a variable argument list.
2342 *
2343 * $options is passed through to wfMsgExt(), see that function for details.
2344 */
2345 public function addWikiMsgArray( $name, $args, $options = array() ) {
2346 $options[] = 'parse';
2347 $text = wfMsgExt( $name, $options, $args );
2348 $this->addHTML( $text );
2349 }
2350
2351 /**
2352 * This function takes a number of message/argument specifications, wraps them in
2353 * some overall structure, and then parses the result and adds it to the output.
2354 *
2355 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2356 * on. The subsequent arguments may either be strings, in which case they are the
2357 * message names, or arrays, in which case the first element is the message name,
2358 * and subsequent elements are the parameters to that message.
2359 *
2360 * The special named parameter 'options' in a message specification array is passed
2361 * through to the $options parameter of wfMsgExt().
2362 *
2363 * Don't use this for messages that are not in users interface language.
2364 *
2365 * For example:
2366 *
2367 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>", 'some-error' );
2368 *
2369 * Is equivalent to:
2370 *
2371 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . '</div>' );
2372 *
2373 * The newline after opening div is needed in some wikitext. See bug 19226.
2374 */
2375 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2376 $msgSpecs = func_get_args();
2377 array_shift( $msgSpecs );
2378 $msgSpecs = array_values( $msgSpecs );
2379 $s = $wrap;
2380 foreach ( $msgSpecs as $n => $spec ) {
2381 $options = array();
2382 if ( is_array( $spec ) ) {
2383 $args = $spec;
2384 $name = array_shift( $args );
2385 if ( isset( $args['options'] ) ) {
2386 $options = $args['options'];
2387 unset( $args['options'] );
2388 }
2389 } else {
2390 $args = array();
2391 $name = $spec;
2392 }
2393 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2394 }
2395 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2396 }
2397
2398 /**
2399 * Include jQuery core. Use this to avoid loading it multiple times
2400 * before we get a usable script loader.
2401 *
2402 * @param array $modules List of jQuery modules which should be loaded
2403 *
2404 * Returns the list of modules which were not loaded.
2405 */
2406 public function includeJQuery( $modules = array() ) {
2407 global $wgScriptPath, $wgStyleVersion, $wgJsMimeType;
2408
2409 $supportedModules = array( /** TODO: add things here */ );
2410 $unsupported = array_diff( $modules, $supportedModules );
2411
2412 $params = array(
2413 'type' => $wgJsMimeType,
2414 'src' => "$wgScriptPath/skins/common/jquery.min.js?$wgStyleVersion",
2415 );
2416 if ( !$this->mJQueryDone ) {
2417 $this->mJQueryDone = true;
2418 $this->mScripts = Html::element( 'script', $params ) . "\n" . $this->mScripts;
2419 }
2420 return $unsupported;
2421 }
2422
2423 }