Use wfMsg()'s parameters
[mediawiki.git] / includes / OutputPage.php
blob1bf092348396b8e43df0c165b0da939cd0d97ed6
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;
16 function OutputPage()
18 $this->mHeaders = $this->mCookies = $this->mMetatags =
19 $this->mKeywords = $this->mLinktags = array();
20 $this->mHTMLtitle = $this->mPagetitle = $this->mBodytext =
21 $this->mLastSection = $this->mRedirect = $this->mLastModified =
22 $this->mSubtitle = $this->mDebugtext = $this->mRobotpolicy = "";
23 $this->mIsarticle = $this->mPrintable = true;
24 $this->mSupressQuickbar = $this->mDTopen = $this->mPrintable = false;
25 $this->mLanguageLinks = array();
26 $this->mCategoryLinks = array() ;
27 $this->mAutonumber = 0;
30 function addHeader( $name, $val ) { array_push( $this->mHeaders, "$name: $val" ) ; }
31 function addCookie( $name, $val ) { array_push( $this->mCookies, array( $name, $val ) ); }
32 function redirect( $url ) { $this->mRedirect = $url; }
34 # To add an http-equiv meta tag, precede the name with "http:"
35 function addMeta( $name, $val ) { array_push( $this->mMetatags, array( $name, $val ) ); }
36 function addKeyword( $text ) { array_push( $this->mKeywords, $text ); }
37 function addLink( $rel, $rev, $target ) { array_push( $this->mLinktags, array( $rel, $rev, $target ) ); }
39 function checkLastModified ( $timestamp )
41 global $wgLang, $wgCachePages, $wgUser;
42 if( !$wgCachePages ) {
43 wfDebug( "CACHE DISABLED\n", false );
44 return;
46 if( preg_match( '/MSIE ([1-4]|5\.0)/', $_SERVER["HTTP_USER_AGENT"] ) ) {
47 # IE 5.0 has probs with our caching
48 wfDebug( "-- bad client, not caching\n", false );
49 return;
51 if( $wgUser->getOption( "nocache" ) ) {
52 wfDebug( "USER DISABLED CACHE\n", false );
53 return;
56 $lastmod = gmdate( "D, j M Y H:i:s", wfTimestamp2Unix(
57 max( $timestamp, $wgUser->mTouched ) ) ) . " GMT";
59 if( $_SERVER["HTTP_IF_MODIFIED_SINCE"] != "" ) {
60 # IE sends sizes after the date like this:
61 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
62 # this breaks strtotime().
63 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
64 $ismodsince = wfUnix2Timestamp( strtotime( $modsince ) );
65 wfDebug( "-- client send If-Modified-Since: " . $modsince . "\n", false );
66 wfDebug( "-- we might send Last-Modified : $lastmod\n", false );
68 if( ($ismodsince >= $timestamp ) and $wgUser->validateCache( $ismodsince ) ) {
69 # Make sure you're in a place you can leave when you call us!
70 header( "HTTP/1.0 304 Not Modified" );
71 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
72 header( "Cache-Control: private, must-revalidate, max-age=0" );
73 header( "Last-Modified: {$lastmod}" );
74 wfDebug( "CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
75 $this->reportTime(); # For profiling
76 exit;
77 } else {
78 wfDebug( "READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
79 $this->mLastModified = $lastmod;
81 } else {
82 wfDebug( "We're confused.\n", false );
83 $this->mLastModified = $lastmod;
87 function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
88 function setHTMLtitle( $name ) { $this->mHTMLtitle = $name; }
89 function setPageTitle( $name ) { $this->mPagetitle = $name; }
90 function getPageTitle() { return $this->mPagetitle; }
91 function setSubtitle( $str ) { $this->mSubtitle = $str; }
92 function getSubtitle() { return $this->mSubtitle; }
93 function setArticleFlag( $v ) { $this->mIsarticle = $v; }
94 function isArticle() { return $this->mIsarticle; }
95 function setPrintable() { $this->mPrintable = true; }
96 function isPrintable() { return $this->mPrintable; }
98 function getLanguageLinks() {
99 global $wgTitle, $wgLanguageCode;
100 global $wgDBconnection, $wgDBname;
101 return $this->mLanguageLinks;
103 function supressQuickbar() { $this->mSupressQuickbar = true; }
104 function isQuickbarSupressed() { return $this->mSupressQuickbar; }
106 function addHTML( $text ) { $this->mBodytext .= $text; }
107 function addHeadtext( $text ) { $this->mHeadtext .= $text; }
108 function debug( $text ) { $this->mDebugtext .= $text; }
110 # First pass--just handle <nowiki> sections, pass the rest off
111 # to doWikiPass2() which does all the real work.
114 function addWikiText( $text, $linestart = true )
116 global $wgUseTeX;
117 $fname = "OutputPage::addWikiText";
118 wfProfileIn( $fname );
119 $unique = "3iyZiyA7iMwg5rhxP0Dcc9oTnj8qD1jm1Sfv4";
120 $unique2 = "4LIQ9nXtiYFPCSfitVwDw7EYwQlL4GeeQ7qSO";
121 $unique3 = "fPaA8gDfdLBqzj68Yjg9Hil3qEF8JGO0uszIp";
122 $nwlist = array();
123 $nwsecs = 0;
124 $mathlist = array();
125 $mathsecs = 0;
126 $prelist = array ();
127 $presecs = 0;
128 $stripped = "";
129 $stripped2 = "";
130 $stripped3 = "";
132 while ( "" != $text ) {
133 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
134 $stripped .= $p[0];
135 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
136 else {
137 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
138 ++$nwsecs;
139 $nwlist[$nwsecs] = wfEscapeHTMLTagsOnly($q[0]);
140 $stripped .= $unique;
141 $text = $q[1];
145 if( $wgUseTeX ) {
146 while ( "" != $stripped ) {
147 $p = preg_split( "/<\\s*math\\s*>/i", $stripped, 2 );
148 $stripped2 .= $p[0];
149 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped = ""; }
150 else {
151 $q = preg_split( "/<\\/\\s*math\\s*>/i", $p[1], 2 );
152 ++$mathsecs;
153 $mathlist[$mathsecs] = renderMath($q[0]);
154 $stripped2 .= $unique2;
155 $stripped = $q[1];
158 } else {
159 $stripped2 = $stripped;
162 while ( "" != $stripped2 ) {
163 $p = preg_split( "/<\\s*pre\\s*>/i", $stripped2, 2 );
164 $stripped3 .= $p[0];
165 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped2 = ""; }
166 else {
167 $q = preg_split( "/<\\/\\s*pre\\s*>/i", $p[1], 2 );
168 ++$presecs;
169 $prelist[$presecs] = "<pre>". wfEscapeHTMLTagsOnly($q[0]). "</pre>";
170 $stripped3 .= $unique3;
171 $stripped2 = $q[1];
175 $text = $this->doWikiPass2( $stripped3, $linestart );
177 $specialChars = array("\\", "$");
178 $escapedChars = array("\\\\", "\\$");
179 for ( $i = 1; $i <= $presecs; ++$i ) {
180 $text = preg_replace( "/{$unique3}/", str_replace( $specialChars,
181 $escapedChars, $prelist[$i] ), $text, 1 );
184 for ( $i = 1; $i <= $mathsecs; ++$i ) {
185 $text = preg_replace( "/{$unique2}/", str_replace( $specialChars,
186 $escapedChars, $mathlist[$i] ), $text, 1 );
189 for ( $i = 1; $i <= $nwsecs; ++$i ) {
190 $text = preg_replace( "/{$unique}/", str_replace( $specialChars,
191 $escapedChars, $nwlist[$i] ), $text, 1 );
193 $this->addHTML( $text );
194 wfProfileOut( $fname );
197 function sendCacheControl() {
198 global $wgUseGzip;
199 if( $this->mLastModified != "" ) {
200 wfDebug( "** private caching; {$this->mLastModified} **\n", false );
201 header( "Cache-Control: private, must-revalidate, max-age=0" );
202 header( "Last-modified: {$this->mLastModified}" );
203 if( $wgUseGzip ) {
204 # We should put in Accept-Encoding, but IE chokes on anything but
205 # User-Agent in a Vary: header (at least through 6.0)
206 header( "Vary: User-Agent" );
208 } else {
209 wfDebug( "** no caching **\n", false );
210 header( "Cache-Control: no-cache" ); # Experimental - see below
211 header( "Pragma: no-cache" );
212 header( "Last-modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
214 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
217 # Finally, all the text has been munged and accumulated into
218 # the object, let's actually output it:
220 function output()
222 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
223 global $wgInputEncoding, $wgOutputEncoding, $wgLanguageCode;
225 $fname = "OutputPage::output";
226 wfProfileIn( $fname );
228 $sk = $wgUser->getSkin();
230 $this->sendCacheControl();
232 header( "Content-type: text/html; charset={$wgOutputEncoding}" );
233 header( "Content-language: {$wgLanguageCode}" );
235 if ( "" != $this->mRedirect ) {
236 header( "Location: {$this->mRedirect}" );
237 return;
240 $exp = time() + $wgCookieExpiration;
241 foreach( $this->mCookies as $name => $val ) {
242 setcookie( $name, $val, $exp, "/" );
245 $sk->outputPage( $this );
246 flush();
249 function out( $ins )
251 global $wgInputEncoding, $wgOutputEncoding, $wgLang;
252 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
253 $outs = $ins;
254 } else {
255 $outs = $wgLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
256 if ( false === $outs ) { $outs = $ins; }
258 print $outs;
261 function setEncodings()
263 global $HTTP_SERVER_VARS, $wgInputEncoding, $wgOutputEncoding;
264 global $wgUser, $wgLang;
266 $wgInputEncoding = strtolower( $wgInputEncoding );
267 $s = $HTTP_SERVER_VARS['HTTP_ACCEPT_CHARSET'];
269 if( $wgUser->getOption( 'altencoding' ) ) {
270 $wgLang->setAltEncoding();
271 return;
274 if ( "" == $s ) {
275 $wgOutputEncoding = strtolower( $wgOutputEncoding );
276 return;
278 $a = explode( ",", $s );
279 $best = 0.0;
280 $bestset = "*";
282 foreach ( $a as $s ) {
283 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
284 $set = $m[1];
285 $q = (float)($m[2]);
286 } else {
287 $set = $s;
288 $q = 1.0;
290 if ( $q > $best ) {
291 $bestset = $set;
292 $best = $q;
295 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
296 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
297 $wgOutputEncoding = strtolower( $bestset );
299 # Disable for now
301 $wgOutputEncoding = $wgInputEncoding;
304 function reportTime()
306 global $wgRequestTime, $wgDebugLogFile, $HTTP_SERVER_VARS;
307 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
309 list( $usec, $sec ) = explode( " ", microtime() );
310 $now = (float)$sec + (float)$usec;
312 list( $usec, $sec ) = explode( " ", $wgRequestTime );
313 $start = (float)$sec + (float)$usec;
314 $elapsed = $now - $start;
316 if ( "" != $wgDebugLogFile ) {
317 $prof = wfGetProfilingOutput( $start, $elapsed );
318 if( $forward = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'] )
319 $forward = " forwarded for $forward";
320 if( $client = $HTTP_SERVER_VARS['HTTP_CLIENT_IP'] )
321 $forward .= " client IP $client";
322 if( $from = $HTTP_SERVER_VARS['HTTP_FROM'] )
323 $forward .= " from $from";
324 if( $forward )
325 $forward = "\t(proxied via {$HTTP_SERVER_VARS['REMOTE_ADDR']}{$forward})";
326 if($wgUser->getId() == 0)
327 $forward .= " anon";
328 $log = sprintf( "%s\t%04.3f\t%s\n",
329 gmdate( "YmdHis" ), $elapsed,
330 urldecode( $HTTP_SERVER_VARS['REQUEST_URI'] . $forward ) );
331 error_log( $log . $prof, 3, $wgDebugLogFile );
333 $com = sprintf( "<!-- Time since request: %01.2f secs. -->",
334 $elapsed );
335 return $com;
338 # Note: these arguments are keys into wfMsg(), not text!
340 function errorpage( $title, $msg )
342 global $wgTitle;
344 $this->mDebugtext .= "Original title: " .
345 $wgTitle->getPrefixedText() . "\n";
346 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
347 $this->setPageTitle( wfMsg( $title ) );
348 $this->setRobotpolicy( "noindex,nofollow" );
349 $this->setArticleFlag( false );
351 $this->mBodytext = "";
352 $this->addHTML( "<p>" . wfMsg( $msg ) . "\n" );
353 $this->returnToMain( false );
355 $this->output();
356 exit;
359 function sysopRequired()
361 global $wgUser;
363 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
364 $this->setPageTitle( wfMsg( "sysoptitle" ) );
365 $this->setRobotpolicy( "noindex,nofollow" );
366 $this->setArticleFlag( false );
367 $this->mBodytext = "";
369 $sk = $wgUser->getSkin();
370 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
371 $this->addHTML( wfMsg( "sysoptext", $ap ) );
372 $this->returnToMain();
375 function developerRequired()
377 global $wgUser;
379 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
380 $this->setPageTitle( wfMsg( "developertitle" ) );
381 $this->setRobotpolicy( "noindex,nofollow" );
382 $this->setArticleFlag( false );
383 $this->mBodytext = "";
385 $sk = $wgUser->getSkin();
386 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
387 $this->addHTML( wfMsg( "developertext", $ap ) );
388 $this->returnToMain();
391 function databaseError( $fname )
393 global $wgUser, $wgCommandLineMode;
395 $this->setPageTitle( wfMsgNoDB( "databaseerror" ) );
396 $this->setRobotpolicy( "noindex,nofollow" );
397 $this->setArticleFlag( false );
399 if ( $wgCommandLineMode ) {
400 $msg = wfMsgNoDB( "dberrortextcl" );
401 } else {
402 $msg = wfMsgNoDB( "dberrortext" );
405 $msg = str_replace( "$1", htmlspecialchars( wfLastDBquery() ), $msg );
406 $msg = str_replace( "$2", htmlspecialchars( $fname ), $msg );
407 $msg = str_replace( "$3", wfLastErrno(), $msg );
408 $msg = str_replace( "$4", htmlspecialchars( wfLastError() ), $msg );
410 if ( $wgCommandLineMode ) {
411 print "$msg\n";
412 exit();
414 $sk = $wgUser->getSkin();
415 $shlink = $sk->makeKnownLink( wfMsgNoDB( "searchhelppage" ),
416 wfMsgNoDB( "searchingwikipedia" ) );
417 $msg = str_replace( "$5", $shlink, $msg );
419 $this->mBodytext = $msg;
420 $this->output();
421 exit();
424 function readOnlyPage( $source = "", $protected = false )
426 global $wgUser, $wgReadOnlyFile;
428 $this->setRobotpolicy( "noindex,nofollow" );
429 $this->setArticleFlag( false );
431 if( $protected ) {
432 $this->setPageTitle( wfMsg( "viewsource" ) );
433 $this->addWikiText( wfMsg( "protectedtext" ) );
434 } else {
435 $this->setPageTitle( wfMsg( "readonly" ) );
436 $reason = file_get_contents( $wgReadOnlyFile );
437 $this->addHTML( wfMsg( "readonlytext", $reason ) );
440 if($source) {
441 $rows = $wgUser->getOption( "rows" );
442 $cols = $wgUser->getOption( "cols" );
443 $text .= "</p>\n<textarea cols='$cols' rows='$rows' readonly>" .
444 htmlspecialchars( $source ) . "\n</textarea>";
445 $this->addHTML( $text );
448 $this->returnToMain( false );
451 function fatalError( $message )
453 $this->setPageTitle( wfMsg( "internalerror" ) );
454 $this->setRobotpolicy( "noindex,nofollow" );
455 $this->setArticleFlag( false );
457 $this->mBodytext = $message;
458 $this->output();
459 exit;
462 function unexpectedValueError( $name, $val )
464 $this->fatalError( wfMsg( "unexpected", $name, $val ) );
467 function fileCopyError( $old, $new )
469 $this->fatalError( wfMsg( "filecopyerror", $old, $new ) );
472 function fileRenameError( $old, $new )
474 $this->fatalError( wfMsg( "filerenameerror", $old, $new ) );
477 function fileDeleteError( $name )
479 $this->fatalError( wfMsg( "filedeleteerror", $name ) );
482 function fileNotFoundError( $name )
484 $this->fatalError( wfMsg( "filenotfound", $name ) );
487 function returnToMain( $auto = true )
489 global $wgUser, $wgOut, $returnto;
491 $sk = $wgUser->getSkin();
492 if ( "" == $returnto ) {
493 $returnto = wfMsg( "mainpage" );
495 $link = $sk->makeKnownLink( $returnto, "" );
497 $r = wfMsg( "returnto", $link );
498 if ( $auto ) {
499 $wgOut->addMeta( "http:Refresh", "10;url=" .
500 wfLocalUrlE( wfUrlencode( $returnto ) ) );
502 $wgOut->addHTML( "\n<p>$r\n" );
506 function categoryMagic ()
508 global $wgTitle , $wgUseCategoryMagic ;
509 if ( !isset ( $wgUseCategoryMagic ) || !$wgUseCategoryMagic ) return ;
510 $id = $wgTitle->getArticleID() ;
511 $cat = ucfirst ( wfMsg ( "category" ) ) ;
512 $ti = $wgTitle->getText() ;
513 $ti = explode ( ":" , $ti , 2 ) ;
514 if ( $cat != $ti[0] ) return "" ;
515 $r = "<br break=all>\n" ;
517 $articles = array() ;
518 $parents = array () ;
519 $children = array() ;
522 global $wgUser ;
523 $sk = $wgUser->getSkin() ;
524 $sql = "SELECT l_from FROM links WHERE l_to={$id}" ;
525 $res = wfQuery ( $sql, DB_READ ) ;
526 while ( $x = wfFetchObject ( $res ) )
528 # $t = new Title ;
529 # $t->newFromDBkey ( $x->l_from ) ;
530 # $t = $t->getText() ;
531 $t = $x->l_from ;
532 $y = explode ( ":" , $t , 2 ) ;
533 if ( count ( $y ) == 2 && $y[0] == $cat ) {
534 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
535 } else {
536 array_push ( $articles , $sk->makeLink ( $t ) ) ;
539 wfFreeResult ( $res ) ;
541 # Children
542 if ( count ( $children ) > 0 )
544 asort ( $children ) ;
545 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
546 $r .= implode ( ", " , $children ) ;
549 # Articles
550 if ( count ( $articles ) > 0 )
552 asort ( $articles ) ;
553 $h = wfMsg( "category_header", $ti[1] );
554 $r .= "<h2>{$h}</h2>\n" ;
555 $r .= implode ( ", " , $articles ) ;
559 return $r ;
562 function getHTMLattrs ()
564 $htmlattrs = array( # Allowed attributes--no scripting, etc.
565 "title", "align", "lang", "dir", "width", "height",
566 "bgcolor", "clear", /* BR */ "noshade", /* HR */
567 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
568 /* FONT */ "type", "start", "value", "compact",
569 /* For various lists, mostly deprecated but safe */
570 "summary", "width", "border", "frame", "rules",
571 "cellspacing", "cellpadding", "valign", "char",
572 "charoff", "colgroup", "col", "span", "abbr", "axis",
573 "headers", "scope", "rowspan", "colspan", /* Tables */
574 "id", "class", "name", "style" /* For CSS */
576 return $htmlattrs ;
579 function fixTableTags ( $t )
581 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
582 $htmlattrs = $this->getHTMLattrs() ;
584 # Strip non-approved attributes from the tag
585 $t = preg_replace(
586 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
587 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
588 $t);
590 return trim ( $t ) ;
593 function doTableStuff ( $t )
595 $t = explode ( "\n" , $t ) ;
596 $td = array () ; # Is currently a td tag open?
597 $ltd = array () ; # Was it TD or TH?
598 $tr = array () ; # Is currently a tr tag open?
599 $ltr = array () ; # tr attributes
600 foreach ( $t AS $k => $x )
602 $x = rtrim ( $x ) ;
603 $fc = substr ( $x , 0 , 1 ) ;
604 if ( "{|" == substr ( $x , 0 , 2 ) )
606 $t[$k] = "<table " . $this->fixTableTags ( substr ( $x , 3 ) ) . ">" ;
607 array_push ( $td , false ) ;
608 array_push ( $ltd , "" ) ;
609 array_push ( $tr , false ) ;
610 array_push ( $ltr , "" ) ;
612 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
613 else if ( "|}" == substr ( $x , 0 , 2 ) )
615 $z = "</table>\n" ;
616 $l = array_pop ( $ltd ) ;
617 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
618 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
619 array_pop ( $ltr ) ;
620 $t[$k] = $z ;
622 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
624 $z = trim ( substr ( $x , 2 ) ) ;
625 $t[$k] = "<caption>{$z}</caption>\n" ;
627 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
629 $x = substr ( $x , 1 ) ;
630 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
631 $z = "" ;
632 $l = array_pop ( $ltd ) ;
633 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
634 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
635 array_pop ( $ltr ) ;
636 $t[$k] = $z ;
637 array_push ( $tr , false ) ;
638 array_push ( $td , false ) ;
639 array_push ( $ltd , "" ) ;
640 array_push ( $ltr , $this->fixTableTags ( $x ) ) ;
642 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
644 if ( "|+" == substr ( $x , 0 , 2 ) )
646 $fc = "+" ;
647 $x = substr ( $x , 1 ) ;
649 $after = substr ( $x , 1 ) ;
650 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
651 $after = explode ( "||" , $after ) ;
652 $t[$k] = "" ;
653 foreach ( $after AS $theline )
655 $z = "" ;
656 $tra = array_pop ( $ltr ) ;
657 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
658 array_push ( $tr , true ) ;
659 array_push ( $ltr , "" ) ;
661 $l = array_pop ( $ltd ) ;
662 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
663 if ( $fc == "|" ) $l = "TD" ;
664 else if ( $fc == "!" ) $l = "TH" ;
665 else if ( $fc == "+" ) $l = "CAPTION" ;
666 else $l = "" ;
667 array_push ( $ltd , $l ) ;
668 $y = explode ( "|" , $theline , 2 ) ;
669 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
670 else $y = $y = "{$z}<{$l} ".$this->fixTableTags($y[0]).">{$y[1]}" ;
671 $t[$k] .= $y ;
672 array_push ( $td , true ) ;
677 # Closing open td, tr && table
678 while ( count ( $td ) > 0 )
680 if ( array_pop ( $td ) ) $t[] = "</td>" ;
681 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
682 $t[] = "</table>" ;
685 $t = implode ( "\n" , $t ) ;
686 # $t = $this->removeHTMLtags( $t );
687 return $t ;
690 # Well, OK, it's actually about 14 passes. But since all the
691 # hard lifting is done inside PHP's regex code, it probably
692 # wouldn't speed things up much to add a real parser.
694 function doWikiPass2( $text, $linestart )
696 global $wgUser, $wgLang, $wgUseDynamicDates;
697 $fname = "OutputPage::doWikiPass2";
698 wfProfileIn( $fname );
700 $text = $this->removeHTMLtags( $text );
701 $text = $this->replaceVariables( $text );
703 $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
704 $text = str_replace ( "<HR>", "<hr>", $text );
706 $text = $this->doAllQuotes( $text );
707 $text = $this->doHeadings( $text );
708 $text = $this->doBlockLevels( $text, $linestart );
710 if($wgUseDynamicDates) {
711 $text = $wgLang->replaceDates( $text );
714 $text = $this->replaceExternalLinks( $text );
715 $text = $this->replaceInternalLinks ( $text );
716 $text = $this->doTableStuff ( $text ) ;
718 $text = $this->magicISBN( $text );
719 $text = $this->magicRFC( $text );
720 $text = $this->formatHeadings( $text );
722 $sk = $wgUser->getSkin();
723 $text = $sk->transformContent( $text );
724 $text .= $this->categoryMagic () ;
726 wfProfileOut( $fname );
727 return $text;
730 /* private */ function doAllQuotes( $text )
732 $outtext = "";
733 $lines = explode( "\r\n", $text );
734 foreach ( $lines as $line ) {
735 $outtext .= $this->doQuotes ( "", $line, "" ) . "\r\n";
737 return $outtext;
740 /* private */ function doQuotes( $pre, $text, $mode )
742 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
743 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
744 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
745 if ( substr ($m[2], 0, 1) == "'" ) {
746 $m[2] = substr ($m[2], 1);
747 if ($mode == "em") {
748 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "emstrong" );
749 } else if ($mode == "strong") {
750 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
751 } else if (($mode == "emstrong") || ($mode == "both")) {
752 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
753 } else if ($mode == "strongem") {
754 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
755 } else {
756 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
758 } else {
759 if ($mode == "strong") {
760 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "strongem" );
761 } else if ($mode == "em") {
762 return $m1_em . $this->doQuotes ( "", $m[2], "" );
763 } else if ($mode == "emstrong") {
764 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
765 } else if (($mode == "strongem") || ($mode == "both")) {
766 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
767 } else {
768 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
771 } else {
772 $text_strong = ($text == "") ? "" : "<strong>{$text}</strong>";
773 $text_em = ($text == "") ? "" : "<em>{$text}</em>";
774 if ($mode == "") {
775 return $pre . $text;
776 } else if ($mode == "em") {
777 return $pre . $text_em;
778 } else if ($mode == "strong") {
779 return $pre . $text_strong;
780 } else if ($mode == "strongem") {
781 return (($pre == "") && ($text == "")) ? "" : "<strong>{$pre}{$text_em}</strong>";
782 } else {
783 return (($pre == "") && ($text == "")) ? "" : "<em>{$pre}{$text_strong}</em>";
788 /* private */ function doHeadings( $text )
790 for ( $i = 6; $i >= 1; --$i ) {
791 $h = substr( "======", 0, $i );
792 $text = preg_replace( "/^{$h}([^=]+){$h}(\\s|$)/m",
793 "<h{$i}>\\1</h{$i}>\\2", $text );
795 return $text;
798 # Note: we have to do external links before the internal ones,
799 # and otherwise take great care in the order of things here, so
800 # that we don't end up interpreting some URLs twice.
802 /* private */ function replaceExternalLinks( $text )
804 $fname = "OutputPage::replaceExternalLinks";
805 wfProfileIn( $fname );
806 $text = $this->subReplaceExternalLinks( $text, "http", true );
807 $text = $this->subReplaceExternalLinks( $text, "https", true );
808 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
809 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
810 $text = $this->subReplaceExternalLinks( $text, "news", false );
811 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
812 wfProfileOut( $fname );
813 return $text;
816 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
818 global $wgUser, $printable;
819 global $wgAllowExternalImages;
822 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
823 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
825 # this is the list of separators that should be ignored if they
826 # are the last character of an URL but that should be included
827 # if they occur within the URL, e.g. "go to www.foo.com, where .."
828 # in this case, the last comma should not become part of the URL,
829 # but in "www.foo.com/123,2342,32.htm" it should.
830 $sep = ",;\.:";
831 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
832 $images = "gif|png|jpg|jpeg";
834 # PLEASE NOTE: The curly braces { } are not part of the regex,
835 # they are interpreted as part of the string (used to tell PHP
836 # that the content of the string should be inserted there).
837 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
838 "((?i){$images})([^{$uc}]|$)/";
840 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
841 $sk = $wgUser->getSkin();
843 if ( $autonumber and $wgAllowExternalImages) { # Use img tags only for HTTP urls
844 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
845 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
847 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
848 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
849 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
850 "</a>\\5", $s );
851 $s = str_replace( $unique, $protocol, $s );
853 $a = explode( "[{$protocol}:", " " . $s );
854 $s = array_shift( $a );
855 $s = substr( $s, 1 );
857 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
858 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
860 foreach ( $a as $line ) {
861 if ( preg_match( $e1, $line, $m ) ) {
862 $link = "{$protocol}:{$m[1]}";
863 $trail = $m[2];
864 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
865 else { $text = wfEscapeHTML( $link ); }
866 } else if ( preg_match( $e2, $line, $m ) ) {
867 $link = "{$protocol}:{$m[1]}";
868 $text = $m[2];
869 $trail = $m[3];
870 } else {
871 $s .= "[{$protocol}:" . $line;
872 continue;
874 if ( $printable == "yes") $paren = " (<i>" . htmlspecialchars ( $link ) . "</i>)";
875 else $paren = "";
876 $la = $sk->getExternalLinkAttributes( $link, $text );
877 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
880 return $s;
883 /* private */ function replaceInternalLinks( $s )
885 global $wgTitle, $wgUser, $wgLang;
886 global $wgLinkCache, $wgInterwikiMagic, $wgUseCategoryMagic;
887 global $wgNamespacesWithSubpages, $wgLanguageCode;
888 wfProfileIn( $fname = "OutputPage::replaceInternalLinks" );
890 wfProfileIn( "$fname-setup" );
891 $tc = Title::legalChars() . "#";
892 $sk = $wgUser->getSkin();
894 $a = explode( "[[", " " . $s );
895 $s = array_shift( $a );
896 $s = substr( $s, 1 );
898 $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD";
900 # Special and Media are pseudo-namespaces; no pages actually exist in them
901 $image = Namespace::getImage();
902 $special = Namespace::getSpecial();
903 $media = Namespace::getMedia();
904 $nottalk = !Namespace::isTalk( $wgTitle->getNamespace() );
905 wfProfileOut( "$fname-setup" );
907 foreach ( $a as $line ) {
908 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
909 $text = $m[2];
910 $trail = $m[3];
911 } else { # Invalid form; output directly
912 $s .= "[[" . $line ;
913 continue;
916 /* Valid link forms:
917 Foobar -- normal
918 :Foobar -- override special treatment of prefix (images, language links)
919 /Foobar -- convert to CurrentPage/Foobar
920 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
922 $c = substr($m[1],0,1);
923 $noforce = ($c != ":");
924 if( $c == "/" ) { # subpage
925 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
926 $m[1]=substr($m[1],1,strlen($m[1])-2);
927 $noslash=$m[1];
928 } else {
929 $noslash=substr($m[1],1);
931 if($wgNamespacesWithSubpages[$wgTitle->getNamespace()]) { # subpages allowed here
932 $link = $wgTitle->getPrefixedText(). "/" . trim($noslash);
933 if(!$text) {
934 $text= $m[1];
935 } # this might be changed for ugliness reasons
936 } else {
937 $link = $noslash; # no subpage allowed, use standard link
939 } elseif( $noforce ) { # no subpage
940 $link = $m[1];
941 } else {
942 $link = substr( $m[1], 1 );
944 if( empty( $text ) )
945 $text = $link;
947 $nt = Title::newFromText( $link );
948 if( !$nt ) {
949 $s .= "[[" . $line;
950 continue;
952 $ns = $nt->getNamespace();
953 $iw = $nt->getInterWiki();
954 if( $noforce ) {
955 if( $iw && $wgInterwikiMagic && $nottalk && $wgLang->getLanguageName( $iw ) ) {
956 array_push( $this->mLanguageLinks, $nt->getPrefixedText() );
957 $s .= $trail;
958 /* CHECK MERGE @@@
959 } else if ( "media" == $pre ) {
960 $nt = Title::newFromText( $suf );
961 $name = $nt->getDBkey();
962 if ( "" == $text ) { $text = $nt->GetText(); }
964 $wgLinkCache->addImageLink( $name );
965 $s .= $sk->makeMediaLink( $name,
966 wfImageUrl( $name ), $text );
967 $s .= $trail;
968 } else if ( isset($wgUseCategoryMagic) && $wgUseCategoryMagic && $pre == wfMsg ( "category" ) ) {
969 $l = $sk->makeLink ( $pre.":".ucfirst( $m[2] ), ucfirst ( $m[2] ) ) ;
970 array_push ( $this->mCategoryLinks , $l ) ;
971 $s .= $trail ;
972 } else {
973 $l = $wgLang->getLanguageName( $pre );
974 if ( "" == $l or !$wgInterwikiMagic or Namespace::isTalk( $wgTitle->getNamespace() ) ) {
975 if ( "" == $text ) {
976 $text = $link;
978 $s .= $sk->makeLink( $link, $text, "", $trail );
979 } else if ( $pre != $wgLanguageCode ) {
980 array_push( $this->mLanguageLinks, "$pre:$suf" );
981 $s .= $trail;
984 continue;
986 if( $ns == $image ) {
987 $s .= $sk->makeImageLinkObj( $nt, $text ) . $trail;
988 $wgLinkCache->addImageLinkObj( $nt );
989 continue;
991 /* CHECK MERGE @@@
992 # } else if ( 0 == strcmp( "##", substr( $link, 0, 2 ) ) ) {
993 # $link = substr( $link, 2 );
994 # $s .= "<a name=\"{$link}\">{$text}</a>{$trail}";
995 } else {
996 if ( "" == $text ) { $text = $link; }
997 # Hotspot:
998 $s .= $sk->makeLink( $link, $text, "", $trail );
1001 if( $ns == $media ) {
1002 $s .= $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1003 $wgLinkCache->addImageLinkObj( $nt );
1004 continue;
1005 } elseif( $ns == $special ) {
1006 $s .= $sk->makeKnownLinkObj( $nt, $text, "", $trail );
1007 continue;
1009 $s .= $sk->makeLinkObj( $nt, $text, "", $trail );
1011 wfProfileOut( $fname );
1012 return $s;
1015 # Some functions here used by doBlockLevels()
1017 /* private */ function closeParagraph()
1019 $result = "";
1020 if ( 0 != strcmp( "p", $this->mLastSection ) &&
1021 0 != strcmp( "", $this->mLastSection ) ) {
1022 $result = "</" . $this->mLastSection . ">";
1024 $this->mLastSection = "";
1025 return $result;
1027 # getCommon() returns the length of the longest common substring
1028 # of both arguments, starting at the beginning of both.
1030 /* private */ function getCommon( $st1, $st2 )
1032 $fl = strlen( $st1 );
1033 $shorter = strlen( $st2 );
1034 if ( $fl < $shorter ) { $shorter = $fl; }
1036 for ( $i = 0; $i < $shorter; ++$i ) {
1037 if ( $st1{$i} != $st2{$i} ) { break; }
1039 return $i;
1041 # These next three functions open, continue, and close the list
1042 # element appropriate to the prefix character passed into them.
1044 /* private */ function openList( $char )
1046 $result = $this->closeParagraph();
1048 if ( "*" == $char ) { $result .= "<ul><li>"; }
1049 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1050 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1051 else if ( ";" == $char ) {
1052 $result .= "<dl><dt>";
1053 $this->mDTopen = true;
1055 else { $result = "<!-- ERR 1 -->"; }
1057 return $result;
1060 /* private */ function nextItem( $char )
1062 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1063 else if ( ":" == $char || ";" == $char ) {
1064 $close = "</dd>";
1065 if ( $this->mDTopen ) { $close = "</dt>"; }
1066 if ( ";" == $char ) {
1067 $this->mDTopen = true;
1068 return $close . "<dt>";
1069 } else {
1070 $this->mDTopen = false;
1071 return $close . "<dd>";
1074 return "<!-- ERR 2 -->";
1077 /* private */function closeList( $char )
1079 if ( "*" == $char ) { return "</li></ul>"; }
1080 else if ( "#" == $char ) { return "</li></ol>"; }
1081 else if ( ":" == $char ) {
1082 if ( $this->mDTopen ) {
1083 $this->mDTopen = false;
1084 return "</dt></dl>";
1085 } else {
1086 return "</dd></dl>";
1089 return "<!-- ERR 3 -->";
1092 /* private */ function doBlockLevels( $text, $linestart )
1094 $fname = "OutputPage::doBlockLevels";
1095 wfProfileIn( $fname );
1096 # Parsing through the text line by line. The main thing
1097 # happening here is handling of block-level elements p, pre,
1098 # and making lists from lines starting with * # : etc.
1100 $a = explode( "\n", $text );
1101 $text = $lastPref = "";
1102 $this->mDTopen = $inBlockElem = false;
1104 if ( ! $linestart ) { $text .= array_shift( $a ); }
1105 foreach ( $a as $t ) {
1106 if ( "" != $text ) { $text .= "\n"; }
1108 $oLine = $t;
1109 $opl = strlen( $lastPref );
1110 $npl = strspn( $t, "*#:;" );
1111 $pref = substr( $t, 0, $npl );
1112 $pref2 = str_replace( ";", ":", $pref );
1113 $t = substr( $t, $npl );
1115 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1116 $text .= $this->nextItem( substr( $pref, -1 ) );
1118 if ( ";" == substr( $pref, -1 ) ) {
1119 $cpos = strpos( $t, ":" );
1120 if ( ! ( false === $cpos ) ) {
1121 $term = substr( $t, 0, $cpos );
1122 $text .= $term . $this->nextItem( ":" );
1123 $t = substr( $t, $cpos + 1 );
1126 } else if (0 != $npl || 0 != $opl) {
1127 $cpl = $this->getCommon( $pref, $lastPref );
1129 while ( $cpl < $opl ) {
1130 $text .= $this->closeList( $lastPref{$opl-1} );
1131 --$opl;
1133 if ( $npl <= $cpl && $cpl > 0 ) {
1134 $text .= $this->nextItem( $pref{$cpl-1} );
1136 while ( $npl > $cpl ) {
1137 $char = substr( $pref, $cpl, 1 );
1138 $text .= $this->openList( $char );
1140 if ( ";" == $char ) {
1141 $cpos = strpos( $t, ":" );
1142 if ( ! ( false === $cpos ) ) {
1143 $term = substr( $t, 0, $cpos );
1144 $text .= $term . $this->nextItem( ":" );
1145 $t = substr( $t, $cpos + 1 );
1148 ++$cpl;
1150 $lastPref = $pref2;
1152 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1153 if ( preg_match(
1154 "/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6)/i", $t ) ) {
1155 $text .= $this->closeParagraph();
1156 $inBlockElem = true;
1158 if ( ! $inBlockElem ) {
1159 if ( " " == $t{0} ) {
1160 $newSection = "pre";
1161 # $t = wfEscapeHTML( $t );
1163 else { $newSection = "p"; }
1165 if ( 0 == strcmp( "", trim( $oLine ) ) ) {
1166 $text .= $this->closeParagraph();
1167 $text .= "<" . $newSection . ">";
1168 } else if ( 0 != strcmp( $this->mLastSection,
1169 $newSection ) ) {
1170 $text .= $this->closeParagraph();
1171 if ( 0 != strcmp( "p", $newSection ) ) {
1172 $text .= "<" . $newSection . ">";
1175 $this->mLastSection = $newSection;
1177 if ( $inBlockElem &&
1178 preg_match( "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6)/i", $t ) ) {
1179 $inBlockElem = false;
1182 $text .= $t;
1184 while ( $npl ) {
1185 $text .= $this->closeList( $pref2{$npl-1} );
1186 --$npl;
1188 if ( "" != $this->mLastSection ) {
1189 if ( "p" != $this->mLastSection ) {
1190 $text .= "</" . $this->mLastSection . ">";
1192 $this->mLastSection = "";
1194 wfProfileOut( $fname );
1195 return $text;
1198 /* private */ function replaceVariables( $text )
1200 global $wgLang;
1201 $fname = "OutputPage::replaceVariables";
1202 wfProfileIn( $fname );
1205 # Basic variables
1206 # See Language.php for the definition of each magic word
1208 # As with sigs, this uses the server's local time -- ensure
1209 # this is appropriate for your audience!
1210 $v = date( "m" );
1211 $mw =& MagicWord::get( MAG_CURRENTMONTH );
1212 $text = $mw->replace( $v, $text );
1214 $v = $wgLang->getMonthName( date( "n" ) );
1215 $mw =& MagicWord::get( MAG_CURRENTMONTHNAME );
1216 $text = $mw->replace( $v, $text );
1218 $v = $wgLang->getMonthNameGen( date( "n" ) );
1219 $mw =& MagicWord::get( MAG_CURRENTMONTHNAMEGEN );
1220 $text = $mw->replace( $v, $text );
1222 $v = date( "j" );
1223 $mw = MagicWord::get( MAG_CURRENTDAY );
1224 $text = $mw->replace( $v, $text );
1226 $v = $wgLang->getWeekdayName( date( "w" )+1 );
1227 $mw =& MagicWord::get( MAG_CURRENTDAYNAME );
1228 $text = $mw->replace( $v, $text );
1230 $v = date( "Y" );
1231 $mw =& MagicWord::get( MAG_CURRENTYEAR );
1232 $text = $mw->replace( $v, $text );
1234 $v = $wgLang->time( wfTimestampNow(), false );
1235 $mw =& MagicWord::get( MAG_CURRENTTIME );
1236 $text = $mw->replace( $v, $text );
1238 $mw =& MagicWord::get( MAG_NUMBEROFARTICLES );
1239 if ( $mw->match( $text ) ) {
1240 $v = wfNumberOfArticles();
1241 $text = $mw->replace( $v, $text );
1244 # "Variables" with an additional parameter e.g. {{MSG:wikipedia}}
1245 # The callbacks are at the bottom of this file
1246 $mw =& MagicWord::get( MAG_MSG );
1247 $text = $mw->substituteCallback( $text, "wfReplaceMsgVar" );
1249 $mw =& MagicWord::get( MAG_MSGNW );
1250 $text = $mw->substituteCallback( $text, "wfReplaceMsgnwVar" );
1252 wfProfileOut( $fname );
1253 return $text;
1256 # Cleans up HTML, removes dangerous tags and attributes
1257 /* private */ function removeHTMLtags( $text )
1259 $fname = "OutputPage::removeHTMLtags";
1260 wfProfileIn( $fname );
1261 $htmlpairs = array( # Tags that must be closed
1262 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1263 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1264 "strike", "strong", "tt", "var", "div", "center",
1265 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1266 "ruby", "rt" , "rb" , "rp"
1268 $htmlsingle = array(
1269 "br", "p", "hr", "li", "dt", "dd"
1271 $htmlnest = array( # Tags that can be nested--??
1272 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1273 "dl", "font", "big", "small", "sub", "sup"
1275 $tabletags = array( # Can only appear inside table
1276 "td", "th", "tr"
1279 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1280 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1282 $htmlattrs = $this->getHTMLattrs () ;
1284 # Remove HTML comments
1285 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1287 $bits = explode( "<", $text );
1288 $text = array_shift( $bits );
1289 $tagstack = array(); $tablestack = array();
1291 foreach ( $bits as $x ) {
1292 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1293 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1294 $x, $regs );
1295 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1296 error_reporting( $prev );
1298 $badtag = 0 ;
1299 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1300 # Check our stack
1301 if ( $slash ) {
1302 # Closing a tag...
1303 if ( ! in_array( $t, $htmlsingle ) &&
1304 ( $ot = array_pop( $tagstack ) ) != $t ) {
1305 array_push( $tagstack, $ot );
1306 $badtag = 1;
1307 } else {
1308 if ( $t == "table" ) {
1309 $tagstack = array_pop( $tablestack );
1311 $newparams = "";
1313 } else {
1314 # Keep track for later
1315 if ( in_array( $t, $tabletags ) &&
1316 ! in_array( "table", $tagstack ) ) {
1317 $badtag = 1;
1318 } else if ( in_array( $t, $tagstack ) &&
1319 ! in_array ( $t , $htmlnest ) ) {
1320 $badtag = 1 ;
1321 } else if ( ! in_array( $t, $htmlsingle ) ) {
1322 if ( $t == "table" ) {
1323 array_push( $tablestack, $tagstack );
1324 $tagstack = array();
1326 array_push( $tagstack, $t );
1328 # Strip non-approved attributes from the tag
1329 $newparams = preg_replace(
1330 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
1331 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
1332 $params);
1334 if ( ! $badtag ) {
1335 $rest = str_replace( ">", "&gt;", $rest );
1336 $text .= "<$slash$t$newparams$brace$rest";
1337 continue;
1340 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1342 # Close off any remaining tags
1343 while ( $t = array_pop( $tagstack ) ) {
1344 $text .= "</$t>\n";
1345 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1347 wfProfileOut( $fname );
1348 return $text;
1354 * This function accomplishes several tasks:
1355 * 1) Auto-number headings if that option is enabled
1356 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1357 * 3) Add a Table of contents on the top for users who have enabled the option
1358 * 4) Auto-anchor headings
1360 * It loops through all headlines, collects the necessary data, then splits up the
1361 * string and re-inserts the newly formatted headlines.
1363 * */
1364 /* private */ function formatHeadings( $text )
1366 global $wgUser,$wgArticle,$wgTitle,$wpPreview;
1367 $nh=$wgUser->getOption( "numberheadings" );
1368 $st=$wgUser->getOption( "showtoc" );
1369 if(!$wgTitle->userCanEdit()) {
1370 $es=0;
1371 $esr=0;
1372 } else {
1373 $es=$wgUser->getID() && $wgUser->getOption( "editsection" );
1374 $esr=$wgUser->getID() && $wgUser->getOption( "editsectiononrightclick" );
1377 # Inhibit editsection links if requested in the page
1378 if ($es) {
1379 $esw=& MagicWord::get(MAG_NOEDITSECTION);
1380 if ($esw->matchAndRemove( $text )) {
1381 $es=0;
1384 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1385 # do not add TOC
1386 $mw =& MagicWord::get( MAG_NOTOC );
1387 if ($mw->matchAndRemove( $text ))
1389 $st = 0;
1392 # never add the TOC to the Main Page. This is an entry page that should not
1393 # be more than 1-2 screens large anyway
1394 if($wgTitle->getPrefixedText()==wfMsg("mainpage")) {$st=0;}
1396 # We need this to perform operations on the HTML
1397 $sk=$wgUser->getSkin();
1399 # Get all headlines for numbering them and adding funky stuff like [edit]
1400 # links
1401 preg_match_all("/<H([1-6])(.*?>)(.*?)<\/H[1-6]>/i",$text,$matches);
1403 # headline counter
1404 $c=0;
1406 # Ugh .. the TOC should have neat indentation levels which can be
1407 # passed to the skin functions. These are determined here
1408 foreach($matches[3] as $headline) {
1409 if($level) { $prevlevel=$level;}
1410 $level=$matches[1][$c];
1411 if(($nh||$st) && $prevlevel && $level>$prevlevel) {
1413 $h[$level]=0; // reset when we enter a new level
1414 $toc.=$sk->tocIndent($level-$prevlevel);
1415 $toclevel+=$level-$prevlevel;
1418 if(($nh||$st) && $level<$prevlevel) {
1419 $h[$level+1]=0; // reset when we step back a level
1420 $toc.=$sk->tocUnindent($prevlevel-$level);
1421 $toclevel-=$prevlevel-$level;
1424 $h[$level]++; // count number of headlines for each level
1426 if($nh||$st) {
1427 for($i=1;$i<=$level;$i++) {
1428 if($h[$i]) {
1429 if($dot) {$numbering.=".";}
1430 $numbering.=$h[$i];
1431 $dot=1;
1436 // The canonized header is a version of the header text safe to use for links
1438 $canonized_headline=preg_replace("/<.*?>/","",$headline); // strip out HTML
1439 $tocline=$canonized_headline;
1440 $canonized_headline=str_replace('"',"",$canonized_headline);
1441 $canonized_headline=str_replace(" ","_",trim($canonized_headline));
1442 $refer[$c]=$canonized_headline;
1443 $refers[$canonized_headline]++; // count how many in assoc. array so we can track dupes in anchors
1444 $refcount[$c]=$refers[$canonized_headline];
1446 // Prepend the number to the heading text
1448 if($nh||$st) {
1449 $tocline=$numbering ." ". $tocline;
1451 // Don't number the heading if it is the only one (looks silly)
1452 if($nh && count($matches[3]) > 1) {
1453 $headline=$numbering . " " . $headline; // the two are different if the line contains a link
1457 // Create the anchor for linking from the TOC to the section
1459 $anchor=$canonized_headline;
1460 if($refcount[$c]>1) {$anchor.="_".$refcount[$c];}
1461 if($st) {
1462 $toc.=$sk->tocLine($anchor,$tocline,$toclevel);
1464 if($es && !isset($wpPreview)) {
1465 $head[$c].=$sk->editSectionLink($c+1);
1468 // Put it all together
1470 $head[$c].="<h".$level.$matches[2][$c]
1471 ."<a name=\"".$anchor."\">"
1472 .$headline
1473 ."</a>"
1474 ."</h".$level.">";
1476 // Add the edit section link
1478 if($esr && !isset($wpPreview)) {
1479 $head[$c]=$sk->editSectionScript($c+1,$head[$c]);
1482 $numbering="";
1483 $c++;
1484 $dot=0;
1487 if($st) {
1488 $toclines=$c;
1489 $toc.=$sk->tocUnindent($toclevel);
1490 $toc=$sk->tocTable($toc);
1493 // split up and insert constructed headlines
1495 $blocks=preg_split("/<H[1-6].*?>.*?<\/H[1-6]>/i",$text);
1496 $i=0;
1498 foreach($blocks as $block) {
1499 if(($es) && !isset($wpPreview) && $c>0 && $i==0) {
1500 # This is the [edit] link that appears for the top block of text when
1501 # section editing is enabled
1502 $full.=$sk->editSectionLink(0);
1504 $full.=$block;
1505 if($st && $toclines>3 && !$i) {
1506 # Let's add a top anchor just in case we want to link to the top of the page
1507 $full="<a name=\"top\"></a>".$full.$toc;
1510 $full.=$head[$i];
1511 $i++;
1514 return $full;
1517 /* private */ function magicISBN( $text )
1519 global $wgLang;
1521 $a = split( "ISBN ", " $text" );
1522 if ( count ( $a ) < 2 ) return $text;
1523 $text = substr( array_shift( $a ), 1);
1524 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1526 foreach ( $a as $x ) {
1527 $isbn = $blank = "" ;
1528 while ( " " == $x{0} ) {
1529 $blank .= " ";
1530 $x = substr( $x, 1 );
1532 while ( strstr( $valid, $x{0} ) != false ) {
1533 $isbn .= $x{0};
1534 $x = substr( $x, 1 );
1536 $num = str_replace( "-", "", $isbn );
1537 $num = str_replace( " ", "", $num );
1539 if ( "" == $num ) {
1540 $text .= "ISBN $blank$x";
1541 } else {
1542 $text .= "<a href=\"" . wfLocalUrlE( $wgLang->specialPage(
1543 "Booksources"), "isbn={$num}" ) . "\" class=\"internal\">ISBN $isbn</a>";
1544 $text .= $x;
1547 return $text;
1550 /* private */ function magicRFC( $text )
1552 return $text;
1555 /* private */ function headElement()
1557 global $wgDocType, $wgDTD, $wgUser, $wgLanguageCode, $wgOutputEncoding, $wgLang;
1559 $ret = "<!DOCTYPE HTML PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1561 if ( "" == $this->mHTMLtitle ) {
1562 $this->mHTMLtitle = $this->mPagetitle;
1564 $rtl = $wgLang->isRTL() ? " dir='RTL'" : "";
1565 $ret .= "<html lang=\"$wgLanguageCode\"$rtl><head><title>{$this->mHTMLtitle}</title>\n";
1566 array_push( $this->mMetatags, array( "http:Content-type", "text/html; charset={$wgOutputEncoding}" ) );
1567 foreach ( $this->mMetatags as $tag ) {
1568 if ( 0 == strcasecmp( "http:", substr( $tag[0], 0, 5 ) ) ) {
1569 $a = "http-equiv";
1570 $tag[0] = substr( $tag[0], 5 );
1571 } else {
1572 $a = "name";
1574 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\">\n";
1576 $p = $this->mRobotpolicy;
1577 if ( "" == $p ) { $p = "index,follow"; }
1578 $ret .= "<meta name=\"robots\" content=\"$p\">\n";
1580 if ( count( $this->mKeywords ) > 0 ) {
1581 $ret .= "<meta name=\"keywords\" content=\"" .
1582 implode( ",", $this->mKeywords ) . "\">\n";
1584 foreach ( $this->mLinktags as $tag ) {
1585 $ret .= "<link ";
1586 if ( "" != $tag[0] ) { $ret .= "rel=\"{$tag[0]}\" "; }
1587 if ( "" != $tag[1] ) { $ret .= "rev=\"{$tag[1]}\" "; }
1588 $ret .= "href=\"{$tag[2]}\">\n";
1590 $sk = $wgUser->getSkin();
1591 $ret .= $sk->getHeadScripts();
1592 $ret .= $sk->getUserStyles();
1594 $ret .= "</head>\n";
1595 return $ret;
1599 # Regex callbacks, used in OutputPage::replaceVariables
1601 # Just get rid of the dangerous stuff
1602 # Necessary because replaceVariables is called after removeHTMLtags,
1603 # and message text can come from any user
1604 function wfReplaceMsgVar( $matches ) {
1605 global $wgOut;
1606 $text = $wgOut->removeHTMLtags( wfMsg( $matches[1] ) );
1607 return $text;
1610 # Effective <nowiki></nowiki>
1611 # Not real <nowiki> because this is called after nowiki sections are processed
1612 function wfReplaceMsgnwVar( $matches ) {
1613 $text = wfEscapeWikiText( wfMsg( $matches[1] ) );
1614 return $text;