same minor typo as in LocalSettings (in example config url)
[mediawiki.git] / includes / OutputPage.php
blob03c50c9bd48e3395c92177f6c386d53077ea5576
1 <?
2 # See design.doc
4 if($wgUseTeX) include_once( "Math.php" );
6 class OutputPage {
7 var $mHeaders, $mCookies, $mMetatags, $mKeywords;
8 var $mLinktags, $mPagetitle, $mBodytext, $mDebugtext;
9 var $mHTMLtitle, $mRobotpolicy, $mIsarticle, $mPrintable;
10 var $mSubtitle, $mRedirect, $mAutonumber, $mHeadtext;
11 var $mLastModified, $mCategoryLinks;
13 var $mDTopen, $mLastSection; # Used for processing DL, PRE
14 var $mLanguageLinks, $mSupressQuickbar;
15 var $mOnloadHandler;
16 var $mDoNothing;
17 var $mContainsOldMagic, $mContainsNewMagic;
18 var $mIsArticleRelated;
20 function OutputPage()
22 $this->mHeaders = $this->mCookies = $this->mMetatags =
23 $this->mKeywords = $this->mLinktags = array();
24 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
25 $this->mLastSection = $this->mRedirect = $this->mLastModified =
26 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy =
27 $this->mOnloadHandler = "";
28 $this->mIsArticleRelated = $this->mIsarticle = $this->mPrintable = true;
29 $this->mSupressQuickbar = $this->mDTopen = $this->mPrintable = false;
30 $this->mLanguageLinks = array();
31 $this->mCategoryLinks = array() ;
32 $this->mAutonumber = 0;
33 $this->mDoNothing = false;
34 $this->mContainsOldMagic = $this->mContainsNewMagic = 0;
37 function addHeader( $name, $val ) { array_push( $this->mHeaders, "$name: $val" ) ; }
38 function addCookie( $name, $val ) { array_push( $this->mCookies, array( $name, $val ) ); }
39 function redirect( $url ) { $this->mRedirect = $url; }
41 # To add an http-equiv meta tag, precede the name with "http:"
42 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
43 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
44 function addLink( $rel, $rev, $target ) { array_push( $this->mLinktags, array( $rel, $rev, $target ) ); }
46 # checkLastModified tells the client to use the client-cached page if
47 # possible. If sucessful, the OutputPage is disabled so that
48 # any future call to OutputPage->output() have no effect. The method
49 # returns true iff cache-ok headers was sent.
50 function checkLastModified ( $timestamp )
52 global $wgLang, $wgCachePages, $wgUser;
53 if( !$wgCachePages ) {
54 wfDebug( "CACHE DISABLED\n", false );
55 return;
57 if( preg_match( '/MSIE ([1-4]|5\.0)/', $_SERVER["HTTP_USER_AGENT"] ) ) {
58 # IE 5.0 has probs with our caching
59 wfDebug( "-- bad client, not caching\n", false );
60 return;
62 if( $wgUser->getOption( "nocache" ) ) {
63 wfDebug( "USER DISABLED CACHE\n", false );
64 return;
67 $this->sendCacheControl();
69 $lastmod = gmdate( "D, j M Y H:i:s", wfTimestamp2Unix(
70 max( $timestamp, $wgUser->mTouched ) ) ) . " GMT";
72 if( !empty( $_SERVER["HTTP_IF_MODIFIED_SINCE"] ) ) {
73 # IE sends sizes after the date like this:
74 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
75 # this breaks strtotime().
76 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
77 $ismodsince = wfUnix2Timestamp( strtotime( $modsince ) );
78 wfDebug( "-- client send If-Modified-Since: " . $modsince . "\n", false );
79 wfDebug( "-- we might send Last-Modified : $lastmod\n", false );
81 if( ($ismodsince >= $timestamp ) and $wgUser->validateCache( $ismodsince ) ) {
82 # Make sure you're in a place you can leave when you call us!
83 header( "HTTP/1.0 304 Not Modified" );
84 header( "Last-Modified: {$lastmod}" );
85 wfDebug( "CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
86 $this->disable();
87 return true;
88 } else {
89 wfDebug( "READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
90 $this->mLastModified = $lastmod;
92 } else {
93 wfDebug( "We're confused.\n", false );
94 $this->mLastModified = $lastmod;
98 function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
99 function setHTMLtitle( $name ) { $this->mHTMLtitle = $name; }
100 function setPageTitle( $name ) { $this->mPagetitle = $name; }
101 function getPageTitle() { return $this->mPagetitle; }
102 function setSubtitle( $str ) { $this->mSubtitle = $str; }
103 function getSubtitle() { return $this->mSubtitle; }
104 function isArticle() { return $this->mIsarticle; }
105 function setPrintable() { $this->mPrintable = true; }
106 function isPrintable() { return $this->mPrintable; }
107 function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
108 function getOnloadHandler() { return $this->mOnloadHandler; }
109 function disable() { $this->mDoNothing = true; }
111 function setArticleRelated( $v )
113 $this->mIsArticleRelated = $v;
114 if ( !$v ) {
115 $this->mIsarticle = false;
118 function setArticleFlag( $v ) {
119 $this->mIsarticle = $v;
120 if ( $v ) {
121 $this->mIsArticleRelated = $v;
125 function isArticleRelated()
127 return $this->mIsArticleRelated;
130 function getLanguageLinks() {
131 global $wgTitle, $wgLanguageCode;
132 global $wgDBconnection, $wgDBname;
133 return $this->mLanguageLinks;
135 function supressQuickbar() { $this->mSupressQuickbar = true; }
136 function isQuickbarSupressed() { return $this->mSupressQuickbar; }
138 function addHTML( $text ) { $this->mBodytext .= $text; }
139 function addHeadtext( $text ) { $this->mHeadtext .= $text; }
140 function debug( $text ) { $this->mDebugtext .= $text; }
142 # First pass--just handle <nowiki> sections, pass the rest off
143 # to doWikiPass2() which does all the real work.
145 function addWikiText( $text, $linestart = true )
147 global $wgUseTeX, $wgArticle, $wgUser, $action;
148 $fname = "OutputPage::addWikiText";
149 wfProfileIn( $fname );
150 $unique = "3iyZiyA7iMwg5rhxP0Dcc9oTnj8qD1jm1Sfv4";
151 $unique2 = "4LIQ9nXtiYFPCSfitVwDw7EYwQlL4GeeQ7qSO";
152 $unique3 = "fPaA8gDfdLBqzj68Yjg9Hil3qEF8JGO0uszIp";
153 $nwlist = array();
154 $nwsecs = 0;
155 $mathlist = array();
156 $mathsecs = 0;
157 $prelist = array ();
158 $presecs = 0;
159 $stripped = "";
160 $stripped2 = "";
161 $stripped3 = "";
163 # Replace any instances of the placeholders
164 $text = str_replace( $unique, wfHtmlEscapeFirst( $unique ), $text );
165 $text = str_replace( $unique2, wfHtmlEscapeFirst( $unique2 ), $text );
166 $text = str_replace( $unique3, wfHtmlEscapeFirst( $unique3 ), $text );
168 global $wgEnableParserCache;
169 $use_parser_cache =
170 $wgEnableParserCache && $action == "view" &&
171 intval($wgUser->getOption( "stubthreshold" )) == 0 &&
172 isset($wgArticle) && $wgArticle->getID() > 0;
174 if( $use_parser_cache ){
175 if( $this->fillFromParserCache() ){
176 wfProfileOut( $fname );
177 return;
181 while ( "" != $text ) {
182 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
183 $stripped .= $p[0];
184 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
185 else {
186 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
187 ++$nwsecs;
188 $nwlist[$nwsecs] = wfEscapeHTMLTagsOnly($q[0]);
189 $stripped .= $unique . $nwsecs . "s";
190 $text = $q[1];
194 if( $wgUseTeX ) {
195 while ( "" != $stripped ) {
196 $p = preg_split( "/<\\s*math\\s*>/i", $stripped, 2 );
197 $stripped2 .= $p[0];
198 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped = ""; }
199 else {
200 $q = preg_split( "/<\\/\\s*math\\s*>/i", $p[1], 2 );
201 ++$mathsecs;
202 $mathlist[$mathsecs] = renderMath($q[0]);
203 $stripped2 .= $unique2 . $mathsecs . "s";
204 $stripped = $q[1];
207 } else {
208 $stripped2 = $stripped;
211 while ( "" != $stripped2 ) {
212 $p = preg_split( "/<\\s*pre\\s*>/i", $stripped2, 2 );
213 $stripped3 .= $p[0];
214 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped2 = ""; }
215 else {
216 $q = preg_split( "/<\\/\\s*pre\\s*>/i", $p[1], 2 );
217 ++$presecs;
218 $prelist[$presecs] = "<pre>". wfEscapeHTMLTagsOnly($q[0]). "</pre>\n";
219 $stripped3 .= $unique3 . $presecs . "s";
220 $stripped2 = $q[1];
224 $text = $this->doWikiPass2( $stripped3, $linestart );
226 $specialChars = array("\\", "$");
227 $escapedChars = array("\\\\", "\\$");
228 for ( $i = 1; $i <= $presecs; ++$i ) {
229 $text = preg_replace( "/{$unique3}{$i}s/", str_replace( $specialChars,
230 $escapedChars, $prelist[$i] ), $text );
233 for ( $i = 1; $i <= $mathsecs; ++$i ) {
234 $text = preg_replace( "/{$unique2}{$i}s/", str_replace( $specialChars,
235 $escapedChars, $mathlist[$i] ), $text );
238 for ( $i = 1; $i <= $nwsecs; ++$i ) {
239 $text = preg_replace( "/{$unique}{$i}s/", str_replace( $specialChars,
240 $escapedChars, $nwlist[$i] ), $text );
242 $this->addHTML( $text );
244 if($use_parser_cache ){
245 $this->saveParserCache( $text );
247 wfProfileOut( $fname );
250 function sendCacheControl() {
251 header( "Vary: Accept-Encoding, Cookie" );
252 if( $this->mLastModified != "" ) {
253 wfDebug( "** private caching; {$this->mLastModified} **\n", false );
254 if (isset($_COOKIE[ini_get("session.name")] )){
255 header( "Cache-Control: no-cache, must-revalidate, max-age=0" );
256 } else {
257 header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
259 header( "Last-modified: {$this->mLastModified}" );
260 } else {
261 wfDebug( "** no caching **\n", false );
262 header( "Cache-Control: no-cache" ); # Experimental - see below
263 header( "Pragma: no-cache" );
264 header( "Last-modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
268 # Finally, all the text has been munged and accumulated into
269 # the object, let's actually output it:
271 function output()
273 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
274 global $wgInputEncoding, $wgOutputEncoding, $wgLanguageCode;
275 if( $this->mDoNothing ){
276 return;
278 $fname = "OutputPage::output";
279 wfProfileIn( $fname );
281 $sk = $wgUser->getSkin();
283 $this->sendCacheControl();
285 header( "Content-type: text/html; charset={$wgOutputEncoding}" );
286 header( "Content-language: {$wgLanguageCode}" );
288 if ( "" != $this->mRedirect ) {
289 if( substr( $this->mRedirect, 0, 4 ) != "http" ) {
290 # Standards require redirect URLs to be absolute
291 global $wgServer;
292 $this->mRedirect = $wgServer . $this->mRedirect;
294 header( "Location: {$this->mRedirect}" );
295 return;
298 $exp = time() + $wgCookieExpiration;
299 foreach( $this->mCookies as $name => $val ) {
300 setcookie( $name, $val, $exp, "/" );
303 $sk->outputPage( $this );
304 # flush();
307 function out( $ins )
309 global $wgInputEncoding, $wgOutputEncoding, $wgLang;
310 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
311 $outs = $ins;
312 } else {
313 $outs = $wgLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
314 if ( false === $outs ) { $outs = $ins; }
316 print $outs;
319 function setEncodings()
321 global $wgInputEncoding, $wgOutputEncoding;
322 global $wgUser, $wgLang;
324 $wgInputEncoding = strtolower( $wgInputEncoding );
326 if( $wgUser->getOption( 'altencoding' ) ) {
327 $wgLang->setAltEncoding();
328 return;
331 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
332 $wgOutputEncoding = strtolower( $wgOutputEncoding );
333 return;
337 # This code is unused anyway!
338 # Commenting out. --bv 2003-11-15
340 $a = explode( ",", $_SERVER['HTTP_ACCEPT_CHARSET'] );
341 $best = 0.0;
342 $bestset = "*";
344 foreach ( $a as $s ) {
345 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
346 $set = $m[1];
347 $q = (float)($m[2]);
348 } else {
349 $set = $s;
350 $q = 1.0;
352 if ( $q > $best ) {
353 $bestset = $set;
354 $best = $q;
357 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
358 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
359 $wgOutputEncoding = strtolower( $bestset );
361 # Disable for now
364 $wgOutputEncoding = $wgInputEncoding;
367 # Returns a HTML comment with the elapsed time since request.
368 # This method has no side effects.
369 function reportTime()
371 global $wgRequestTime;
373 list( $usec, $sec ) = explode( " ", microtime() );
374 $now = (float)$sec + (float)$usec;
376 list( $usec, $sec ) = explode( " ", $wgRequestTime );
377 $start = (float)$sec + (float)$usec;
378 $elapsed = $now - $start;
379 $com = sprintf( "<!-- Time since request: %01.2f secs. -->",
380 $elapsed );
381 return $com;
384 # Note: these arguments are keys into wfMsg(), not text!
386 function errorpage( $title, $msg )
388 global $wgTitle;
390 $this->mDebugtext .= "Original title: " .
391 $wgTitle->getPrefixedText() . "\n";
392 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
393 $this->setPageTitle( wfMsg( $title ) );
394 $this->setRobotpolicy( "noindex,nofollow" );
395 $this->setArticleRelated( false );
397 $this->mBodytext = "";
398 $this->addHTML( "<p>" . wfMsg( $msg ) . "\n" );
399 $this->returnToMain( false );
401 $this->output();
402 wfAbruptExit();
405 function sysopRequired()
407 global $wgUser;
409 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
410 $this->setPageTitle( wfMsg( "sysoptitle" ) );
411 $this->setRobotpolicy( "noindex,nofollow" );
412 $this->setArticleRelated( false );
413 $this->mBodytext = "";
415 $sk = $wgUser->getSkin();
416 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
417 $this->addHTML( wfMsg( "sysoptext", $ap ) );
418 $this->returnToMain();
421 function developerRequired()
423 global $wgUser;
425 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
426 $this->setPageTitle( wfMsg( "developertitle" ) );
427 $this->setRobotpolicy( "noindex,nofollow" );
428 $this->setArticleRelated( false );
429 $this->mBodytext = "";
431 $sk = $wgUser->getSkin();
432 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
433 $this->addHTML( wfMsg( "developertext", $ap ) );
434 $this->returnToMain();
437 function databaseError( $fname )
439 global $wgUser, $wgCommandLineMode;
441 $this->setPageTitle( wfMsgNoDB( "databaseerror" ) );
442 $this->setRobotpolicy( "noindex,nofollow" );
443 $this->setArticleRelated( false );
445 if ( $wgCommandLineMode ) {
446 $msg = wfMsgNoDB( "dberrortextcl" );
447 } else {
448 $msg = wfMsgNoDB( "dberrortext" );
451 $msg = str_replace( "$1", htmlspecialchars( wfLastDBquery() ), $msg );
452 $msg = str_replace( "$2", htmlspecialchars( $fname ), $msg );
453 $msg = str_replace( "$3", wfLastErrno(), $msg );
454 $msg = str_replace( "$4", htmlspecialchars( wfLastError() ), $msg );
456 if ( $wgCommandLineMode || !is_object( $wgUser )) {
457 print "$msg\n";
458 wfAbruptExit();
460 $sk = $wgUser->getSkin();
461 $shlink = $sk->makeKnownLink( wfMsgNoDB( "searchhelppage" ),
462 wfMsgNoDB( "searchingwikipedia" ) );
463 $msg = str_replace( "$5", $shlink, $msg );
464 $this->mBodytext = $msg;
465 $this->output();
466 wfAbruptExit();
469 function readOnlyPage( $source = "", $protected = false )
471 global $wgUser, $wgReadOnlyFile;
473 $this->setRobotpolicy( "noindex,nofollow" );
474 $this->setArticleRelated( false );
476 if( $protected ) {
477 $this->setPageTitle( wfMsg( "viewsource" ) );
478 $this->addWikiText( wfMsg( "protectedtext" ) );
479 } else {
480 $this->setPageTitle( wfMsg( "readonly" ) );
481 $reason = file_get_contents( $wgReadOnlyFile );
482 $this->addHTML( wfMsg( "readonlytext", $reason ) );
485 if($source) {
486 $rows = $wgUser->getOption( "rows" );
487 $cols = $wgUser->getOption( "cols" );
488 $text .= "</p>\n<textarea cols='$cols' rows='$rows' readonly>" .
489 htmlspecialchars( $source ) . "\n</textarea>";
490 $this->addHTML( $text );
493 $this->returnToMain( false );
496 function fatalError( $message )
498 $this->setPageTitle( wfMsg( "internalerror" ) );
499 $this->setRobotpolicy( "noindex,nofollow" );
500 $this->setArticleRelated( false );
502 $this->mBodytext = $message;
503 $this->output();
504 wfAbruptExit();
507 function unexpectedValueError( $name, $val )
509 $this->fatalError( wfMsg( "unexpected", $name, $val ) );
512 function fileCopyError( $old, $new )
514 $this->fatalError( wfMsg( "filecopyerror", $old, $new ) );
517 function fileRenameError( $old, $new )
519 $this->fatalError( wfMsg( "filerenameerror", $old, $new ) );
522 function fileDeleteError( $name )
524 $this->fatalError( wfMsg( "filedeleteerror", $name ) );
527 function fileNotFoundError( $name )
529 $this->fatalError( wfMsg( "filenotfound", $name ) );
532 function returnToMain( $auto = true )
534 global $wgUser, $wgOut, $returnto;
536 $sk = $wgUser->getSkin();
537 if ( "" == $returnto ) {
538 $returnto = wfMsg( "mainpage" );
540 $link = $sk->makeKnownLink( $returnto, "" );
542 $r = wfMsg( "returnto", $link );
543 if ( $auto ) {
544 $wgOut->addMeta( "http:Refresh", "10;url=" .
545 wfLocalUrlE( wfUrlencode( $returnto ) ) );
547 $wgOut->addHTML( "\n<p>$r\n" );
551 function categoryMagic ()
553 global $wgTitle , $wgUseCategoryMagic ;
554 if ( !isset ( $wgUseCategoryMagic ) || !$wgUseCategoryMagic ) return ;
555 $id = $wgTitle->getArticleID() ;
556 $cat = ucfirst ( wfMsg ( "category" ) ) ;
557 $ti = $wgTitle->getText() ;
558 $ti = explode ( ":" , $ti , 2 ) ;
559 if ( $cat != $ti[0] ) return "" ;
560 $r = "<br break=all>\n" ;
562 $articles = array() ;
563 $parents = array () ;
564 $children = array() ;
567 global $wgUser ;
568 $sk = $wgUser->getSkin() ;
569 $sql = "SELECT l_from FROM links WHERE l_to={$id}" ;
570 $res = wfQuery ( $sql, DB_READ ) ;
571 while ( $x = wfFetchObject ( $res ) )
573 # $t = new Title ;
574 # $t->newFromDBkey ( $x->l_from ) ;
575 # $t = $t->getText() ;
576 $t = $x->l_from ;
577 $y = explode ( ":" , $t , 2 ) ;
578 if ( count ( $y ) == 2 && $y[0] == $cat ) {
579 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
580 } else {
581 array_push ( $articles , $sk->makeLink ( $t ) ) ;
584 wfFreeResult ( $res ) ;
586 # Children
587 if ( count ( $children ) > 0 )
589 asort ( $children ) ;
590 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
591 $r .= implode ( ", " , $children ) ;
594 # Articles
595 if ( count ( $articles ) > 0 )
597 asort ( $articles ) ;
598 $h = wfMsg( "category_header", $ti[1] );
599 $r .= "<h2>{$h}</h2>\n" ;
600 $r .= implode ( ", " , $articles ) ;
604 return $r ;
607 function getHTMLattrs ()
609 $htmlattrs = array( # Allowed attributes--no scripting, etc.
610 "title", "align", "lang", "dir", "width", "height",
611 "bgcolor", "clear", /* BR */ "noshade", /* HR */
612 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
613 /* FONT */ "type", "start", "value", "compact",
614 /* For various lists, mostly deprecated but safe */
615 "summary", "width", "border", "frame", "rules",
616 "cellspacing", "cellpadding", "valign", "char",
617 "charoff", "colgroup", "col", "span", "abbr", "axis",
618 "headers", "scope", "rowspan", "colspan", /* Tables */
619 "id", "class", "name", "style" /* For CSS */
621 return $htmlattrs ;
624 function fixTagAttributes ( $t )
626 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
627 $htmlattrs = $this->getHTMLattrs() ;
629 # Strip non-approved attributes from the tag
630 $t = preg_replace(
631 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
632 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
633 $t);
634 # Strip javascript "expression" from stylesheets. Brute force approach:
635 # If anythin offensive is found, all attributes of the HTML tag are dropped
637 if( preg_match(
638 "/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is",
639 wfMungeToUtf8( $t ) ) )
641 $t="";
644 return trim ( $t ) ;
647 function doTableStuff ( $t )
649 $t = explode ( "\n" , $t ) ;
650 $td = array () ; # Is currently a td tag open?
651 $ltd = array () ; # Was it TD or TH?
652 $tr = array () ; # Is currently a tr tag open?
653 $ltr = array () ; # tr attributes
654 foreach ( $t AS $k => $x )
656 $x = rtrim ( $x ) ;
657 $fc = substr ( $x , 0 , 1 ) ;
658 if ( "{|" == substr ( $x , 0 , 2 ) )
660 $t[$k] = "<table " . $this->fixTagAttributes ( substr ( $x , 3 ) ) . ">" ;
661 array_push ( $td , false ) ;
662 array_push ( $ltd , "" ) ;
663 array_push ( $tr , false ) ;
664 array_push ( $ltr , "" ) ;
666 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
667 else if ( "|}" == substr ( $x , 0 , 2 ) )
669 $z = "</table>\n" ;
670 $l = array_pop ( $ltd ) ;
671 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
672 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
673 array_pop ( $ltr ) ;
674 $t[$k] = $z ;
676 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
678 $z = trim ( substr ( $x , 2 ) ) ;
679 $t[$k] = "<caption>{$z}</caption>\n" ;
681 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
683 $x = substr ( $x , 1 ) ;
684 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
685 $z = "" ;
686 $l = array_pop ( $ltd ) ;
687 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
688 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
689 array_pop ( $ltr ) ;
690 $t[$k] = $z ;
691 array_push ( $tr , false ) ;
692 array_push ( $td , false ) ;
693 array_push ( $ltd , "" ) ;
694 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
696 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
698 if ( "|+" == substr ( $x , 0 , 2 ) )
700 $fc = "+" ;
701 $x = substr ( $x , 1 ) ;
703 $after = substr ( $x , 1 ) ;
704 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
705 $after = explode ( "||" , $after ) ;
706 $t[$k] = "" ;
707 foreach ( $after AS $theline )
709 $z = "" ;
710 $tra = array_pop ( $ltr ) ;
711 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
712 array_push ( $tr , true ) ;
713 array_push ( $ltr , "" ) ;
715 $l = array_pop ( $ltd ) ;
716 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
717 if ( $fc == "|" ) $l = "TD" ;
718 else if ( $fc == "!" ) $l = "TH" ;
719 else if ( $fc == "+" ) $l = "CAPTION" ;
720 else $l = "" ;
721 array_push ( $ltd , $l ) ;
722 $y = explode ( "|" , $theline , 2 ) ;
723 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
724 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
725 $t[$k] .= $y ;
726 array_push ( $td , true ) ;
731 # Closing open td, tr && table
732 while ( count ( $td ) > 0 )
734 if ( array_pop ( $td ) ) $t[] = "</td>" ;
735 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
736 $t[] = "</table>" ;
739 $t = implode ( "\n" , $t ) ;
740 # $t = $this->removeHTMLtags( $t );
741 return $t ;
744 # Well, OK, it's actually about 14 passes. But since all the
745 # hard lifting is done inside PHP's regex code, it probably
746 # wouldn't speed things up much to add a real parser.
748 function doWikiPass2( $text, $linestart )
750 global $wgUser, $wgLang, $wgUseDynamicDates;
751 $fname = "OutputPage::doWikiPass2";
752 wfProfileIn( $fname );
754 $text = $this->removeHTMLtags( $text );
755 $text = $this->replaceVariables( $text );
757 $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
758 $text = str_replace ( "<HR>", "<hr>", $text );
760 $text = $this->doAllQuotes( $text );
761 $text = $this->doHeadings( $text );
762 $text = $this->doBlockLevels( $text, $linestart );
764 if($wgUseDynamicDates) {
765 global $wgDateFormatter;
766 $text = $wgDateFormatter->reformat( $wgUser->getOption("date"), $text );
769 $text = $this->replaceExternalLinks( $text );
770 $text = $this->replaceInternalLinks ( $text );
771 $text = $this->doTableStuff ( $text ) ;
773 $text = $this->magicISBN( $text );
774 $text = $this->magicRFC( $text );
775 $text = $this->formatHeadings( $text );
777 $sk = $wgUser->getSkin();
778 $text = $sk->transformContent( $text );
779 $text .= $this->categoryMagic () ;
781 wfProfileOut( $fname );
782 return $text;
785 /* private */ function doAllQuotes( $text )
787 $outtext = "";
788 $lines = explode( "\r\n", $text );
789 foreach ( $lines as $line ) {
790 $outtext .= $this->doQuotes ( "", $line, "" ) . "\r\n";
792 return $outtext;
795 /* private */ function doQuotes( $pre, $text, $mode )
797 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
798 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
799 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
800 if ( substr ($m[2], 0, 1) == "'" ) {
801 $m[2] = substr ($m[2], 1);
802 if ($mode == "em") {
803 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "emstrong" );
804 } else if ($mode == "strong") {
805 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
806 } else if (($mode == "emstrong") || ($mode == "both")) {
807 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
808 } else if ($mode == "strongem") {
809 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
810 } else {
811 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
813 } else {
814 if ($mode == "strong") {
815 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "strongem" );
816 } else if ($mode == "em") {
817 return $m1_em . $this->doQuotes ( "", $m[2], "" );
818 } else if ($mode == "emstrong") {
819 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
820 } else if (($mode == "strongem") || ($mode == "both")) {
821 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
822 } else {
823 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
826 } else {
827 $text_strong = ($text == "") ? "" : "<strong>{$text}</strong>";
828 $text_em = ($text == "") ? "" : "<em>{$text}</em>";
829 if ($mode == "") {
830 return $pre . $text;
831 } else if ($mode == "em") {
832 return $pre . $text_em;
833 } else if ($mode == "strong") {
834 return $pre . $text_strong;
835 } else if ($mode == "strongem") {
836 return (($pre == "") && ($text == "")) ? "" : "<strong>{$pre}{$text_em}</strong>";
837 } else {
838 return (($pre == "") && ($text == "")) ? "" : "<em>{$pre}{$text_strong}</em>";
843 /* private */ function doHeadings( $text )
845 for ( $i = 6; $i >= 1; --$i ) {
846 $h = substr( "======", 0, $i );
847 $text = preg_replace( "/^{$h}([^=]+){$h}(\\s|$)/m",
848 "<h{$i}>\\1</h{$i}>\\2", $text );
850 return $text;
853 # Note: we have to do external links before the internal ones,
854 # and otherwise take great care in the order of things here, so
855 # that we don't end up interpreting some URLs twice.
857 /* private */ function replaceExternalLinks( $text )
859 $fname = "OutputPage::replaceExternalLinks";
860 wfProfileIn( $fname );
861 $text = $this->subReplaceExternalLinks( $text, "http", true );
862 $text = $this->subReplaceExternalLinks( $text, "https", true );
863 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
864 $text = $this->subReplaceExternalLinks( $text, "irc", false );
865 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
866 $text = $this->subReplaceExternalLinks( $text, "news", false );
867 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
868 wfProfileOut( $fname );
869 return $text;
872 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
874 global $wgUser, $printable;
875 global $wgAllowExternalImages;
878 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
879 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
881 # this is the list of separators that should be ignored if they
882 # are the last character of an URL but that should be included
883 # if they occur within the URL, e.g. "go to www.foo.com, where .."
884 # in this case, the last comma should not become part of the URL,
885 # but in "www.foo.com/123,2342,32.htm" it should.
886 $sep = ",;\.:";
887 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
888 $images = "gif|png|jpg|jpeg";
890 # PLEASE NOTE: The curly braces { } are not part of the regex,
891 # they are interpreted as part of the string (used to tell PHP
892 # that the content of the string should be inserted there).
893 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
894 "((?i){$images})([^{$uc}]|$)/";
896 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
897 $sk = $wgUser->getSkin();
899 if ( $autonumber and $wgAllowExternalImages) { # Use img tags only for HTTP urls
900 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
901 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
903 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
904 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
905 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
906 "</a>\\5", $s );
907 $s = str_replace( $unique, $protocol, $s );
909 $a = explode( "[{$protocol}:", " " . $s );
910 $s = array_shift( $a );
911 $s = substr( $s, 1 );
913 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
914 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
916 foreach ( $a as $line ) {
917 if ( preg_match( $e1, $line, $m ) ) {
918 $link = "{$protocol}:{$m[1]}";
919 $trail = $m[2];
920 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
921 else { $text = wfEscapeHTML( $link ); }
922 } else if ( preg_match( $e2, $line, $m ) ) {
923 $link = "{$protocol}:{$m[1]}";
924 $text = $m[2];
925 $trail = $m[3];
926 } else {
927 $s .= "[{$protocol}:" . $line;
928 continue;
930 if ( $printable == "yes") $paren = " (<i>" . htmlspecialchars ( $link ) . "</i>)";
931 else $paren = "";
932 $la = $sk->getExternalLinkAttributes( $link, $text );
933 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
936 return $s;
939 /* private */ function replaceInternalLinks( $s )
941 global $wgTitle, $wgUser, $wgLang;
942 global $wgLinkCache, $wgInterwikiMagic, $wgUseCategoryMagic;
943 global $wgNamespacesWithSubpages, $wgLanguageCode;
944 wfProfileIn( $fname = "OutputPage::replaceInternalLinks" );
946 wfProfileIn( "$fname-setup" );
947 $tc = Title::legalChars() . "#";
948 $sk = $wgUser->getSkin();
950 $a = explode( "[[", " " . $s );
951 $s = array_shift( $a );
952 $s = substr( $s, 1 );
954 $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD";
956 # Special and Media are pseudo-namespaces; no pages actually exist in them
957 $image = Namespace::getImage();
958 $special = Namespace::getSpecial();
959 $media = Namespace::getMedia();
960 $nottalk = !Namespace::isTalk( $wgTitle->getNamespace() );
961 wfProfileOut( "$fname-setup" );
963 foreach ( $a as $line ) {
964 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
965 $text = $m[2];
966 $trail = $m[3];
967 } else { # Invalid form; output directly
968 $s .= "[[" . $line ;
969 continue;
972 /* Valid link forms:
973 Foobar -- normal
974 :Foobar -- override special treatment of prefix (images, language links)
975 /Foobar -- convert to CurrentPage/Foobar
976 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
978 $c = substr($m[1],0,1);
979 $noforce = ($c != ":");
980 if( $c == "/" ) { # subpage
981 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
982 $m[1]=substr($m[1],1,strlen($m[1])-2);
983 $noslash=$m[1];
984 } else {
985 $noslash=substr($m[1],1);
987 if($wgNamespacesWithSubpages[$wgTitle->getNamespace()]) { # subpages allowed here
988 $link = $wgTitle->getPrefixedText(). "/" . trim($noslash);
989 if( "" == $text ) {
990 $text= $m[1];
991 } # this might be changed for ugliness reasons
992 } else {
993 $link = $noslash; # no subpage allowed, use standard link
995 } elseif( $noforce ) { # no subpage
996 $link = $m[1];
997 } else {
998 $link = substr( $m[1], 1 );
1000 if( "" == $text )
1001 $text = $link;
1003 $nt = Title::newFromText( $link );
1004 if( !$nt ) {
1005 $s .= "[[" . $line;
1006 continue;
1008 $ns = $nt->getNamespace();
1009 $iw = $nt->getInterWiki();
1010 if( $noforce ) {
1011 if( $iw && $wgInterwikiMagic && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1012 array_push( $this->mLanguageLinks, $nt->getPrefixedText() );
1013 $s .= $trail;
1014 /* CHECK MERGE @@@
1015 } else if ( "media" == $pre ) {
1016 $nt = Title::newFromText( $suf );
1017 $name = $nt->getDBkey();
1018 if ( "" == $text ) { $text = $nt->GetText(); }
1020 $wgLinkCache->addImageLink( $name );
1021 $s .= $sk->makeMediaLink( $name,
1022 wfImageUrl( $name ), $text );
1023 $s .= $trail;
1024 } else if ( isset($wgUseCategoryMagic) && $wgUseCategoryMagic && $pre == wfMsg ( "category" ) ) {
1025 $l = $sk->makeLink ( $pre.":".ucfirst( $m[2] ), ucfirst ( $m[2] ) ) ;
1026 array_push ( $this->mCategoryLinks , $l ) ;
1027 $s .= $trail ;
1028 } else {
1029 $l = $wgLang->getLanguageName( $pre );
1030 if ( "" == $l or !$wgInterwikiMagic or Namespace::isTalk( $wgTitle->getNamespace() ) ) {
1031 if ( "" == $text ) {
1032 $text = $link;
1034 $s .= $sk->makeLink( $link, $text, "", $trail );
1035 } else if ( $pre != $wgLanguageCode ) {
1036 array_push( $this->mLanguageLinks, "$pre:$suf" );
1037 $s .= $trail;
1040 continue;
1042 if( $ns == $image ) {
1043 $s .= $sk->makeImageLinkObj( $nt, $text ) . $trail;
1044 $wgLinkCache->addImageLinkObj( $nt );
1045 continue;
1047 /* CHECK MERGE @@@
1048 # } else if ( 0 == strcmp( "##", substr( $link, 0, 2 ) ) ) {
1049 # $link = substr( $link, 2 );
1050 # $s .= "<a name=\"{$link}\">{$text}</a>{$trail}";
1051 } else {
1052 if ( "" == $text ) { $text = $link; }
1053 # Hotspot:
1054 $s .= $sk->makeLink( $link, $text, "", $trail );
1057 if( $ns == $media ) {
1058 $s .= $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1059 $wgLinkCache->addImageLinkObj( $nt );
1060 continue;
1061 } elseif( $ns == $special ) {
1062 $s .= $sk->makeKnownLinkObj( $nt, $text, "", $trail );
1063 continue;
1065 $s .= $sk->makeLinkObj( $nt, $text, "", $trail );
1067 wfProfileOut( $fname );
1068 return $s;
1071 # Some functions here used by doBlockLevels()
1073 /* private */ function closeParagraph()
1075 $result = "";
1076 if ( 0 != strcmp( "p", $this->mLastSection ) &&
1077 0 != strcmp( "", $this->mLastSection ) ) {
1078 $result = "</" . $this->mLastSection . ">";
1080 $this->mLastSection = "";
1081 return $result."\n";
1083 # getCommon() returns the length of the longest common substring
1084 # of both arguments, starting at the beginning of both.
1086 /* private */ function getCommon( $st1, $st2 )
1088 $fl = strlen( $st1 );
1089 $shorter = strlen( $st2 );
1090 if ( $fl < $shorter ) { $shorter = $fl; }
1092 for ( $i = 0; $i < $shorter; ++$i ) {
1093 if ( $st1{$i} != $st2{$i} ) { break; }
1095 return $i;
1097 # These next three functions open, continue, and close the list
1098 # element appropriate to the prefix character passed into them.
1100 /* private */ function openList( $char )
1102 $result = $this->closeParagraph();
1104 if ( "*" == $char ) { $result .= "<ul><li>"; }
1105 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1106 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1107 else if ( ";" == $char ) {
1108 $result .= "<dl><dt>";
1109 $this->mDTopen = true;
1111 else { $result = "<!-- ERR 1 -->"; }
1113 return $result;
1116 /* private */ function nextItem( $char )
1118 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1119 else if ( ":" == $char || ";" == $char ) {
1120 $close = "</dd>";
1121 if ( $this->mDTopen ) { $close = "</dt>"; }
1122 if ( ";" == $char ) {
1123 $this->mDTopen = true;
1124 return $close . "<dt>";
1125 } else {
1126 $this->mDTopen = false;
1127 return $close . "<dd>";
1130 return "<!-- ERR 2 -->";
1133 /* private */function closeList( $char )
1135 if ( "*" == $char ) { $text = "</li></ul>"; }
1136 else if ( "#" == $char ) { $text = "</li></ol>"; }
1137 else if ( ":" == $char ) {
1138 if ( $this->mDTopen ) {
1139 $this->mDTopen = false;
1140 $text = "</dt></dl>";
1141 } else {
1142 $text = "</dd></dl>";
1145 else { return "<!-- ERR 3 -->"; }
1146 return $text."\n";
1149 /* private */ function doBlockLevels( $text, $linestart )
1151 $fname = "OutputPage::doBlockLevels";
1152 wfProfileIn( $fname );
1153 # Parsing through the text line by line. The main thing
1154 # happening here is handling of block-level elements p, pre,
1155 # and making lists from lines starting with * # : etc.
1157 $a = explode( "\n", $text );
1158 $text = $lastPref = "";
1159 $this->mDTopen = $inBlockElem = false;
1161 if ( ! $linestart ) { $text .= array_shift( $a ); }
1162 foreach ( $a as $t ) {
1163 if ( "" != $text ) { $text .= "\n"; }
1165 $oLine = $t;
1166 $opl = strlen( $lastPref );
1167 $npl = strspn( $t, "*#:;" );
1168 $pref = substr( $t, 0, $npl );
1169 $pref2 = str_replace( ";", ":", $pref );
1170 $t = substr( $t, $npl );
1172 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1173 $text .= $this->nextItem( substr( $pref, -1 ) );
1175 if ( ";" == substr( $pref, -1 ) ) {
1176 $cpos = strpos( $t, ":" );
1177 if ( ! ( false === $cpos ) ) {
1178 $term = substr( $t, 0, $cpos );
1179 $text .= $term . $this->nextItem( ":" );
1180 $t = substr( $t, $cpos + 1 );
1183 } else if (0 != $npl || 0 != $opl) {
1184 $cpl = $this->getCommon( $pref, $lastPref );
1186 while ( $cpl < $opl ) {
1187 $text .= $this->closeList( $lastPref{$opl-1} );
1188 --$opl;
1190 if ( $npl <= $cpl && $cpl > 0 ) {
1191 $text .= $this->nextItem( $pref{$cpl-1} );
1193 while ( $npl > $cpl ) {
1194 $char = substr( $pref, $cpl, 1 );
1195 $text .= $this->openList( $char );
1197 if ( ";" == $char ) {
1198 $cpos = strpos( $t, ":" );
1199 if ( ! ( false === $cpos ) ) {
1200 $term = substr( $t, 0, $cpos );
1201 $text .= $term . $this->nextItem( ":" );
1202 $t = substr( $t, $cpos + 1 );
1205 ++$cpl;
1207 $lastPref = $pref2;
1209 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1210 if ( preg_match(
1211 "/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6)/i", $t ) ) {
1212 $text .= $this->closeParagraph();
1213 $inBlockElem = true;
1215 if ( ! $inBlockElem ) {
1216 if ( " " == $t{0} ) {
1217 $newSection = "pre";
1218 # $t = wfEscapeHTML( $t );
1220 else { $newSection = "p"; }
1222 if ( 0 == strcmp( "", trim( $oLine ) ) ) {
1223 $text .= $this->closeParagraph();
1224 $text .= "<" . $newSection . ">";
1225 } else if ( 0 != strcmp( $this->mLastSection,
1226 $newSection ) ) {
1227 $text .= $this->closeParagraph();
1228 if ( 0 != strcmp( "p", $newSection ) ) {
1229 $text .= "<" . $newSection . ">";
1232 $this->mLastSection = $newSection;
1234 if ( $inBlockElem &&
1235 preg_match( "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6)/i", $t ) ) {
1236 $inBlockElem = false;
1239 $text .= $t;
1241 while ( $npl ) {
1242 $text .= $this->closeList( $pref2{$npl-1} );
1243 --$npl;
1245 if ( "" != $this->mLastSection ) {
1246 if ( "p" != $this->mLastSection ) {
1247 $text .= "</" . $this->mLastSection . ">";
1249 $this->mLastSection = "";
1251 wfProfileOut( $fname );
1252 return $text;
1255 /* private */ function replaceVariables( $text )
1257 global $wgLang, $wgCurOut;
1258 $fname = "OutputPage::replaceVariables";
1259 wfProfileIn( $fname );
1261 $magic = array();
1263 # Basic variables
1264 # See Language.php for the definition of each magic word
1265 # As with sigs, this uses the server's local time -- ensure
1266 # this is appropriate for your audience!
1268 $magic[MAG_CURRENTMONTH] = date( "m" );
1269 $magic[MAG_CURRENTMONTHNAME] = $wgLang->getMonthName( date("n") );
1270 $magic[MAG_CURRENTMONTHNAMEGEN] = $wgLang->getMonthNameGen( date("n") );
1271 $magic[MAG_CURRENTDAY] = date("j");
1272 $magic[MAG_CURRENTDAYNAME] = $wgLang->getWeekdayName( date("w")+1 );
1273 $magic[MAG_CURRENTYEAR] = date( "Y" );
1274 $magic[MAG_CURRENTTIME] = $wgLang->time( wfTimestampNow(), false );
1276 $this->mContainsOldMagic += MagicWord::replaceMultiple($magic, $text, $text);
1278 $mw =& MagicWord::get( MAG_NUMBEROFARTICLES );
1279 if ( $mw->match( $text ) ) {
1280 $v = wfNumberOfArticles();
1281 $text = $mw->replace( $v, $text );
1282 if( $mw->getWasModified() ) { $this->mContainsOldMagic++; }
1285 # "Variables" with an additional parameter e.g. {{MSG:wikipedia}}
1286 # The callbacks are at the bottom of this file
1287 $wgCurOut = $this;
1288 $mw =& MagicWord::get( MAG_MSG );
1289 $text = $mw->substituteCallback( $text, "wfReplaceMsgVar" );
1290 if( $mw->getWasModified() ) { $this->mContainsNewMagic++; }
1292 $mw =& MagicWord::get( MAG_MSGNW );
1293 $text = $mw->substituteCallback( $text, "wfReplaceMsgnwVar" );
1294 if( $mw->getWasModified() ) { $this->mContainsNewMagic++; }
1296 wfProfileOut( $fname );
1297 return $text;
1300 # Cleans up HTML, removes dangerous tags and attributes
1301 /* private */ function removeHTMLtags( $text )
1303 $fname = "OutputPage::removeHTMLtags";
1304 wfProfileIn( $fname );
1305 $htmlpairs = array( # Tags that must be closed
1306 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1307 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1308 "strike", "strong", "tt", "var", "div", "center",
1309 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1310 "ruby", "rt" , "rb" , "rp"
1312 $htmlsingle = array(
1313 "br", "p", "hr", "li", "dt", "dd"
1315 $htmlnest = array( # Tags that can be nested--??
1316 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1317 "dl", "font", "big", "small", "sub", "sup"
1319 $tabletags = array( # Can only appear inside table
1320 "td", "th", "tr"
1323 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1324 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1326 $htmlattrs = $this->getHTMLattrs () ;
1328 # Remove HTML comments
1329 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1331 $bits = explode( "<", $text );
1332 $text = array_shift( $bits );
1333 $tagstack = array(); $tablestack = array();
1335 foreach ( $bits as $x ) {
1336 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1337 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1338 $x, $regs );
1339 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1340 error_reporting( $prev );
1342 $badtag = 0 ;
1343 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1344 # Check our stack
1345 if ( $slash ) {
1346 # Closing a tag...
1347 if ( ! in_array( $t, $htmlsingle ) &&
1348 ( $ot = array_pop( $tagstack ) ) != $t ) {
1349 array_push( $tagstack, $ot );
1350 $badtag = 1;
1351 } else {
1352 if ( $t == "table" ) {
1353 $tagstack = array_pop( $tablestack );
1355 $newparams = "";
1357 } else {
1358 # Keep track for later
1359 if ( in_array( $t, $tabletags ) &&
1360 ! in_array( "table", $tagstack ) ) {
1361 $badtag = 1;
1362 } else if ( in_array( $t, $tagstack ) &&
1363 ! in_array ( $t , $htmlnest ) ) {
1364 $badtag = 1 ;
1365 } else if ( ! in_array( $t, $htmlsingle ) ) {
1366 if ( $t == "table" ) {
1367 array_push( $tablestack, $tagstack );
1368 $tagstack = array();
1370 array_push( $tagstack, $t );
1372 # Strip non-approved attributes from the tag
1373 $newparams = $this->fixTagAttributes($params);
1376 if ( ! $badtag ) {
1377 $rest = str_replace( ">", "&gt;", $rest );
1378 $text .= "<$slash$t $newparams$brace$rest";
1379 continue;
1382 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1384 # Close off any remaining tags
1385 while ( $t = array_pop( $tagstack ) ) {
1386 $text .= "</$t>\n";
1387 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1389 wfProfileOut( $fname );
1390 return $text;
1395 * This function accomplishes several tasks:
1396 * 1) Auto-number headings if that option is enabled
1397 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1398 * 3) Add a Table of contents on the top for users who have enabled the option
1399 * 4) Auto-anchor headings
1401 * It loops through all headlines, collects the necessary data, then splits up the
1402 * string and re-inserts the newly formatted headlines.
1404 * */
1405 /* private */ function formatHeadings( $text )
1407 global $wgUser,$wgArticle,$wgTitle,$wpPreview;
1408 $nh=$wgUser->getOption( "numberheadings" );
1409 $st=$wgUser->getOption( "showtoc" );
1410 if(!$wgTitle->userCanEdit()) {
1411 $es=0;
1412 $esr=0;
1413 } else {
1414 $es=$wgUser->getID() && $wgUser->getOption( "editsection" );
1415 $esr=$wgUser->getID() && $wgUser->getOption( "editsectiononrightclick" );
1418 # Inhibit editsection links if requested in the page
1419 $esw =& MagicWord::get( MAG_NOEDITSECTION );
1420 if ($esw->matchAndRemove( $text )) {
1421 $es=0;
1423 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1424 # do not add TOC
1425 $mw =& MagicWord::get( MAG_NOTOC );
1426 if ($mw->matchAndRemove( $text ))
1428 $st = 0;
1431 # never add the TOC to the Main Page. This is an entry page that should not
1432 # be more than 1-2 screens large anyway
1433 if($wgTitle->getPrefixedText()==wfMsg("mainpage")) {$st=0;}
1435 # We need this to perform operations on the HTML
1436 $sk=$wgUser->getSkin();
1438 # Get all headlines for numbering them and adding funky stuff like [edit]
1439 # links
1440 preg_match_all("/<H([1-6])(.*?>)(.*?)<\/H[1-6]>/i",$text,$matches);
1442 # headline counter
1443 $c=0;
1445 # Ugh .. the TOC should have neat indentation levels which can be
1446 # passed to the skin functions. These are determined here
1447 foreach($matches[3] as $headline) {
1448 if($level) { $prevlevel=$level;}
1449 $level=$matches[1][$c];
1450 if(($nh||$st) && $prevlevel && $level>$prevlevel) {
1452 $h[$level]=0; // reset when we enter a new level
1453 $toc.=$sk->tocIndent($level-$prevlevel);
1454 $toclevel+=$level-$prevlevel;
1457 if(($nh||$st) && $level<$prevlevel) {
1458 $h[$level+1]=0; // reset when we step back a level
1459 $toc.=$sk->tocUnindent($prevlevel-$level);
1460 $toclevel-=$prevlevel-$level;
1463 $h[$level]++; // count number of headlines for each level
1465 if($nh||$st) {
1466 for($i=1;$i<=$level;$i++) {
1467 if($h[$i]) {
1468 if($dot) {$numbering.=".";}
1469 $numbering.=$h[$i];
1470 $dot=1;
1475 // The canonized header is a version of the header text safe to use for links
1477 $canonized_headline=preg_replace("/<.*?>/","",$headline); // strip out HTML
1478 $tocline = trim( $canonized_headline );
1479 $canonized_headline=str_replace('"',"",$canonized_headline);
1480 $canonized_headline=str_replace(" ","_",trim($canonized_headline));
1481 $refer[$c]=$canonized_headline;
1482 $refers[$canonized_headline]++; // count how many in assoc. array so we can track dupes in anchors
1483 $refcount[$c]=$refers[$canonized_headline];
1485 // Prepend the number to the heading text
1487 if($nh||$st) {
1488 $tocline=$numbering ." ". $tocline;
1490 // Don't number the heading if it is the only one (looks silly)
1491 if($nh && count($matches[3]) > 1) {
1492 $headline=$numbering . " " . $headline; // the two are different if the line contains a link
1496 // Create the anchor for linking from the TOC to the section
1498 $anchor=$canonized_headline;
1499 if($refcount[$c]>1) {$anchor.="_".$refcount[$c];}
1500 if($st) {
1501 $toc.=$sk->tocLine($anchor,$tocline,$toclevel);
1503 if($es && !isset($wpPreview)) {
1504 $head[$c].=$sk->editSectionLink($c+1);
1507 // Put it all together
1509 $head[$c].="<h".$level.$matches[2][$c]
1510 ."<a name=\"".$anchor."\">"
1511 .$headline
1512 ."</a>"
1513 ."</h".$level.">";
1515 // Add the edit section link
1517 if($esr && !isset($wpPreview)) {
1518 $head[$c]=$sk->editSectionScript($c+1,$head[$c]);
1521 $numbering="";
1522 $c++;
1523 $dot=0;
1526 if($st) {
1527 $toclines=$c;
1528 $toc.=$sk->tocUnindent($toclevel);
1529 $toc=$sk->tocTable($toc);
1532 // split up and insert constructed headlines
1534 $blocks=preg_split("/<H[1-6].*?>.*?<\/H[1-6]>/i",$text);
1535 $i=0;
1537 foreach($blocks as $block) {
1538 if(($es) && !isset($wpPreview) && $c>0 && $i==0) {
1539 # This is the [edit] link that appears for the top block of text when
1540 # section editing is enabled
1541 $full.=$sk->editSectionLink(0);
1543 $full.=$block;
1544 if($st && $toclines>3 && !$i) {
1545 # Let's add a top anchor just in case we want to link to the top of the page
1546 $full="<a name=\"top\"></a>".$full.$toc;
1549 $full.=$head[$i];
1550 $i++;
1553 return $full;
1556 /* private */ function magicISBN( $text )
1558 global $wgLang;
1560 $a = split( "ISBN ", " $text" );
1561 if ( count ( $a ) < 2 ) return $text;
1562 $text = substr( array_shift( $a ), 1);
1563 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1565 foreach ( $a as $x ) {
1566 $isbn = $blank = "" ;
1567 while ( " " == $x{0} ) {
1568 $blank .= " ";
1569 $x = substr( $x, 1 );
1571 while ( strstr( $valid, $x{0} ) != false ) {
1572 $isbn .= $x{0};
1573 $x = substr( $x, 1 );
1575 $num = str_replace( "-", "", $isbn );
1576 $num = str_replace( " ", "", $num );
1578 if ( "" == $num ) {
1579 $text .= "ISBN $blank$x";
1580 } else {
1581 $text .= "<a href=\"" . wfLocalUrlE( $wgLang->specialPage(
1582 "Booksources"), "isbn={$num}" ) . "\" class=\"internal\">ISBN $isbn</a>";
1583 $text .= $x;
1586 return $text;
1589 /* private */ function magicRFC( $text )
1591 return $text;
1594 /* private */ function headElement()
1596 global $wgDocType, $wgDTD, $wgUser, $wgLanguageCode, $wgOutputEncoding, $wgLang;
1598 $ret = "<!DOCTYPE HTML PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1600 if ( "" == $this->mHTMLtitle ) {
1601 $this->mHTMLtitle = $this->mPagetitle;
1603 $rtl = $wgLang->isRTL() ? " dir='RTL'" : "";
1604 $ret .= "<html lang=\"$wgLanguageCode\"$rtl><head><title>{$this->mHTMLtitle}</title>\n";
1605 array_push( $this->mMetatags, array( "http:Content-type", "text/html; charset={$wgOutputEncoding}" ) );
1606 foreach ( $this->mMetatags as $tag ) {
1607 if ( 0 == strcasecmp( "http:", substr( $tag[0], 0, 5 ) ) ) {
1608 $a = "http-equiv";
1609 $tag[0] = substr( $tag[0], 5 );
1610 } else {
1611 $a = "name";
1613 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\">\n";
1615 $p = $this->mRobotpolicy;
1616 if ( "" == $p ) { $p = "index,follow"; }
1617 $ret .= "<meta name=\"robots\" content=\"$p\">\n";
1619 if ( count( $this->mKeywords ) > 0 ) {
1620 $ret .= "<meta name=\"keywords\" content=\"" .
1621 implode( ",", $this->mKeywords ) . "\">\n";
1623 foreach ( $this->mLinktags as $tag ) {
1624 $ret .= "<link ";
1625 if ( "" != $tag[0] ) { $ret .= "rel=\"{$tag[0]}\" "; }
1626 if ( "" != $tag[1] ) { $ret .= "rev=\"{$tag[1]}\" "; }
1627 $ret .= "href=\"{$tag[2]}\">\n";
1629 $sk = $wgUser->getSkin();
1630 $ret .= $sk->getHeadScripts();
1631 $ret .= $sk->getUserStyles();
1633 $ret .= "</head>\n";
1634 return $ret;
1637 /* private */ function fillFromParserCache(){
1638 global $wgUser, $wgArticle;
1639 $hash = $wgUser->getPageRenderingHash();
1640 $pageid = intval( $wgArticle->getID() );
1641 $res = wfQuery("SELECT pc_data FROM parsercache WHERE pc_pageid = {$pageid} ".
1642 " AND pc_prefhash = '{$hash}' AND pc_expire > NOW()", DB_WRITE);
1643 $row = wfFetchObject ( $res );
1644 if( $row ){
1645 $data = unserialize( gzuncompress($row->pc_data) );
1646 $this->addHTML( $data['html'] );
1647 $this->mLanguageLinks = $data['mLanguageLinks'];
1648 $this->mCategoryLinks = $data['mCategoryLinks'];
1649 wfProfileOut( $fname );
1650 return true;
1651 } else {
1652 return false;
1656 /* private */ function saveParserCache( $text ){
1657 global $wgUser, $wgArticle;
1658 $hash = $wgUser->getPageRenderingHash();
1659 $pageid = intval( $wgArticle->getID() );
1660 $title = wfStrencode( $wgArticle->mTitle->getPrefixedDBKey() );
1661 $data = array();
1662 $data['html'] = $text;
1663 $data['mLanguageLinks'] = $this->mLanguageLinks;
1664 $data['mCategoryLinks'] = $this->mCategoryLinks;
1665 $ser = addslashes( gzcompress( serialize( $data ) ) );
1666 if( $this->mContainsOldMagic ){
1667 $expire = "1 HOUR";
1668 } else if( $this->mContainsNewMagic ){
1669 $expire = "1 DAY";
1670 } else {
1671 $expire = "7 DAY";
1674 wfQuery("REPLACE INTO parsercache (pc_prefhash,pc_pageid,pc_title,pc_data, pc_expire) ".
1675 "VALUES('{$hash}', {$pageid}, '{$title}', '{$ser}', ".
1676 "DATE_ADD(NOW(), INTERVAL {$expire}))", DB_WRITE);
1678 if( rand() % 50 == 0 ){ // more efficient to just do it sometimes
1679 $this->purgeParserCache();
1683 /* static private */ function purgeParserCache(){
1684 wfQuery("DELETE FROM parsercache WHERE pc_expire < NOW() LIMIT 250", DB_WRITE);
1687 /* static */ function parsercacheClearLinksTo( $pid ){
1688 $pid = intval( $pid );
1689 wfQuery("DELETE parsercache FROM parsercache,links ".
1690 "WHERE pc_title=links.l_from AND l_to={$pid}", DB_WRITE);
1691 wfQuery("DELETE FROM parsercache WHERE pc_pageid='{$pid}'", DB_WRITE);
1694 # $title is a prefixed db title, for example like Title->getPrefixedDBkey() returns.
1695 /* static */ function parsercacheClearBrokenLinksTo( $title ){
1696 $title = wfStrencode( $title );
1697 wfQuery("DELETE parsercache FROM parsercache,brokenlinks ".
1698 "WHERE pc_pageid=bl_from AND bl_to='{$title}'", DB_WRITE);
1701 # $pid is a page id
1702 /* static */ function parsercacheClearPage( $pid ){
1703 $pid = intval( $pid );
1704 wfQuery("DELETE FROM parsercache WHERE pc_pageid='{$pid}'", DB_WRITE);
1708 # Regex callbacks, used in OutputPage::replaceVariables
1710 # Just get rid of the dangerous stuff
1711 # Necessary because replaceVariables is called after removeHTMLtags,
1712 # and message text can come from any user
1713 function wfReplaceMsgVar( $matches ) {
1714 global $wgCurOut, $wgLinkCache;
1715 $text = $wgCurOut->removeHTMLtags( wfMsg( $matches[1] ) );
1716 $wgLinkCache->suspend();
1717 $text = $wgCurOut->replaceInternalLinks( $text );
1718 $wgLinkCache->resume();
1719 $wgLinkCache->addLinkObj( Title::makeTitle( NS_MEDIAWIKI, $matches[1] ) );
1720 return $text;
1723 # Effective <nowiki></nowiki>
1724 # Not real <nowiki> because this is called after nowiki sections are processed
1725 function wfReplaceMsgnwVar( $matches ) {
1726 global $wgCurOut, $wgLinkCache;
1727 $text = wfEscapeWikiText( wfMsg( $matches[1] ) );
1728 $wgLinkCache->addLinkObj( Title::makeTitle( NS_MEDIAWIKI, $matches[1] ) );
1729 return $text;