Duh! wgMagicWordsEn => wgMagicWordsRo, as it should have been (I guess?)
[mediawiki.git] / includes / OutputPage.php
blob6ff2cc2fd20189abee2c88a00e463f770009c9c9
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( !empty( $_SERVER["HTTP_IF_MODIFIED_SINCE"] ) ) {
60 # IE sends sizes after the date like this:
61 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
62 # this breaks strtotime().
63 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
64 $ismodsince = wfUnix2Timestamp( strtotime( $modsince ) );
65 wfDebug( "-- client send If-Modified-Since: " . $modsince . "\n", false );
66 wfDebug( "-- we might send Last-Modified : $lastmod\n", false );
68 if( ($ismodsince >= $timestamp ) and $wgUser->validateCache( $ismodsince ) ) {
69 # Make sure you're in a place you can leave when you call us!
70 header( "HTTP/1.0 304 Not Modified" );
71 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
72 header( "Cache-Control: private, must-revalidate, max-age=0" );
73 header( "Last-Modified: {$lastmod}" );
74 wfDebug( "CACHED client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
75 $this->reportTime(); # For profiling
76 exit;
77 } else {
78 wfDebug( "READY client: $ismodsince ; user: $wgUser->mTouched ; page: $timestamp\n", false );
79 $this->mLastModified = $lastmod;
81 } else {
82 wfDebug( "We're confused.\n", false );
83 $this->mLastModified = $lastmod;
87 function setRobotpolicy( $str ) { $this->mRobotpolicy = $str; }
88 function setHTMLtitle( $name ) { $this->mHTMLtitle = $name; }
89 function setPageTitle( $name ) { $this->mPagetitle = $name; }
90 function getPageTitle() { return $this->mPagetitle; }
91 function setSubtitle( $str ) { $this->mSubtitle = $str; }
92 function getSubtitle() { return $this->mSubtitle; }
93 function setArticleFlag( $v ) { $this->mIsarticle = $v; }
94 function isArticle() { return $this->mIsarticle; }
95 function setPrintable() { $this->mPrintable = true; }
96 function isPrintable() { return $this->mPrintable; }
98 function getLanguageLinks() {
99 global $wgTitle, $wgLanguageCode;
100 global $wgDBconnection, $wgDBname;
101 return $this->mLanguageLinks;
103 function supressQuickbar() { $this->mSupressQuickbar = true; }
104 function isQuickbarSupressed() { return $this->mSupressQuickbar; }
106 function addHTML( $text ) { $this->mBodytext .= $text; }
107 function addHeadtext( $text ) { $this->mHeadtext .= $text; }
108 function debug( $text ) { $this->mDebugtext .= $text; }
110 # First pass--just handle <nowiki> sections, pass the rest off
111 # to doWikiPass2() which does all the real work.
114 function addWikiText( $text, $linestart = true )
116 global $wgUseTeX;
117 $fname = "OutputPage::addWikiText";
118 wfProfileIn( $fname );
119 $unique = "3iyZiyA7iMwg5rhxP0Dcc9oTnj8qD1jm1Sfv4";
120 $unique2 = "4LIQ9nXtiYFPCSfitVwDw7EYwQlL4GeeQ7qSO";
121 $unique3 = "fPaA8gDfdLBqzj68Yjg9Hil3qEF8JGO0uszIp";
122 $nwlist = array();
123 $nwsecs = 0;
124 $mathlist = array();
125 $mathsecs = 0;
126 $prelist = array ();
127 $presecs = 0;
128 $stripped = "";
129 $stripped2 = "";
130 $stripped3 = "";
132 while ( "" != $text ) {
133 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
134 $stripped .= $p[0];
135 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
136 else {
137 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
138 ++$nwsecs;
139 $nwlist[$nwsecs] = wfEscapeHTMLTagsOnly($q[0]);
140 $stripped .= $unique;
141 $text = $q[1];
145 if( $wgUseTeX ) {
146 while ( "" != $stripped ) {
147 $p = preg_split( "/<\\s*math\\s*>/i", $stripped, 2 );
148 $stripped2 .= $p[0];
149 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped = ""; }
150 else {
151 $q = preg_split( "/<\\/\\s*math\\s*>/i", $p[1], 2 );
152 ++$mathsecs;
153 $mathlist[$mathsecs] = renderMath($q[0]);
154 $stripped2 .= $unique2;
155 $stripped = $q[1];
158 } else {
159 $stripped2 = $stripped;
162 while ( "" != $stripped2 ) {
163 $p = preg_split( "/<\\s*pre\\s*>/i", $stripped2, 2 );
164 $stripped3 .= $p[0];
165 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $stripped2 = ""; }
166 else {
167 $q = preg_split( "/<\\/\\s*pre\\s*>/i", $p[1], 2 );
168 ++$presecs;
169 $prelist[$presecs] = "<pre>". wfEscapeHTMLTagsOnly($q[0]). "</pre>";
170 $stripped3 .= $unique3;
171 $stripped2 = $q[1];
175 $text = $this->doWikiPass2( $stripped3, $linestart );
177 $specialChars = array("\\", "$");
178 $escapedChars = array("\\\\", "\\$");
179 for ( $i = 1; $i <= $presecs; ++$i ) {
180 $text = preg_replace( "/{$unique3}/", str_replace( $specialChars,
181 $escapedChars, $prelist[$i] ), $text, 1 );
184 for ( $i = 1; $i <= $mathsecs; ++$i ) {
185 $text = preg_replace( "/{$unique2}/", str_replace( $specialChars,
186 $escapedChars, $mathlist[$i] ), $text, 1 );
189 for ( $i = 1; $i <= $nwsecs; ++$i ) {
190 $text = preg_replace( "/{$unique}/", str_replace( $specialChars,
191 $escapedChars, $nwlist[$i] ), $text, 1 );
193 $this->addHTML( $text );
194 wfProfileOut( $fname );
197 function sendCacheControl() {
198 global $wgUseGzip;
199 if( $this->mLastModified != "" ) {
200 wfDebug( "** private caching; {$this->mLastModified} **\n", false );
201 header( "Cache-Control: private, must-revalidate, max-age=0" );
202 header( "Last-modified: {$this->mLastModified}" );
203 if( $wgUseGzip ) {
204 # We should put in Accept-Encoding, but IE chokes on anything but
205 # User-Agent in a Vary: header (at least through 6.0)
206 header( "Vary: User-Agent" );
208 } else {
209 wfDebug( "** no caching **\n", false );
210 header( "Cache-Control: no-cache" ); # Experimental - see below
211 header( "Pragma: no-cache" );
212 header( "Last-modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
214 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
217 # Finally, all the text has been munged and accumulated into
218 # the object, let's actually output it:
220 function output()
222 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
223 global $wgInputEncoding, $wgOutputEncoding, $wgLanguageCode;
225 $fname = "OutputPage::output";
226 wfProfileIn( $fname );
228 $sk = $wgUser->getSkin();
230 $this->sendCacheControl();
232 header( "Content-type: text/html; charset={$wgOutputEncoding}" );
233 header( "Content-language: {$wgLanguageCode}" );
235 if ( "" != $this->mRedirect ) {
236 header( "Location: {$this->mRedirect}" );
237 return;
240 $exp = time() + $wgCookieExpiration;
241 foreach( $this->mCookies as $name => $val ) {
242 setcookie( $name, $val, $exp, "/" );
245 $sk->outputPage( $this );
246 flush();
249 function out( $ins )
251 global $wgInputEncoding, $wgOutputEncoding, $wgLang;
252 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
253 $outs = $ins;
254 } else {
255 $outs = $wgLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
256 if ( false === $outs ) { $outs = $ins; }
258 print $outs;
261 function setEncodings()
263 global $wgInputEncoding, $wgOutputEncoding;
264 global $wgUser, $wgLang;
266 $wgInputEncoding = strtolower( $wgInputEncoding );
268 if( $wgUser->getOption( 'altencoding' ) ) {
269 $wgLang->setAltEncoding();
270 return;
273 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
274 $wgOutputEncoding = strtolower( $wgOutputEncoding );
275 return;
279 # This code is unused anyway!
280 # Commenting out. --bv 2003-11-15
282 $a = explode( ",", $_SERVER['HTTP_ACCEPT_CHARSET'] );
283 $best = 0.0;
284 $bestset = "*";
286 foreach ( $a as $s ) {
287 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
288 $set = $m[1];
289 $q = (float)($m[2]);
290 } else {
291 $set = $s;
292 $q = 1.0;
294 if ( $q > $best ) {
295 $bestset = $set;
296 $best = $q;
299 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
300 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
301 $wgOutputEncoding = strtolower( $bestset );
303 # Disable for now
306 $wgOutputEncoding = $wgInputEncoding;
309 function reportTime()
311 global $wgRequestTime, $wgDebugLogFile;
312 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
314 list( $usec, $sec ) = explode( " ", microtime() );
315 $now = (float)$sec + (float)$usec;
317 list( $usec, $sec ) = explode( " ", $wgRequestTime );
318 $start = (float)$sec + (float)$usec;
319 $elapsed = $now - $start;
321 if ( "" != $wgDebugLogFile ) {
322 $prof = wfGetProfilingOutput( $start, $elapsed );
323 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
324 $forward = " forwarded for " . $_SERVER['HTTP_X_FORWARDED_FOR'];
325 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
326 $forward .= " client IP " . $_SERVER['HTTP_CLIENT_IP'];
327 if( !empty( $_SERVER['HTTP_FROM'] ) )
328 $forward .= " from " . $_SERVER['HTTP_FROM'];
329 if( $forward )
330 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
331 if($wgUser->getId() == 0)
332 $forward .= " anon";
333 $log = sprintf( "%s\t%04.3f\t%s\n",
334 gmdate( "YmdHis" ), $elapsed,
335 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
336 error_log( $log . $prof, 3, $wgDebugLogFile );
338 $com = sprintf( "<!-- Time since request: %01.2f secs. -->",
339 $elapsed );
340 return $com;
343 # Note: these arguments are keys into wfMsg(), not text!
345 function errorpage( $title, $msg )
347 global $wgTitle;
349 $this->mDebugtext .= "Original title: " .
350 $wgTitle->getPrefixedText() . "\n";
351 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
352 $this->setPageTitle( wfMsg( $title ) );
353 $this->setRobotpolicy( "noindex,nofollow" );
354 $this->setArticleFlag( false );
356 $this->mBodytext = "";
357 $this->addHTML( "<p>" . wfMsg( $msg ) . "\n" );
358 $this->returnToMain( false );
360 $this->output();
361 exit;
364 function sysopRequired()
366 global $wgUser;
368 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
369 $this->setPageTitle( wfMsg( "sysoptitle" ) );
370 $this->setRobotpolicy( "noindex,nofollow" );
371 $this->setArticleFlag( false );
372 $this->mBodytext = "";
374 $sk = $wgUser->getSkin();
375 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
376 $this->addHTML( wfMsg( "sysoptext", $ap ) );
377 $this->returnToMain();
380 function developerRequired()
382 global $wgUser;
384 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
385 $this->setPageTitle( wfMsg( "developertitle" ) );
386 $this->setRobotpolicy( "noindex,nofollow" );
387 $this->setArticleFlag( false );
388 $this->mBodytext = "";
390 $sk = $wgUser->getSkin();
391 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
392 $this->addHTML( wfMsg( "developertext", $ap ) );
393 $this->returnToMain();
396 function databaseError( $fname )
398 global $wgUser, $wgCommandLineMode;
400 $this->setPageTitle( wfMsgNoDB( "databaseerror" ) );
401 $this->setRobotpolicy( "noindex,nofollow" );
402 $this->setArticleFlag( false );
404 if ( $wgCommandLineMode ) {
405 $msg = wfMsgNoDB( "dberrortextcl" );
406 } else {
407 $msg = wfMsgNoDB( "dberrortext" );
410 $msg = str_replace( "$1", htmlspecialchars( wfLastDBquery() ), $msg );
411 $msg = str_replace( "$2", htmlspecialchars( $fname ), $msg );
412 $msg = str_replace( "$3", wfLastErrno(), $msg );
413 $msg = str_replace( "$4", htmlspecialchars( wfLastError() ), $msg );
415 if ( $wgCommandLineMode ) {
416 print "$msg\n";
417 exit();
419 $sk = $wgUser->getSkin();
420 $shlink = $sk->makeKnownLink( wfMsgNoDB( "searchhelppage" ),
421 wfMsgNoDB( "searchingwikipedia" ) );
422 $msg = str_replace( "$5", $shlink, $msg );
424 $this->mBodytext = $msg;
425 $this->output();
426 exit();
429 function readOnlyPage( $source = "", $protected = false )
431 global $wgUser, $wgReadOnlyFile;
433 $this->setRobotpolicy( "noindex,nofollow" );
434 $this->setArticleFlag( false );
436 if( $protected ) {
437 $this->setPageTitle( wfMsg( "viewsource" ) );
438 $this->addWikiText( wfMsg( "protectedtext" ) );
439 } else {
440 $this->setPageTitle( wfMsg( "readonly" ) );
441 $reason = file_get_contents( $wgReadOnlyFile );
442 $this->addHTML( wfMsg( "readonlytext", $reason ) );
445 if($source) {
446 $rows = $wgUser->getOption( "rows" );
447 $cols = $wgUser->getOption( "cols" );
448 $text .= "</p>\n<textarea cols='$cols' rows='$rows' readonly>" .
449 htmlspecialchars( $source ) . "\n</textarea>";
450 $this->addHTML( $text );
453 $this->returnToMain( false );
456 function fatalError( $message )
458 $this->setPageTitle( wfMsg( "internalerror" ) );
459 $this->setRobotpolicy( "noindex,nofollow" );
460 $this->setArticleFlag( false );
462 $this->mBodytext = $message;
463 $this->output();
464 exit;
467 function unexpectedValueError( $name, $val )
469 $this->fatalError( wfMsg( "unexpected", $name, $val ) );
472 function fileCopyError( $old, $new )
474 $this->fatalError( wfMsg( "filecopyerror", $old, $new ) );
477 function fileRenameError( $old, $new )
479 $this->fatalError( wfMsg( "filerenameerror", $old, $new ) );
482 function fileDeleteError( $name )
484 $this->fatalError( wfMsg( "filedeleteerror", $name ) );
487 function fileNotFoundError( $name )
489 $this->fatalError( wfMsg( "filenotfound", $name ) );
492 function returnToMain( $auto = true )
494 global $wgUser, $wgOut, $returnto;
496 $sk = $wgUser->getSkin();
497 if ( "" == $returnto ) {
498 $returnto = wfMsg( "mainpage" );
500 $link = $sk->makeKnownLink( $returnto, "" );
502 $r = wfMsg( "returnto", $link );
503 if ( $auto ) {
504 $wgOut->addMeta( "http:Refresh", "10;url=" .
505 wfLocalUrlE( wfUrlencode( $returnto ) ) );
507 $wgOut->addHTML( "\n<p>$r\n" );
511 function categoryMagic ()
513 global $wgTitle , $wgUseCategoryMagic ;
514 if ( !isset ( $wgUseCategoryMagic ) || !$wgUseCategoryMagic ) return ;
515 $id = $wgTitle->getArticleID() ;
516 $cat = ucfirst ( wfMsg ( "category" ) ) ;
517 $ti = $wgTitle->getText() ;
518 $ti = explode ( ":" , $ti , 2 ) ;
519 if ( $cat != $ti[0] ) return "" ;
520 $r = "<br break=all>\n" ;
522 $articles = array() ;
523 $parents = array () ;
524 $children = array() ;
527 global $wgUser ;
528 $sk = $wgUser->getSkin() ;
529 $sql = "SELECT l_from FROM links WHERE l_to={$id}" ;
530 $res = wfQuery ( $sql, DB_READ ) ;
531 while ( $x = wfFetchObject ( $res ) )
533 # $t = new Title ;
534 # $t->newFromDBkey ( $x->l_from ) ;
535 # $t = $t->getText() ;
536 $t = $x->l_from ;
537 $y = explode ( ":" , $t , 2 ) ;
538 if ( count ( $y ) == 2 && $y[0] == $cat ) {
539 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
540 } else {
541 array_push ( $articles , $sk->makeLink ( $t ) ) ;
544 wfFreeResult ( $res ) ;
546 # Children
547 if ( count ( $children ) > 0 )
549 asort ( $children ) ;
550 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
551 $r .= implode ( ", " , $children ) ;
554 # Articles
555 if ( count ( $articles ) > 0 )
557 asort ( $articles ) ;
558 $h = wfMsg( "category_header", $ti[1] );
559 $r .= "<h2>{$h}</h2>\n" ;
560 $r .= implode ( ", " , $articles ) ;
564 return $r ;
567 function getHTMLattrs ()
569 $htmlattrs = array( # Allowed attributes--no scripting, etc.
570 "title", "align", "lang", "dir", "width", "height",
571 "bgcolor", "clear", /* BR */ "noshade", /* HR */
572 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
573 /* FONT */ "type", "start", "value", "compact",
574 /* For various lists, mostly deprecated but safe */
575 "summary", "width", "border", "frame", "rules",
576 "cellspacing", "cellpadding", "valign", "char",
577 "charoff", "colgroup", "col", "span", "abbr", "axis",
578 "headers", "scope", "rowspan", "colspan", /* Tables */
579 "id", "class", "name", "style" /* For CSS */
581 return $htmlattrs ;
584 function fixTableTags ( $t )
586 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
587 $htmlattrs = $this->getHTMLattrs() ;
589 # Strip non-approved attributes from the tag
590 $t = preg_replace(
591 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
592 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
593 $t);
595 return trim ( $t ) ;
598 function doTableStuff ( $t )
600 $t = explode ( "\n" , $t ) ;
601 $td = array () ; # Is currently a td tag open?
602 $ltd = array () ; # Was it TD or TH?
603 $tr = array () ; # Is currently a tr tag open?
604 $ltr = array () ; # tr attributes
605 foreach ( $t AS $k => $x )
607 $x = rtrim ( $x ) ;
608 $fc = substr ( $x , 0 , 1 ) ;
609 if ( "{|" == substr ( $x , 0 , 2 ) )
611 $t[$k] = "<table " . $this->fixTableTags ( substr ( $x , 3 ) ) . ">" ;
612 array_push ( $td , false ) ;
613 array_push ( $ltd , "" ) ;
614 array_push ( $tr , false ) ;
615 array_push ( $ltr , "" ) ;
617 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
618 else if ( "|}" == substr ( $x , 0 , 2 ) )
620 $z = "</table>\n" ;
621 $l = array_pop ( $ltd ) ;
622 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
623 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
624 array_pop ( $ltr ) ;
625 $t[$k] = $z ;
627 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
629 $z = trim ( substr ( $x , 2 ) ) ;
630 $t[$k] = "<caption>{$z}</caption>\n" ;
632 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
634 $x = substr ( $x , 1 ) ;
635 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
636 $z = "" ;
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 ;
642 array_push ( $tr , false ) ;
643 array_push ( $td , false ) ;
644 array_push ( $ltd , "" ) ;
645 array_push ( $ltr , $this->fixTableTags ( $x ) ) ;
647 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
649 if ( "|+" == substr ( $x , 0 , 2 ) )
651 $fc = "+" ;
652 $x = substr ( $x , 1 ) ;
654 $after = substr ( $x , 1 ) ;
655 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
656 $after = explode ( "||" , $after ) ;
657 $t[$k] = "" ;
658 foreach ( $after AS $theline )
660 $z = "" ;
661 $tra = array_pop ( $ltr ) ;
662 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
663 array_push ( $tr , true ) ;
664 array_push ( $ltr , "" ) ;
666 $l = array_pop ( $ltd ) ;
667 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
668 if ( $fc == "|" ) $l = "TD" ;
669 else if ( $fc == "!" ) $l = "TH" ;
670 else if ( $fc == "+" ) $l = "CAPTION" ;
671 else $l = "" ;
672 array_push ( $ltd , $l ) ;
673 $y = explode ( "|" , $theline , 2 ) ;
674 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
675 else $y = $y = "{$z}<{$l} ".$this->fixTableTags($y[0]).">{$y[1]}" ;
676 $t[$k] .= $y ;
677 array_push ( $td , true ) ;
682 # Closing open td, tr && table
683 while ( count ( $td ) > 0 )
685 if ( array_pop ( $td ) ) $t[] = "</td>" ;
686 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
687 $t[] = "</table>" ;
690 $t = implode ( "\n" , $t ) ;
691 # $t = $this->removeHTMLtags( $t );
692 return $t ;
695 # Well, OK, it's actually about 14 passes. But since all the
696 # hard lifting is done inside PHP's regex code, it probably
697 # wouldn't speed things up much to add a real parser.
699 function doWikiPass2( $text, $linestart )
701 global $wgUser, $wgLang, $wgUseDynamicDates;
702 $fname = "OutputPage::doWikiPass2";
703 wfProfileIn( $fname );
705 $text = $this->removeHTMLtags( $text );
706 $text = $this->replaceVariables( $text );
708 $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
709 $text = str_replace ( "<HR>", "<hr>", $text );
711 $text = $this->doAllQuotes( $text );
712 $text = $this->doHeadings( $text );
713 $text = $this->doBlockLevels( $text, $linestart );
715 if($wgUseDynamicDates) {
716 global $wgDateFormatter;
717 $text = $wgDateFormatter->reformat( $wgUser->getOption("date"), $text );
720 $text = $this->replaceExternalLinks( $text );
721 $text = $this->replaceInternalLinks ( $text );
722 $text = $this->doTableStuff ( $text ) ;
724 $text = $this->magicISBN( $text );
725 $text = $this->magicRFC( $text );
726 $text = $this->formatHeadings( $text );
728 $sk = $wgUser->getSkin();
729 $text = $sk->transformContent( $text );
730 $text .= $this->categoryMagic () ;
732 wfProfileOut( $fname );
733 return $text;
736 /* private */ function doAllQuotes( $text )
738 $outtext = "";
739 $lines = explode( "\r\n", $text );
740 foreach ( $lines as $line ) {
741 $outtext .= $this->doQuotes ( "", $line, "" ) . "\r\n";
743 return $outtext;
746 /* private */ function doQuotes( $pre, $text, $mode )
748 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
749 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
750 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
751 if ( substr ($m[2], 0, 1) == "'" ) {
752 $m[2] = substr ($m[2], 1);
753 if ($mode == "em") {
754 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "emstrong" );
755 } else if ($mode == "strong") {
756 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
757 } else if (($mode == "emstrong") || ($mode == "both")) {
758 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
759 } else if ($mode == "strongem") {
760 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
761 } else {
762 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
764 } else {
765 if ($mode == "strong") {
766 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "strongem" );
767 } else if ($mode == "em") {
768 return $m1_em . $this->doQuotes ( "", $m[2], "" );
769 } else if ($mode == "emstrong") {
770 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
771 } else if (($mode == "strongem") || ($mode == "both")) {
772 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
773 } else {
774 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
777 } else {
778 $text_strong = ($text == "") ? "" : "<strong>{$text}</strong>";
779 $text_em = ($text == "") ? "" : "<em>{$text}</em>";
780 if ($mode == "") {
781 return $pre . $text;
782 } else if ($mode == "em") {
783 return $pre . $text_em;
784 } else if ($mode == "strong") {
785 return $pre . $text_strong;
786 } else if ($mode == "strongem") {
787 return (($pre == "") && ($text == "")) ? "" : "<strong>{$pre}{$text_em}</strong>";
788 } else {
789 return (($pre == "") && ($text == "")) ? "" : "<em>{$pre}{$text_strong}</em>";
794 /* private */ function doHeadings( $text )
796 for ( $i = 6; $i >= 1; --$i ) {
797 $h = substr( "======", 0, $i );
798 $text = preg_replace( "/^{$h}([^=]+){$h}(\\s|$)/m",
799 "<h{$i}>\\1</h{$i}>\\2", $text );
801 return $text;
804 # Note: we have to do external links before the internal ones,
805 # and otherwise take great care in the order of things here, so
806 # that we don't end up interpreting some URLs twice.
808 /* private */ function replaceExternalLinks( $text )
810 $fname = "OutputPage::replaceExternalLinks";
811 wfProfileIn( $fname );
812 $text = $this->subReplaceExternalLinks( $text, "http", true );
813 $text = $this->subReplaceExternalLinks( $text, "https", true );
814 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
815 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
816 $text = $this->subReplaceExternalLinks( $text, "news", false );
817 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
818 wfProfileOut( $fname );
819 return $text;
822 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
824 global $wgUser, $printable;
825 global $wgAllowExternalImages;
828 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
829 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
831 # this is the list of separators that should be ignored if they
832 # are the last character of an URL but that should be included
833 # if they occur within the URL, e.g. "go to www.foo.com, where .."
834 # in this case, the last comma should not become part of the URL,
835 # but in "www.foo.com/123,2342,32.htm" it should.
836 $sep = ",;\.:";
837 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
838 $images = "gif|png|jpg|jpeg";
840 # PLEASE NOTE: The curly braces { } are not part of the regex,
841 # they are interpreted as part of the string (used to tell PHP
842 # that the content of the string should be inserted there).
843 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
844 "((?i){$images})([^{$uc}]|$)/";
846 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
847 $sk = $wgUser->getSkin();
849 if ( $autonumber and $wgAllowExternalImages) { # Use img tags only for HTTP urls
850 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
851 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
853 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
854 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
855 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
856 "</a>\\5", $s );
857 $s = str_replace( $unique, $protocol, $s );
859 $a = explode( "[{$protocol}:", " " . $s );
860 $s = array_shift( $a );
861 $s = substr( $s, 1 );
863 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
864 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
866 foreach ( $a as $line ) {
867 if ( preg_match( $e1, $line, $m ) ) {
868 $link = "{$protocol}:{$m[1]}";
869 $trail = $m[2];
870 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
871 else { $text = wfEscapeHTML( $link ); }
872 } else if ( preg_match( $e2, $line, $m ) ) {
873 $link = "{$protocol}:{$m[1]}";
874 $text = $m[2];
875 $trail = $m[3];
876 } else {
877 $s .= "[{$protocol}:" . $line;
878 continue;
880 if ( $printable == "yes") $paren = " (<i>" . htmlspecialchars ( $link ) . "</i>)";
881 else $paren = "";
882 $la = $sk->getExternalLinkAttributes( $link, $text );
883 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
886 return $s;
889 /* private */ function replaceInternalLinks( $s )
891 global $wgTitle, $wgUser, $wgLang;
892 global $wgLinkCache, $wgInterwikiMagic, $wgUseCategoryMagic;
893 global $wgNamespacesWithSubpages, $wgLanguageCode;
894 wfProfileIn( $fname = "OutputPage::replaceInternalLinks" );
896 wfProfileIn( "$fname-setup" );
897 $tc = Title::legalChars() . "#";
898 $sk = $wgUser->getSkin();
900 $a = explode( "[[", " " . $s );
901 $s = array_shift( $a );
902 $s = substr( $s, 1 );
904 $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD";
906 # Special and Media are pseudo-namespaces; no pages actually exist in them
907 $image = Namespace::getImage();
908 $special = Namespace::getSpecial();
909 $media = Namespace::getMedia();
910 $nottalk = !Namespace::isTalk( $wgTitle->getNamespace() );
911 wfProfileOut( "$fname-setup" );
913 foreach ( $a as $line ) {
914 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
915 $text = $m[2];
916 $trail = $m[3];
917 } else { # Invalid form; output directly
918 $s .= "[[" . $line ;
919 continue;
922 /* Valid link forms:
923 Foobar -- normal
924 :Foobar -- override special treatment of prefix (images, language links)
925 /Foobar -- convert to CurrentPage/Foobar
926 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
928 $c = substr($m[1],0,1);
929 $noforce = ($c != ":");
930 if( $c == "/" ) { # subpage
931 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
932 $m[1]=substr($m[1],1,strlen($m[1])-2);
933 $noslash=$m[1];
934 } else {
935 $noslash=substr($m[1],1);
937 if($wgNamespacesWithSubpages[$wgTitle->getNamespace()]) { # subpages allowed here
938 $link = $wgTitle->getPrefixedText(). "/" . trim($noslash);
939 if(!$text) {
940 $text= $m[1];
941 } # this might be changed for ugliness reasons
942 } else {
943 $link = $noslash; # no subpage allowed, use standard link
945 } elseif( $noforce ) { # no subpage
946 $link = $m[1];
947 } else {
948 $link = substr( $m[1], 1 );
950 if( empty( $text ) )
951 $text = $link;
953 $nt = Title::newFromText( $link );
954 if( !$nt ) {
955 $s .= "[[" . $line;
956 continue;
958 $ns = $nt->getNamespace();
959 $iw = $nt->getInterWiki();
960 if( $noforce ) {
961 if( $iw && $wgInterwikiMagic && $nottalk && $wgLang->getLanguageName( $iw ) ) {
962 array_push( $this->mLanguageLinks, $nt->getPrefixedText() );
963 $s .= $trail;
964 /* CHECK MERGE @@@
965 } else if ( "media" == $pre ) {
966 $nt = Title::newFromText( $suf );
967 $name = $nt->getDBkey();
968 if ( "" == $text ) { $text = $nt->GetText(); }
970 $wgLinkCache->addImageLink( $name );
971 $s .= $sk->makeMediaLink( $name,
972 wfImageUrl( $name ), $text );
973 $s .= $trail;
974 } else if ( isset($wgUseCategoryMagic) && $wgUseCategoryMagic && $pre == wfMsg ( "category" ) ) {
975 $l = $sk->makeLink ( $pre.":".ucfirst( $m[2] ), ucfirst ( $m[2] ) ) ;
976 array_push ( $this->mCategoryLinks , $l ) ;
977 $s .= $trail ;
978 } else {
979 $l = $wgLang->getLanguageName( $pre );
980 if ( "" == $l or !$wgInterwikiMagic or Namespace::isTalk( $wgTitle->getNamespace() ) ) {
981 if ( "" == $text ) {
982 $text = $link;
984 $s .= $sk->makeLink( $link, $text, "", $trail );
985 } else if ( $pre != $wgLanguageCode ) {
986 array_push( $this->mLanguageLinks, "$pre:$suf" );
987 $s .= $trail;
990 continue;
992 if( $ns == $image ) {
993 $s .= $sk->makeImageLinkObj( $nt, $text ) . $trail;
994 $wgLinkCache->addImageLinkObj( $nt );
995 continue;
997 /* CHECK MERGE @@@
998 # } else if ( 0 == strcmp( "##", substr( $link, 0, 2 ) ) ) {
999 # $link = substr( $link, 2 );
1000 # $s .= "<a name=\"{$link}\">{$text}</a>{$trail}";
1001 } else {
1002 if ( "" == $text ) { $text = $link; }
1003 # Hotspot:
1004 $s .= $sk->makeLink( $link, $text, "", $trail );
1007 if( $ns == $media ) {
1008 $s .= $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1009 $wgLinkCache->addImageLinkObj( $nt );
1010 continue;
1011 } elseif( $ns == $special ) {
1012 $s .= $sk->makeKnownLinkObj( $nt, $text, "", $trail );
1013 continue;
1015 $s .= $sk->makeLinkObj( $nt, $text, "", $trail );
1017 wfProfileOut( $fname );
1018 return $s;
1021 # Some functions here used by doBlockLevels()
1023 /* private */ function closeParagraph()
1025 $result = "";
1026 if ( 0 != strcmp( "p", $this->mLastSection ) &&
1027 0 != strcmp( "", $this->mLastSection ) ) {
1028 $result = "</" . $this->mLastSection . ">";
1030 $this->mLastSection = "";
1031 return $result;
1033 # getCommon() returns the length of the longest common substring
1034 # of both arguments, starting at the beginning of both.
1036 /* private */ function getCommon( $st1, $st2 )
1038 $fl = strlen( $st1 );
1039 $shorter = strlen( $st2 );
1040 if ( $fl < $shorter ) { $shorter = $fl; }
1042 for ( $i = 0; $i < $shorter; ++$i ) {
1043 if ( $st1{$i} != $st2{$i} ) { break; }
1045 return $i;
1047 # These next three functions open, continue, and close the list
1048 # element appropriate to the prefix character passed into them.
1050 /* private */ function openList( $char )
1052 $result = $this->closeParagraph();
1054 if ( "*" == $char ) { $result .= "<ul><li>"; }
1055 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1056 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1057 else if ( ";" == $char ) {
1058 $result .= "<dl><dt>";
1059 $this->mDTopen = true;
1061 else { $result = "<!-- ERR 1 -->"; }
1063 return $result;
1066 /* private */ function nextItem( $char )
1068 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1069 else if ( ":" == $char || ";" == $char ) {
1070 $close = "</dd>";
1071 if ( $this->mDTopen ) { $close = "</dt>"; }
1072 if ( ";" == $char ) {
1073 $this->mDTopen = true;
1074 return $close . "<dt>";
1075 } else {
1076 $this->mDTopen = false;
1077 return $close . "<dd>";
1080 return "<!-- ERR 2 -->";
1083 /* private */function closeList( $char )
1085 if ( "*" == $char ) { return "</li></ul>"; }
1086 else if ( "#" == $char ) { return "</li></ol>"; }
1087 else if ( ":" == $char ) {
1088 if ( $this->mDTopen ) {
1089 $this->mDTopen = false;
1090 return "</dt></dl>";
1091 } else {
1092 return "</dd></dl>";
1095 return "<!-- ERR 3 -->";
1098 /* private */ function doBlockLevels( $text, $linestart )
1100 $fname = "OutputPage::doBlockLevels";
1101 wfProfileIn( $fname );
1102 # Parsing through the text line by line. The main thing
1103 # happening here is handling of block-level elements p, pre,
1104 # and making lists from lines starting with * # : etc.
1106 $a = explode( "\n", $text );
1107 $text = $lastPref = "";
1108 $this->mDTopen = $inBlockElem = false;
1110 if ( ! $linestart ) { $text .= array_shift( $a ); }
1111 foreach ( $a as $t ) {
1112 if ( "" != $text ) { $text .= "\n"; }
1114 $oLine = $t;
1115 $opl = strlen( $lastPref );
1116 $npl = strspn( $t, "*#:;" );
1117 $pref = substr( $t, 0, $npl );
1118 $pref2 = str_replace( ";", ":", $pref );
1119 $t = substr( $t, $npl );
1121 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1122 $text .= $this->nextItem( substr( $pref, -1 ) );
1124 if ( ";" == substr( $pref, -1 ) ) {
1125 $cpos = strpos( $t, ":" );
1126 if ( ! ( false === $cpos ) ) {
1127 $term = substr( $t, 0, $cpos );
1128 $text .= $term . $this->nextItem( ":" );
1129 $t = substr( $t, $cpos + 1 );
1132 } else if (0 != $npl || 0 != $opl) {
1133 $cpl = $this->getCommon( $pref, $lastPref );
1135 while ( $cpl < $opl ) {
1136 $text .= $this->closeList( $lastPref{$opl-1} );
1137 --$opl;
1139 if ( $npl <= $cpl && $cpl > 0 ) {
1140 $text .= $this->nextItem( $pref{$cpl-1} );
1142 while ( $npl > $cpl ) {
1143 $char = substr( $pref, $cpl, 1 );
1144 $text .= $this->openList( $char );
1146 if ( ";" == $char ) {
1147 $cpos = strpos( $t, ":" );
1148 if ( ! ( false === $cpos ) ) {
1149 $term = substr( $t, 0, $cpos );
1150 $text .= $term . $this->nextItem( ":" );
1151 $t = substr( $t, $cpos + 1 );
1154 ++$cpl;
1156 $lastPref = $pref2;
1158 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1159 if ( preg_match(
1160 "/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6)/i", $t ) ) {
1161 $text .= $this->closeParagraph();
1162 $inBlockElem = true;
1164 if ( ! $inBlockElem ) {
1165 if ( " " == $t{0} ) {
1166 $newSection = "pre";
1167 # $t = wfEscapeHTML( $t );
1169 else { $newSection = "p"; }
1171 if ( 0 == strcmp( "", trim( $oLine ) ) ) {
1172 $text .= $this->closeParagraph();
1173 $text .= "<" . $newSection . ">";
1174 } else if ( 0 != strcmp( $this->mLastSection,
1175 $newSection ) ) {
1176 $text .= $this->closeParagraph();
1177 if ( 0 != strcmp( "p", $newSection ) ) {
1178 $text .= "<" . $newSection . ">";
1181 $this->mLastSection = $newSection;
1183 if ( $inBlockElem &&
1184 preg_match( "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6)/i", $t ) ) {
1185 $inBlockElem = false;
1188 $text .= $t;
1190 while ( $npl ) {
1191 $text .= $this->closeList( $pref2{$npl-1} );
1192 --$npl;
1194 if ( "" != $this->mLastSection ) {
1195 if ( "p" != $this->mLastSection ) {
1196 $text .= "</" . $this->mLastSection . ">";
1198 $this->mLastSection = "";
1200 wfProfileOut( $fname );
1201 return $text;
1204 /* private */ function replaceVariables( $text )
1206 global $wgLang;
1207 $fname = "OutputPage::replaceVariables";
1208 wfProfileIn( $fname );
1211 # Basic variables
1212 # See Language.php for the definition of each magic word
1214 # As with sigs, this uses the server's local time -- ensure
1215 # this is appropriate for your audience!
1216 $v = date( "m" );
1217 $mw =& MagicWord::get( MAG_CURRENTMONTH );
1218 $text = $mw->replace( $v, $text );
1220 $v = $wgLang->getMonthName( date( "n" ) );
1221 $mw =& MagicWord::get( MAG_CURRENTMONTHNAME );
1222 $text = $mw->replace( $v, $text );
1224 $v = $wgLang->getMonthNameGen( date( "n" ) );
1225 $mw =& MagicWord::get( MAG_CURRENTMONTHNAMEGEN );
1226 $text = $mw->replace( $v, $text );
1228 $v = date( "j" );
1229 $mw = MagicWord::get( MAG_CURRENTDAY );
1230 $text = $mw->replace( $v, $text );
1232 $v = $wgLang->getWeekdayName( date( "w" )+1 );
1233 $mw =& MagicWord::get( MAG_CURRENTDAYNAME );
1234 $text = $mw->replace( $v, $text );
1236 $v = date( "Y" );
1237 $mw =& MagicWord::get( MAG_CURRENTYEAR );
1238 $text = $mw->replace( $v, $text );
1240 $v = $wgLang->time( wfTimestampNow(), false );
1241 $mw =& MagicWord::get( MAG_CURRENTTIME );
1242 $text = $mw->replace( $v, $text );
1244 $mw =& MagicWord::get( MAG_NUMBEROFARTICLES );
1245 if ( $mw->match( $text ) ) {
1246 $v = wfNumberOfArticles();
1247 $text = $mw->replace( $v, $text );
1250 # "Variables" with an additional parameter e.g. {{MSG:wikipedia}}
1251 # The callbacks are at the bottom of this file
1252 $mw =& MagicWord::get( MAG_MSG );
1253 $text = $mw->substituteCallback( $text, "wfReplaceMsgVar" );
1255 $mw =& MagicWord::get( MAG_MSGNW );
1256 $text = $mw->substituteCallback( $text, "wfReplaceMsgnwVar" );
1258 wfProfileOut( $fname );
1259 return $text;
1262 # Cleans up HTML, removes dangerous tags and attributes
1263 /* private */ function removeHTMLtags( $text )
1265 $fname = "OutputPage::removeHTMLtags";
1266 wfProfileIn( $fname );
1267 $htmlpairs = array( # Tags that must be closed
1268 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1269 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1270 "strike", "strong", "tt", "var", "div", "center",
1271 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1272 "ruby", "rt" , "rb" , "rp"
1274 $htmlsingle = array(
1275 "br", "p", "hr", "li", "dt", "dd"
1277 $htmlnest = array( # Tags that can be nested--??
1278 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1279 "dl", "font", "big", "small", "sub", "sup"
1281 $tabletags = array( # Can only appear inside table
1282 "td", "th", "tr"
1285 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1286 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1288 $htmlattrs = $this->getHTMLattrs () ;
1290 # Remove HTML comments
1291 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1293 $bits = explode( "<", $text );
1294 $text = array_shift( $bits );
1295 $tagstack = array(); $tablestack = array();
1297 foreach ( $bits as $x ) {
1298 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1299 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1300 $x, $regs );
1301 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1302 error_reporting( $prev );
1304 $badtag = 0 ;
1305 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1306 # Check our stack
1307 if ( $slash ) {
1308 # Closing a tag...
1309 if ( ! in_array( $t, $htmlsingle ) &&
1310 ( $ot = array_pop( $tagstack ) ) != $t ) {
1311 array_push( $tagstack, $ot );
1312 $badtag = 1;
1313 } else {
1314 if ( $t == "table" ) {
1315 $tagstack = array_pop( $tablestack );
1317 $newparams = "";
1319 } else {
1320 # Keep track for later
1321 if ( in_array( $t, $tabletags ) &&
1322 ! in_array( "table", $tagstack ) ) {
1323 $badtag = 1;
1324 } else if ( in_array( $t, $tagstack ) &&
1325 ! in_array ( $t , $htmlnest ) ) {
1326 $badtag = 1 ;
1327 } else if ( ! in_array( $t, $htmlsingle ) ) {
1328 if ( $t == "table" ) {
1329 array_push( $tablestack, $tagstack );
1330 $tagstack = array();
1332 array_push( $tagstack, $t );
1334 # Strip non-approved attributes from the tag
1335 $newparams = preg_replace(
1336 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
1337 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
1338 $params);
1340 if ( ! $badtag ) {
1341 $rest = str_replace( ">", "&gt;", $rest );
1342 $text .= "<$slash$t$newparams$brace$rest";
1343 continue;
1346 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1348 # Close off any remaining tags
1349 while ( $t = array_pop( $tagstack ) ) {
1350 $text .= "</$t>\n";
1351 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1353 wfProfileOut( $fname );
1354 return $text;
1360 * This function accomplishes several tasks:
1361 * 1) Auto-number headings if that option is enabled
1362 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1363 * 3) Add a Table of contents on the top for users who have enabled the option
1364 * 4) Auto-anchor headings
1366 * It loops through all headlines, collects the necessary data, then splits up the
1367 * string and re-inserts the newly formatted headlines.
1369 * */
1370 /* private */ function formatHeadings( $text )
1372 global $wgUser,$wgArticle,$wgTitle,$wpPreview;
1373 $nh=$wgUser->getOption( "numberheadings" );
1374 $st=$wgUser->getOption( "showtoc" );
1375 if(!$wgTitle->userCanEdit()) {
1376 $es=0;
1377 $esr=0;
1378 } else {
1379 $es=$wgUser->getID() && $wgUser->getOption( "editsection" );
1380 $esr=$wgUser->getID() && $wgUser->getOption( "editsectiononrightclick" );
1383 # Inhibit editsection links if requested in the page
1384 if ($es) {
1385 $esw=& MagicWord::get(MAG_NOEDITSECTION);
1386 if ($esw->matchAndRemove( $text )) {
1387 $es=0;
1390 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1391 # do not add TOC
1392 $mw =& MagicWord::get( MAG_NOTOC );
1393 if ($mw->matchAndRemove( $text ))
1395 $st = 0;
1398 # never add the TOC to the Main Page. This is an entry page that should not
1399 # be more than 1-2 screens large anyway
1400 if($wgTitle->getPrefixedText()==wfMsg("mainpage")) {$st=0;}
1402 # We need this to perform operations on the HTML
1403 $sk=$wgUser->getSkin();
1405 # Get all headlines for numbering them and adding funky stuff like [edit]
1406 # links
1407 preg_match_all("/<H([1-6])(.*?>)(.*?)<\/H[1-6]>/i",$text,$matches);
1409 # headline counter
1410 $c=0;
1412 # Ugh .. the TOC should have neat indentation levels which can be
1413 # passed to the skin functions. These are determined here
1414 foreach($matches[3] as $headline) {
1415 if($level) { $prevlevel=$level;}
1416 $level=$matches[1][$c];
1417 if(($nh||$st) && $prevlevel && $level>$prevlevel) {
1419 $h[$level]=0; // reset when we enter a new level
1420 $toc.=$sk->tocIndent($level-$prevlevel);
1421 $toclevel+=$level-$prevlevel;
1424 if(($nh||$st) && $level<$prevlevel) {
1425 $h[$level+1]=0; // reset when we step back a level
1426 $toc.=$sk->tocUnindent($prevlevel-$level);
1427 $toclevel-=$prevlevel-$level;
1430 $h[$level]++; // count number of headlines for each level
1432 if($nh||$st) {
1433 for($i=1;$i<=$level;$i++) {
1434 if($h[$i]) {
1435 if($dot) {$numbering.=".";}
1436 $numbering.=$h[$i];
1437 $dot=1;
1442 // The canonized header is a version of the header text safe to use for links
1444 $canonized_headline=preg_replace("/<.*?>/","",$headline); // strip out HTML
1445 $tocline=$canonized_headline;
1446 $canonized_headline=str_replace('"',"",$canonized_headline);
1447 $canonized_headline=str_replace(" ","_",trim($canonized_headline));
1448 $refer[$c]=$canonized_headline;
1449 $refers[$canonized_headline]++; // count how many in assoc. array so we can track dupes in anchors
1450 $refcount[$c]=$refers[$canonized_headline];
1452 // Prepend the number to the heading text
1454 if($nh||$st) {
1455 $tocline=$numbering ." ". $tocline;
1457 // Don't number the heading if it is the only one (looks silly)
1458 if($nh && count($matches[3]) > 1) {
1459 $headline=$numbering . " " . $headline; // the two are different if the line contains a link
1463 // Create the anchor for linking from the TOC to the section
1465 $anchor=$canonized_headline;
1466 if($refcount[$c]>1) {$anchor.="_".$refcount[$c];}
1467 if($st) {
1468 $toc.=$sk->tocLine($anchor,$tocline,$toclevel);
1470 if($es && !isset($wpPreview)) {
1471 $head[$c].=$sk->editSectionLink($c+1);
1474 // Put it all together
1476 $head[$c].="<h".$level.$matches[2][$c]
1477 ."<a name=\"".$anchor."\">"
1478 .$headline
1479 ."</a>"
1480 ."</h".$level.">";
1482 // Add the edit section link
1484 if($esr && !isset($wpPreview)) {
1485 $head[$c]=$sk->editSectionScript($c+1,$head[$c]);
1488 $numbering="";
1489 $c++;
1490 $dot=0;
1493 if($st) {
1494 $toclines=$c;
1495 $toc.=$sk->tocUnindent($toclevel);
1496 $toc=$sk->tocTable($toc);
1499 // split up and insert constructed headlines
1501 $blocks=preg_split("/<H[1-6].*?>.*?<\/H[1-6]>/i",$text);
1502 $i=0;
1504 foreach($blocks as $block) {
1505 if(($es) && !isset($wpPreview) && $c>0 && $i==0) {
1506 # This is the [edit] link that appears for the top block of text when
1507 # section editing is enabled
1508 $full.=$sk->editSectionLink(0);
1510 $full.=$block;
1511 if($st && $toclines>3 && !$i) {
1512 # Let's add a top anchor just in case we want to link to the top of the page
1513 $full="<a name=\"top\"></a>".$full.$toc;
1516 $full.=$head[$i];
1517 $i++;
1520 return $full;
1523 /* private */ function magicISBN( $text )
1525 global $wgLang;
1527 $a = split( "ISBN ", " $text" );
1528 if ( count ( $a ) < 2 ) return $text;
1529 $text = substr( array_shift( $a ), 1);
1530 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1532 foreach ( $a as $x ) {
1533 $isbn = $blank = "" ;
1534 while ( " " == $x{0} ) {
1535 $blank .= " ";
1536 $x = substr( $x, 1 );
1538 while ( strstr( $valid, $x{0} ) != false ) {
1539 $isbn .= $x{0};
1540 $x = substr( $x, 1 );
1542 $num = str_replace( "-", "", $isbn );
1543 $num = str_replace( " ", "", $num );
1545 if ( "" == $num ) {
1546 $text .= "ISBN $blank$x";
1547 } else {
1548 $text .= "<a href=\"" . wfLocalUrlE( $wgLang->specialPage(
1549 "Booksources"), "isbn={$num}" ) . "\" class=\"internal\">ISBN $isbn</a>";
1550 $text .= $x;
1553 return $text;
1556 /* private */ function magicRFC( $text )
1558 return $text;
1561 /* private */ function headElement()
1563 global $wgDocType, $wgDTD, $wgUser, $wgLanguageCode, $wgOutputEncoding, $wgLang;
1565 $ret = "<!DOCTYPE HTML PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1567 if ( "" == $this->mHTMLtitle ) {
1568 $this->mHTMLtitle = $this->mPagetitle;
1570 $rtl = $wgLang->isRTL() ? " dir='RTL'" : "";
1571 $ret .= "<html lang=\"$wgLanguageCode\"$rtl><head><title>{$this->mHTMLtitle}</title>\n";
1572 array_push( $this->mMetatags, array( "http:Content-type", "text/html; charset={$wgOutputEncoding}" ) );
1573 foreach ( $this->mMetatags as $tag ) {
1574 if ( 0 == strcasecmp( "http:", substr( $tag[0], 0, 5 ) ) ) {
1575 $a = "http-equiv";
1576 $tag[0] = substr( $tag[0], 5 );
1577 } else {
1578 $a = "name";
1580 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\">\n";
1582 $p = $this->mRobotpolicy;
1583 if ( "" == $p ) { $p = "index,follow"; }
1584 $ret .= "<meta name=\"robots\" content=\"$p\">\n";
1586 if ( count( $this->mKeywords ) > 0 ) {
1587 $ret .= "<meta name=\"keywords\" content=\"" .
1588 implode( ",", $this->mKeywords ) . "\">\n";
1590 foreach ( $this->mLinktags as $tag ) {
1591 $ret .= "<link ";
1592 if ( "" != $tag[0] ) { $ret .= "rel=\"{$tag[0]}\" "; }
1593 if ( "" != $tag[1] ) { $ret .= "rev=\"{$tag[1]}\" "; }
1594 $ret .= "href=\"{$tag[2]}\">\n";
1596 $sk = $wgUser->getSkin();
1597 $ret .= $sk->getHeadScripts();
1598 $ret .= $sk->getUserStyles();
1600 $ret .= "</head>\n";
1601 return $ret;
1605 # Regex callbacks, used in OutputPage::replaceVariables
1607 # Just get rid of the dangerous stuff
1608 # Necessary because replaceVariables is called after removeHTMLtags,
1609 # and message text can come from any user
1610 function wfReplaceMsgVar( $matches ) {
1611 global $wgOut;
1612 $text = $wgOut->removeHTMLtags( wfMsg( $matches[1] ) );
1613 return $text;
1616 # Effective <nowiki></nowiki>
1617 # Not real <nowiki> because this is called after nowiki sections are processed
1618 function wfReplaceMsgnwVar( $matches ) {
1619 $text = wfEscapeWikiText( wfMsg( $matches[1] ) );
1620 return $text;