Fix bounding box feature of thumbnails (e.g. |200x200px|)
[mediawiki.git] / includes / OutputPage.php
blob0e8d5338442ed299f22ebfcc5de7a6236a887867
1 <?php
2 /**
3 * @version $Id$
4 * @package MediaWiki
5 */
7 /**
8 * This is not a valid entry point, perform no further processing unless MEDIAWIKI is defined
9 */
10 if( defined( 'MEDIAWIKI' ) ) {
12 # See design.doc
14 if($wgUseTeX) require_once( 'Math.php' );
16 define( 'RLH_FOR_UPDATE', 1 );
18 /**
19 * @todo document
20 * @package MediaWiki
22 class OutputPage {
23 var $mHeaders, $mCookies, $mMetatags, $mKeywords;
24 var $mLinktags, $mPagetitle, $mBodytext, $mDebugtext;
25 var $mHTMLtitle, $mRobotpolicy, $mIsarticle, $mPrintable;
26 var $mSubtitle, $mRedirect;
27 var $mLastModified, $mCategoryLinks;
28 var $mScripts, $mLinkColours;
30 var $mSuppressQuickbar;
31 var $mOnloadHandler;
32 var $mDoNothing;
33 var $mContainsOldMagic, $mContainsNewMagic;
34 var $mIsArticleRelated;
35 var $mParserOptions;
36 var $mShowFeedLinks = false;
37 var $mEnableClientCache = true;
39 /**
40 * Constructor
41 * Initialise private variables
43 function OutputPage() {
44 $this->mHeaders = $this->mCookies = $this->mMetatags =
45 $this->mKeywords = $this->mLinktags = array();
46 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
47 $this->mRedirect = $this->mLastModified =
48 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
49 $this->mOnloadHandler = '';
50 $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
51 $this->mSuppressQuickbar = $this->mPrintable = false;
52 $this->mLanguageLinks = array();
53 $this->mCategoryLinks = array() ;
54 $this->mDoNothing = false;
55 $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
56 $this->mParserOptions = ParserOptions::newFromUser( $temp = NULL );
57 $this->mSquidMaxage = 0;
58 $this->mScripts = '';
61 function addHeader( $name, $val ) { array_push( $this->mHeaders, $name.': '.$val ) ; }
62 function addCookie( $name, $val ) { array_push( $this->mCookies, array( $name, $val ) ); }
63 function redirect( $url, $responsecode = '302' ) { $this->mRedirect = $url; $this->mRedirectCode = $responsecode; }
65 # To add an http-equiv meta tag, precede the name with "http:"
66 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
67 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
68 function addScript( $script ) { $this->mScripts .= $script; }
69 function getScript() { return $this->mScripts; }
71 function addLink( $linkarr ) {
72 # $linkarr should be an associative array of attributes. We'll escape on output.
73 array_push( $this->mLinktags, $linkarr );
76 function addMetadataLink( $linkarr ) {
77 # note: buggy CC software only reads first "meta" link
78 static $haveMeta = false;
79 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
80 $this->addLink( $linkarr );
81 $haveMeta = true;
84 /**
85 * checkLastModified tells the client to use the client-cached page if
86 * possible. If sucessful, the OutputPage is disabled so that
87 * any future call to OutputPage->output() have no effect. The method
88 * returns true iff cache-ok headers was sent.
90 function checkLastModified ( $timestamp ) {
91 global $wgLang, $wgCachePages, $wgUser;
92 $timestamp=wfTimestamp(TS_MW,$timestamp);
93 if( !$wgCachePages ) {
94 wfDebug( "CACHE DISABLED\n", false );
95 return;
97 if( preg_match( '/MSIE ([1-4]|5\.0)/', $_SERVER["HTTP_USER_AGENT"] ) ) {
98 # IE 5.0 has probs with our caching
99 wfDebug( "-- bad client, not caching\n", false );
100 return;
102 if( $wgUser->getOption( 'nocache' ) ) {
103 wfDebug( "USER DISABLED CACHE\n", false );
104 return;
107 $lastmod = gmdate( 'D, j M Y H:i:s', wfTimestamp(TS_UNIX, max( $timestamp, $wgUser->mTouched ) ) ) . ' GMT';
109 if( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
110 # IE sends sizes after the date like this:
111 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
112 # this breaks strtotime().
113 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
114 $ismodsince = wfTimestamp( TS_MW, strtotime( $modsince ) );
115 wfDebug( "-- client send If-Modified-Since: " . $modsince . "\n", false );
116 wfDebug( "-- we might send Last-Modified : $lastmod\n", false );
117 if( ($ismodsince >= $timestamp ) and $wgUser->validateCache( $ismodsince ) ) {
118 # Make sure you're in a place you can leave when you call us!
119 header( "HTTP/1.0 304 Not Modified" );
120 $this->mLastModified = $lastmod;
121 $this->sendCacheControl();
122 wfDebug( "CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
123 $this->disable();
124 return true;
125 } else {
126 wfDebug( "READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
127 $this->mLastModified = $lastmod;
129 } else {
130 wfDebug( "We're confused.\n", false );
131 $this->mLastModified = $lastmod;
135 function getPageTitleActionText () {
136 global $action;
137 switch($action) {
138 case 'edit':
139 return wfMsg('edit');
140 case 'history':
141 return wfMsg('history_short');
142 case 'protect':
143 return wfMsg('protect');
144 case 'unprotect':
145 return wfMsg('unprotect');
146 case 'delete':
147 return wfMsg('delete');
148 case 'watch':
149 return wfMsg('watch');
150 case 'unwatch':
151 return wfMsg('unwatch');
152 case 'submit':
153 return wfMsg('preview');
154 case 'info':
155 return wfMsg('info_short');
156 default:
157 return '';
161 function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
162 function setHTMLTitle( $name ) {$this->mHTMLtitle = $name; }
163 function setPageTitle( $name ) {
164 global $action, $wgContLang;
165 $name = $wgContLang->autoConvert($name);
166 $this->mPagetitle = $name;
167 if(!empty($action)) {
168 $taction = $this->getPageTitleActionText();
169 if( !empty( $taction ) ) {
170 $name .= ' - '.$taction;
173 $this->setHTMLTitle( $name . ' - ' . wfMsg( 'wikititlesuffix' ) );
175 function getHTMLTitle() { return $this->mHTMLtitle; }
176 function getPageTitle() { return $this->mPagetitle; }
177 function setSubtitle( $str ) { $this->mSubtitle = $str; }
178 function getSubtitle() { return $this->mSubtitle; }
179 function isArticle() { return $this->mIsarticle; }
180 function setPrintable() { $this->mPrintable = true; }
181 function isPrintable() { return $this->mPrintable; }
182 function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
183 function isSyndicated() { return $this->mShowFeedLinks; }
184 function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
185 function getOnloadHandler() { return $this->mOnloadHandler; }
186 function disable() { $this->mDoNothing = true; }
188 function setArticleRelated( $v ) {
189 $this->mIsArticleRelated = $v;
190 if ( !$v ) {
191 $this->mIsarticle = false;
194 function setArticleFlag( $v ) {
195 $this->mIsarticle = $v;
196 if ( $v ) {
197 $this->mIsArticleRelated = $v;
201 function isArticleRelated() { return $this->mIsArticleRelated; }
203 function getLanguageLinks() { return $this->mLanguageLinks; }
204 function addLanguageLinks($newLinkArray) {
205 $this->mLanguageLinks += $newLinkArray;
207 function setLanguageLinks($newLinkArray) {
208 $this->mLanguageLinks = $newLinkArray;
211 function getCategoryLinks() {
212 return $this->mCategoryLinks;
214 function addCategoryLinks($newLinkArray) {
215 $this->mCategoryLinks += $newLinkArray;
217 function setCategoryLinks($newLinkArray) {
218 $this->mCategoryLinks += $newLinkArray;
221 function suppressQuickbar() { $this->mSuppressQuickbar = true; }
222 function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
224 function addHTML( $text ) { $this->mBodytext .= $text; }
225 function clearHTML() { $this->mBodytext = ''; }
226 function debug( $text ) { $this->mDebugtext .= $text; }
228 function setParserOptions( $options ) {
229 return wfSetVar( $this->mParserOptions, $options );
233 * Convert wikitext to HTML and add it to the buffer
235 function addWikiText( $text, $linestart = true ) {
236 global $wgParser, $wgTitle, $wgUseTidy;
238 $parserOutput = $wgParser->parse( $text, $wgTitle, $this->mParserOptions, $linestart );
239 if ($wgUseTidy) {
240 $text = Parser::tidy($text);
242 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
243 $this->mCategoryLinks += $parserOutput->getCategoryLinks();
244 $this->addHTML( $parserOutput->getText() );
248 * Add wikitext to the buffer, assuming that this is the primary text for a page view
249 * Saves the text into the parser cache if possible
251 function addPrimaryWikiText( $text, $cacheArticle ) {
252 global $wgParser, $wgParserCache, $wgUser, $wgTitle, $wgUseTidy;
254 $parserOutput = $wgParser->parse( $text, $wgTitle, $this->mParserOptions, true );
256 # Replace link holders
257 $text = $parserOutput->getText();
258 $this->replaceLinkHolders( $text );
259 if ($wgUseTidy) {
260 $text = Parser::tidy($text);
262 $parserOutput->setText( $text );
264 if ( $cacheArticle ) {
265 $wgParserCache->save( $parserOutput, $cacheArticle, $wgUser );
268 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
269 $this->mCategoryLinks += $parserOutput->getCategoryLinks();
270 $this->addHTML( $text );
274 * @param $article
275 * @param $user
277 function tryParserCache( $article, $user ) {
278 global $wgParserCache;
279 $parserOutput = $wgParserCache->get( $article, $user );
280 if ( $parserOutput !== false ) {
281 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
282 $this->mCategoryLinks += $parserOutput->getCategoryLinks();
283 $this->addHTML( $parserOutput->getText() );
284 return true;
285 } else {
286 return false;
291 * Set the maximum cache time on the Squid in seconds
292 * @param $maxage
294 function setSquidMaxage( $maxage ) {
295 $this->mSquidMaxage = $maxage;
299 * Use enableClientCache(false) to force it to send nocache headers
300 * @param $state
302 function enableClientCache( $state ) {
303 return wfSetVar( $this->mEnableClientCache, $state );
306 function sendCacheControl() {
307 global $wgUseSquid, $wgUseESI;
308 # FIXME: This header may cause trouble with some versions of Internet Explorer
309 header( 'Vary: Accept-Encoding, Cookie' );
310 if( $this->mEnableClientCache ) {
311 if( $wgUseSquid && ! isset( $_COOKIE[ini_get( 'session.name') ] ) &&
312 ! $this->isPrintable() && $this->mSquidMaxage != 0 )
314 if ( $wgUseESI ) {
315 # We'll purge the proxy cache explicitly, but require end user agents
316 # to revalidate against the proxy on each visit.
317 # Surrogate-Control controls our Squid, Cache-Control downstream caches
318 wfDebug( "** proxy caching with ESI; {$this->mLastModified} **\n", false );
319 # start with a shorter timeout for initial testing
320 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
321 header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
322 header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
323 } else {
324 # We'll purge the proxy cache for anons explicitly, but require end user agents
325 # to revalidate against the proxy on each visit.
326 # IMPORTANT! The Squid needs to replace the Cache-Control header with
327 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
328 wfDebug( "** local proxy caching; {$this->mLastModified} **\n", false );
329 # start with a shorter timeout for initial testing
330 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
331 header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
333 } else {
334 # We do want clients to cache if they can, but they *must* check for updates
335 # on revisiting the page.
336 wfDebug( "** private caching; {$this->mLastModified} **\n", false );
337 header( "Expires: -1" );
338 header( "Cache-Control: private, must-revalidate, max-age=0" );
340 if($this->mLastModified) header( "Last-modified: {$this->mLastModified}" );
341 } else {
342 wfDebug( "** no caching **\n", false );
344 # In general, the absence of a last modified header should be enough to prevent
345 # the client from using its cache. We send a few other things just to make sure.
346 header( 'Expires: -1' );
347 header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
348 header( 'Pragma: no-cache' );
353 * Finally, all the text has been munged and accumulated into
354 * the object, let's actually output it:
356 function output() {
357 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
358 global $wgInputEncoding, $wgOutputEncoding, $wgContLanguageCode;
359 global $wgDebugRedirects, $wgMimeType, $wgProfiler;
361 if( $this->mDoNothing ){
362 return;
364 $fname = 'OutputPage::output';
365 wfProfileIn( $fname );
366 $sk = $wgUser->getSkin();
368 if ( '' != $this->mRedirect ) {
369 if( substr( $this->mRedirect, 0, 4 ) != 'http' ) {
370 # Standards require redirect URLs to be absolute
371 global $wgServer;
372 $this->mRedirect = $wgServer . $this->mRedirect;
374 if( $this->mRedirectCode == '301') {
375 if( !$wgDebugRedirects ) {
376 header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
378 $this->mLastModified = gmdate( 'D, j M Y H:i:s' ) . ' GMT';
381 $this->sendCacheControl();
383 if( $wgDebugRedirects ) {
384 $url = htmlspecialchars( $this->mRedirect );
385 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
386 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
387 print "</body>\n</html>\n";
388 } else {
389 header( 'Location: '.$this->mRedirect );
391 if ( isset( $wgProfiler ) ) { wfDebug( $wgProfiler->getOutput() ); }
392 return;
396 $this->sendCacheControl();
397 # Perform link colouring
398 $this->transformBuffer();
399 $this->replaceLinkHolders( $this->mSubtitle );
401 # Disable temporary placeholders, so that the skin produces HTML
402 $sk->postParseLinkColour( false );
404 header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
405 header( 'Content-language: '.$wgContLanguageCode );
407 $exp = time() + $wgCookieExpiration;
408 foreach( $this->mCookies as $name => $val ) {
409 setcookie( $name, $val, $exp, '/' );
412 $sk->outputPage( $this );
413 # flush();
416 function out( $ins ) {
417 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
418 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
419 $outs = $ins;
420 } else {
421 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
422 if ( false === $outs ) { $outs = $ins; }
424 print $outs;
427 function setEncodings() {
428 global $wgInputEncoding, $wgOutputEncoding;
429 global $wgUser, $wgContLang;
431 $wgInputEncoding = strtolower( $wgInputEncoding );
433 if( $wgUser->getOption( 'altencoding' ) ) {
434 $wgContLang->setAltEncoding();
435 return;
438 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
439 $wgOutputEncoding = strtolower( $wgOutputEncoding );
440 return;
444 # This code is unused anyway!
445 # Commenting out. --bv 2003-11-15
447 $a = explode( ",", $_SERVER['HTTP_ACCEPT_CHARSET'] );
448 $best = 0.0;
449 $bestset = "*";
451 foreach ( $a as $s ) {
452 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
453 $set = $m[1];
454 $q = (float)($m[2]);
455 } else {
456 $set = $s;
457 $q = 1.0;
459 if ( $q > $best ) {
460 $bestset = $set;
461 $best = $q;
464 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
465 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
466 $wgOutputEncoding = strtolower( $bestset );
468 # Disable for now
471 $wgOutputEncoding = $wgInputEncoding;
475 * Returns a HTML comment with the elapsed time since request.
476 * This method has no side effects.
478 function reportTime() {
479 global $wgRequestTime;
481 $now = wfTime();
482 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
483 $start = (float)$sec + (float)$usec;
484 $elapsed = $now - $start;
486 # Use real server name if available, so we know which machine
487 # in a server farm generated the current page.
488 if ( function_exists( 'posix_uname' ) ) {
489 $uname = @posix_uname();
490 } else {
491 $uname = false;
493 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
494 $hostname = $uname['nodename'];
495 } else {
496 # This may be a virtual server.
497 $hostname = $_SERVER['SERVER_NAME'];
499 $com = sprintf( "<!-- Served by %s in %01.2f secs. -->",
500 $hostname, $elapsed );
501 return $com;
505 * Note: these arguments are keys into wfMsg(), not text!
507 function errorpage( $title, $msg ) {
508 global $wgTitle;
510 $this->mDebugtext .= 'Original title: ' .
511 $wgTitle->getPrefixedText() . "\n";
512 $this->setPageTitle( wfMsg( $title ) );
513 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
514 $this->setRobotpolicy( 'noindex,nofollow' );
515 $this->setArticleRelated( false );
516 $this->suppressQuickbar();
518 $this->enableClientCache( false );
519 $this->mRedirect = '';
521 $this->mBodytext = '';
522 $this->addHTML( '<p>' . wfMsg( $msg ) . "</p>\n" );
523 $this->returnToMain( false );
525 $this->output();
526 wfErrorExit();
529 function sysopRequired() {
530 global $wgUser;
532 $this->setPageTitle( wfMsg( 'sysoptitle' ) );
533 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
534 $this->setRobotpolicy( 'noindex,nofollow' );
535 $this->setArticleRelated( false );
536 $this->mBodytext = '';
538 $sk = $wgUser->getSkin();
539 $ap = $sk->makeKnownLink( wfMsgForContent( 'administrators' ), '' );
540 $this->addHTML( wfMsg( 'sysoptext', $ap ) );
541 $this->returnToMain();
544 function developerRequired() {
545 global $wgUser;
547 $this->setPageTitle( wfMsg( 'developertitle' ) );
548 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
549 $this->setRobotpolicy( 'noindex,nofollow' );
550 $this->setArticleRelated( false );
551 $this->mBodytext = '';
553 $sk = $wgUser->getSkin();
554 $ap = $sk->makeKnownLink( wfMsgForContent( 'administrators' ), '' );
555 $this->addHTML( wfMsg( 'developertext', $ap ) );
556 $this->returnToMain();
559 function loginToUse() {
560 global $wgUser, $wgTitle, $wgContLang;
562 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
563 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
564 $this->setRobotpolicy( 'noindex,nofollow' );
565 $this->setArticleFlag( false );
566 $this->mBodytext = '';
567 $this->addWikiText( wfMsg( 'loginreqtext' ) );
569 # We put a comment in the .html file so a Sysop can diagnose the page the
570 # user can't see.
571 $this->addHTML( "\n<!--" .
572 $wgContLang->getNsText( $wgTitle->getNamespace() ) .
573 ':' .
574 $wgTitle->getDBkey() . '-->' );
575 $this->returnToMain(); # Flip back to the main page after 10 seconds.
578 function databaseError( $fname, $sql, $error, $errno ) {
579 global $wgUser, $wgCommandLineMode;
581 $this->setPageTitle( wfMsgNoDB( 'databaseerror' ) );
582 $this->setRobotpolicy( 'noindex,nofollow' );
583 $this->setArticleRelated( false );
584 $this->enableClientCache( false );
585 $this->mRedirect = '';
587 if ( $wgCommandLineMode ) {
588 $msg = wfMsgNoDB( 'dberrortextcl', htmlspecialchars( $sql ),
589 htmlspecialchars( $fname ), $errno, htmlspecialchars( $error ) );
590 } else {
591 $msg = wfMsgNoDB( 'dberrortext', htmlspecialchars( $sql ),
592 htmlspecialchars( $fname ), $errno, htmlspecialchars( $error ) );
595 if ( $wgCommandLineMode || !is_object( $wgUser )) {
596 print $msg."\n";
597 wfErrorExit();
599 $this->mBodytext = $msg;
600 $this->output();
601 wfErrorExit();
604 function readOnlyPage( $source = null, $protected = false ) {
605 global $wgUser, $wgReadOnlyFile;
607 $this->setRobotpolicy( 'noindex,nofollow' );
608 $this->setArticleRelated( false );
610 if( $protected ) {
611 $this->setPageTitle( wfMsg( 'viewsource' ) );
612 $this->addWikiText( wfMsg( 'protectedtext' ) );
613 } else {
614 $this->setPageTitle( wfMsg( 'readonly' ) );
615 $reason = file_get_contents( $wgReadOnlyFile );
616 $this->addWikiText( wfMsg( 'readonlytext', $reason ) );
619 if( is_string( $source ) ) {
620 if( strcmp( $source, '' ) == 0 ) {
621 $source = wfMsg( 'noarticletext' );
623 $rows = $wgUser->getOption( 'rows' );
624 $cols = $wgUser->getOption( 'cols' );
625 $text = "\n<textarea cols='$cols' rows='$rows' readonly='readonly'>" .
626 htmlspecialchars( $source ) . "\n</textarea>";
627 $this->addHTML( $text );
630 $this->returnToMain( false );
633 function fatalError( $message ) {
634 $this->setPageTitle( wfMsg( "internalerror" ) );
635 $this->setRobotpolicy( "noindex,nofollow" );
636 $this->setArticleRelated( false );
637 $this->enableClientCache( false );
638 $this->mRedirect = '';
640 $this->mBodytext = $message;
641 $this->output();
642 wfErrorExit();
645 function unexpectedValueError( $name, $val ) {
646 $this->fatalError( wfMsg( 'unexpected', $name, $val ) );
649 function fileCopyError( $old, $new ) {
650 $this->fatalError( wfMsg( 'filecopyerror', $old, $new ) );
653 function fileRenameError( $old, $new ) {
654 $this->fatalError( wfMsg( 'filerenameerror', $old, $new ) );
657 function fileDeleteError( $name ) {
658 $this->fatalError( wfMsg( 'filedeleteerror', $name ) );
661 function fileNotFoundError( $name ) {
662 $this->fatalError( wfMsg( 'filenotfound', $name ) );
666 * return from error messages or notes
667 * @param $auto automatically redirect the user after 10 seconds
668 * @param $returnto page title to return to. Default is Main Page.
670 function returnToMain( $auto = true, $returnto = NULL ) {
671 global $wgUser, $wgOut, $wgRequest;
673 if ( $returnto == NULL ) {
674 $returnto = $wgRequest->getText( 'returnto' );
677 $sk = $wgUser->getSkin();
678 if ( '' == $returnto ) {
679 $returnto = wfMsgForContent( 'mainpage' );
681 $link = $sk->makeKnownLink( $returnto, '' );
683 $r = wfMsg( 'returnto', $link );
684 if ( $auto ) {
685 $titleObj = Title::newFromText( $returnto );
686 $wgOut->addMeta( 'http:Refresh', '10;url=' . $titleObj->escapeFullURL() );
688 $wgOut->addHTML( "\n<p>$r</p>\n" );
692 * This function takes the existing and broken links for the page
693 * and uses the first 10 of them for META keywords
695 function addMetaTags () {
696 global $wgLinkCache , $wgOut ;
697 $good = array_keys ( $wgLinkCache->mGoodLinks ) ;
698 $bad = array_keys ( $wgLinkCache->mBadLinks ) ;
699 $a = array_merge ( $good , $bad ) ;
700 $a = array_slice ( $a , 0 , 10 ) ; # 10 keywords max
701 $a = implode ( ',' , $a ) ;
702 $strip = array(
703 "/<.*?" . ">/" => '',
704 "/[_]/" => ' '
706 $a = htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),$a ));
708 $wgOut->addMeta ( 'KEYWORDS' , $a ) ;
712 * @private
714 function headElement() {
715 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
716 global $wgUser, $wgContLang, $wgRequest;
718 $xml = ($wgMimeType == 'text/xml');
719 if( $xml ) {
720 $ret = "<" . "?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
721 } else {
722 $ret = '';
725 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
727 if ( "" == $this->mHTMLtitle ) {
728 $this->mHTMLtitle = wfMsg( "pagetitle", $this->mPagetitle );
730 if( $xml ) {
731 $xmlbits = "xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\"";
732 } else {
733 $xmlbits = '';
735 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
736 $ret .= "<html $xmlbits lang=\"$wgContLanguageCode\" $rtl>\n";
737 $ret .= "<head>\n<title>" . htmlspecialchars( $this->mHTMLtitle ) . "</title>\n";
738 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
740 $ret .= $this->getHeadLinks();
741 global $wgStylePath;
742 if( $this->isPrintable() ) {
743 $media = '';
744 } else {
745 $media = "media='print'";
747 $printsheet = htmlspecialchars( "$wgStylePath/common/wikiprintable.css" );
748 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
750 $sk = $wgUser->getSkin();
751 $ret .= $sk->getHeadScripts();
752 $ret .= $this->mScripts;
753 $ret .= $sk->getUserStyles();
755 $ret .= "</head>\n";
756 return $ret;
759 function getHeadLinks() {
760 global $wgRequest, $wgStylePath;
761 $ret = '';
762 foreach ( $this->mMetatags as $tag ) {
763 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
764 $a = 'http-equiv';
765 $tag[0] = substr( $tag[0], 5 );
766 } else {
767 $a = 'name';
769 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
771 $p = $this->mRobotpolicy;
772 if ( '' == $p ) { $p = 'index,follow'; }
773 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
775 if ( count( $this->mKeywords ) > 0 ) {
776 $strip = array(
777 "/<.*?" . ">/" => '',
778 "/[_]/" => ' '
780 $ret .= "<meta name=\"keywords\" content=\"" .
781 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
783 foreach ( $this->mLinktags as $tag ) {
784 $ret .= '<link';
785 foreach( $tag as $attr => $val ) {
786 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
788 $ret .= " />\n";
790 if( $this->isSyndicated() ) {
791 # FIXME: centralize the mime-type and name information in Feed.php
792 $link = $wgRequest->escapeAppendQuery( 'feed=rss' );
793 $ret .= "<link rel='alternate' type='application/rss+xml' title='RSS 2.0' href='$link' />\n";
794 $link = $wgRequest->escapeAppendQuery( 'feed=atom' );
795 $ret .= "<link rel='alternate' type='application/rss+atom' title='Atom 0.3' href='$link' />\n";
797 # FIXME: get these working
798 # $fix = htmlspecialchars( $wgStylePath . "/ie-png-fix.js" );
799 # $ret .= "<!--[if gte IE 5.5000]><script type='text/javascript' src='$fix'>< /script><![endif]-->";
800 return $ret;
804 * Run any necessary pre-output transformations on the buffer text
806 function transformBuffer( $options = 0 ) {
807 $this->replaceLinkHolders( $this->mBodytext, $options );
811 * Replace <!--LINK--> link placeholders with actual links, in the buffer
812 * Placeholders created in Skin::makeLinkObj()
813 * Returns an array of links found, indexed by PDBK:
814 * 0 - broken
815 * 1 - normal link
816 * 2 - stub
817 * $options is a bit field, RLH_FOR_UPDATE to select for update
819 function replaceLinkHolders( &$text, $options = 0 ) {
820 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck, $wgLinkHolders;
822 if ( $wgUseOldExistenceCheck ) {
823 return array();
826 $fname = 'OutputPage::replaceLinkHolders';
827 wfProfileIn( $fname );
829 $pdbks = array();
830 $colours = array();
832 #if ( !empty( $tmpLinks[0] ) ) { #TODO
833 if ( !empty( $wgLinkHolders['namespaces'] ) ) {
834 wfProfileIn( $fname.'-check' );
835 $dbr =& wfGetDB( DB_SLAVE );
836 $cur = $dbr->tableName( 'cur' );
837 $sk = $wgUser->getSkin();
838 $threshold = $wgUser->getOption('stubthreshold');
840 # Sort by namespace
841 asort( $wgLinkHolders['namespaces'] );
843 # Generate query
844 $query = false;
845 foreach ( $wgLinkHolders['namespaces'] as $key => $val ) {
846 # Make title object
847 $title = $wgLinkHolders['titles'][$key];
849 # Skip invalid entries.
850 # Result will be ugly, but prevents crash.
851 if ( is_null( $title ) ) {
852 continue;
854 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
856 # Check if it's in the link cache already
857 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
858 $colours[$pdbk] = 1;
859 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
860 $colours[$pdbk] = 0;
861 } else {
862 # Not in the link cache, add it to the query
863 if ( !isset( $current ) ) {
864 $current = $val;
865 $query = "SELECT cur_id, cur_namespace, cur_title";
866 if ( $threshold > 0 ) {
867 $query .= ", LENGTH(cur_text) AS cur_len, cur_is_redirect";
869 $query .= " FROM $cur WHERE (cur_namespace=$val AND cur_title IN(";
870 } elseif ( $current != $val ) {
871 $current = $val;
872 $query .= ")) OR (cur_namespace=$val AND cur_title IN(";
873 } else {
874 $query .= ', ';
877 $query .= $dbr->addQuotes( $wgLinkHolders['dbkeys'][$key] );
880 if ( $query ) {
881 $query .= '))';
882 if ( $options & RLH_FOR_UPDATE ) {
883 $query .= ' FOR UPDATE';
886 $res = $dbr->query( $query, $fname );
888 # Fetch data and form into an associative array
889 # non-existent = broken
890 # 1 = known
891 # 2 = stub
892 while ( $s = $dbr->fetchObject($res) ) {
893 $title = Title::makeTitle( $s->cur_namespace, $s->cur_title );
894 $pdbk = $title->getPrefixedDBkey();
895 $wgLinkCache->addGoodLink( $s->cur_id, $pdbk );
897 if ( $threshold > 0 ) {
898 $size = $s->cur_len;
899 if ( $s->cur_is_redirect || $s->cur_namespace != 0 || $length < $threshold ) {
900 $colours[$pdbk] = 1;
901 } else {
902 $colours[$pdbk] = 2;
904 } else {
905 $colours[$pdbk] = 1;
909 wfProfileOut( $fname.'-check' );
911 # Construct search and replace arrays
912 wfProfileIn( $fname.'-construct' );
913 global $outputReplace;
914 $outputReplace = array();
915 foreach ( $wgLinkHolders['namespaces'] as $key => $ns ) {
916 $pdbk = $pdbks[$key];
917 $searchkey = '<!--LINK '.$key.'-->';
918 $title = $wgLinkHolders['titles'][$key];
919 if ( empty( $colours[$pdbk] ) ) {
920 $wgLinkCache->addBadLink( $pdbk );
921 $colours[$pdbk] = 0;
922 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
923 $wgLinkHolders['texts'][$key],
924 $wgLinkHolders['queries'][$key] );
925 } elseif ( $colours[$pdbk] == 1 ) {
926 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
927 $wgLinkHolders['texts'][$key],
928 $wgLinkHolders['queries'][$key] );
929 } elseif ( $colours[$pdbk] == 2 ) {
930 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
931 $wgLinkHolders['texts'][$key],
932 $wgLinkHolders['queries'][$key] );
935 wfProfileOut( $fname.'-construct' );
937 # Do the thing
938 wfProfileIn( $fname.'-replace' );
940 $text = preg_replace_callback(
941 '/(<!--LINK .*?-->)/',
942 "outputReplaceMatches",
943 $text);
944 wfProfileOut( $fname.'-replace' );
946 wfProfileIn( $fname.'-interwiki' );
947 global $wgInterwikiLinkHolders;
948 $outputReplace = $wgInterwikiLinkHolders;
949 $text = preg_replace_callback(
950 '/<!--IWLINK (.*?)-->/',
951 "outputReplaceMatches",
952 $text);
953 wfProfileOut( $fname.'-interwiki' );
956 wfProfileOut( $fname );
957 return $colours;
961 function &outputReplaceMatches($matches) {
962 global $outputReplace;
963 return $outputReplace[$matches[1]];