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