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