fix two typo / cleanup
[mediawiki.git] / includes / OutputPage.php
blob1bff75d9278319c3615be2728b7410c190907923
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 for compressed pages:
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 exit;
76 } else {
77 wfDebug( "READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
78 $this->mLastModified = $lastmod;
80 } else {
81 wfDebug( "We're confused.\n", false );
82 $this->mLastModified = $lastmod;
86 function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
87 function setHTMLtitle( $name ) { $this->mHTMLtitle = $name; }
88 function setPageTitle( $name ) { $this->mPagetitle = $name; }
89 function getPageTitle() { return $this->mPagetitle; }
90 function setSubtitle( $str ) { $this->mSubtitle = $str; }
91 function getSubtitle() { return $this->mSubtitle; }
92 function setArticleFlag( $v ) { $this->mIsarticle = $v; }
93 function isArticle() { return $this->mIsarticle; }
94 function setPrintable() { $this->mPrintable = true; }
95 function isPrintable() { return $this->mPrintable; }
97 function getLanguageLinks() {
98 global $wgUseNewInterlanguage, $wgTitle, $wgLanguageCode;
99 global $wgDBconnection, $wgDBname, $wgDBintlname;
101 if ( ! $wgUseNewInterlanguage )
102 return $this->mLanguageLinks;
104 mysql_select_db( $wgDBintlname, $wgDBconnection ) or die(
105 htmlspecialchars(mysql_error()) );
107 $list = array();
108 $sql = "SELECT * FROM ilinks WHERE lang_from=\"" .
109 "{$wgLanguageCode}\" AND title_from=\"" . $wgTitle->getDBkey() . "\"";
110 $res = mysql_query( $sql, $wgDBconnection );
112 while ( $q = mysql_fetch_object ( $res ) ) {
113 $list[] = $q->lang_to . ":" . $q->title_to;
115 mysql_free_result( $res );
116 mysql_select_db( $wgDBname, $wgDBconnection ) or die(
117 htmlspecialchars(mysql_error()) );
119 return $list;
122 function supressQuickbar() { $this->mSupressQuickbar = true; }
123 function isQuickbarSupressed() { return $this->mSupressQuickbar; }
125 function addHTML( $text ) { $this->mBodytext .= $text; }
126 function addHeadtext( $text ) { $this->mHeadtext .= $text; }
127 function debug( $text ) { $this->mDebugtext .= $text; }
129 # First pass--just handle <nowiki> sections, pass the rest off
130 # to doWikiPass2() which does all the real work.
133 function addWikiText( $text, $linestart = true )
135 global $wgUseTeX;
136 $fname = "OutputPage::addWikiText";
137 wfProfileIn( $fname );
138 $unique = "3iyZiyA7iMwg5rhxP0Dcc9oTnj8qD1jm1Sfv4";
139 $unique2 = "4LIQ9nXtiYFPCSfitVwDw7EYwQlL4GeeQ7qSO";
140 $unique3 = "fPaA8gDfdLBqzj68Yjg9Hil3qEF8JGO0uszIp";
141 $nwlist = array();
142 $nwsecs = 0;
143 $mathlist = array();
144 $mathsecs = 0;
145 $prelist = array ();
146 $presecs = 0;
147 $stripped = "";
148 $stripped2 = "";
149 $stripped3 = "";
151 while ( "" != $text ) {
152 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
153 $stripped .= $p[0];
154 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
155 else {
156 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
157 ++$nwsecs;
158 $nwlist[$nwsecs] = wfEscapeHTMLTagsOnly($q[0]);
159 $stripped .= $unique;
160 $text = $q[1];
164 if( $wgUseTeX ) {
165 while ( "" != $stripped ) {
166 $p = preg_split( "/<\\s*math\\s*>/i", $stripped, 2 );
167 $stripped2 .= $p[0];
168 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped = ""; }
169 else {
170 $q = preg_split( "/<\\/\\s*math\\s*>/i", $p[1], 2 );
171 ++$mathsecs;
172 $mathlist[$mathsecs] = renderMath($q[0]);
173 $stripped2 .= $unique2;
174 $stripped = $q[1];
177 } else {
178 $stripped2 = $stripped;
181 while ( "" != $stripped2 ) {
182 $p = preg_split( "/<\\s*pre\\s*>/i", $stripped2, 2 );
183 $stripped3 .= $p[0];
184 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped2 = ""; }
185 else {
186 $q = preg_split( "/<\\/\\s*pre\\s*>/i", $p[1], 2 );
187 ++$presecs;
188 $prelist[$presecs] = "<pre>". wfEscapeHTMLTagsOnly($q[0]). "</pre>";
189 $stripped3 .= $unique3;
190 $stripped2 = $q[1];
194 $text = $this->doWikiPass2( $stripped3, $linestart );
196 $specialChars = array("\\", "$");
197 $escapedChars = array("\\\\", "\\$");
198 for ( $i = 1; $i <= $presecs; ++$i ) {
199 $text = preg_replace( "/{$unique3}/", str_replace( $specialChars,
200 $escapedChars, $prelist[$i] ), $text, 1 );
203 for ( $i = 1; $i <= $mathsecs; ++$i ) {
204 $text = preg_replace( "/{$unique2}/", str_replace( $specialChars,
205 $escapedChars, $mathlist[$i] ), $text, 1 );
208 for ( $i = 1; $i <= $nwsecs; ++$i ) {
209 $text = preg_replace( "/{$unique}/", str_replace( $specialChars,
210 $escapedChars, $nwlist[$i] ), $text, 1 );
212 $this->addHTML( $text );
213 wfProfileOut( $fname );
216 function sendCacheControl() {
217 global $wgUseGzip;
218 if( $this->mLastModified != "" ) {
219 wfDebug( "** private caching; {$this->mLastModified} **\n", false );
220 header( "Cache-Control: private, must-revalidate, max-age=0" );
221 header( "Last-modified: {$this->mLastModified}" );
222 if( $wgUseGzip ) {
223 # We should put in Accept-Encoding, but IE chokes on anything but
224 # User-Agent in a Vary: header (at least through 6.0)
225 header( "Vary: User-Agent" );
227 } else {
228 wfDebug( "** no caching **\n", false );
229 header( "Cache-Control: no-cache" ); # Experimental - see below
230 header( "Pragma: no-cache" );
231 header( "Last-modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
233 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
236 # Finally, all the text has been munged and accumulated into
237 # the object, let's actually output it:
239 function output()
241 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
242 global $wgInputEncoding, $wgOutputEncoding, $wgLanguageCode;
243 $sk = $wgUser->getSkin();
245 $this->sendCacheControl();
247 header( "Content-type: text/html; charset={$wgOutputEncoding}" );
248 header( "Content-language: {$wgLanguageCode}" );
250 if ( "" != $this->mRedirect ) {
251 header( "Location: {$this->mRedirect}" );
252 return;
255 $exp = time() + $wgCookieExpiration;
256 foreach( $this->mCookies as $name => $val ) {
257 setcookie( $name, $val, $exp, "/" );
260 $sk->outputPage( $this );
261 flush();
264 function out( $ins )
266 global $wgInputEncoding, $wgOutputEncoding, $wgLang;
267 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
268 $outs = $ins;
269 } else {
270 $outs = $wgLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
271 if ( false === $outs ) { $outs = $ins; }
273 print $outs;
276 function setEncodings()
278 global $HTTP_SERVER_VARS, $wgInputEncoding, $wgOutputEncoding;
279 global $wgUser, $wgLang;
281 $wgInputEncoding = strtolower( $wgInputEncoding );
282 $s = $HTTP_SERVER_VARS['HTTP_ACCEPT_CHARSET'];
284 if( $wgUser->getOption( 'altencoding' ) ) {
285 $wgLang->setAltEncoding();
286 return;
289 if ( "" == $s ) {
290 $wgOutputEncoding = strtolower( $wgOutputEncoding );
291 return;
293 $a = explode( ",", $s );
294 $best = 0.0;
295 $bestset = "*";
297 foreach ( $a as $s ) {
298 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
299 $set = $m[1];
300 $q = (float)($m[2]);
301 } else {
302 $set = $s;
303 $q = 1.0;
305 if ( $q > $best ) {
306 $bestset = $set;
307 $best = $q;
310 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
311 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
312 $wgOutputEncoding = strtolower( $bestset );
314 # Disable for now
316 $wgOutputEncoding = $wgInputEncoding;
319 function reportTime()
321 global $wgRequestTime, $wgDebugLogFile, $HTTP_SERVER_VARS;
322 global $wgProfiling, $wgProfileStack, $wgUser;
324 list( $usec, $sec ) = explode( " ", microtime() );
325 $now = (float)$sec + (float)$usec;
327 list( $usec, $sec ) = explode( " ", $wgRequestTime );
328 $start = (float)$sec + (float)$usec;
329 $elapsed = $now - $start;
331 if ( "" != $wgDebugLogFile ) {
332 $prof = wfGetProfilingOutput( $start, $elapsed );
334 if( $forward = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'] )
335 $forward = " forwarded for $forward";
336 if( $client = $HTTP_SERVER_VARS['HTTP_CLIENT_IP'] )
337 $forward .= " client IP $client";
338 if( $from = $HTTP_SERVER_VARS['HTTP_FROM'] )
339 $forward .= " from $from";
340 if( $forward )
341 $forward = "\t(proxied via {$HTTP_SERVER_VARS['REMOTE_ADDR']}{$forward})";
342 if($wgUser->getId() == 0)
343 $forward .= " anon";
344 $log = sprintf( "%s\t%04.3f\t%s\n",
345 gmdate( "YmdHis" ), $elapsed,
346 urldecode( $HTTP_SERVER_VARS['REQUEST_URI'] . $forward ) );
347 error_log( $log . $prof, 3, $wgDebugLogFile );
349 $com = sprintf( "<!-- Time since request: %01.2f secs. -->",
350 $elapsed );
351 return $com;
354 # Note: these arguments are keys into wfMsg(), not text!
356 function errorpage( $title, $msg )
358 global $wgTitle;
360 $this->mDebugtext .= "Original title: " .
361 $wgTitle->getPrefixedText() . "\n";
362 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
363 $this->setPageTitle( wfMsg( $title ) );
364 $this->setRobotpolicy( "noindex,nofollow" );
365 $this->setArticleFlag( false );
367 $this->mBodytext = "";
368 $this->addHTML( "<p>" . wfMsg( $msg ) . "\n" );
369 $this->returnToMain( false );
371 $this->output();
372 exit;
375 function sysopRequired()
377 global $wgUser;
379 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
380 $this->setPageTitle( wfMsg( "sysoptitle" ) );
381 $this->setRobotpolicy( "noindex,nofollow" );
382 $this->setArticleFlag( false );
383 $this->mBodytext = "";
385 $sk = $wgUser->getSkin();
386 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
387 $text = str_replace( "$1", $ap, wfMsg( "sysoptext" ) );
388 $this->addHTML( $text );
389 $this->returnToMain();
392 function developerRequired()
394 global $wgUser;
396 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
397 $this->setPageTitle( wfMsg( "developertitle" ) );
398 $this->setRobotpolicy( "noindex,nofollow" );
399 $this->setArticleFlag( false );
400 $this->mBodytext = "";
402 $sk = $wgUser->getSkin();
403 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
404 $text = str_replace( "$1", $ap, wfMsg( "developertext" ) );
405 $this->addHTML( $text );
406 $this->returnToMain();
409 function databaseError( $fname )
411 global $wgUser, $wgCommandLineMode;
413 $this->setPageTitle( wfMsgNoDB( "databaseerror" ) );
414 $this->setRobotpolicy( "noindex,nofollow" );
415 $this->setArticleFlag( false );
417 if ( $wgCommandLineMode ) {
418 $msg = wfMsgNoDB( "dberrortextcl" );
419 } else {
420 $msg = wfMsgNoDB( "dberrortextcl" );
423 $msg = str_replace( "$1", htmlspecialchars( wfLastDBquery() ), $msg );
424 $msg = str_replace( "$2", htmlspecialchars( $fname ), $msg );
425 $msg = str_replace( "$3", wfLastErrno(), $msg );
426 $msg = str_replace( "$4", htmlspecialchars( wfLastError() ), $msg );
428 if ( $wgCommandLineMode ) {
429 print "$msg\n";
430 exit();
432 $sk = $wgUser->getSkin();
433 $shlink = $sk->makeKnownLink( wfMsgNoDB( "searchhelppage" ),
434 wfMsgNoDB( "searchingwikipedia" ) );
435 $msg = str_replace( "$5", $shlink, $msg );
437 $this->mBodytext = $msg;
438 $this->output();
439 exit();
442 function readOnlyPage( $source = "" )
444 global $wgUser, $wgReadOnlyFile;
446 $this->setPageTitle( wfMsg( "readonly" ) );
447 $this->setRobotpolicy( "noindex,nofollow" );
448 $this->setArticleFlag( false );
450 $reason = implode( "", file( $wgReadOnlyFile ) );
451 $text = str_replace( "$1", $reason, wfMsg( "readonlytext" ) );
453 if($source) {
454 $rows = $wgUser->getOption( "rows" );
455 $cols = $wgUser->getOption( "cols" );
456 $text .= "</p>\n<textarea cols='$cols' rows='$rows' readonly>" .
457 htmlspecialchars( $source ) . "\n</textarea>";
460 $this->addHTML( $text );
461 $this->returnToMain( false );
464 function fatalError( $message )
466 $this->setPageTitle( wfMsg( "internalerror" ) );
467 $this->setRobotpolicy( "noindex,nofollow" );
468 $this->setArticleFlag( false );
470 $this->mBodytext = $message;
471 $this->output();
472 exit;
475 function unexpectedValueError( $name, $val )
477 $msg = str_replace( "$1", $name, wfMsg( "unexpected" ) );
478 $msg = str_replace( "$2", $val, $msg );
479 $this->fatalError( $msg );
482 function fileCopyError( $old, $new )
484 $msg = str_replace( "$1", $old, wfMsg( "filecopyerror" ) );
485 $msg = str_replace( "$2", $new, $msg );
486 $this->fatalError( $msg );
489 function fileRenameError( $old, $new )
491 $msg = str_replace( "$1", $old, wfMsg( "filerenameerror" ) );
492 $msg = str_replace( "$2", $new, $msg );
493 $this->fatalError( $msg );
496 function fileDeleteError( $name )
498 $msg = str_replace( "$1", $name, wfMsg( "filedeleteerror" ) );
499 $this->fatalError( $msg );
502 function fileNotFoundError( $name )
504 $msg = str_replace( "$1", $name, wfMsg( "filenotfound" ) );
505 $this->fatalError( $msg );
508 function returnToMain( $auto = true )
510 global $wgUser, $wgOut, $returnto;
512 $sk = $wgUser->getSkin();
513 if ( "" == $returnto ) {
514 $returnto = wfMsg( "mainpage" );
516 $link = $sk->makeKnownLink( $returnto, "" );
518 $r = str_replace( "$1", $link, wfMsg( "returnto" ) );
519 if ( $auto ) {
520 $wgOut->addMeta( "http:Refresh", "10;url=" .
521 wfLocalUrlE( wfUrlencode( $returnto ) ) );
523 $wgOut->addHTML( "\n<p>$r\n" );
527 function categoryMagic ()
529 global $wgTitle , $wgUseCategoryMagic ;
530 if ( !isset ( $wgUseCategoryMagic ) || !$wgUseCategoryMagic ) return ;
531 $id = $wgTitle->getArticleID() ;
532 $cat = ucfirst ( wfMsg ( "category" ) ) ;
533 $ti = $wgTitle->getText() ;
534 $ti = explode ( ":" , $ti , 2 ) ;
535 if ( $cat != $ti[0] ) return "" ;
536 $r = "<br break=all>\n" ;
538 $articles = array() ;
539 $parents = array () ;
540 $children = array() ;
543 global $wgUser ;
544 $sk = $wgUser->getSkin() ;
545 $sql = "SELECT l_from FROM links WHERE l_to={$id}" ;
546 $res = wfQuery ( $sql, DB_READ ) ;
547 while ( $x = wfFetchObject ( $res ) )
549 # $t = new Title ;
550 # $t->newFromDBkey ( $x->l_from ) ;
551 # $t = $t->getText() ;
552 $t = $x->l_from ;
553 $y = explode ( ":" , $t , 2 ) ;
554 if ( count ( $y ) == 2 && $y[0] == $cat )
556 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
558 else array_push ( $articles , $sk->makeLink ( $t ) ) ;
560 wfFreeResult ( $res ) ;
562 # Children
563 if ( count ( $children ) > 0 )
565 asort ( $children ) ;
566 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
567 $r .= implode ( ", " , $children ) ;
570 # Articles
571 if ( count ( $articles ) > 0 )
573 asort ( $articles ) ;
574 $h = str_replace ( "$1" , $ti[1] , wfMsg("category_header") ) ;
575 $r .= "<h2>{$h}</h2>\n" ;
576 $r .= implode ( ", " , $articles ) ;
580 return $r ;
583 function getHTMLattrs ()
585 $htmlattrs = array( # Allowed attributes--no scripting, etc.
586 "title", "align", "lang", "dir", "width", "height",
587 "bgcolor", "clear", /* BR */ "noshade", /* HR */
588 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
589 /* FONT */ "type", "start", "value", "compact",
590 /* For various lists, mostly deprecated but safe */
591 "summary", "width", "border", "frame", "rules",
592 "cellspacing", "cellpadding", "valign", "char",
593 "charoff", "colgroup", "col", "span", "abbr", "axis",
594 "headers", "scope", "rowspan", "colspan", /* Tables */
595 "id", "class", "name", "style" /* For CSS */
597 return $htmlattrs ;
600 function fixTableTags ( $t )
602 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
603 $htmlattrs = $this->getHTMLattrs() ;
605 # Strip non-approved attributes from the tag
606 $t = preg_replace(
607 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
608 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
609 $t);
611 return trim ( $t ) ;
614 function doTableStuff ( $t )
616 $t = explode ( "\n" , $t ) ;
617 $td = array () ; # Is currently a td tag open?
618 $ltd = array () ; # Was it TD or TH?
619 $tr = array () ; # Is currently a tr tag open?
620 $ltr = array () ; # tr attributes
621 foreach ( $t AS $k => $x )
623 $x = rtrim ( $x ) ;
624 $fc = substr ( $x , 0 , 1 ) ;
625 if ( "{|" == substr ( $x , 0 , 2 ) )
627 $t[$k] = "<table " . $this->fixTableTags ( substr ( $x , 3 ) ) . ">" ;
628 array_push ( $td , false ) ;
629 array_push ( $ltd , "" ) ;
630 array_push ( $tr , false ) ;
631 array_push ( $ltr , "" ) ;
633 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
634 else if ( "|}" == substr ( $x , 0 , 2 ) )
636 $z = "</table>\n" ;
637 $l = array_pop ( $ltd ) ;
638 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
639 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
640 array_pop ( $ltr ) ;
641 $t[$k] = $z ;
643 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
645 $z = trim ( substr ( $x , 2 ) ) ;
646 $t[$k] = "<caption>{$z}</caption>\n" ;
648 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
650 $x = substr ( $x , 1 ) ;
651 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
652 $z = "" ;
653 $l = array_pop ( $ltd ) ;
654 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
655 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
656 array_pop ( $ltr ) ;
657 $t[$k] = $z ;
658 array_push ( $tr , false ) ;
659 array_push ( $td , false ) ;
660 array_push ( $ltd , "" ) ;
661 array_push ( $ltr , $this->fixTableTags ( $x ) ) ;
663 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
665 if ( "|+" == substr ( $x , 0 , 2 ) )
667 $fc = "+" ;
668 $x = substr ( $x , 1 ) ;
670 $after = substr ( $x , 1 ) ;
671 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
672 $after = explode ( "||" , $after ) ;
673 $t[$k] = "" ;
674 foreach ( $after AS $theline )
676 $z = "" ;
677 $tra = array_pop ( $ltr ) ;
678 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
679 array_push ( $tr , true ) ;
680 array_push ( $ltr , "" ) ;
682 $l = array_pop ( $ltd ) ;
683 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
684 if ( $fc == "|" ) $l = "TD" ;
685 else if ( $fc == "!" ) $l = "TH" ;
686 else if ( $fc == "+" ) $l = "CAPTION" ;
687 else $l = "" ;
688 array_push ( $ltd , $l ) ;
689 $y = explode ( "|" , $theline , 2 ) ;
690 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
691 else $y = $y = "{$z}<{$l} ".$this->fixTableTags($y[0]).">{$y[1]}" ;
692 $t[$k] .= $y ;
693 array_push ( $td , true ) ;
698 # Closing open td, tr && table
699 while ( count ( $td ) > 0 )
701 if ( array_pop ( $td ) ) $t[] = "</td>" ;
702 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
703 $t[] = "</table>" ;
706 $t = implode ( "\n" , $t ) ;
707 # $t = $this->removeHTMLtags( $t );
708 return $t ;
711 # Well, OK, it's actually about 14 passes. But since all the
712 # hard lifting is done inside PHP's regex code, it probably
713 # wouldn't speed things up much to add a real parser.
715 function doWikiPass2( $text, $linestart )
717 global $wgUser, $wgLang, $wgUseDynamicDates;
718 $fname = "OutputPage::doWikiPass2";
719 wfProfileIn( $fname );
721 $text = $this->removeHTMLtags( $text );
722 $text = $this->replaceVariables( $text );
724 $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
725 $text = str_replace ( "<HR>", "<hr>", $text );
727 $text = $this->doAllQuotes( $text );
728 $text = $this->doHeadings( $text );
729 $text = $this->doBlockLevels( $text, $linestart );
731 if($wgUseDynamicDates) {
732 $text = $wgLang->replaceDates( $text );
735 $text = $this->replaceExternalLinks( $text );
736 $text = $this->replaceInternalLinks ( $text );
737 $text = $this->doTableStuff ( $text ) ;
739 $text = $this->magicISBN( $text );
740 $text = $this->magicRFC( $text );
741 $text = $this->formatHeadings( $text );
743 $sk = $wgUser->getSkin();
744 $text = $sk->transformContent( $text );
745 $text .= $this->categoryMagic () ;
747 wfProfileOut( $fname );
748 return $text;
751 /* private */ function doAllQuotes( $text )
753 $outtext = "";
754 $lines = explode( "\r\n", $text );
755 foreach ( $lines as $line ) {
756 $outtext .= $this->doQuotes ( "", $line, "" ) . "\r\n";
758 return $outtext;
761 /* private */ function doQuotes( $pre, $text, $mode )
763 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
764 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
765 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
766 if ( substr ($m[2], 0, 1) == "'" ) {
767 $m[2] = substr ($m[2], 1);
768 if ($mode == "em") {
769 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "emstrong" );
770 } else if ($mode == "strong") {
771 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
772 } else if (($mode == "emstrong") || ($mode == "both")) {
773 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
774 } else if ($mode == "strongem") {
775 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
776 } else {
777 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
779 } else {
780 if ($mode == "strong") {
781 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "strongem" );
782 } else if ($mode == "em") {
783 return $m1_em . $this->doQuotes ( "", $m[2], "" );
784 } else if ($mode == "emstrong") {
785 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
786 } else if (($mode == "strongem") || ($mode == "both")) {
787 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
788 } else {
789 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
792 } else {
793 $text_strong = ($text == "") ? "" : "<strong>{$text}</strong>";
794 $text_em = ($text == "") ? "" : "<em>{$text}</em>";
795 if ($mode == "") {
796 return $pre . $text;
797 } else if ($mode == "em") {
798 return $pre . $text_em;
799 } else if ($mode == "strong") {
800 return $pre . $text_strong;
801 } else if ($mode == "strongem") {
802 return (($pre == "") && ($text == "")) ? "" : "<strong>{$pre}{$text_em}</strong>";
803 } else {
804 return (($pre == "") && ($text == "")) ? "" : "<em>{$pre}{$text_strong}</em>";
809 /* private */ function doHeadings( $text )
811 for ( $i = 6; $i >= 1; --$i ) {
812 $h = substr( "======", 0, $i );
813 $text = preg_replace( "/^{$h}([^=]+){$h}(\\s|$)/m",
814 "<h{$i}>\\1</h{$i}>\\2", $text );
816 return $text;
819 # Note: we have to do external links before the internal ones,
820 # and otherwise take great care in the order of things here, so
821 # that we don't end up interpreting some URLs twice.
823 /* private */ function replaceExternalLinks( $text )
825 $fname = "OutputPage::replaceExternalLinks";
826 wfProfileIn( $fname );
827 $text = $this->subReplaceExternalLinks( $text, "http", true );
828 $text = $this->subReplaceExternalLinks( $text, "https", true );
829 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
830 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
831 $text = $this->subReplaceExternalLinks( $text, "news", false );
832 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
833 wfProfileOut( $fname );
834 return $text;
837 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
839 global $wgUser, $printable;
840 global $wgAllowExternalImages;
843 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
844 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
846 # this is the list of separators that should be ignored if they
847 # are the last character of an URL but that should be included
848 # if they occur within the URL, e.g. "go to www.foo.com, where .."
849 # in this case, the last comma should not become part of the URL,
850 # but in "www.foo.com/123,2342,32.htm" it should.
851 $sep = ",;\.:";
852 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
853 $images = "gif|png|jpg|jpeg";
855 # PLEASE NOTE: The curly braces { } are not part of the regex,
856 # they are interpreted as part of the string (used to tell PHP
857 # that the content of the string should be inserted there).
858 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
859 "((?i){$images})([^{$uc}]|$)/";
861 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
862 $sk = $wgUser->getSkin();
864 if ( $autonumber and $wgAllowExternalImages) { # Use img tags only for HTTP urls
865 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
866 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
868 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
869 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
870 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
871 "</a>\\5", $s );
872 $s = str_replace( $unique, $protocol, $s );
874 $a = explode( "[{$protocol}:", " " . $s );
875 $s = array_shift( $a );
876 $s = substr( $s, 1 );
878 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
879 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
881 foreach ( $a as $line ) {
882 if ( preg_match( $e1, $line, $m ) ) {
883 $link = "{$protocol}:{$m[1]}";
884 $trail = $m[2];
885 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
886 else { $text = wfEscapeHTML( $link ); }
887 } else if ( preg_match( $e2, $line, $m ) ) {
888 $link = "{$protocol}:{$m[1]}";
889 $text = $m[2];
890 $trail = $m[3];
891 } else {
892 $s .= "[{$protocol}:" . $line;
893 continue;
895 if ( $printable == "yes") $paren = " (<i>" . htmlspecialchars ( $link ) . "</i>)";
896 else $paren = "";
897 $la = $sk->getExternalLinkAttributes( $link, $text );
898 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
901 return $s;
904 /* private */ function replaceInternalLinks( $s )
906 global $wgTitle, $wgUser, $wgLang;
907 global $wgLinkCache, $wgInterwikiMagic, $wgUseCategoryMagic;
908 global $wgNamespacesWithSubpages, $wgLanguageCode;
909 wfProfileIn( $fname = "OutputPage::replaceInternalLinks" );
911 wfProfileIn( "$fname-setup" );
912 $tc = Title::legalChars() . "#";
913 $sk = $wgUser->getSkin();
915 $a = explode( "[[", " " . $s );
916 $s = array_shift( $a );
917 $s = substr( $s, 1 );
919 $e1 = "/^([{$tc}]+)\\|([^]]+)]](.*)\$/sD";
920 $e2 = "/^([{$tc}]+)]](.*)\$/sD";
921 wfProfileOut( "$fname-setup" );
923 foreach ( $a as $line ) {
924 wfProfileIn( "$fname-loop" );
925 if ( preg_match( $e1, $line, $m ) ) { # page with alternate text
927 $text = $m[2];
928 $trail = $m[3];
930 } else if ( preg_match( $e2, $line, $m ) ) { # page with normal text
932 $text = "";
933 $trail = $m[2];
936 else { # Invalid form; output directly
937 $s .= "[[" . $line ;
938 wfProfileOut( "$fname-loop" );
939 continue;
941 if(substr($m[1],0,1)=="/") { # subpage
942 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
943 $m[1]=substr($m[1],1,strlen($m[1])-2);
944 $noslash=$m[1];
946 } else {
947 $noslash=substr($m[1],1);
949 if($wgNamespacesWithSubpages[$wgTitle->getNamespace()]) { # subpages allowed here
950 $link = $wgTitle->getPrefixedText(). "/" . trim($noslash);
951 if(!$text) {
952 $text= $m[1];
953 } # this might be changed for ugliness reasons
954 } else {
955 $link = $noslash; # no subpage allowed, use standard link
957 } else { # no subpage
958 $link = $m[1];
961 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z\\x80-\\xff]+):(.*)\$/", $link, $m ) ) {
962 $pre = strtolower( $m[1] );
963 $suf = trim($m[2]);
964 if( empty( $suf ) ) {
965 $s .= $trail;
966 } else if ( $wgLang->getNsIndex( $pre ) ==
967 Namespace::getImage() ) {
968 $nt = Title::newFromText( $suf );
969 $name = $nt->getDBkey();
970 if ( "" == $text ) { $text = $nt->GetText(); }
972 $wgLinkCache->addImageLink( $name );
973 $s .= $sk->makeImageLink( $name,
974 wfImageUrl( $name ), $text );
975 $s .= $trail;
976 } else if ( "media" == $pre ) {
977 $nt = Title::newFromText( $suf );
978 $name = $nt->getDBkey();
979 if ( "" == $text ) { $text = $nt->GetText(); }
981 $wgLinkCache->addImageLink( $name );
982 $s .= $sk->makeMediaLink( $name,
983 wfImageUrl( $name ), $text );
984 $s .= $trail;
985 } else if ( isset($wgUseCategoryMagic) && $wgUseCategoryMagic && $pre == wfMsg ( "category" ) ) {
986 $l = $sk->makeLink ( $pre.":".ucfirst($m[2]) , ucfirst ( $m[2] ) ) ;
987 array_push ( $this->mCategoryLinks , $l ) ;
988 $s .= $trail ;
989 } else {
990 $l = $wgLang->getLanguageName( $pre );
991 if ( "" == $l or !$wgInterwikiMagic or
992 Namespace::isTalk( $wgTitle->getNamespace() ) ) {
993 if ( "" == $text ) { $text = $link; }
994 $s .= $sk->makeLink( $link, $text, "", $trail );
995 } else if ( $pre != $wgLanguageCode ) {
996 array_push( $this->mLanguageLinks, "$pre:$suf" );
997 $s .= $trail;
1000 # } else if ( 0 == strcmp( "##", substr( $link, 0, 2 ) ) ) {
1001 # $link = substr( $link, 2 );
1002 # $s .= "<a name=\"{$link}\">{$text}</a>{$trail}";
1003 } else {
1004 if ( "" == $text ) { $text = $link; }
1005 $s .= $sk->makeLink( $link, $text, "", $trail );
1007 wfProfileOut( "$fname-loop" );
1009 wfProfileOut( $fname );
1010 return $s;
1013 # Some functions here used by doBlockLevels()
1015 /* private */ function closeParagraph()
1017 $result = "";
1018 if ( 0 != strcmp( "p", $this->mLastSection ) &&
1019 0 != strcmp( "", $this->mLastSection ) ) {
1020 $result = "</" . $this->mLastSection . ">";
1022 $this->mLastSection = "";
1023 return $result;
1025 # getCommon() returns the length of the longest common substring
1026 # of both arguments, starting at the beginning of both.
1028 /* private */ function getCommon( $st1, $st2 )
1030 $fl = strlen( $st1 );
1031 $shorter = strlen( $st2 );
1032 if ( $fl < $shorter ) { $shorter = $fl; }
1034 for ( $i = 0; $i < $shorter; ++$i ) {
1035 if ( $st1{$i} != $st2{$i} ) { break; }
1037 return $i;
1039 # These next three functions open, continue, and close the list
1040 # element appropriate to the prefix character passed into them.
1042 /* private */ function openList( $char )
1044 $result = $this->closeParagraph();
1046 if ( "*" == $char ) { $result .= "<ul><li>"; }
1047 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1048 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1049 else if ( ";" == $char ) {
1050 $result .= "<dl><dt>";
1051 $this->mDTopen = true;
1053 else { $result = "<!-- ERR 1 -->"; }
1055 return $result;
1058 /* private */ function nextItem( $char )
1060 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1061 else if ( ":" == $char || ";" == $char ) {
1062 $close = "</dd>";
1063 if ( $this->mDTopen ) { $close = "</dt>"; }
1064 if ( ";" == $char ) {
1065 $this->mDTopen = true;
1066 return $close . "<dt>";
1067 } else {
1068 $this->mDTopen = false;
1069 return $close . "<dd>";
1072 return "<!-- ERR 2 -->";
1075 /* private */function closeList( $char )
1077 if ( "*" == $char ) { return "</li></ul>"; }
1078 else if ( "#" == $char ) { return "</li></ol>"; }
1079 else if ( ":" == $char ) {
1080 if ( $this->mDTopen ) {
1081 $this->mDTopen = false;
1082 return "</dt></dl>";
1083 } else {
1084 return "</dd></dl>";
1087 return "<!-- ERR 3 -->";
1090 /* private */ function doBlockLevels( $text, $linestart )
1092 $fname = "OutputPage::doBlockLevels";
1093 wfProfileIn( $fname );
1094 # Parsing through the text line by line. The main thing
1095 # happening here is handling of block-level elements p, pre,
1096 # and making lists from lines starting with * # : etc.
1098 $a = explode( "\n", $text );
1099 $text = $lastPref = "";
1100 $this->mDTopen = $inBlockElem = false;
1102 if ( ! $linestart ) { $text .= array_shift( $a ); }
1103 foreach ( $a as $t ) {
1104 if ( "" != $text ) { $text .= "\n"; }
1106 $oLine = $t;
1107 $opl = strlen( $lastPref );
1108 $npl = strspn( $t, "*#:;" );
1109 $pref = substr( $t, 0, $npl );
1110 $pref2 = str_replace( ";", ":", $pref );
1111 $t = substr( $t, $npl );
1113 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1114 $text .= $this->nextItem( substr( $pref, -1 ) );
1116 if ( ";" == substr( $pref, -1 ) ) {
1117 $cpos = strpos( $t, ":" );
1118 if ( ! ( false === $cpos ) ) {
1119 $term = substr( $t, 0, $cpos );
1120 $text .= $term . $this->nextItem( ":" );
1121 $t = substr( $t, $cpos + 1 );
1124 } else if (0 != $npl || 0 != $opl) {
1125 $cpl = $this->getCommon( $pref, $lastPref );
1127 while ( $cpl < $opl ) {
1128 $text .= $this->closeList( $lastPref{$opl-1} );
1129 --$opl;
1131 if ( $npl <= $cpl && $cpl > 0 ) {
1132 $text .= $this->nextItem( $pref{$cpl-1} );
1134 while ( $npl > $cpl ) {
1135 $char = substr( $pref, $cpl, 1 );
1136 $text .= $this->openList( $char );
1138 if ( ";" == $char ) {
1139 $cpos = strpos( $t, ":" );
1140 if ( ! ( false === $cpos ) ) {
1141 $term = substr( $t, 0, $cpos );
1142 $text .= $term . $this->nextItem( ":" );
1143 $t = substr( $t, $cpos + 1 );
1146 ++$cpl;
1148 $lastPref = $pref2;
1150 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1151 if ( preg_match(
1152 "/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6)/i", $t ) ) {
1153 $text .= $this->closeParagraph();
1154 $inBlockElem = true;
1156 if ( ! $inBlockElem ) {
1157 if ( " " == $t{0} ) {
1158 $newSection = "pre";
1159 # $t = wfEscapeHTML( $t );
1161 else { $newSection = "p"; }
1163 if ( 0 == strcmp( "", trim( $oLine ) ) ) {
1164 $text .= $this->closeParagraph();
1165 $text .= "<" . $newSection . ">";
1166 } else if ( 0 != strcmp( $this->mLastSection,
1167 $newSection ) ) {
1168 $text .= $this->closeParagraph();
1169 if ( 0 != strcmp( "p", $newSection ) ) {
1170 $text .= "<" . $newSection . ">";
1173 $this->mLastSection = $newSection;
1175 if ( $inBlockElem &&
1176 preg_match( "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6)/i", $t ) ) {
1177 $inBlockElem = false;
1180 $text .= $t;
1182 while ( $npl ) {
1183 $text .= $this->closeList( $pref2{$npl-1} );
1184 --$npl;
1186 if ( "" != $this->mLastSection ) {
1187 if ( "p" != $this->mLastSection ) {
1188 $text .= "</" . $this->mLastSection . ">";
1190 $this->mLastSection = "";
1192 wfProfileOut( $fname );
1193 return $text;
1196 /* private */ function replaceVariables( $text )
1198 global $wgLang;
1199 $fname = "OutputPage:replaceVariables";
1200 wfProfileIn( $fname );
1202 /* As with sigs, use server's local time --
1203 ensure this is appropriate for your audience! */
1204 $v = date( "m" );
1205 $mw =& MagicWord::get( MAG_CURRENTMONTH );
1206 $text = $mw->replace( $v, $text );
1208 $v = $wgLang->getMonthName( date( "n" ) );
1209 $mw =& MagicWord::get( MAG_CURRENTMONTHNAME );
1210 $text = $mw->replace( $v, $text );
1212 $v = $wgLang->getMonthNameGen( date( "n" ) );
1213 $mw =& MagicWord::get( MAG_CURRENTMONTHNAMEGEN );
1214 $text = $mw->replace( $v, $text );
1216 $v = date( "j" );
1217 $mw = MagicWord::get( MAG_CURRENTDAY );
1218 $text = $mw->replace( $v, $text );
1220 $v = $wgLang->getWeekdayName( date( "w" )+1 );
1221 $mw =& MagicWord::get( MAG_CURRENTDAYNAME );
1222 $text = $mw->replace( $v, $text );
1224 $v = date( "Y" );
1225 $mw =& MagicWord::get( MAG_CURRENTYEAR );
1226 $text = $mw->replace( $v, $text );
1228 $v = $wgLang->time( wfTimestampNow(), false );
1229 $mw =& MagicWord::get( MAG_CURRENTTIME );
1230 $text = $mw->replace( $v, $text );
1232 $mw =& MagicWord::get( MAG_NUMBEROFARTICLES );
1233 if ( $mw->match( $text ) ) {
1234 $v = wfNumberOfArticles();
1235 $text = $mw->replace( $v, $text );
1238 # The callbacks are in GlobalFunctions.php
1239 $mw =& MagicWord::get( MAG_MSG );
1240 $text = $mw->substituteCallback( $text, "replaceMsgVar" );
1242 $mw =& MagicWord::get( MAG_MSGNW );
1243 $text = $mw->substituteCallback( $text, "replaceMsgVarNw" );
1245 wfProfileOut( $fname );
1246 return $text;
1249 /* private */ function removeHTMLtags( $text )
1251 $fname = "OutputPage::removeHTMLtags";
1252 wfProfileIn( $fname );
1253 $htmlpairs = array( # Tags that must be closed
1254 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1255 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1256 "strike", "strong", "tt", "var", "div", "center",
1257 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1258 "ruby", "rt" , "rb" , "rp"
1260 $htmlsingle = array(
1261 "br", "p", "hr", "li", "dt", "dd"
1263 $htmlnest = array( # Tags that can be nested--??
1264 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1265 "dl", "font", "big", "small", "sub", "sup"
1267 $tabletags = array( # Can only appear inside table
1268 "td", "th", "tr"
1271 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1272 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1274 $htmlattrs = $this->getHTMLattrs () ;
1276 # Remove HTML comments
1277 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1279 $bits = explode( "<", $text );
1280 $text = array_shift( $bits );
1281 $tagstack = array(); $tablestack = array();
1283 foreach ( $bits as $x ) {
1284 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1285 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1286 $x, $regs );
1287 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1288 error_reporting( $prev );
1290 $badtag = 0 ;
1291 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1292 # Check our stack
1293 if ( $slash ) {
1294 # Closing a tag...
1295 if ( ! in_array( $t, $htmlsingle ) &&
1296 ( $ot = array_pop( $tagstack ) ) != $t ) {
1297 array_push( $tagstack, $ot );
1298 $badtag = 1;
1299 } else {
1300 if ( $t == "table" ) {
1301 $tagstack = array_pop( $tablestack );
1303 $newparams = "";
1305 } else {
1306 # Keep track for later
1307 if ( in_array( $t, $tabletags ) &&
1308 ! in_array( "table", $tagstack ) ) {
1309 $badtag = 1;
1310 } else if ( in_array( $t, $tagstack ) &&
1311 ! in_array ( $t , $htmlnest ) ) {
1312 $badtag = 1 ;
1313 } else if ( ! in_array( $t, $htmlsingle ) ) {
1314 if ( $t == "table" ) {
1315 array_push( $tablestack, $tagstack );
1316 $tagstack = array();
1318 array_push( $tagstack, $t );
1320 # Strip non-approved attributes from the tag
1321 $newparams = preg_replace(
1322 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
1323 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
1324 $params);
1326 if ( ! $badtag ) {
1327 $rest = str_replace( ">", "&gt;", $rest );
1328 $text .= "<$slash$t$newparams$brace$rest";
1329 continue;
1332 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1334 # Close off any remaining tags
1335 while ( $t = array_pop( $tagstack ) ) {
1336 $text .= "</$t>\n";
1337 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1339 wfProfileOut( $fname );
1340 return $text;
1346 * This function accomplishes several tasks:
1347 * 1) Auto-number headings if that option is enabled
1348 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1349 * 3) Add a Table of contents on the top for users who have enabled the option
1350 * 4) Auto-anchor headings
1352 * It loops through all headlines, collects the necessary data, then splits up the
1353 * string and re-inserts the newly formatted headlines.
1355 * */
1356 /* private */ function formatHeadings( $text )
1358 global $wgUser,$wgArticle,$wgTitle,$wpPreview;
1359 $nh=$wgUser->getOption( "numberheadings" );
1360 $st=$wgUser->getOption( "showtoc" );
1361 if(!$wgTitle->userCanEdit()) {
1362 $es=0;
1363 $esr=0;
1364 } else {
1365 $es=$wgUser->getID() && $wgUser->getOption( "editsection" );
1366 $esr=$wgUser->getID() && $wgUser->getOption( "editsectiononrightclick" );
1369 # Inhibit editsection links if requested in the page
1370 if ($es) {
1371 $esw=& MagicWord::get(MAG_NOEDITSECTION);
1372 if ($esw->matchAndRemove( $text )) {
1373 $es=0;
1376 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1377 # do not add TOC
1378 $mw =& MagicWord::get( MAG_NOTOC );
1379 if ($mw->matchAndRemove( $text ))
1381 $st = 0;
1384 # never add the TOC to the Main Page. This is an entry page that should not
1385 # be more than 1-2 screens large anyway
1386 if($wgTitle->getPrefixedText()==wfMsg("mainpage")) {$st=0;}
1388 # We need this to perform operations on the HTML
1389 $sk=$wgUser->getSkin();
1391 # Get all headlines for numbering them and adding funky stuff like [edit]
1392 # links
1393 preg_match_all("/<H([1-6])(.*?>)(.*?)<\/H[1-6]>/i",$text,$matches);
1395 # headline counter
1396 $c=0;
1398 # Ugh .. the TOC should have neat indentation levels which can be
1399 # passed to the skin functions. These are determined here
1400 foreach($matches[3] as $headline) {
1401 if($level) { $prevlevel=$level;}
1402 $level=$matches[1][$c];
1403 if(($nh||$st) && $prevlevel && $level>$prevlevel) {
1405 $h[$level]=0; // reset when we enter a new level
1406 $toc.=$sk->tocIndent($level-$prevlevel);
1407 $toclevel+=$level-$prevlevel;
1410 if(($nh||$st) && $level<$prevlevel) {
1411 $h[$level+1]=0; // reset when we step back a level
1412 $toc.=$sk->tocUnindent($prevlevel-$level);
1413 $toclevel-=$prevlevel-$level;
1416 $h[$level]++; // count number of headlines for each level
1418 if($nh||$st) {
1419 for($i=1;$i<=$level;$i++) {
1420 if($h[$i]) {
1421 if($dot) {$numbering.=".";}
1422 $numbering.=$h[$i];
1423 $dot=1;
1429 $canonized_headline=preg_replace("/<.*?>/","",$headline); // strip out HTML
1430 $tocline=$canonized_headline;
1431 $canonized_headline=str_replace('"',"",$canonized_headline);
1432 $canonized_headline=str_replace(" ","_",trim($canonized_headline));
1433 $refer[$c]=$canonized_headline;
1434 $refers[$canonized_headline]++; // count how many in assoc. array so we can track dupes in anchors
1435 $refcount[$c]=$refers[$canonized_headline];
1436 if($nh||$st) {
1437 $tocline=$numbering ." ". $tocline;
1438 if($nh) {
1439 $headline=$numbering . " " . $headline; // the two are different if the line contains a link
1442 $anchor=$canonized_headline;
1443 if($refcount[$c]>1) {$anchor.="_".$refcount[$c];}
1444 if($st) {
1445 $toc.=$sk->tocLine($anchor,$tocline,$toclevel);
1447 if($es && !isset($wpPreview)) {
1448 $head[$c].=$sk->editSectionLink($c+1);
1450 $head[$c].="<H".$level.$matches[2][$c]
1451 ."<a name=\"".$anchor."\">"
1452 .$headline
1453 ."</a>"
1454 ."</H".$level.">";
1455 if($esr && !isset($wpPreview)) {
1456 $head[$c]=$sk->editSectionScript($c+1,$head[$c]);
1458 $numbering="";
1459 $c++;
1460 $dot=0;
1463 if($st) {
1464 $toclines=$c;
1465 $toc.=$sk->tocUnindent($toclevel);
1466 $toc=$sk->tocTable($toc);
1469 // split up and insert constructed headlines
1471 $blocks=preg_split("/<H[1-6].*?>.*?<\/H[1-6]>/i",$text);
1472 $i=0;
1475 foreach($blocks as $block) {
1476 if(($es) && !isset($wpPreview) && $c>0 && $i==0) {
1477 # This is the [edit] link that appears for the top block of text when
1478 # section editing is enabled
1479 $full.=$sk->editSectionLink(0);
1481 $full.=$block;
1482 if($st && $toclines>3 && !$i) {
1483 # Let's add a top anchor just in case we want to link to the top of the page
1484 $full="<a name=\"top\"></a>".$full.$toc;
1487 $full.=$head[$i];
1488 $i++;
1490 return $full;
1493 /* private */ function magicISBN( $text )
1495 global $wgLang;
1497 $a = split( "ISBN ", " $text" );
1498 if ( count ( $a ) < 2 ) return $text;
1499 $text = substr( array_shift( $a ), 1);
1500 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1502 foreach ( $a as $x ) {
1503 $isbn = $blank = "" ;
1504 while ( " " == $x{0} ) {
1505 $blank .= " ";
1506 $x = substr( $x, 1 );
1508 while ( strstr( $valid, $x{0} ) != false ) {
1509 $isbn .= $x{0};
1510 $x = substr( $x, 1 );
1512 $num = str_replace( "-", "", $isbn );
1513 $num = str_replace( " ", "", $num );
1515 if ( "" == $num ) {
1516 $text .= "ISBN $blank$x";
1517 } else {
1518 $text .= "<a href=\"" . wfLocalUrlE( $wgLang->specialPage(
1519 "Booksources"), "isbn={$num}" ) . "\" CLASS=\"internal\">ISBN $isbn</a>";
1520 $text .= $x;
1523 return $text;
1526 /* private */ function magicRFC( $text )
1528 return $text;
1531 /* private */ function headElement()
1533 global $wgDocType, $wgDTD, $wgUser, $wgLanguageCode, $wgOutputEncoding, $wgLang;
1535 $ret = "<!DOCTYPE HTML PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1537 if ( "" == $this->mHTMLtitle ) {
1538 $this->mHTMLtitle = $this->mPagetitle;
1540 $rtl = $wgLang->isRTL() ? " dir='RTL'" : "";
1541 $ret .= "<html lang=\"$wgLanguageCode\"$rtl><head><title>{$this->mHTMLtitle}</title>\n";
1542 array_push( $this->mMetatags, array( "http:Content-type", "text/html; charset={$wgOutputEncoding}" ) );
1543 foreach ( $this->mMetatags as $tag ) {
1544 if ( 0 == strcasecmp( "http:", substr( $tag[0], 0, 5 ) ) ) {
1545 $a = "http-equiv";
1546 $tag[0] = substr( $tag[0], 5 );
1547 } else {
1548 $a = "name";
1550 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\">\n";
1552 $p = $this->mRobotpolicy;
1553 if ( "" == $p ) { $p = "index,follow"; }
1554 $ret .= "<meta name=\"robots\" content=\"$p\">\n";
1556 if ( count( $this->mKeywords ) > 0 ) {
1557 $ret .= "<meta name=\"keywords\" content=\"" .
1558 implode( ",", $this->mKeywords ) . "\">\n";
1560 foreach ( $this->mLinktags as $tag ) {
1561 $ret .= "<link ";
1562 if ( "" != $tag[0] ) { $ret .= "rel=\"{$tag[0]}\" "; }
1563 if ( "" != $tag[1] ) { $ret .= "rev=\"{$tag[1]}\" "; }
1564 $ret .= "href=\"{$tag[2]}\">\n";
1566 $sk = $wgUser->getSkin();
1567 $ret .= $sk->getHeadScripts();
1568 $ret .= $sk->getUserStyles();
1570 $ret .= "</head>\n";
1571 return $ret;