Link fix for "About protected pages"
[mediawiki.git] / includes / OutputPage.php
blob284d1553f3afe615c04bbd06c0d11230d5ed2a49
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 wfProfileIn( "OutputPage::addWikiText" );
137 $unique = "3iyZiyA7iMwg5rhxP0Dcc9oTnj8qD1jm1Sfv4";
138 $unique2 = "4LIQ9nXtiYFPCSfitVwDw7EYwQlL4GeeQ7qSO";
139 $unique3 = "fPaA8gDfdLBqzj68Yjg9Hil3qEF8JGO0uszIp";
140 $nwlist = array();
141 $nwsecs = 0;
142 $mathlist = array();
143 $mathsecs = 0;
144 $prelist = array ();
145 $presecs = 0;
146 $stripped = "";
147 $stripped2 = "";
148 $stripped3 = "";
150 while ( "" != $text ) {
151 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
152 $stripped .= $p[0];
153 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
154 else {
155 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
156 ++$nwsecs;
157 $nwlist[$nwsecs] = wfEscapeHTMLTagsOnly($q[0]);
158 $stripped .= $unique;
159 $text = $q[1];
163 if( $wgUseTeX ) {
164 while ( "" != $stripped ) {
165 $p = preg_split( "/<\\s*math\\s*>/i", $stripped, 2 );
166 $stripped2 .= $p[0];
167 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped = ""; }
168 else {
169 $q = preg_split( "/<\\/\\s*math\\s*>/i", $p[1], 2 );
170 ++$mathsecs;
171 $mathlist[$mathsecs] = renderMath($q[0]);
172 $stripped2 .= $unique2;
173 $stripped = $q[1];
176 } else {
177 $stripped2 = $stripped;
180 while ( "" != $stripped2 ) {
181 $p = preg_split( "/<\\s*pre\\s*>/i", $stripped2, 2 );
182 $stripped3 .= $p[0];
183 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped2 = ""; }
184 else {
185 $q = preg_split( "/<\\/\\s*pre\\s*>/i", $p[1], 2 );
186 ++$presecs;
187 $prelist[$presecs] = "<pre>". wfEscapeHTMLTagsOnly($q[0]). "</pre>";
188 $stripped3 .= $unique3;
189 $stripped2 = $q[1];
193 $text = $this->doWikiPass2( $stripped3, $linestart );
195 $specialChars = array("\\", "$");
196 $escapedChars = array("\\\\", "\\$");
197 for ( $i = 1; $i <= $presecs; ++$i ) {
198 $text = preg_replace( "/{$unique3}/", str_replace( $specialChars,
199 $escapedChars, $prelist[$i] ), $text, 1 );
202 for ( $i = 1; $i <= $mathsecs; ++$i ) {
203 $text = preg_replace( "/{$unique2}/", str_replace( $specialChars,
204 $escapedChars, $mathlist[$i] ), $text, 1 );
207 for ( $i = 1; $i <= $nwsecs; ++$i ) {
208 $text = preg_replace( "/{$unique}/", str_replace( $specialChars,
209 $escapedChars, $nwlist[$i] ), $text, 1 );
211 $this->addHTML( $text );
212 wfProfileOut();
215 function sendCacheControl() {
216 global $wgUseGzip;
217 if( $this->mLastModified != "" ) {
218 wfDebug( "** private caching; {$this->mLastModified} **\n", false );
219 header( "Cache-Control: private, must-revalidate, max-age=0" );
220 header( "Last-modified: {$this->mLastModified}" );
221 if( $wgUseGzip ) {
222 # We should put in Accept-Encoding, but IE chokes on anything but
223 # User-Agent in a Vary: header (at least through 6.0)
224 header( "Vary: User-Agent" );
226 } else {
227 wfDebug( "** no caching **\n", false );
228 header( "Cache-Control: no-cache" ); # Experimental - see below
229 header( "Pragma: no-cache" );
230 header( "Last-modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
232 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
235 # Finally, all the text has been munged and accumulated into
236 # the object, let's actually output it:
238 function output()
240 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
241 global $wgInputEncoding, $wgOutputEncoding, $wgLanguageCode;
242 $sk = $wgUser->getSkin();
244 $this->sendCacheControl();
246 header( "Content-type: text/html; charset={$wgOutputEncoding}" );
247 header( "Content-language: {$wgLanguageCode}" );
249 if ( "" != $this->mRedirect ) {
250 header( "Location: {$this->mRedirect}" );
251 return;
254 $exp = time() + $wgCookieExpiration;
255 foreach( $this->mCookies as $name => $val ) {
256 setcookie( $name, $val, $exp, "/" );
259 $sk->outputPage( $this );
260 flush();
263 function out( $ins )
265 global $wgInputEncoding, $wgOutputEncoding, $wgLang;
266 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
267 $outs = $ins;
268 } else {
269 $outs = $wgLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
270 if ( false === $outs ) { $outs = $ins; }
272 print $outs;
275 function setEncodings()
277 global $HTTP_SERVER_VARS, $wgInputEncoding, $wgOutputEncoding;
278 global $wgUser, $wgLang;
280 $wgInputEncoding = strtolower( $wgInputEncoding );
281 $s = $HTTP_SERVER_VARS['HTTP_ACCEPT_CHARSET'];
283 if( $wgUser->getOption( 'altencoding' ) ) {
284 $wgLang->setAltEncoding();
285 return;
288 if ( "" == $s ) {
289 $wgOutputEncoding = strtolower( $wgOutputEncoding );
290 return;
292 $a = explode( ",", $s );
293 $best = 0.0;
294 $bestset = "*";
296 foreach ( $a as $s ) {
297 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
298 $set = $m[1];
299 $q = (float)($m[2]);
300 } else {
301 $set = $s;
302 $q = 1.0;
304 if ( $q > $best ) {
305 $bestset = $set;
306 $best = $q;
309 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
310 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
311 $wgOutputEncoding = strtolower( $bestset );
313 # Disable for now
315 $wgOutputEncoding = $wgInputEncoding;
318 function reportTime()
320 global $wgRequestTime, $wgDebugLogFile, $HTTP_SERVER_VARS;
321 global $wgProfiling, $wgProfileStack, $wgUser;
323 list( $usec, $sec ) = explode( " ", microtime() );
324 $now = (float)$sec + (float)$usec;
326 list( $usec, $sec ) = explode( " ", $wgRequestTime );
327 $start = (float)$sec + (float)$usec;
328 $elapsed = $now - $start;
330 if ( "" != $wgDebugLogFile ) {
331 $prof = "";
332 if( $wgProfiling and count( $wgProfileStack ) ) {
333 $lasttime = $start;
334 foreach( $wgProfileStack as $ile ) {
335 # "foo::bar 99 0.12345 1 0.23456 2"
336 if( preg_match( '/^(\S+)\s+([0-9]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)\s+([0-9\.]+)/', $ile, $m ) ) {
337 $thisstart = (float)$m[3] + (float)$m[4] - $start;
338 $thisend = (float)$m[5] + (float)$m[6] - $start;
339 $thiselapsed = $thisend - $thisstart;
340 $thispercent = $thiselapsed / $elapsed * 100.0;
342 $prof .= sprintf( "\tat %04.3f in %04.3f (%2.1f%%) - %s %s\n",
343 $thisstart, $thiselapsed, $thispercent,
344 str_repeat( "*", $m[2] ), $m[1] );
345 $lasttime = $thistime;
346 #$prof .= "\t(^ $ile)\n";
347 } else {
348 $prof .= "\t?broken? $ile\n";
353 if( $forward = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'] )
354 $forward = " forwarded for $forward";
355 if( $client = $HTTP_SERVER_VARS['HTTP_CLIENT_IP'] )
356 $forward .= " client IP $client";
357 if( $from = $HTTP_SERVER_VARS['HTTP_FROM'] )
358 $forward .= " from $from";
359 if( $forward )
360 $forward = "\t(proxied via {$HTTP_SERVER_VARS['REMOTE_ADDR']}{$forward})";
361 if($wgUser->getId() == 0)
362 $forward .= " anon";
363 $log = sprintf( "%s\t%04.3f\t%s\n",
364 gmdate( "YmdHis" ), $elapsed,
365 urldecode( $HTTP_SERVER_VARS['REQUEST_URI'] . $forward ) );
366 error_log( $log . $prof, 3, $wgDebugLogFile );
368 $com = sprintf( "<!-- Time since request: %01.2f secs. -->",
369 $elapsed );
370 return $com;
373 # Note: these arguments are keys into wfMsg(), not text!
375 function errorpage( $title, $msg )
377 global $wgTitle;
379 $this->mDebugtext .= "Original title: " .
380 $wgTitle->getPrefixedText() . "\n";
381 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
382 $this->setPageTitle( wfMsg( $title ) );
383 $this->setRobotpolicy( "noindex,nofollow" );
384 $this->setArticleFlag( false );
386 $this->mBodytext = "";
387 $this->addHTML( "<p>" . wfMsg( $msg ) . "\n" );
388 $this->returnToMain( false );
390 $this->output();
391 exit;
394 function sysopRequired()
396 global $wgUser;
398 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
399 $this->setPageTitle( wfMsg( "sysoptitle" ) );
400 $this->setRobotpolicy( "noindex,nofollow" );
401 $this->setArticleFlag( false );
402 $this->mBodytext = "";
404 $sk = $wgUser->getSkin();
405 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
406 $text = str_replace( "$1", $ap, wfMsg( "sysoptext" ) );
407 $this->addHTML( $text );
408 $this->returnToMain();
411 function developerRequired()
413 global $wgUser;
415 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
416 $this->setPageTitle( wfMsg( "developertitle" ) );
417 $this->setRobotpolicy( "noindex,nofollow" );
418 $this->setArticleFlag( false );
419 $this->mBodytext = "";
421 $sk = $wgUser->getSkin();
422 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
423 $text = str_replace( "$1", $ap, wfMsg( "developertext" ) );
424 $this->addHTML( $text );
425 $this->returnToMain();
428 function databaseError( $fname )
430 global $wgUser, $wgCommandLineMode;
432 $this->setPageTitle( wfMsgNoDB( "databaseerror" ) );
433 $this->setRobotpolicy( "noindex,nofollow" );
434 $this->setArticleFlag( false );
436 if ( $wgCommandLineMode ) {
437 $msg = wfMsgNoDB( "dberrortextcl" );
438 } else {
439 $msg = wfMsgNoDB( "dberrortextcl" );
442 $msg = str_replace( "$1", htmlspecialchars( wfLastDBquery() ), $msg );
443 $msg = str_replace( "$2", htmlspecialchars( $fname ), $msg );
444 $msg = str_replace( "$3", wfLastErrno(), $msg );
445 $msg = str_replace( "$4", htmlspecialchars( wfLastError() ), $msg );
447 if ( $wgCommandLineMode ) {
448 print "$msg\n";
449 exit();
451 $sk = $wgUser->getSkin();
452 $shlink = $sk->makeKnownLink( wfMsgNoDB( "searchhelppage" ),
453 wfMsgNoDB( "searchingwikipedia" ) );
454 $msg = str_replace( "$5", $shlink, $msg );
456 $this->mBodytext = $msg;
457 $this->output();
458 exit();
461 function readOnlyPage( $source = "" )
463 global $wgUser, $wgReadOnlyFile;
465 $this->setPageTitle( wfMsg( "readonly" ) );
466 $this->setRobotpolicy( "noindex,nofollow" );
467 $this->setArticleFlag( false );
469 $reason = implode( "", file( $wgReadOnlyFile ) );
470 $text = str_replace( "$1", $reason, wfMsg( "readonlytext" ) );
472 if($source) {
473 $rows = $wgUser->getOption( "rows" );
474 $cols = $wgUser->getOption( "cols" );
475 $text .= "</p>\n<textarea cols='$cols' rows='$rows' readonly>" .
476 htmlspecialchars( $source ) . "\n</textarea>";
479 $this->addHTML( $text );
480 $this->returnToMain( false );
483 function fatalError( $message )
485 $this->setPageTitle( wfMsg( "internalerror" ) );
486 $this->setRobotpolicy( "noindex,nofollow" );
487 $this->setArticleFlag( false );
489 $this->mBodytext = $message;
490 $this->output();
491 exit;
494 function unexpectedValueError( $name, $val )
496 $msg = str_replace( "$1", $name, wfMsg( "unexpected" ) );
497 $msg = str_replace( "$2", $val, $msg );
498 $this->fatalError( $msg );
501 function fileCopyError( $old, $new )
503 $msg = str_replace( "$1", $old, wfMsg( "filecopyerror" ) );
504 $msg = str_replace( "$2", $new, $msg );
505 $this->fatalError( $msg );
508 function fileRenameError( $old, $new )
510 $msg = str_replace( "$1", $old, wfMsg( "filerenameerror" ) );
511 $msg = str_replace( "$2", $new, $msg );
512 $this->fatalError( $msg );
515 function fileDeleteError( $name )
517 $msg = str_replace( "$1", $name, wfMsg( "filedeleteerror" ) );
518 $this->fatalError( $msg );
521 function fileNotFoundError( $name )
523 $msg = str_replace( "$1", $name, wfMsg( "filenotfound" ) );
524 $this->fatalError( $msg );
527 function returnToMain( $auto = true )
529 global $wgUser, $wgOut, $returnto;
531 $sk = $wgUser->getSkin();
532 if ( "" == $returnto ) {
533 $returnto = wfMsg( "mainpage" );
535 $link = $sk->makeKnownLink( $returnto, "" );
537 $r = str_replace( "$1", $link, wfMsg( "returnto" ) );
538 if ( $auto ) {
539 $wgOut->addMeta( "http:Refresh", "10;url=" .
540 wfLocalUrlE( wfUrlencode( $returnto ) ) );
542 $wgOut->addHTML( "\n<p>$r\n" );
546 function categoryMagic ()
548 global $wgTitle , $wgUseCategoryMagic ;
549 if ( !isset ( $wgUseCategoryMagic ) || !$wgUseCategoryMagic ) return ;
550 $id = $wgTitle->getArticleID() ;
551 $cat = ucfirst ( wfMsg ( "category" ) ) ;
552 $ti = $wgTitle->getText() ;
553 $ti = explode ( ":" , $ti , 2 ) ;
554 if ( $cat != $ti[0] ) return "" ;
555 $r = "<br break=all>\n" ;
557 $articles = array() ;
558 $parents = array () ;
559 $children = array() ;
562 global $wgUser ;
563 $sk = $wgUser->getSkin() ;
564 $sql = "SELECT l_from FROM links WHERE l_to={$id}" ;
565 $res = wfQuery ( $sql, DB_READ ) ;
566 while ( $x = wfFetchObject ( $res ) )
568 # $t = new Title ;
569 # $t->newFromDBkey ( $x->l_from ) ;
570 # $t = $t->getText() ;
571 $t = $x->l_from ;
572 $y = explode ( ":" , $t , 2 ) ;
573 if ( count ( $y ) == 2 && $y[0] == $cat )
575 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
577 else array_push ( $articles , $sk->makeLink ( $t ) ) ;
579 wfFreeResult ( $res ) ;
581 # Children
582 if ( count ( $children ) > 0 )
584 asort ( $children ) ;
585 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
586 $r .= implode ( ", " , $children ) ;
589 # Articles
590 if ( count ( $articles ) > 0 )
592 asort ( $articles ) ;
593 $h = str_replace ( "$1" , $ti[1] , wfMsg("category_header") ) ;
594 $r .= "<h2>{$h}</h2>\n" ;
595 $r .= implode ( ", " , $articles ) ;
599 return $r ;
602 function getHTMLattrs ()
604 $htmlattrs = array( # Allowed attributes--no scripting, etc.
605 "title", "align", "lang", "dir", "width", "height",
606 "bgcolor", "clear", /* BR */ "noshade", /* HR */
607 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
608 /* FONT */ "type", "start", "value", "compact",
609 /* For various lists, mostly deprecated but safe */
610 "summary", "width", "border", "frame", "rules",
611 "cellspacing", "cellpadding", "valign", "char",
612 "charoff", "colgroup", "col", "span", "abbr", "axis",
613 "headers", "scope", "rowspan", "colspan", /* Tables */
614 "id", "class", "name", "style" /* For CSS */
616 return $htmlattrs ;
619 function fixTableTags ( $t )
621 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
622 $htmlattrs = $this->getHTMLattrs() ;
624 # Strip non-approved attributes from the tag
625 $t = preg_replace(
626 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
627 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
628 $t);
630 return trim ( $t ) ;
633 function doTableStuff ( $t )
635 $t = explode ( "\n" , $t ) ;
636 $td = array () ; # Is currently a td tag open?
637 $ltd = array () ; # Was it TD or TH?
638 $tr = array () ; # Is currently a tr tag open?
639 $ltr = array () ; # tr attributes
640 foreach ( $t AS $k => $x )
642 $x = rtrim ( $x ) ;
643 $fc = substr ( $x , 0 , 1 ) ;
644 if ( "{|" == substr ( $x , 0 , 2 ) )
646 $t[$k] = "<table " . $this->fixTableTags ( substr ( $x , 3 ) ) . ">" ;
647 array_push ( $td , false ) ;
648 array_push ( $ltd , "" ) ;
649 array_push ( $tr , false ) ;
650 array_push ( $ltr , "" ) ;
652 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
653 else if ( "|}" == substr ( $x , 0 , 2 ) )
655 $z = "</table>\n" ;
656 $l = array_pop ( $ltd ) ;
657 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
658 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
659 array_pop ( $ltr ) ;
660 $t[$k] = $z ;
662 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
664 $z = trim ( substr ( $x , 2 ) ) ;
665 $t[$k] = "<caption>{$z}</caption>\n" ;
667 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
669 $x = substr ( $x , 1 ) ;
670 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
671 $z = "" ;
672 $l = array_pop ( $ltd ) ;
673 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
674 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
675 array_pop ( $ltr ) ;
676 $t[$k] = $z ;
677 array_push ( $tr , false ) ;
678 array_push ( $td , false ) ;
679 array_push ( $ltd , "" ) ;
680 array_push ( $ltr , $this->fixTableTags ( $x ) ) ;
682 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
684 if ( "|+" == substr ( $x , 0 , 2 ) )
686 $fc = "+" ;
687 $x = substr ( $x , 1 ) ;
689 $after = substr ( $x , 1 ) ;
690 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
691 $after = explode ( "||" , $after ) ;
692 $t[$k] = "" ;
693 foreach ( $after AS $theline )
695 $z = "" ;
696 $tra = array_pop ( $ltr ) ;
697 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
698 array_push ( $tr , true ) ;
699 array_push ( $ltr , "" ) ;
701 $l = array_pop ( $ltd ) ;
702 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
703 if ( $fc == "|" ) $l = "TD" ;
704 else if ( $fc == "!" ) $l = "TH" ;
705 else if ( $fc == "+" ) $l = "CAPTION" ;
706 else $l = "" ;
707 array_push ( $ltd , $l ) ;
708 $y = explode ( "|" , $theline , 2 ) ;
709 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
710 else $y = $y = "{$z}<{$l} ".$this->fixTableTags($y[0]).">{$y[1]}" ;
711 $t[$k] .= $y ;
712 array_push ( $td , true ) ;
717 # Closing open td, tr && table
718 while ( count ( $td ) > 0 )
720 if ( array_pop ( $td ) ) $t[] = "</td>" ;
721 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
722 $t[] = "</table>" ;
725 $t = implode ( "\n" , $t ) ;
726 # $t = $this->removeHTMLtags( $t );
727 return $t ;
730 # Well, OK, it's actually about 14 passes. But since all the
731 # hard lifting is done inside PHP's regex code, it probably
732 # wouldn't speed things up much to add a real parser.
734 function doWikiPass2( $text, $linestart )
736 global $wgUser, $wgLang, $wgUseDynamicDates;
737 wfProfileIn( "OutputPage::doWikiPass2" );
739 $text = $this->removeHTMLtags( $text );
740 $text = $this->replaceVariables( $text );
742 $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
743 $text = str_replace ( "<HR>", "<hr>", $text );
745 $text = $this->doAllQuotes( $text );
746 $text = $this->doHeadings( $text );
747 $text = $this->doBlockLevels( $text, $linestart );
749 if($wgUseDynamicDates) {
750 $text = $wgLang->replaceDates( $text );
753 $text = $this->replaceExternalLinks( $text );
754 $text = $this->replaceInternalLinks ( $text );
755 $text = $this->doTableStuff ( $text ) ;
757 $text = $this->magicISBN( $text );
758 $text = $this->magicRFC( $text );
759 $text = $this->formatHeadings( $text );
761 $sk = $wgUser->getSkin();
762 $text = $sk->transformContent( $text );
763 $text .= $this->categoryMagic () ;
765 wfProfileOut();
766 return $text;
769 /* private */ function doAllQuotes( $text )
771 $outtext = "";
772 $lines = explode( "\r\n", $text );
773 foreach ( $lines as $line ) {
774 $outtext .= $this->doQuotes ( "", $line, "" ) . "\r\n";
776 return $outtext;
779 /* private */ function doQuotes( $pre, $text, $mode )
781 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
782 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
783 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
784 if ( substr ($m[2], 0, 1) == "'" ) {
785 $m[2] = substr ($m[2], 1);
786 if ($mode == "em") {
787 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "emstrong" );
788 } else if ($mode == "strong") {
789 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
790 } else if (($mode == "emstrong") || ($mode == "both")) {
791 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
792 } else if ($mode == "strongem") {
793 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
794 } else {
795 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
797 } else {
798 if ($mode == "strong") {
799 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "strongem" );
800 } else if ($mode == "em") {
801 return $m1_em . $this->doQuotes ( "", $m[2], "" );
802 } else if ($mode == "emstrong") {
803 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
804 } else if (($mode == "strongem") || ($mode == "both")) {
805 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
806 } else {
807 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
810 } else {
811 $text_strong = ($text == "") ? "" : "<strong>{$text}</strong>";
812 $text_em = ($text == "") ? "" : "<em>{$text}</em>";
813 if ($mode == "") {
814 return $pre . $text;
815 } else if ($mode == "em") {
816 return $pre . $text_em;
817 } else if ($mode == "strong") {
818 return $pre . $text_strong;
819 } else if ($mode == "strongem") {
820 return (($pre == "") && ($text == "")) ? "" : "<strong>{$pre}{$text_em}</strong>";
821 } else {
822 return (($pre == "") && ($text == "")) ? "" : "<em>{$pre}{$text_strong}</em>";
827 /* private */ function doHeadings( $text )
829 for ( $i = 6; $i >= 1; --$i ) {
830 $h = substr( "======", 0, $i );
831 $text = preg_replace( "/^{$h}([^=]+){$h}(\\s|$)/m",
832 "<h{$i}>\\1</h{$i}>\\2", $text );
834 return $text;
837 # Note: we have to do external links before the internal ones,
838 # and otherwise take great care in the order of things here, so
839 # that we don't end up interpreting some URLs twice.
841 /* private */ function replaceExternalLinks( $text )
843 wfProfileIn( "OutputPage::replaceExternalLinks" );
844 $text = $this->subReplaceExternalLinks( $text, "http", true );
845 $text = $this->subReplaceExternalLinks( $text, "https", true );
846 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
847 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
848 $text = $this->subReplaceExternalLinks( $text, "news", false );
849 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
850 wfProfileOut();
851 return $text;
854 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
856 global $wgUser, $printable;
857 global $wgAllowExternalImages;
860 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
861 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
863 # this is the list of separators that should be ignored if they
864 # are the last character of an URL but that should be included
865 # if they occur within the URL, e.g. "go to www.foo.com, where .."
866 # in this case, the last comma should not become part of the URL,
867 # but in "www.foo.com/123,2342,32.htm" it should.
868 $sep = ",;\.:";
869 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
870 $images = "gif|png|jpg|jpeg";
872 # PLEASE NOTE: The curly braces { } are not part of the regex,
873 # they are interpreted as part of the string (used to tell PHP
874 # that the content of the string should be inserted there).
875 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
876 "((?i){$images})([^{$uc}]|$)/";
878 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
879 $sk = $wgUser->getSkin();
881 if ( $autonumber and $wgAllowExternalImages) { # Use img tags only for HTTP urls
882 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
883 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
885 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
886 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
887 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
888 "</a>\\5", $s );
889 $s = str_replace( $unique, $protocol, $s );
891 $a = explode( "[{$protocol}:", " " . $s );
892 $s = array_shift( $a );
893 $s = substr( $s, 1 );
895 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
896 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
898 foreach ( $a as $line ) {
899 if ( preg_match( $e1, $line, $m ) ) {
900 $link = "{$protocol}:{$m[1]}";
901 $trail = $m[2];
902 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
903 else { $text = wfEscapeHTML( $link ); }
904 } else if ( preg_match( $e2, $line, $m ) ) {
905 $link = "{$protocol}:{$m[1]}";
906 $text = $m[2];
907 $trail = $m[3];
908 } else {
909 $s .= "[{$protocol}:" . $line;
910 continue;
912 if ( $printable == "yes") $paren = " (<i>" . htmlspecialchars ( $link ) . "</i>)";
913 else $paren = "";
914 $la = $sk->getExternalLinkAttributes( $link, $text );
915 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
918 return $s;
921 /* private */ function replaceInternalLinks( $s )
923 global $wgTitle, $wgUser, $wgLang;
924 global $wgLinkCache, $wgInterwikiMagic, $wgUseCategoryMagic;
925 global $wgNamespacesWithSubpages, $wgLanguageCode;
926 wfProfileIn( $fname = "OutputPage::replaceInternalLinks" );
928 wfProfileIn( "$fname-setup" );
929 $tc = Title::legalChars() . "#";
930 $sk = $wgUser->getSkin();
932 $a = explode( "[[", " " . $s );
933 $s = array_shift( $a );
934 $s = substr( $s, 1 );
936 $e1 = "/^([{$tc}]+)\\|([^]]+)]](.*)\$/sD";
937 $e2 = "/^([{$tc}]+)]](.*)\$/sD";
938 wfProfileOut();
940 foreach ( $a as $line ) {
941 wfProfileIn( "$fname-loop" );
942 if ( preg_match( $e1, $line, $m ) ) { # page with alternate text
944 $text = $m[2];
945 $trail = $m[3];
947 } else if ( preg_match( $e2, $line, $m ) ) { # page with normal text
949 $text = "";
950 $trail = $m[2];
953 else { # Invalid form; output directly
954 $s .= "[[" . $line ;
955 wfProfileOut();
956 continue;
958 if(substr($m[1],0,1)=="/") { # subpage
959 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
960 $m[1]=substr($m[1],1,strlen($m[1])-2);
961 $noslash=$m[1];
963 } else {
964 $noslash=substr($m[1],1);
966 if($wgNamespacesWithSubpages[$wgTitle->getNamespace()]) { # subpages allowed here
967 $link = $wgTitle->getPrefixedText(). "/" . trim($noslash);
968 if(!$text) {
969 $text= $m[1];
970 } # this might be changed for ugliness reasons
971 } else {
972 $link = $noslash; # no subpage allowed, use standard link
974 } else { # no subpage
975 $link = $m[1];
978 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z\\x80-\\xff]+):(.*)\$/", $link, $m ) ) {
979 $pre = strtolower( $m[1] );
980 $suf = $m[2];
981 if ( $wgLang->getNsIndex( $pre ) ==
982 Namespace::getImage() ) {
983 $nt = Title::newFromText( $suf );
984 $name = $nt->getDBkey();
985 if ( "" == $text ) { $text = $nt->GetText(); }
987 $wgLinkCache->addImageLink( $name );
988 $s .= $sk->makeImageLink( $name,
989 wfImageUrl( $name ), $text );
990 $s .= $trail;
991 } else if ( "media" == $pre ) {
992 $nt = Title::newFromText( $suf );
993 $name = $nt->getDBkey();
994 if ( "" == $text ) { $text = $nt->GetText(); }
996 $wgLinkCache->addImageLink( $name );
997 $s .= $sk->makeMediaLink( $name,
998 wfImageUrl( $name ), $text );
999 $s .= $trail;
1000 } else if ( isset($wgUseCategoryMagic) && $wgUseCategoryMagic && $pre == wfMsg ( "category" ) ) {
1001 $l = $sk->makeLink ( $pre.":".ucfirst($m[2]) , ucfirst ( $m[2] ) ) ;
1002 array_push ( $this->mCategoryLinks , $l ) ;
1003 $s .= $trail ;
1004 } else {
1005 $l = $wgLang->getLanguageName( $pre );
1006 if ( "" == $l or !$wgInterwikiMagic or
1007 Namespace::isTalk( $wgTitle->getNamespace() ) ) {
1008 if ( "" == $text ) { $text = $link; }
1009 $s .= $sk->makeLink( $link, $text, "", $trail );
1010 } else if ( $pre != $wgLanguageCode ) {
1011 array_push( $this->mLanguageLinks, "$pre:$suf" );
1012 $s .= $trail;
1015 # } else if ( 0 == strcmp( "##", substr( $link, 0, 2 ) ) ) {
1016 # $link = substr( $link, 2 );
1017 # $s .= "<a name=\"{$link}\">{$text}</a>{$trail}";
1018 } else {
1019 if ( "" == $text ) { $text = $link; }
1020 $s .= $sk->makeLink( $link, $text, "", $trail );
1022 wfProfileOut();
1024 wfProfileOut();
1025 return $s;
1028 # Some functions here used by doBlockLevels()
1030 /* private */ function closeParagraph()
1032 $result = "";
1033 if ( 0 != strcmp( "p", $this->mLastSection ) &&
1034 0 != strcmp( "", $this->mLastSection ) ) {
1035 $result = "</" . $this->mLastSection . ">";
1037 $this->mLastSection = "";
1038 return $result;
1040 # getCommon() returns the length of the longest common substring
1041 # of both arguments, starting at the beginning of both.
1043 /* private */ function getCommon( $st1, $st2 )
1045 $fl = strlen( $st1 );
1046 $shorter = strlen( $st2 );
1047 if ( $fl < $shorter ) { $shorter = $fl; }
1049 for ( $i = 0; $i < $shorter; ++$i ) {
1050 if ( $st1{$i} != $st2{$i} ) { break; }
1052 return $i;
1054 # These next three functions open, continue, and close the list
1055 # element appropriate to the prefix character passed into them.
1057 /* private */ function openList( $char )
1059 $result = $this->closeParagraph();
1061 if ( "*" == $char ) { $result .= "<ul><li>"; }
1062 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1063 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1064 else if ( ";" == $char ) {
1065 $result .= "<dl><dt>";
1066 $this->mDTopen = true;
1068 else { $result = "<!-- ERR 1 -->"; }
1070 return $result;
1073 /* private */ function nextItem( $char )
1075 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1076 else if ( ":" == $char || ";" == $char ) {
1077 $close = "</dd>";
1078 if ( $this->mDTopen ) { $close = "</dt>"; }
1079 if ( ";" == $char ) {
1080 $this->mDTopen = true;
1081 return $close . "<dt>";
1082 } else {
1083 $this->mDTopen = false;
1084 return $close . "<dd>";
1087 return "<!-- ERR 2 -->";
1090 /* private */function closeList( $char )
1092 if ( "*" == $char ) { return "</li></ul>"; }
1093 else if ( "#" == $char ) { return "</li></ol>"; }
1094 else if ( ":" == $char ) {
1095 if ( $this->mDTopen ) {
1096 $this->mDTopen = false;
1097 return "</dt></dl>";
1098 } else {
1099 return "</dd></dl>";
1102 return "<!-- ERR 3 -->";
1105 /* private */ function doBlockLevels( $text, $linestart )
1107 wfProfileIn( "OutputPage::doBlockLevels" );
1108 # Parsing through the text line by line. The main thing
1109 # happening here is handling of block-level elements p, pre,
1110 # and making lists from lines starting with * # : etc.
1112 $a = explode( "\n", $text );
1113 $text = $lastPref = "";
1114 $this->mDTopen = $inBlockElem = false;
1116 if ( ! $linestart ) { $text .= array_shift( $a ); }
1117 foreach ( $a as $t ) {
1118 if ( "" != $text ) { $text .= "\n"; }
1120 $oLine = $t;
1121 $opl = strlen( $lastPref );
1122 $npl = strspn( $t, "*#:;" );
1123 $pref = substr( $t, 0, $npl );
1124 $pref2 = str_replace( ";", ":", $pref );
1125 $t = substr( $t, $npl );
1127 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1128 $text .= $this->nextItem( substr( $pref, -1 ) );
1130 if ( ";" == substr( $pref, -1 ) ) {
1131 $cpos = strpos( $t, ":" );
1132 if ( ! ( false === $cpos ) ) {
1133 $term = substr( $t, 0, $cpos );
1134 $text .= $term . $this->nextItem( ":" );
1135 $t = substr( $t, $cpos + 1 );
1138 } else if (0 != $npl || 0 != $opl) {
1139 $cpl = $this->getCommon( $pref, $lastPref );
1141 while ( $cpl < $opl ) {
1142 $text .= $this->closeList( $lastPref{$opl-1} );
1143 --$opl;
1145 if ( $npl <= $cpl && $cpl > 0 ) {
1146 $text .= $this->nextItem( $pref{$cpl-1} );
1148 while ( $npl > $cpl ) {
1149 $char = substr( $pref, $cpl, 1 );
1150 $text .= $this->openList( $char );
1152 if ( ";" == $char ) {
1153 $cpos = strpos( $t, ":" );
1154 if ( ! ( false === $cpos ) ) {
1155 $term = substr( $t, 0, $cpos );
1156 $text .= $term . $this->nextItem( ":" );
1157 $t = substr( $t, $cpos + 1 );
1160 ++$cpl;
1162 $lastPref = $pref2;
1164 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1165 if ( preg_match(
1166 "/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6)/i", $t ) ) {
1167 $text .= $this->closeParagraph();
1168 $inBlockElem = true;
1170 if ( ! $inBlockElem ) {
1171 if ( " " == $t{0} ) {
1172 $newSection = "pre";
1173 # $t = wfEscapeHTML( $t );
1175 else { $newSection = "p"; }
1177 if ( 0 == strcmp( "", trim( $oLine ) ) ) {
1178 $text .= $this->closeParagraph();
1179 $text .= "<" . $newSection . ">";
1180 } else if ( 0 != strcmp( $this->mLastSection,
1181 $newSection ) ) {
1182 $text .= $this->closeParagraph();
1183 if ( 0 != strcmp( "p", $newSection ) ) {
1184 $text .= "<" . $newSection . ">";
1187 $this->mLastSection = $newSection;
1189 if ( $inBlockElem &&
1190 preg_match( "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6)/i", $t ) ) {
1191 $inBlockElem = false;
1194 $text .= $t;
1196 while ( $npl ) {
1197 $text .= $this->closeList( $pref2{$npl-1} );
1198 --$npl;
1200 if ( "" != $this->mLastSection ) {
1201 if ( "p" != $this->mLastSection ) {
1202 $text .= "</" . $this->mLastSection . ">";
1204 $this->mLastSection = "";
1206 wfProfileOut();
1207 return $text;
1210 /* private */ function replaceVariables( $text )
1212 global $wgLang;
1213 wfProfileIn( "OutputPage:replaceVariables" );
1215 /* As with sigs, use server's local time --
1216 ensure this is appropriate for your audience! */
1217 $v = date( "m" );
1218 $mw =& MagicWord::get( MAG_CURRENTMONTH );
1219 $text = $mw->replace( $v, $text );
1221 $v = $wgLang->getMonthName( date( "n" ) );
1222 $mw =& MagicWord::get( MAG_CURRENTMONTHNAME );
1223 $text = $mw->replace( $v, $text );
1225 $v = $wgLang->getMonthNameGen( date( "n" ) );
1226 $mw =& MagicWord::get( MAG_CURRENTMONTHNAMEGEN );
1227 $text = $mw->replace( $v, $text );
1229 $v = date( "j" );
1230 $mw = MagicWord::get( MAG_CURRENTDAY );
1231 $text = $mw->replace( $v, $text );
1233 $v = $wgLang->getWeekdayName( date( "w" )+1 );
1234 $mw =& MagicWord::get( MAG_CURRENTDAYNAME );
1235 $text = $mw->replace( $v, $text );
1237 $v = date( "Y" );
1238 $mw =& MagicWord::get( MAG_CURRENTYEAR );
1239 $text = $mw->replace( $v, $text );
1241 $v = $wgLang->time( wfTimestampNow(), false );
1242 $mw =& MagicWord::get( MAG_CURRENTTIME );
1243 $text = $mw->replace( $v, $text );
1245 $mw =& MagicWord::get( MAG_NUMBEROFARTICLES );
1246 if ( $mw->match( $text ) ) {
1247 $v = wfNumberOfArticles();
1248 $text = $mw->replace( $v, $text );
1251 # The callbacks are in GlobalFunctions.php
1252 $mw =& MagicWord::get( MAG_MSG );
1253 $text = $mw->substituteCallback( $text, "replaceMsgVar" );
1255 $mw =& MagicWord::get( MAG_MSGNW );
1256 $text = $mw->substituteCallback( $text, "replaceMsgVarNw" );
1258 wfProfileOut();
1259 return $text;
1262 /* private */ function removeHTMLtags( $text )
1264 wfProfileIn( "OutputPage::removeHTMLtags" );
1265 $htmlpairs = array( # Tags that must be closed
1266 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1267 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1268 "strike", "strong", "tt", "var", "div", "center",
1269 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1270 "ruby", "rt" , "rb" , "rp"
1272 $htmlsingle = array(
1273 "br", "p", "hr", "li", "dt", "dd"
1275 $htmlnest = array( # Tags that can be nested--??
1276 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1277 "dl", "font", "big", "small", "sub", "sup"
1279 $tabletags = array( # Can only appear inside table
1280 "td", "th", "tr"
1283 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1284 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1286 $htmlattrs = $this->getHTMLattrs () ;
1288 # Remove HTML comments
1289 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1291 $bits = explode( "<", $text );
1292 $text = array_shift( $bits );
1293 $tagstack = array(); $tablestack = array();
1295 foreach ( $bits as $x ) {
1296 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1297 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1298 $x, $regs );
1299 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1300 error_reporting( $prev );
1302 $badtag = 0 ;
1303 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1304 # Check our stack
1305 if ( $slash ) {
1306 # Closing a tag...
1307 if ( ! in_array( $t, $htmlsingle ) &&
1308 ( $ot = array_pop( $tagstack ) ) != $t ) {
1309 array_push( $tagstack, $ot );
1310 $badtag = 1;
1311 } else {
1312 if ( $t == "table" ) {
1313 $tagstack = array_pop( $tablestack );
1315 $newparams = "";
1317 } else {
1318 # Keep track for later
1319 if ( in_array( $t, $tabletags ) &&
1320 ! in_array( "table", $tagstack ) ) {
1321 $badtag = 1;
1322 } else if ( in_array( $t, $tagstack ) &&
1323 ! in_array ( $t , $htmlnest ) ) {
1324 $badtag = 1 ;
1325 } else if ( ! in_array( $t, $htmlsingle ) ) {
1326 if ( $t == "table" ) {
1327 array_push( $tablestack, $tagstack );
1328 $tagstack = array();
1330 array_push( $tagstack, $t );
1332 # Strip non-approved attributes from the tag
1333 $newparams = preg_replace(
1334 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
1335 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
1336 $params);
1338 if ( ! $badtag ) {
1339 $rest = str_replace( ">", "&gt;", $rest );
1340 $text .= "<$slash$t$newparams$brace$rest";
1341 continue;
1344 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1346 # Close off any remaining tags
1347 while ( $t = array_pop( $tagstack ) ) {
1348 $text .= "</$t>\n";
1349 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1351 wfProfileOut();
1352 return $text;
1358 * This function accomplishes several tasks:
1359 * 1) Auto-number headings if that option is enabled
1360 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1361 * 3) Add a Table of contents on the top for users who have enabled the option
1362 * 4) Auto-anchor headings
1364 * It loops through all headlines, collects the necessary data, then splits up the
1365 * string and re-inserts the newly formatted headlines.
1367 * */
1368 /* private */ function formatHeadings( $text )
1370 global $wgUser,$wgArticle,$wgTitle,$wpPreview;
1371 $nh=$wgUser->getOption( "numberheadings" );
1372 $st=$wgUser->getOption( "showtoc" );
1373 if(!$wgTitle->userCanEdit()) {
1374 $es=0;
1375 $esr=0;
1376 } else {
1377 $es=$wgUser->getID() && $wgUser->getOption( "editsection" );
1378 $esr=$wgUser->getID() && $wgUser->getOption( "editsectiononrightclick" );
1381 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1382 # do not add TOC
1383 $mw =& MagicWord::get( MAG_NOTOC );
1384 if ($mw->matchAndRemove( $text ))
1386 $st = 0;
1389 # never add the TOC to the Main Page. This is an entry page that should not
1390 # be more than 1-2 screens large anyway
1391 if($wgTitle->getPrefixedText()==wfMsg("mainpage")) {$st=0;}
1393 # We need this to perform operations on the HTML
1394 $sk=$wgUser->getSkin();
1396 # Get all headlines for numbering them and adding funky stuff like [edit]
1397 # links
1398 preg_match_all("/<H([1-6])(.*?>)(.*?)<\/H[1-6]>/i",$text,$matches);
1400 # headline counter
1401 $c=0;
1403 # Ugh .. the TOC should have neat indentation levels which can be
1404 # passed to the skin functions. These are determined here
1405 foreach($matches[3] as $headline) {
1406 if($level) { $prevlevel=$level;}
1407 $level=$matches[1][$c];
1408 if(($nh||$st) && $prevlevel && $level>$prevlevel) {
1410 $h[$level]=0; // reset when we enter a new level
1411 $toc.=$sk->tocIndent($level-$prevlevel);
1412 $toclevel+=$level-$prevlevel;
1415 if(($nh||$st) && $level<$prevlevel) {
1416 $h[$level+1]=0; // reset when we step back a level
1417 $toc.=$sk->tocUnindent($prevlevel-$level);
1418 $toclevel-=$prevlevel-$level;
1421 $h[$level]++; // count number of headlines for each level
1423 if($nh||$st) {
1424 for($i=1;$i<=$level;$i++) {
1425 if($h[$i]) {
1426 if($dot) {$numbering.=".";}
1427 $numbering.=$h[$i];
1428 $dot=1;
1434 $canonized_headline=preg_replace("/<.*?>/","",$headline); // strip out HTML
1435 $tocline=$canonized_headline;
1436 $canonized_headline=str_replace('"',"",$canonized_headline);
1437 $canonized_headline=str_replace(" ","_",trim($canonized_headline));
1438 $refer[$c]=$canonized_headline;
1439 $refers[$canonized_headline]++; // count how many in assoc. array so we can track dupes in anchors
1440 $refcount[$c]=$refers[$canonized_headline];
1441 if($nh||$st) {
1442 $tocline=$numbering ." ". $tocline;
1443 if($nh) {
1444 $headline=$numbering . " " . $headline; // the two are different if the line contains a link
1447 $anchor=$canonized_headline;
1448 if($refcount[$c]>1) {$anchor.="_".$refcount[$c];}
1449 if($st) {
1450 $toc.=$sk->tocLine($anchor,$tocline,$toclevel);
1452 if($es && !isset($wpPreview)) {
1453 $head[$c].=$sk->editSectionLink($c+1);
1455 $head[$c].="<H".$level.$matches[2][$c]
1456 ."<a name=\"".$anchor."\">"
1457 .$headline
1458 ."</a>"
1459 ."</H".$level.">";
1460 if($esr && !isset($wpPreview)) {
1461 $head[$c]=$sk->editSectionScript($c+1,$head[$c]);
1463 $numbering="";
1464 $c++;
1465 $dot=0;
1468 if($st) {
1469 $toclines=$c;
1470 $toc.=$sk->tocUnindent($toclevel);
1471 $toc=$sk->tocTable($toc);
1474 // split up and insert constructed headlines
1476 $blocks=preg_split("/<H[1-6].*?>.*?<\/H[1-6]>/i",$text);
1477 $i=0;
1480 foreach($blocks as $block) {
1481 if(($es) && !isset($wpPreview) && $c>0 && $i==0) {
1482 # This is the [edit] link that appears for the top block of text when
1483 # section editing is enabled
1484 $full.=$sk->editSectionLink(0);
1486 $full.=$block;
1487 if($st && $toclines>3 && !$i) {
1488 # Let's add a top anchor just in case we want to link to the top of the page
1489 $full="<a name=\"top\"></a>".$full.$toc;
1492 $full.=$head[$i];
1493 $i++;
1495 return $full;
1498 /* private */ function magicISBN( $text )
1500 global $wgLang;
1502 $a = split( "ISBN ", " $text" );
1503 if ( count ( $a ) < 2 ) return $text;
1504 $text = substr( array_shift( $a ), 1);
1505 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1507 foreach ( $a as $x ) {
1508 $isbn = $blank = "" ;
1509 while ( " " == $x{0} ) {
1510 $blank .= " ";
1511 $x = substr( $x, 1 );
1513 while ( strstr( $valid, $x{0} ) != false ) {
1514 $isbn .= $x{0};
1515 $x = substr( $x, 1 );
1517 $num = str_replace( "-", "", $isbn );
1518 $num = str_replace( " ", "", $num );
1520 if ( "" == $num ) {
1521 $text .= "ISBN $blank$x";
1522 } else {
1523 $text .= "<a href=\"" . wfLocalUrlE( $wgLang->specialPage(
1524 "Booksources"), "isbn={$num}" ) . "\" CLASS=\"internal\">ISBN $isbn</a>";
1525 $text .= $x;
1528 return $text;
1531 /* private */ function magicRFC( $text )
1533 return $text;
1536 /* private */ function headElement()
1538 global $wgDocType, $wgDTD, $wgUser, $wgLanguageCode, $wgOutputEncoding, $wgLang;
1540 $ret = "<!DOCTYPE HTML PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1542 if ( "" == $this->mHTMLtitle ) {
1543 $this->mHTMLtitle = $this->mPagetitle;
1545 $rtl = $wgLang->isRTL() ? " dir='RTL'" : "";
1546 $ret .= "<html lang=\"$wgLanguageCode\"$rtl><head><title>{$this->mHTMLtitle}</title>\n";
1547 array_push( $this->mMetatags, array( "http:Content-type", "text/html; charset={$wgOutputEncoding}" ) );
1548 foreach ( $this->mMetatags as $tag ) {
1549 if ( 0 == strcasecmp( "http:", substr( $tag[0], 0, 5 ) ) ) {
1550 $a = "http-equiv";
1551 $tag[0] = substr( $tag[0], 5 );
1552 } else {
1553 $a = "name";
1555 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\">\n";
1557 $p = $this->mRobotpolicy;
1558 if ( "" == $p ) { $p = "index,follow"; }
1559 $ret .= "<meta name=\"robots\" content=\"$p\">\n";
1561 if ( count( $this->mKeywords ) > 0 ) {
1562 $ret .= "<meta name=\"keywords\" content=\"" .
1563 implode( ",", $this->mKeywords ) . "\">\n";
1565 foreach ( $this->mLinktags as $tag ) {
1566 $ret .= "<link ";
1567 if ( "" != $tag[0] ) { $ret .= "rel=\"{$tag[0]}\" "; }
1568 if ( "" != $tag[1] ) { $ret .= "rev=\"{$tag[1]}\" "; }
1569 $ret .= "href=\"{$tag[2]}\">\n";
1571 $sk = $wgUser->getSkin();
1572 $ret .= $sk->getHeadScripts();
1573 $ret .= $sk->getUserStyles();
1575 $ret .= "</head>\n";
1576 return $ret;