do not indent code inside the "if( defined( 'MEDIAWIKI' ) ) { }" block
[mediawiki.git] / includes / OutputPage.php
blob6e3cc1be0c15ba2127232225da011ae87147b1d8
1 <?php
3 # This is not a valid entry point, perform no further processing unless MEDIAWIKI is defined
4 if( defined( 'MEDIAWIKI' ) ) {
6 # See design.doc
8 if($wgUseTeX) require_once( 'Math.php' );
10 define( 'RLH_FOR_UPDATE', 1 );
12 class OutputPage {
13 var $mHeaders, $mCookies, $mMetatags, $mKeywords;
14 var $mLinktags, $mPagetitle, $mBodytext, $mDebugtext;
15 var $mHTMLtitle, $mRobotpolicy, $mIsarticle, $mPrintable;
16 var $mSubtitle, $mRedirect;
17 var $mLastModified, $mCategoryLinks;
18 var $mScripts, $mLinkColours;
20 var $mSuppressQuickbar;
21 var $mOnloadHandler;
22 var $mDoNothing;
23 var $mContainsOldMagic, $mContainsNewMagic;
24 var $mIsArticleRelated;
25 var $mParserOptions;
26 var $mShowFeedLinks = false;
27 var $mEnableClientCache = true;
29 function OutputPage()
31 $this->mHeaders = $this->mCookies = $this->mMetatags =
32 $this->mKeywords = $this->mLinktags = array();
33 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
34 $this->mRedirect = $this->mLastModified =
35 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
36 $this->mOnloadHandler = "";
37 $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
38 $this->mSuppressQuickbar = $this->mPrintable = false;
39 $this->mLanguageLinks = array();
40 $this->mCategoryLinks = array() ;
41 $this->mDoNothing = false;
42 $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
43 $this->mParserOptions = ParserOptions::newFromUser( $temp = NULL );
44 $this->mSquidMaxage = 0;
45 $this->mScripts = "";
48 function addHeader( $name, $val ) { array_push( $this->mHeaders, "$name: $val" ) ; }
49 function addCookie( $name, $val ) { array_push( $this->mCookies, array( $name, $val ) ); }
50 function redirect( $url, $responsecode = '302' ) { $this->mRedirect = $url; $this->mRedirectCode = $responsecode; }
52 # To add an http-equiv meta tag, precede the name with "http:"
53 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
54 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
55 function addScript( $script ) { $this->mScripts .= $script; }
56 function getScript() { return $this->mScripts; }
58 function addLink( $linkarr ) {
59 # $linkarr should be an associative array of attributes. We'll escape on output.
60 array_push( $this->mLinktags, $linkarr );
63 function addMetadataLink( $linkarr ) {
64 # note: buggy CC software only reads first "meta" link
65 static $haveMeta = false;
66 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
67 $this->addLink( $linkarr );
68 $haveMeta = true;
71 # checkLastModified tells the client to use the client-cached page if
72 # possible. If sucessful, the OutputPage is disabled so that
73 # any future call to OutputPage->output() have no effect. The method
74 # returns true iff cache-ok headers was sent.
75 function checkLastModified ( $timestamp )
77 global $wgLang, $wgCachePages, $wgUser;
78 if( !$wgCachePages ) {
79 wfDebug( "CACHE DISABLED\n", false );
80 return;
82 if( preg_match( '/MSIE ([1-4]|5\.0)/', $_SERVER["HTTP_USER_AGENT"] ) ) {
83 # IE 5.0 has probs with our caching
84 wfDebug( "-- bad client, not caching\n", false );
85 return;
87 if( $wgUser->getOption( 'nocache' ) ) {
88 wfDebug( "USER DISABLED CACHE\n", false );
89 return;
92 $lastmod = gmdate( "D, j M Y H:i:s", wfTimestamp2Unix( max( $timestamp, $wgUser->mTouched ) ) ) . " GMT";
94 if( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
95 # IE sends sizes after the date like this:
96 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
97 # this breaks strtotime().
98 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
99 $ismodsince = wfUnix2Timestamp( strtotime( $modsince ) );
100 wfDebug( "-- client send If-Modified-Since: " . $modsince . "\n", false );
101 wfDebug( "-- we might send Last-Modified : $lastmod\n", false );
103 if( ($ismodsince >= $timestamp ) and $wgUser->validateCache( $ismodsince ) ) {
104 # Make sure you're in a place you can leave when you call us!
105 header( "HTTP/1.0 304 Not Modified" );
106 $this->mLastModified = $lastmod;
107 $this->sendCacheControl();
108 wfDebug( "CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
109 $this->disable();
110 return true;
111 } else {
112 wfDebug( "READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
113 $this->mLastModified = $lastmod;
115 } else {
116 wfDebug( "We're confused.\n", false );
117 $this->mLastModified = $lastmod;
121 function getPageTitleActionText () {
122 global $action;
123 switch($action) {
124 case 'edit':
125 return wfMsg('edit');
126 case 'history':
127 return wfMsg('history_short');
128 case 'protect':
129 return wfMsg('protect');
130 case 'unprotect':
131 return wfMsg('unprotect');
132 case 'delete':
133 return wfMsg('delete');
134 case 'watch':
135 return wfMsg('watch');
136 case 'unwatch':
137 return wfMsg('unwatch');
138 case 'submit':
139 return wfMsg('preview');
140 case 'info':
141 return wfMsg('info_short');
142 default:
143 return '';
146 function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
147 function setHTMLTitle( $name ) {$this->mHTMLtitle = $name; }
148 function setPageTitle( $name ) {
149 global $action;
150 $this->mPagetitle = $name;
151 if(!empty($action)) {
152 $taction = $this->getPageTitleActionText();
153 if( !empty( $taction ) ) {
154 $name .= ' - '.$taction;
157 $this->setHTMLTitle( $name . ' - ' . wfMsg( 'wikititlesuffix' ) );
159 function getHTMLTitle() { return $this->mHTMLtitle; }
160 function getPageTitle() { return $this->mPagetitle; }
161 function setSubtitle( $str ) { $this->mSubtitle = $str; }
162 function getSubtitle() { return $this->mSubtitle; }
163 function isArticle() { return $this->mIsarticle; }
164 function setPrintable() { $this->mPrintable = true; }
165 function isPrintable() { return $this->mPrintable; }
166 function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
167 function isSyndicated() { return $this->mShowFeedLinks; }
168 function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
169 function getOnloadHandler() { return $this->mOnloadHandler; }
170 function disable() { $this->mDoNothing = true; }
172 function setArticleRelated( $v )
174 $this->mIsArticleRelated = $v;
175 if ( !$v ) {
176 $this->mIsarticle = false;
179 function setArticleFlag( $v ) {
180 $this->mIsarticle = $v;
181 if ( $v ) {
182 $this->mIsArticleRelated = $v;
186 function isArticleRelated()
188 return $this->mIsArticleRelated;
191 function getLanguageLinks() {
192 return $this->mLanguageLinks;
194 function addLanguageLinks($newLinkArray) {
195 $this->mLanguageLinks += $newLinkArray;
197 function setLanguageLinks($newLinkArray) {
198 $this->mLanguageLinks = $newLinkArray;
200 function getCategoryLinks() {
201 return $this->mCategoryLinks;
203 function addCategoryLinks($newLinkArray) {
204 $this->mCategoryLinks += $newLinkArray;
206 function setCategoryLinks($newLinkArray) {
207 $this->mCategoryLinks += $newLinkArray;
210 function suppressQuickbar() { $this->mSuppressQuickbar = true; }
211 function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
213 function addHTML( $text ) { $this->mBodytext .= $text; }
214 function debug( $text ) { $this->mDebugtext .= $text; }
216 function setParserOptions( $options )
218 return wfSetVar( $this->mParserOptions, $options );
221 # Convert wikitext to HTML and add it to the buffer
223 function addWikiText( $text, $linestart = true )
225 global $wgParser, $wgTitle;
227 $parserOutput = $wgParser->parse( $text, $wgTitle, $this->mParserOptions, $linestart );
228 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
229 $this->mCategoryLinks += $parserOutput->getCategoryLinks();
230 $this->addHTML( $parserOutput->getText() );
233 # Add wikitext to the buffer, assuming that this is the primary text for a page view
234 # Saves the text into the parser cache if possible
236 function addPrimaryWikiText( $text, $cacheArticle ) {
237 global $wgParser, $wgParserCache, $wgUser, $wgTitle;
239 $parserOutput = $wgParser->parse( $text, $wgTitle, $this->mParserOptions, true );
241 # Replace link holders
242 $text = $parserOutput->getText();
243 $this->replaceLinkHolders( $text );
244 $parserOutput->setText( $text );
246 if ( $cacheArticle ) {
247 $wgParserCache->save( $parserOutput, $cacheArticle, $wgUser );
250 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
251 $this->mCategoryLinks += $parserOutput->getCategoryLinks();
252 $this->addHTML( $text );
255 function tryParserCache( $article, $user ) {
256 global $wgParserCache;
257 $parserOutput = $wgParserCache->get( $article, $user );
258 if ( $parserOutput !== false ) {
259 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
260 $this->mCategoryLinks += $parserOutput->getCategoryLinks();
261 $this->addHTML( $parserOutput->getText() );
262 return true;
263 } else {
264 return false;
268 # Set the maximum cache time on the Squid in seconds
269 function setSquidMaxage( $maxage ) {
270 $this->mSquidMaxage = $maxage;
273 # Use enableClientCache(false) to force it to send nocache headers
274 function enableClientCache( $state ) {
275 return wfSetVar( $this->mEnableClientCache, $state );
278 function sendCacheControl() {
279 global $wgUseSquid, $wgUseESI;
280 # FIXME: This header may cause trouble with some versions of Internet Explorer
281 header( 'Vary: Accept-Encoding, Cookie' );
282 if( $this->mEnableClientCache ) {
283 if( $wgUseSquid && ! isset( $_COOKIE[ini_get( 'session.name') ] ) &&
284 ! $this->isPrintable() && $this->mSquidMaxage != 0 )
286 if ( $wgUseESI ) {
287 # We'll purge the proxy cache explicitly, but require end user agents
288 # to revalidate against the proxy on each visit.
289 # Surrogate-Control controls our Squid, Cache-Control downstream caches
290 wfDebug( "** proxy caching with ESI; {$this->mLastModified} **\n", false );
291 # start with a shorter timeout for initial testing
292 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
293 header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
294 header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
295 } else {
296 # We'll purge the proxy cache for anons explicitly, but require end user agents
297 # to revalidate against the proxy on each visit.
298 # IMPORTANT! The Squid needs to replace the Cache-Control header with
299 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
300 wfDebug( "** local proxy caching; {$this->mLastModified} **\n", false );
301 # start with a shorter timeout for initial testing
302 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
303 header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
305 } else {
306 # We do want clients to cache if they can, but they *must* check for updates
307 # on revisiting the page.
308 wfDebug( "** private caching; {$this->mLastModified} **\n", false );
309 header( "Expires: -1" );
310 header( "Cache-Control: private, must-revalidate, max-age=0" );
312 if($this->mLastModified) header( "Last-modified: {$this->mLastModified}" );
313 } else {
314 wfDebug( "** no caching **\n", false );
316 # In general, the absence of a last modified header should be enough to prevent
317 # the client from using its cache. We send a few other things just to make sure.
318 header( 'Expires: -1' );
319 header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
320 header( 'Pragma: no-cache' );
324 # Finally, all the text has been munged and accumulated into
325 # the object, let's actually output it:
327 function output()
329 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
330 global $wgInputEncoding, $wgOutputEncoding, $wgLanguageCode;
331 global $wgDebugRedirects, $wgMimeType, $wgProfiler;
332 if( $this->mDoNothing ){
333 return;
335 $fname = 'OutputPage::output';
336 wfProfileIn( $fname );
338 $sk = $wgUser->getSkin();
340 if ( '' != $this->mRedirect ) {
341 if( substr( $this->mRedirect, 0, 4 ) != 'http' ) {
342 # Standards require redirect URLs to be absolute
343 global $wgServer;
344 $this->mRedirect = $wgServer . $this->mRedirect;
346 if( $this->mRedirectCode == '301') {
347 if( !$wgDebugRedirects ) {
348 header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
350 $this->mLastModified = gmdate( 'D, j M Y H:i:s' ) . ' GMT';
353 $this->sendCacheControl();
355 if( $wgDebugRedirects ) {
356 $url = htmlspecialchars( $this->mRedirect );
357 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
358 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
359 print "</body>\n</html>\n";
360 } else {
361 header( 'Location: '.$this->mRedirect );
363 if ( isset( $wgProfiler ) ) { wfDebug( $wgProfiler->getOutput() ); }
364 return;
368 $this->sendCacheControl();
369 # Perform link colouring
370 $this->transformBuffer();
372 # Disable temporary placeholders, so that the skin produces HTML
373 $sk->postParseLinkColour( false );
375 header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
376 header( 'Content-language: '.$wgLanguageCode );
378 $exp = time() + $wgCookieExpiration;
379 foreach( $this->mCookies as $name => $val ) {
380 setcookie( $name, $val, $exp, '/' );
383 $sk->outputPage( $this );
384 # flush();
387 function out( $ins )
389 global $wgInputEncoding, $wgOutputEncoding, $wgLang;
390 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
391 $outs = $ins;
392 } else {
393 $outs = $wgLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
394 if ( false === $outs ) { $outs = $ins; }
396 print $outs;
399 function setEncodings()
401 global $wgInputEncoding, $wgOutputEncoding;
402 global $wgUser, $wgLang;
404 $wgInputEncoding = strtolower( $wgInputEncoding );
406 if( $wgUser->getOption( 'altencoding' ) ) {
407 $wgLang->setAltEncoding();
408 return;
411 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
412 $wgOutputEncoding = strtolower( $wgOutputEncoding );
413 return;
417 # This code is unused anyway!
418 # Commenting out. --bv 2003-11-15
420 $a = explode( ",", $_SERVER['HTTP_ACCEPT_CHARSET'] );
421 $best = 0.0;
422 $bestset = "*";
424 foreach ( $a as $s ) {
425 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
426 $set = $m[1];
427 $q = (float)($m[2]);
428 } else {
429 $set = $s;
430 $q = 1.0;
432 if ( $q > $best ) {
433 $bestset = $set;
434 $best = $q;
437 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
438 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
439 $wgOutputEncoding = strtolower( $bestset );
441 # Disable for now
444 $wgOutputEncoding = $wgInputEncoding;
447 # Returns a HTML comment with the elapsed time since request.
448 # This method has no side effects.
449 function reportTime()
451 global $wgRequestTime;
453 $now = wfTime();
454 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
455 $start = (float)$sec + (float)$usec;
456 $elapsed = $now - $start;
458 # Use real server name if available, so we know which machine
459 # in a server farm generated the current page.
460 if ( function_exists( 'posix_uname' ) ) {
461 $uname = @posix_uname();
462 } else {
463 $uname = false;
465 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
466 $hostname = $uname['nodename'];
467 } else {
468 # This may be a virtual server.
469 $hostname = $_SERVER['SERVER_NAME'];
471 $com = sprintf( "<!-- Served by %s in %01.2f secs. -->",
472 $hostname, $elapsed );
473 return $com;
476 # Note: these arguments are keys into wfMsg(), not text!
478 function errorpage( $title, $msg )
480 global $wgTitle;
482 $this->mDebugtext .= 'Original title: ' .
483 $wgTitle->getPrefixedText() . "\n";
484 $this->setPageTitle( wfMsg( $title ) );
485 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
486 $this->setRobotpolicy( 'noindex,nofollow' );
487 $this->setArticleRelated( false );
488 $this->enableClientCache( false );
489 $this->mRedirect = '';
491 $this->mBodytext = '';
492 $this->addHTML( '<p>' . wfMsg( $msg ) . "</p>\n" );
493 $this->returnToMain( false );
495 $this->output();
496 wfErrorExit();
499 function sysopRequired()
501 global $wgUser;
503 $this->setPageTitle( wfMsg( 'sysoptitle' ) );
504 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
505 $this->setRobotpolicy( 'noindex,nofollow' );
506 $this->setArticleRelated( false );
507 $this->mBodytext = '';
509 $sk = $wgUser->getSkin();
510 $ap = $sk->makeKnownLink( wfMsg( 'administrators' ), '' );
511 $this->addHTML( wfMsg( 'sysoptext', $ap ) );
512 $this->returnToMain();
515 function developerRequired()
517 global $wgUser;
519 $this->setPageTitle( wfMsg( 'developertitle' ) );
520 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
521 $this->setRobotpolicy( 'noindex,nofollow' );
522 $this->setArticleRelated( false );
523 $this->mBodytext = '';
525 $sk = $wgUser->getSkin();
526 $ap = $sk->makeKnownLink( wfMsg( 'administrators' ), '' );
527 $this->addHTML( wfMsg( 'developertext', $ap ) );
528 $this->returnToMain();
531 function loginToUse()
533 global $wgUser, $wgTitle, $wgLang;
535 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
536 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
537 $this->setRobotpolicy( 'noindex,nofollow' );
538 $this->setArticleFlag( false );
539 $this->mBodytext = '';
540 $this->addWikiText( wfMsg( 'loginreqtext' ) );
542 # We put a comment in the .html file so a Sysop can diagnose the page the
543 # user can't see.
544 $this->addHTML( "\n<!--" .
545 $wgLang->getNsText( $wgTitle->getNamespace() ) .
546 ':' .
547 $wgTitle->getDBkey() . '-->' );
548 $this->returnToMain(); # Flip back to the main page after 10 seconds.
551 function databaseError( $fname, $sql, $error, $errno )
553 global $wgUser, $wgCommandLineMode;
555 $this->setPageTitle( wfMsgNoDB( 'databaseerror' ) );
556 $this->setRobotpolicy( 'noindex,nofollow' );
557 $this->setArticleRelated( false );
558 $this->enableClientCache( false );
559 $this->mRedirect = '';
561 if ( $wgCommandLineMode ) {
562 $msg = wfMsgNoDB( 'dberrortextcl', htmlspecialchars( $sql ),
563 htmlspecialchars( $fname ), $errno, htmlspecialchars( $error ) );
564 } else {
565 $msg = wfMsgNoDB( 'dberrortext', htmlspecialchars( $sql ),
566 htmlspecialchars( $fname ), $errno, htmlspecialchars( $error ) );
569 if ( $wgCommandLineMode || !is_object( $wgUser )) {
570 print $msg."\n";
571 wfErrorExit();
573 $this->mBodytext = $msg;
574 $this->output();
575 wfErrorExit();
578 function readOnlyPage( $source = null, $protected = false )
580 global $wgUser, $wgReadOnlyFile;
582 $this->setRobotpolicy( 'noindex,nofollow' );
583 $this->setArticleRelated( false );
585 if( $protected ) {
586 $this->setPageTitle( wfMsg( 'viewsource' ) );
587 $this->addWikiText( wfMsg( 'protectedtext' ) );
588 } else {
589 $this->setPageTitle( wfMsg( 'readonly' ) );
590 $reason = file_get_contents( $wgReadOnlyFile );
591 $this->addWikiText( wfMsg( 'readonlytext', $reason ) );
594 if( is_string( $source ) ) {
595 if( strcmp( $source, '' ) == 0 ) {
596 $source = wfMsg( 'noarticletext' );
598 $rows = $wgUser->getOption( 'rows' );
599 $cols = $wgUser->getOption( 'cols' );
600 $text = "\n<textarea cols='$cols' rows='$rows' readonly='readonly'>" .
601 htmlspecialchars( $source ) . "\n</textarea>";
602 $this->addHTML( $text );
605 $this->returnToMain( false );
608 function fatalError( $message )
610 $this->setPageTitle( wfMsg( "internalerror" ) );
611 $this->setRobotpolicy( "noindex,nofollow" );
612 $this->setArticleRelated( false );
613 $this->enableClientCache( false );
614 $this->mRedirect = '';
616 $this->mBodytext = $message;
617 $this->output();
618 wfErrorExit();
621 function unexpectedValueError( $name, $val )
623 $this->fatalError( wfMsg( 'unexpected', $name, $val ) );
626 function fileCopyError( $old, $new )
628 $this->fatalError( wfMsg( 'filecopyerror', $old, $new ) );
631 function fileRenameError( $old, $new )
633 $this->fatalError( wfMsg( 'filerenameerror', $old, $new ) );
636 function fileDeleteError( $name )
638 $this->fatalError( wfMsg( 'filedeleteerror', $name ) );
641 function fileNotFoundError( $name )
643 $this->fatalError( wfMsg( 'filenotfound', $name ) );
646 // return from error messages or notes
647 // auto: automatically redirect the user after 10 seconds
648 // returnto: page title to return to. Default is Main Page.
649 function returnToMain( $auto = true, $returnto = NULL )
651 global $wgUser, $wgOut, $wgRequest;
653 if ( $returnto == NULL ) {
654 $returnto = $wgRequest->getText( 'returnto' );
657 $sk = $wgUser->getSkin();
658 if ( '' == $returnto ) {
659 $returnto = wfMsg( 'mainpage' );
661 $link = $sk->makeKnownLink( $returnto, '' );
663 $r = wfMsg( 'returnto', $link );
664 if ( $auto ) {
665 $titleObj = Title::newFromText( $returnto );
666 $wgOut->addMeta( 'http:Refresh', '10;url=' . $titleObj->escapeFullURL() );
668 $wgOut->addHTML( "\n<p>$r</p>\n" );
671 # This function takes the existing and broken links for the page
672 # and uses the first 10 of them for META keywords
673 function addMetaTags ()
675 global $wgLinkCache , $wgOut ;
676 $good = array_keys ( $wgLinkCache->mGoodLinks ) ;
677 $bad = array_keys ( $wgLinkCache->mBadLinks ) ;
678 $a = array_merge ( $good , $bad ) ;
679 $a = array_slice ( $a , 0 , 10 ) ; # 10 keywords max
680 $a = implode ( ',' , $a ) ;
681 $strip = array(
682 "/<.*?" . ">/" => '',
683 "/[_]/" => ' '
685 $a = htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),$a ));
687 $wgOut->addMeta ( 'KEYWORDS' , $a ) ;
690 /* private */ function headElement()
692 global $wgDocType, $wgDTD, $wgLanguageCode, $wgOutputEncoding, $wgMimeType;
693 global $wgUser, $wgLang, $wgRequest;
695 $xml = ($wgMimeType == 'text/xml');
696 if( $xml ) {
697 $ret = "<" . "?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
698 } else {
699 $ret = '';
702 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
704 if ( "" == $this->mHTMLtitle ) {
705 $this->mHTMLtitle = wfMsg( "pagetitle", $this->mPagetitle );
707 if( $xml ) {
708 $xmlbits = "xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\"";
709 } else {
710 $xmlbits = '';
712 $rtl = $wgLang->isRTL() ? " dir='RTL'" : '';
713 $ret .= "<html $xmlbits lang=\"$wgLanguageCode\" $rtl>\n";
714 $ret .= "<head>\n<title>" . htmlspecialchars( $this->mHTMLtitle ) . "</title>\n";
715 array_push( $this->mMetatags, array( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" ) );
717 $ret .= $this->getHeadLinks();
718 global $wgStylePath;
719 if( $this->isPrintable() ) {
720 $media = '';
721 } else {
722 $media = "media='print'";
724 $printsheet = htmlspecialchars( "$wgStylePath/wikiprintable.css" );
725 $ret .= "<link rel='stylesheet' type='text/css' $media href='$printsheet' />\n";
727 $sk = $wgUser->getSkin();
728 $ret .= $sk->getHeadScripts();
729 $ret .= $this->mScripts;
730 $ret .= $sk->getUserStyles();
732 $ret .= "</head>\n";
733 return $ret;
736 function getHeadLinks() {
737 global $wgRequest, $wgStylePath;
738 $ret = '';
739 foreach ( $this->mMetatags as $tag ) {
740 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
741 $a = 'http-equiv';
742 $tag[0] = substr( $tag[0], 5 );
743 } else {
744 $a = 'name';
746 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\" />\n";
748 $p = $this->mRobotpolicy;
749 if ( '' == $p ) { $p = 'index,follow'; }
750 $ret .= "<meta name=\"robots\" content=\"$p\" />\n";
752 if ( count( $this->mKeywords ) > 0 ) {
753 $strip = array(
754 "/<.*?" . ">/" => '',
755 "/[_]/" => ' '
757 $ret .= "<meta name=\"keywords\" content=\"" .
758 htmlspecialchars(preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ))) . "\" />\n";
760 foreach ( $this->mLinktags as $tag ) {
761 $ret .= '<link';
762 foreach( $tag as $attr => $val ) {
763 $ret .= " $attr=\"" . htmlspecialchars( $val ) . "\"";
765 $ret .= " />\n";
767 if( $this->isSyndicated() ) {
768 # FIXME: centralize the mime-type and name information in Feed.php
769 $link = $wgRequest->escapeAppendQuery( 'feed=rss' );
770 $ret .= "<link rel='alternate' type='application/rss+xml' title='RSS 2.0' href='$link' />\n";
771 $link = $wgRequest->escapeAppendQuery( 'feed=atom' );
772 $ret .= "<link rel='alternate' type='application/rss+atom' title='Atom 0.3' href='$link' />\n";
774 # FIXME: get these working
775 # $fix = htmlspecialchars( $wgStylePath . "/ie-png-fix.js" );
776 # $ret .= "<!--[if gte IE 5.5000]><script type='text/javascript' src='$fix'>< /script><![endif]-->";
777 return $ret;
780 # Run any necessary pre-output transformations on the buffer text
781 function transformBuffer( $options = 0 )
783 $this->replaceLinkHolders( $this->mBodytext, $options );
786 # Replace <!--LINK--> link placeholders with actual links, in the buffer
787 # Placeholders created in Skin::makeLinkObj()
788 # Returns an array of links found, indexed by PDBK:
789 # 0 - broken
790 # 1 - normal link
791 # 2 - stub
792 # $options is a bit field, RLH_FOR_UPDATE to select for update
793 function replaceLinkHolders( &$text, $options = 0 ) {
794 global $wgUser, $wgLinkCache, $wgUseOldExistenceCheck;
796 if ( $wgUseOldExistenceCheck ) {
797 return array();
800 $fname = 'OutputPage::replaceLinkHolders';
801 wfProfileIn( $fname );
803 $titles = array();
804 $pdbks = array();
805 $colours = array();
807 # Get placeholders from body
808 wfProfileIn( $fname.'-match' );
809 preg_match_all( "/<!--LINK (.*?) (.*?) (.*?) (.*?)-->/", $text, $tmpLinks );
810 wfProfileOut( $fname.'-match' );
812 if ( !empty( $tmpLinks[0] ) ) {
813 wfProfileIn( $fname.'-check' );
814 $dbr =& wfGetDB( DB_SLAVE );
815 $cur = $dbr->tableName( 'cur' );
816 $sk = $wgUser->getSkin();
817 $threshold = $wgUser->getOption('stubthreshold');
819 $namespaces =& $tmpLinks[1];
820 $dbkeys =& $tmpLinks[2];
821 $queries =& $tmpLinks[3];
822 $texts =& $tmpLinks[4];
824 # Sort by namespace
825 asort( $namespaces );
827 # Generate query
828 $query = false;
829 foreach ( $namespaces as $key => $val ) {
830 # Make title object
831 $dbk = $dbkeys[$key];
832 $title = $titles[$key] = Title::makeTitleSafe( $val, $dbk );
834 # Skip invalid entries.
835 # Result will be ugly, but prevents crash.
836 if ( is_null( $title ) ) {
837 continue;
839 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
841 # Check if it's in the link cache already
842 if ( $wgLinkCache->getGoodLinkID( $pdbk ) ) {
843 $colours[$pdbk] = 1;
844 } elseif ( $wgLinkCache->isBadLink( $pdbk ) ) {
845 $colours[$pdbk] = 0;
846 } else {
847 # Not in the link cache, add it to the query
848 if ( !isset( $current ) ) {
849 $current = $val;
850 $query = "SELECT cur_id, cur_namespace, cur_title";
851 if ( $threshold > 0 ) {
852 $query .= ", LENGTH(cur_text) AS cur_len, cur_is_redirect";
854 $query .= " FROM $cur WHERE (cur_namespace=$val AND cur_title IN(";
855 } elseif ( $current != $val ) {
856 $current = $val;
857 $query .= ")) OR (cur_namespace=$val AND cur_title IN(";
858 } else {
859 $query .= ', ';
862 $query .= $dbr->addQuotes( $dbkeys[$key] );
865 if ( $query ) {
866 $query .= '))';
867 if ( $options & RLH_FOR_UPDATE ) {
868 $query .= ' FOR UPDATE';
871 $res = $dbr->query( $query, $fname );
873 # Fetch data and form into an associative array
874 # non-existent = broken
875 # 1 = known
876 # 2 = stub
877 while ( $s = $dbr->fetchObject($res) ) {
878 $title = Title::makeTitle( $s->cur_namespace, $s->cur_title );
879 $pdbk = $title->getPrefixedDBkey();
880 $wgLinkCache->addGoodLink( $s->cur_id, $pdbk );
882 if ( $threshold > 0 ) {
883 $size = $s->cur_len;
884 if ( $s->cur_is_redirect || $s->cur_namespace != 0 || $length < $threshold ) {
885 $colours[$pdbk] = 1;
886 } else {
887 $colours[$pdbk] = 2;
889 } else {
890 $colours[$pdbk] = 1;
894 wfProfileOut( $fname.'-check' );
896 # Construct search and replace arrays
897 wfProfileIn( $fname.'-construct' );
898 global $outputReplace;
899 $outputReplace = array();
900 foreach ( $namespaces as $key => $ns ) {
901 $pdbk = $pdbks[$key];
902 $searchkey = $tmpLinks[0][$key];
903 $title = $titles[$key];
904 if ( empty( $colours[$pdbk] ) ) {
905 $wgLinkCache->addBadLink( $pdbk );
906 $colours[$pdbk] = 0;
907 $outputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title, $texts[$key], $queries[$key] );
908 } elseif ( $colours[$pdbk] == 1 ) {
909 $outputReplace[$searchkey] = $sk->makeKnownLinkObj( $title, $texts[$key], $queries[$key] );
910 } elseif ( $colours[$pdbk] == 2 ) {
911 $outputReplace[$searchkey] = $sk->makeStubLinkObj( $title, $texts[$key], $queries[$key] );
914 wfProfileOut( $fname.'-construct' );
916 # Do the thing
917 wfProfileIn( $fname.'-replace' );
919 $text = preg_replace_callback(
920 '/(<!--LINK .*? .*? .*? .*?-->)/',
921 "outputReplaceMatches",
922 $text);
923 wfProfileOut( $fname.'-replace' );
925 wfProfileOut( $fname );
926 return $colours;
930 function &outputReplaceMatches($matches) {
931 global $outputReplace;
932 return $outputReplace[$matches[1]];