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