Nov. branch merge. Various features backported from stable, various bug fixes.
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?
2 # See design.doc
3
4 if($wgUseTeX) include_once( "Math.php" );
5
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;
12
13 var $mDTopen, $mLastSection; # Used for processing DL, PRE
14 var $mLanguageLinks, $mSupressQuickbar;
15
16 function OutputPage()
17 {
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;
28 }
29
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; }
33
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 ) ); }
38
39 function checkLastModified ( $timestamp )
40 {
41 global $wgLang, $wgCachePages, $wgUser;
42 if( !$wgCachePages ) {
43 wfDebug( "CACHE DISABLED\n", false );
44 return;
45 }
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;
50 }
51 if( $wgUser->getOption( "nocache" ) ) {
52 wfDebug( "USER DISABLED CACHE\n", false );
53 return;
54 }
55
56 $lastmod = gmdate( "D, j M Y H:i:s", wfTimestamp2Unix(
57 max( $timestamp, $wgUser->mTouched ) ) ) . " GMT";
58
59 if( $_SERVER["HTTP_IF_MODIFIED_SINCE"] != "" ) {
60 # IE sends sizes after the date like this:
61 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
62 # this breaks strtotime().
63 $modsince = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
64 $ismodsince = wfUnix2Timestamp( strtotime( $modsince ) );
65 wfDebug( "-- client send If-Modified-Since: " . $modsince . "\n", false );
66 wfDebug( "-- we might send Last-Modified : $lastmod\n", false );
67
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;
80 }
81 } else {
82 wfDebug( "We're confused.\n", false );
83 $this->mLastModified = $lastmod;
84 }
85 }
86
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; }
97
98 function getLanguageLinks() {
99 global $wgTitle, $wgLanguageCode;
100 global $wgDBconnection, $wgDBname;
101 return $this->mLanguageLinks;
102 }
103 function supressQuickbar() { $this->mSupressQuickbar = true; }
104 function isQuickbarSupressed() { return $this->mSupressQuickbar; }
105
106 function addHTML( $text ) { $this->mBodytext .= $text; }
107 function addHeadtext( $text ) { $this->mHeadtext .= $text; }
108 function debug( $text ) { $this->mDebugtext .= $text; }
109
110 # First pass--just handle <nowiki> sections, pass the rest off
111 # to doWikiPass2() which does all the real work.
112 #
113
114 function addWikiText( $text, $linestart = true )
115 {
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 = "";
131
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];
142 }
143 }
144
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];
156 }
157 }
158 } else {
159 $stripped2 = $stripped;
160 }
161
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];
172 }
173 }
174
175 $text = $this->doWikiPass2( $stripped3, $linestart );
176
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 );
182 }
183
184 for ( $i = 1; $i <= $mathsecs; ++$i ) {
185 $text = preg_replace( "/{$unique2}/", str_replace( $specialChars,
186 $escapedChars, $mathlist[$i] ), $text, 1 );
187 }
188
189 for ( $i = 1; $i <= $nwsecs; ++$i ) {
190 $text = preg_replace( "/{$unique}/", str_replace( $specialChars,
191 $escapedChars, $nwlist[$i] ), $text, 1 );
192 }
193 $this->addHTML( $text );
194 wfProfileOut( $fname );
195 }
196
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" );
207 }
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" );
213 }
214 header( "Expires: Mon, 15 Jan 2001 00:00:00 GMT" ); # Cachers always validate the page!
215 }
216
217 # Finally, all the text has been munged and accumulated into
218 # the object, let's actually output it:
219 #
220 function output()
221 {
222 global $wgUser, $wgLang, $wgDebugComments, $wgCookieExpiration;
223 global $wgInputEncoding, $wgOutputEncoding, $wgLanguageCode;
224
225 $fname = "OutputPage::output";
226 wfProfileIn( $fname );
227
228 $sk = $wgUser->getSkin();
229
230 $this->sendCacheControl();
231
232 header( "Content-type: text/html; charset={$wgOutputEncoding}" );
233 header( "Content-language: {$wgLanguageCode}" );
234
235 if ( "" != $this->mRedirect ) {
236 header( "Location: {$this->mRedirect}" );
237 return;
238 }
239
240 $exp = time() + $wgCookieExpiration;
241 foreach( $this->mCookies as $name => $val ) {
242 setcookie( $name, $val, $exp, "/" );
243 }
244
245 $sk->outputPage( $this );
246 flush();
247 }
248
249 function out( $ins )
250 {
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; }
257 }
258 print $outs;
259 }
260
261 function setEncodings()
262 {
263 global $HTTP_SERVER_VARS, $wgInputEncoding, $wgOutputEncoding;
264 global $wgUser, $wgLang;
265
266 $wgInputEncoding = strtolower( $wgInputEncoding );
267 $s = $HTTP_SERVER_VARS['HTTP_ACCEPT_CHARSET'];
268
269 if( $wgUser->getOption( 'altencoding' ) ) {
270 $wgLang->setAltEncoding();
271 return;
272 }
273
274 if ( "" == $s ) {
275 $wgOutputEncoding = strtolower( $wgOutputEncoding );
276 return;
277 }
278 $a = explode( ",", $s );
279 $best = 0.0;
280 $bestset = "*";
281
282 foreach ( $a as $s ) {
283 if ( preg_match( "/(.*);q=(.*)/", $s, $m ) ) {
284 $set = $m[1];
285 $q = (float)($m[2]);
286 } else {
287 $set = $s;
288 $q = 1.0;
289 }
290 if ( $q > $best ) {
291 $bestset = $set;
292 $best = $q;
293 }
294 }
295 #if ( "*" == $bestset ) { $bestset = "iso-8859-1"; }
296 if ( "*" == $bestset ) { $bestset = $wgOutputEncoding; }
297 $wgOutputEncoding = strtolower( $bestset );
298
299 # Disable for now
300 #
301 $wgOutputEncoding = $wgInputEncoding;
302 }
303
304 function reportTime()
305 {
306 global $wgRequestTime, $wgDebugLogFile, $HTTP_SERVER_VARS;
307 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
308
309 list( $usec, $sec ) = explode( " ", microtime() );
310 $now = (float)$sec + (float)$usec;
311
312 list( $usec, $sec ) = explode( " ", $wgRequestTime );
313 $start = (float)$sec + (float)$usec;
314 $elapsed = $now - $start;
315
316 if ( "" != $wgDebugLogFile ) {
317 $prof = wfGetProfilingOutput( $start, $elapsed );
318 if( $forward = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'] )
319 $forward = " forwarded for $forward";
320 if( $client = $HTTP_SERVER_VARS['HTTP_CLIENT_IP'] )
321 $forward .= " client IP $client";
322 if( $from = $HTTP_SERVER_VARS['HTTP_FROM'] )
323 $forward .= " from $from";
324 if( $forward )
325 $forward = "\t(proxied via {$HTTP_SERVER_VARS['REMOTE_ADDR']}{$forward})";
326 if($wgUser->getId() == 0)
327 $forward .= " anon";
328 $log = sprintf( "%s\t%04.3f\t%s\n",
329 gmdate( "YmdHis" ), $elapsed,
330 urldecode( $HTTP_SERVER_VARS['REQUEST_URI'] . $forward ) );
331 error_log( $log . $prof, 3, $wgDebugLogFile );
332 }
333 $com = sprintf( "<!-- Time since request: %01.2f secs. -->",
334 $elapsed );
335 return $com;
336 }
337
338 # Note: these arguments are keys into wfMsg(), not text!
339 #
340 function errorpage( $title, $msg )
341 {
342 global $wgTitle;
343
344 $this->mDebugtext .= "Original title: " .
345 $wgTitle->getPrefixedText() . "\n";
346 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
347 $this->setPageTitle( wfMsg( $title ) );
348 $this->setRobotpolicy( "noindex,nofollow" );
349 $this->setArticleFlag( false );
350
351 $this->mBodytext = "";
352 $this->addHTML( "<p>" . wfMsg( $msg ) . "\n" );
353 $this->returnToMain( false );
354
355 $this->output();
356 exit;
357 }
358
359 function sysopRequired()
360 {
361 global $wgUser;
362
363 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
364 $this->setPageTitle( wfMsg( "sysoptitle" ) );
365 $this->setRobotpolicy( "noindex,nofollow" );
366 $this->setArticleFlag( false );
367 $this->mBodytext = "";
368
369 $sk = $wgUser->getSkin();
370 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
371 $text = str_replace( "$1", $ap, wfMsg( "sysoptext" ) );
372 $this->addHTML( $text );
373 $this->returnToMain();
374 }
375
376 function developerRequired()
377 {
378 global $wgUser;
379
380 $this->setHTMLTitle( wfMsg( "errorpagetitle" ) );
381 $this->setPageTitle( wfMsg( "developertitle" ) );
382 $this->setRobotpolicy( "noindex,nofollow" );
383 $this->setArticleFlag( false );
384 $this->mBodytext = "";
385
386 $sk = $wgUser->getSkin();
387 $ap = $sk->makeKnownLink( wfMsg( "administrators" ), "" );
388 $text = str_replace( "$1", $ap, wfMsg( "developertext" ) );
389 $this->addHTML( $text );
390 $this->returnToMain();
391 }
392
393 function databaseError( $fname )
394 {
395 global $wgUser, $wgCommandLineMode;
396
397 $this->setPageTitle( wfMsgNoDB( "databaseerror" ) );
398 $this->setRobotpolicy( "noindex,nofollow" );
399 $this->setArticleFlag( false );
400
401 if ( $wgCommandLineMode ) {
402 $msg = wfMsgNoDB( "dberrortextcl" );
403 } else {
404 $msg = wfMsgNoDB( "dberrortextcl" );
405 }
406
407 $msg = str_replace( "$1", htmlspecialchars( wfLastDBquery() ), $msg );
408 $msg = str_replace( "$2", htmlspecialchars( $fname ), $msg );
409 $msg = str_replace( "$3", wfLastErrno(), $msg );
410 $msg = str_replace( "$4", htmlspecialchars( wfLastError() ), $msg );
411
412 if ( $wgCommandLineMode ) {
413 print "$msg\n";
414 exit();
415 }
416 $sk = $wgUser->getSkin();
417 $shlink = $sk->makeKnownLink( wfMsgNoDB( "searchhelppage" ),
418 wfMsgNoDB( "searchingwikipedia" ) );
419 $msg = str_replace( "$5", $shlink, $msg );
420
421 $this->mBodytext = $msg;
422 $this->output();
423 exit();
424 }
425
426 function readOnlyPage( $source = "", $protected = false )
427 {
428 global $wgUser, $wgReadOnlyFile;
429
430 $this->setRobotpolicy( "noindex,nofollow" );
431 $this->setArticleFlag( false );
432
433 if( $protected ) {
434 $this->setPageTitle( wfMsg( "viewsource" ) );
435 $this->addWikiText( wfMsg( "protectedtext" ) );
436 } else {
437 $this->setPageTitle( wfMsg( "readonly" ) );
438 $reason = file_get_contents( $wgReadOnlyFile );
439 $this->addHTML( wfMsg( "readonlytext", $reason ) );
440 }
441
442 if($source) {
443 $rows = $wgUser->getOption( "rows" );
444 $cols = $wgUser->getOption( "cols" );
445 $text .= "</p>\n<textarea cols='$cols' rows='$rows' readonly>" .
446 htmlspecialchars( $source ) . "\n</textarea>";
447 $this->addHTML( $text );
448 }
449
450 $this->returnToMain( false );
451 }
452
453 function fatalError( $message )
454 {
455 $this->setPageTitle( wfMsg( "internalerror" ) );
456 $this->setRobotpolicy( "noindex,nofollow" );
457 $this->setArticleFlag( false );
458
459 $this->mBodytext = $message;
460 $this->output();
461 exit;
462 }
463
464 function unexpectedValueError( $name, $val )
465 {
466 $msg = str_replace( "$1", $name, wfMsg( "unexpected" ) );
467 $msg = str_replace( "$2", $val, $msg );
468 $this->fatalError( $msg );
469 }
470
471 function fileCopyError( $old, $new )
472 {
473 $msg = str_replace( "$1", $old, wfMsg( "filecopyerror" ) );
474 $msg = str_replace( "$2", $new, $msg );
475 $this->fatalError( $msg );
476 }
477
478 function fileRenameError( $old, $new )
479 {
480 $msg = str_replace( "$1", $old, wfMsg( "filerenameerror" ) );
481 $msg = str_replace( "$2", $new, $msg );
482 $this->fatalError( $msg );
483 }
484
485 function fileDeleteError( $name )
486 {
487 $msg = str_replace( "$1", $name, wfMsg( "filedeleteerror" ) );
488 $this->fatalError( $msg );
489 }
490
491 function fileNotFoundError( $name )
492 {
493 $msg = str_replace( "$1", $name, wfMsg( "filenotfound" ) );
494 $this->fatalError( $msg );
495 }
496
497 function returnToMain( $auto = true )
498 {
499 global $wgUser, $wgOut, $returnto;
500
501 $sk = $wgUser->getSkin();
502 if ( "" == $returnto ) {
503 $returnto = wfMsg( "mainpage" );
504 }
505 $link = $sk->makeKnownLink( $returnto, "" );
506
507 $r = str_replace( "$1", $link, wfMsg( "returnto" ) );
508 if ( $auto ) {
509 $wgOut->addMeta( "http:Refresh", "10;url=" .
510 wfLocalUrlE( wfUrlencode( $returnto ) ) );
511 }
512 $wgOut->addHTML( "\n<p>$r\n" );
513 }
514
515
516 function categoryMagic ()
517 {
518 global $wgTitle , $wgUseCategoryMagic ;
519 if ( !isset ( $wgUseCategoryMagic ) || !$wgUseCategoryMagic ) return ;
520 $id = $wgTitle->getArticleID() ;
521 $cat = ucfirst ( wfMsg ( "category" ) ) ;
522 $ti = $wgTitle->getText() ;
523 $ti = explode ( ":" , $ti , 2 ) ;
524 if ( $cat != $ti[0] ) return "" ;
525 $r = "<br break=all>\n" ;
526
527 $articles = array() ;
528 $parents = array () ;
529 $children = array() ;
530
531
532 global $wgUser ;
533 $sk = $wgUser->getSkin() ;
534 $sql = "SELECT l_from FROM links WHERE l_to={$id}" ;
535 $res = wfQuery ( $sql, DB_READ ) ;
536 while ( $x = wfFetchObject ( $res ) )
537 {
538 # $t = new Title ;
539 # $t->newFromDBkey ( $x->l_from ) ;
540 # $t = $t->getText() ;
541 $t = $x->l_from ;
542 $y = explode ( ":" , $t , 2 ) ;
543 if ( count ( $y ) == 2 && $y[0] == $cat ) {
544 array_push ( $children , $sk->makeLink ( $t , $y[1] ) ) ;
545 } else {
546 array_push ( $articles , $sk->makeLink ( $t ) ) ;
547 }
548 }
549 wfFreeResult ( $res ) ;
550
551 # Children
552 if ( count ( $children ) > 0 )
553 {
554 asort ( $children ) ;
555 $r .= "<h2>".wfMsg("subcategories")."</h2>\n" ;
556 $r .= implode ( ", " , $children ) ;
557 }
558
559 # Articles
560 if ( count ( $articles ) > 0 )
561 {
562 asort ( $articles ) ;
563 $h = str_replace ( "$1" , $ti[1] , wfMsg("category_header") ) ;
564 $r .= "<h2>{$h}</h2>\n" ;
565 $r .= implode ( ", " , $articles ) ;
566 }
567
568
569 return $r ;
570 }
571
572 function getHTMLattrs ()
573 {
574 $htmlattrs = array( # Allowed attributes--no scripting, etc.
575 "title", "align", "lang", "dir", "width", "height",
576 "bgcolor", "clear", /* BR */ "noshade", /* HR */
577 "cite", /* BLOCKQUOTE, Q */ "size", "face", "color",
578 /* FONT */ "type", "start", "value", "compact",
579 /* For various lists, mostly deprecated but safe */
580 "summary", "width", "border", "frame", "rules",
581 "cellspacing", "cellpadding", "valign", "char",
582 "charoff", "colgroup", "col", "span", "abbr", "axis",
583 "headers", "scope", "rowspan", "colspan", /* Tables */
584 "id", "class", "name", "style" /* For CSS */
585 );
586 return $htmlattrs ;
587 }
588
589 function fixTableTags ( $t )
590 {
591 if ( trim ( $t ) == "" ) return "" ; # Saves runtime ;-)
592 $htmlattrs = $this->getHTMLattrs() ;
593
594 # Strip non-approved attributes from the tag
595 $t = preg_replace(
596 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
597 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
598 $t);
599
600 return trim ( $t ) ;
601 }
602
603 function doTableStuff ( $t )
604 {
605 $t = explode ( "\n" , $t ) ;
606 $td = array () ; # Is currently a td tag open?
607 $ltd = array () ; # Was it TD or TH?
608 $tr = array () ; # Is currently a tr tag open?
609 $ltr = array () ; # tr attributes
610 foreach ( $t AS $k => $x )
611 {
612 $x = rtrim ( $x ) ;
613 $fc = substr ( $x , 0 , 1 ) ;
614 if ( "{|" == substr ( $x , 0 , 2 ) )
615 {
616 $t[$k] = "<table " . $this->fixTableTags ( substr ( $x , 3 ) ) . ">" ;
617 array_push ( $td , false ) ;
618 array_push ( $ltd , "" ) ;
619 array_push ( $tr , false ) ;
620 array_push ( $ltr , "" ) ;
621 }
622 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
623 else if ( "|}" == substr ( $x , 0 , 2 ) )
624 {
625 $z = "</table>\n" ;
626 $l = array_pop ( $ltd ) ;
627 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
628 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
629 array_pop ( $ltr ) ;
630 $t[$k] = $z ;
631 }
632 /* else if ( "|_" == substr ( $x , 0 , 2 ) ) # Caption
633 {
634 $z = trim ( substr ( $x , 2 ) ) ;
635 $t[$k] = "<caption>{$z}</caption>\n" ;
636 }*/
637 else if ( "|-" == substr ( $x , 0 , 2 ) ) # Allows for |---------------
638 {
639 $x = substr ( $x , 1 ) ;
640 while ( $x != "" && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
641 $z = "" ;
642 $l = array_pop ( $ltd ) ;
643 if ( array_pop ( $tr ) ) $z = "</tr>" . $z ;
644 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
645 array_pop ( $ltr ) ;
646 $t[$k] = $z ;
647 array_push ( $tr , false ) ;
648 array_push ( $td , false ) ;
649 array_push ( $ltd , "" ) ;
650 array_push ( $ltr , $this->fixTableTags ( $x ) ) ;
651 }
652 else if ( "|" == $fc || "!" == $fc || "|+" == substr ( $x , 0 , 2 ) ) # Caption
653 {
654 if ( "|+" == substr ( $x , 0 , 2 ) )
655 {
656 $fc = "+" ;
657 $x = substr ( $x , 1 ) ;
658 }
659 $after = substr ( $x , 1 ) ;
660 if ( $fc == "!" ) $after = str_replace ( "!!" , "||" , $after ) ;
661 $after = explode ( "||" , $after ) ;
662 $t[$k] = "" ;
663 foreach ( $after AS $theline )
664 {
665 $z = "" ;
666 $tra = array_pop ( $ltr ) ;
667 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
668 array_push ( $tr , true ) ;
669 array_push ( $ltr , "" ) ;
670
671 $l = array_pop ( $ltd ) ;
672 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
673 if ( $fc == "|" ) $l = "TD" ;
674 else if ( $fc == "!" ) $l = "TH" ;
675 else if ( $fc == "+" ) $l = "CAPTION" ;
676 else $l = "" ;
677 array_push ( $ltd , $l ) ;
678 $y = explode ( "|" , $theline , 2 ) ;
679 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
680 else $y = $y = "{$z}<{$l} ".$this->fixTableTags($y[0]).">{$y[1]}" ;
681 $t[$k] .= $y ;
682 array_push ( $td , true ) ;
683 }
684 }
685 }
686
687 # Closing open td, tr && table
688 while ( count ( $td ) > 0 )
689 {
690 if ( array_pop ( $td ) ) $t[] = "</td>" ;
691 if ( array_pop ( $tr ) ) $t[] = "</tr>" ;
692 $t[] = "</table>" ;
693 }
694
695 $t = implode ( "\n" , $t ) ;
696 # $t = $this->removeHTMLtags( $t );
697 return $t ;
698 }
699
700 # Well, OK, it's actually about 14 passes. But since all the
701 # hard lifting is done inside PHP's regex code, it probably
702 # wouldn't speed things up much to add a real parser.
703 #
704 function doWikiPass2( $text, $linestart )
705 {
706 global $wgUser, $wgLang, $wgUseDynamicDates;
707 $fname = "OutputPage::doWikiPass2";
708 wfProfileIn( $fname );
709
710 $text = $this->removeHTMLtags( $text );
711 $text = $this->replaceVariables( $text );
712
713 $text = preg_replace( "/(^|\n)-----*/", "\\1<hr>", $text );
714 $text = str_replace ( "<HR>", "<hr>", $text );
715
716 $text = $this->doAllQuotes( $text );
717 $text = $this->doHeadings( $text );
718 $text = $this->doBlockLevels( $text, $linestart );
719
720 if($wgUseDynamicDates) {
721 $text = $wgLang->replaceDates( $text );
722 }
723
724 $text = $this->replaceExternalLinks( $text );
725 $text = $this->replaceInternalLinks ( $text );
726 $text = $this->doTableStuff ( $text ) ;
727
728 $text = $this->magicISBN( $text );
729 $text = $this->magicRFC( $text );
730 $text = $this->formatHeadings( $text );
731
732 $sk = $wgUser->getSkin();
733 $text = $sk->transformContent( $text );
734 $text .= $this->categoryMagic () ;
735
736 wfProfileOut( $fname );
737 return $text;
738 }
739
740 /* private */ function doAllQuotes( $text )
741 {
742 $outtext = "";
743 $lines = explode( "\r\n", $text );
744 foreach ( $lines as $line ) {
745 $outtext .= $this->doQuotes ( "", $line, "" ) . "\r\n";
746 }
747 return $outtext;
748 }
749
750 /* private */ function doQuotes( $pre, $text, $mode )
751 {
752 if ( preg_match( "/^(.*)''(.*)$/sU", $text, $m ) ) {
753 $m1_strong = ($m[1] == "") ? "" : "<strong>{$m[1]}</strong>";
754 $m1_em = ($m[1] == "") ? "" : "<em>{$m[1]}</em>";
755 if ( substr ($m[2], 0, 1) == "'" ) {
756 $m[2] = substr ($m[2], 1);
757 if ($mode == "em") {
758 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "emstrong" );
759 } else if ($mode == "strong") {
760 return $m1_strong . $this->doQuotes ( "", $m[2], "" );
761 } else if (($mode == "emstrong") || ($mode == "both")) {
762 return $this->doQuotes ( "", $pre.$m1_strong.$m[2], "em" );
763 } else if ($mode == "strongem") {
764 return "<strong>{$pre}{$m1_em}</strong>" . $this->doQuotes ( "", $m[2], "em" );
765 } else {
766 return $m[1] . $this->doQuotes ( "", $m[2], "strong" );
767 }
768 } else {
769 if ($mode == "strong") {
770 return $this->doQuotes ( $m[1], $m[2], ($m[1] == "") ? "both" : "strongem" );
771 } else if ($mode == "em") {
772 return $m1_em . $this->doQuotes ( "", $m[2], "" );
773 } else if ($mode == "emstrong") {
774 return "<em>{$pre}{$m1_strong}</em>" . $this->doQuotes ( "", $m[2], "strong" );
775 } else if (($mode == "strongem") || ($mode == "both")) {
776 return $this->doQuotes ( "", $pre.$m1_em.$m[2], "strong" );
777 } else {
778 return $m[1] . $this->doQuotes ( "", $m[2], "em" );
779 }
780 }
781 } else {
782 $text_strong = ($text == "") ? "" : "<strong>{$text}</strong>";
783 $text_em = ($text == "") ? "" : "<em>{$text}</em>";
784 if ($mode == "") {
785 return $pre . $text;
786 } else if ($mode == "em") {
787 return $pre . $text_em;
788 } else if ($mode == "strong") {
789 return $pre . $text_strong;
790 } else if ($mode == "strongem") {
791 return (($pre == "") && ($text == "")) ? "" : "<strong>{$pre}{$text_em}</strong>";
792 } else {
793 return (($pre == "") && ($text == "")) ? "" : "<em>{$pre}{$text_strong}</em>";
794 }
795 }
796 }
797
798 /* private */ function doHeadings( $text )
799 {
800 for ( $i = 6; $i >= 1; --$i ) {
801 $h = substr( "======", 0, $i );
802 $text = preg_replace( "/^{$h}([^=]+){$h}(\\s|$)/m",
803 "<h{$i}>\\1</h{$i}>\\2", $text );
804 }
805 return $text;
806 }
807
808 # Note: we have to do external links before the internal ones,
809 # and otherwise take great care in the order of things here, so
810 # that we don't end up interpreting some URLs twice.
811
812 /* private */ function replaceExternalLinks( $text )
813 {
814 $fname = "OutputPage::replaceExternalLinks";
815 wfProfileIn( $fname );
816 $text = $this->subReplaceExternalLinks( $text, "http", true );
817 $text = $this->subReplaceExternalLinks( $text, "https", true );
818 $text = $this->subReplaceExternalLinks( $text, "ftp", false );
819 $text = $this->subReplaceExternalLinks( $text, "gopher", false );
820 $text = $this->subReplaceExternalLinks( $text, "news", false );
821 $text = $this->subReplaceExternalLinks( $text, "mailto", false );
822 wfProfileOut( $fname );
823 return $text;
824 }
825
826 /* private */ function subReplaceExternalLinks( $s, $protocol, $autonumber )
827 {
828 global $wgUser, $printable;
829 global $wgAllowExternalImages;
830
831
832 $unique = "4jzAfzB8hNvf4sqyO9Edd8pSmk9rE2in0Tgw3";
833 $uc = "A-Za-z0-9_\\/~%\\-+&*#?!=()@\\x80-\\xFF";
834
835 # this is the list of separators that should be ignored if they
836 # are the last character of an URL but that should be included
837 # if they occur within the URL, e.g. "go to www.foo.com, where .."
838 # in this case, the last comma should not become part of the URL,
839 # but in "www.foo.com/123,2342,32.htm" it should.
840 $sep = ",;\.:";
841 $fnc = "A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF";
842 $images = "gif|png|jpg|jpeg";
843
844 # PLEASE NOTE: The curly braces { } are not part of the regex,
845 # they are interpreted as part of the string (used to tell PHP
846 # that the content of the string should be inserted there).
847 $e1 = "/(^|[^\\[])({$protocol}:)([{$uc}{$sep}]+)\\/([{$fnc}]+)\\." .
848 "((?i){$images})([^{$uc}]|$)/";
849
850 $e2 = "/(^|[^\\[])({$protocol}:)(([".$uc."]|[".$sep."][".$uc."])+)([^". $uc . $sep. "]|[".$sep."]|$)/";
851 $sk = $wgUser->getSkin();
852
853 if ( $autonumber and $wgAllowExternalImages) { # Use img tags only for HTTP urls
854 $s = preg_replace( $e1, "\\1" . $sk->makeImage( "{$unique}:\\3" .
855 "/\\4.\\5", "\\4.\\5" ) . "\\6", $s );
856 }
857 $s = preg_replace( $e2, "\\1" . "<a href=\"{$unique}:\\3\"" .
858 $sk->getExternalLinkAttributes( "{$unique}:\\3", wfEscapeHTML(
859 "{$unique}:\\3" ) ) . ">" . wfEscapeHTML( "{$unique}:\\3" ) .
860 "</a>\\5", $s );
861 $s = str_replace( $unique, $protocol, $s );
862
863 $a = explode( "[{$protocol}:", " " . $s );
864 $s = array_shift( $a );
865 $s = substr( $s, 1 );
866
867 $e1 = "/^([{$uc}"."{$sep}]+)](.*)\$/sD";
868 $e2 = "/^([{$uc}"."{$sep}]+)\\s+([^\\]]+)](.*)\$/sD";
869
870 foreach ( $a as $line ) {
871 if ( preg_match( $e1, $line, $m ) ) {
872 $link = "{$protocol}:{$m[1]}";
873 $trail = $m[2];
874 if ( $autonumber ) { $text = "[" . ++$this->mAutonumber . "]"; }
875 else { $text = wfEscapeHTML( $link ); }
876 } else if ( preg_match( $e2, $line, $m ) ) {
877 $link = "{$protocol}:{$m[1]}";
878 $text = $m[2];
879 $trail = $m[3];
880 } else {
881 $s .= "[{$protocol}:" . $line;
882 continue;
883 }
884 if ( $printable == "yes") $paren = " (<i>" . htmlspecialchars ( $link ) . "</i>)";
885 else $paren = "";
886 $la = $sk->getExternalLinkAttributes( $link, $text );
887 $s .= "<a href='{$link}'{$la}>{$text}</a>{$paren}{$trail}";
888
889 }
890 return $s;
891 }
892
893 /* private */ function replaceInternalLinks( $s )
894 {
895 global $wgTitle, $wgUser, $wgLang;
896 global $wgLinkCache, $wgInterwikiMagic, $wgUseCategoryMagic;
897 global $wgNamespacesWithSubpages, $wgLanguageCode;
898 wfProfileIn( $fname = "OutputPage::replaceInternalLinks" );
899
900 wfProfileIn( "$fname-setup" );
901 $tc = Title::legalChars() . "#";
902 $sk = $wgUser->getSkin();
903
904 $a = explode( "[[", " " . $s );
905 $s = array_shift( $a );
906 $s = substr( $s, 1 );
907
908 $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD";
909
910 # Special and Media are pseudo-namespaces; no pages actually exist in them
911 $image = Namespace::getImage();
912 $special = Namespace::getSpecial();
913 $media = Namespace::getMedia();
914 $nottalk = !Namespace::isTalk( $wgTitle->getNamespace() );
915 wfProfileOut( "$fname-setup" );
916
917 foreach ( $a as $line ) {
918 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
919 $text = $m[2];
920 $trail = $m[3];
921 } else { # Invalid form; output directly
922 $s .= "[[" . $line ;
923 continue;
924 }
925
926 /* Valid link forms:
927 Foobar -- normal
928 :Foobar -- override special treatment of prefix (images, language links)
929 /Foobar -- convert to CurrentPage/Foobar
930 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
931 */
932 $c = substr($m[1],0,1);
933 $noforce = ($c != ":");
934 if( $c == "/" ) { # subpage
935 if(substr($m[1],-1,1)=="/") { # / at end means we don't want the slash to be shown
936 $m[1]=substr($m[1],1,strlen($m[1])-2);
937 $noslash=$m[1];
938 } else {
939 $noslash=substr($m[1],1);
940 }
941 if($wgNamespacesWithSubpages[$wgTitle->getNamespace()]) { # subpages allowed here
942 $link = $wgTitle->getPrefixedText(). "/" . trim($noslash);
943 if(!$text) {
944 $text= $m[1];
945 } # this might be changed for ugliness reasons
946 } else {
947 $link = $noslash; # no subpage allowed, use standard link
948 }
949 } elseif( $noforce ) { # no subpage
950 $link = $m[1];
951 } else {
952 $link = substr( $m[1], 1 );
953 }
954 if( empty( $text ) )
955 $text = $link;
956
957 $nt = Title::newFromText( $link );
958 if( !$nt ) {
959 $s .= "[[" . $line;
960 continue;
961 }
962 $ns = $nt->getNamespace();
963 $iw = $nt->getInterWiki();
964 if( $noforce ) {
965 if( $iw && $wgInterwikiMagic && $nottalk && $wgLang->getLanguageName( $iw ) ) {
966 array_push( $this->mLanguageLinks, $nt->getPrefixedText() );
967 $s .= $trail;
968 /* CHECK MERGE @@@
969 } else if ( "media" == $pre ) {
970 $nt = Title::newFromText( $suf );
971 $name = $nt->getDBkey();
972 if ( "" == $text ) { $text = $nt->GetText(); }
973
974 $wgLinkCache->addImageLink( $name );
975 $s .= $sk->makeMediaLink( $name,
976 wfImageUrl( $name ), $text );
977 $s .= $trail;
978 } else if ( isset($wgUseCategoryMagic) && $wgUseCategoryMagic && $pre == wfMsg ( "category" ) ) {
979 $l = $sk->makeLink ( $pre.":".ucfirst( $m[2] ), ucfirst ( $m[2] ) ) ;
980 array_push ( $this->mCategoryLinks , $l ) ;
981 $s .= $trail ;
982 } else {
983 $l = $wgLang->getLanguageName( $pre );
984 if ( "" == $l or !$wgInterwikiMagic or Namespace::isTalk( $wgTitle->getNamespace() ) ) {
985 if ( "" == $text ) {
986 $text = $link;
987 }
988 $s .= $sk->makeLink( $link, $text, "", $trail );
989 } else if ( $pre != $wgLanguageCode ) {
990 array_push( $this->mLanguageLinks, "$pre:$suf" );
991 $s .= $trail;
992 }
993 */
994 continue;
995 }
996 if( $ns == $image ) {
997 $s .= $sk->makeImageLinkObj( $nt, $text ) . $trail;
998 $wgLinkCache->addImageLinkObj( $nt );
999 continue;
1000 }
1001 /* CHECK MERGE @@@
1002 # } else if ( 0 == strcmp( "##", substr( $link, 0, 2 ) ) ) {
1003 # $link = substr( $link, 2 );
1004 # $s .= "<a name=\"{$link}\">{$text}</a>{$trail}";
1005 } else {
1006 if ( "" == $text ) { $text = $link; }
1007 # Hotspot:
1008 $s .= $sk->makeLink( $link, $text, "", $trail );
1009 */
1010 }
1011 if( $ns == $media ) {
1012 $s .= $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1013 $wgLinkCache->addImageLinkObj( $nt );
1014 continue;
1015 } elseif( $ns == $special ) {
1016 $s .= $sk->makeKnownLinkObj( $nt, $text, "", $trail );
1017 continue;
1018 }
1019 $s .= $sk->makeLinkObj( $nt, $text, "", $trail );
1020 }
1021 wfProfileOut( $fname );
1022 return $s;
1023 }
1024
1025 # Some functions here used by doBlockLevels()
1026 #
1027 /* private */ function closeParagraph()
1028 {
1029 $result = "";
1030 if ( 0 != strcmp( "p", $this->mLastSection ) &&
1031 0 != strcmp( "", $this->mLastSection ) ) {
1032 $result = "</" . $this->mLastSection . ">";
1033 }
1034 $this->mLastSection = "";
1035 return $result;
1036 }
1037 # getCommon() returns the length of the longest common substring
1038 # of both arguments, starting at the beginning of both.
1039 #
1040 /* private */ function getCommon( $st1, $st2 )
1041 {
1042 $fl = strlen( $st1 );
1043 $shorter = strlen( $st2 );
1044 if ( $fl < $shorter ) { $shorter = $fl; }
1045
1046 for ( $i = 0; $i < $shorter; ++$i ) {
1047 if ( $st1{$i} != $st2{$i} ) { break; }
1048 }
1049 return $i;
1050 }
1051 # These next three functions open, continue, and close the list
1052 # element appropriate to the prefix character passed into them.
1053 #
1054 /* private */ function openList( $char )
1055 {
1056 $result = $this->closeParagraph();
1057
1058 if ( "*" == $char ) { $result .= "<ul><li>"; }
1059 else if ( "#" == $char ) { $result .= "<ol><li>"; }
1060 else if ( ":" == $char ) { $result .= "<dl><dd>"; }
1061 else if ( ";" == $char ) {
1062 $result .= "<dl><dt>";
1063 $this->mDTopen = true;
1064 }
1065 else { $result = "<!-- ERR 1 -->"; }
1066
1067 return $result;
1068 }
1069
1070 /* private */ function nextItem( $char )
1071 {
1072 if ( "*" == $char || "#" == $char ) { return "</li><li>"; }
1073 else if ( ":" == $char || ";" == $char ) {
1074 $close = "</dd>";
1075 if ( $this->mDTopen ) { $close = "</dt>"; }
1076 if ( ";" == $char ) {
1077 $this->mDTopen = true;
1078 return $close . "<dt>";
1079 } else {
1080 $this->mDTopen = false;
1081 return $close . "<dd>";
1082 }
1083 }
1084 return "<!-- ERR 2 -->";
1085 }
1086
1087 /* private */function closeList( $char )
1088 {
1089 if ( "*" == $char ) { return "</li></ul>"; }
1090 else if ( "#" == $char ) { return "</li></ol>"; }
1091 else if ( ":" == $char ) {
1092 if ( $this->mDTopen ) {
1093 $this->mDTopen = false;
1094 return "</dt></dl>";
1095 } else {
1096 return "</dd></dl>";
1097 }
1098 }
1099 return "<!-- ERR 3 -->";
1100 }
1101
1102 /* private */ function doBlockLevels( $text, $linestart )
1103 {
1104 $fname = "OutputPage::doBlockLevels";
1105 wfProfileIn( $fname );
1106 # Parsing through the text line by line. The main thing
1107 # happening here is handling of block-level elements p, pre,
1108 # and making lists from lines starting with * # : etc.
1109 #
1110 $a = explode( "\n", $text );
1111 $text = $lastPref = "";
1112 $this->mDTopen = $inBlockElem = false;
1113
1114 if ( ! $linestart ) { $text .= array_shift( $a ); }
1115 foreach ( $a as $t ) {
1116 if ( "" != $text ) { $text .= "\n"; }
1117
1118 $oLine = $t;
1119 $opl = strlen( $lastPref );
1120 $npl = strspn( $t, "*#:;" );
1121 $pref = substr( $t, 0, $npl );
1122 $pref2 = str_replace( ";", ":", $pref );
1123 $t = substr( $t, $npl );
1124
1125 if ( 0 != $npl && 0 == strcmp( $lastPref, $pref2 ) ) {
1126 $text .= $this->nextItem( substr( $pref, -1 ) );
1127
1128 if ( ";" == substr( $pref, -1 ) ) {
1129 $cpos = strpos( $t, ":" );
1130 if ( ! ( false === $cpos ) ) {
1131 $term = substr( $t, 0, $cpos );
1132 $text .= $term . $this->nextItem( ":" );
1133 $t = substr( $t, $cpos + 1 );
1134 }
1135 }
1136 } else if (0 != $npl || 0 != $opl) {
1137 $cpl = $this->getCommon( $pref, $lastPref );
1138
1139 while ( $cpl < $opl ) {
1140 $text .= $this->closeList( $lastPref{$opl-1} );
1141 --$opl;
1142 }
1143 if ( $npl <= $cpl && $cpl > 0 ) {
1144 $text .= $this->nextItem( $pref{$cpl-1} );
1145 }
1146 while ( $npl > $cpl ) {
1147 $char = substr( $pref, $cpl, 1 );
1148 $text .= $this->openList( $char );
1149
1150 if ( ";" == $char ) {
1151 $cpos = strpos( $t, ":" );
1152 if ( ! ( false === $cpos ) ) {
1153 $term = substr( $t, 0, $cpos );
1154 $text .= $term . $this->nextItem( ":" );
1155 $t = substr( $t, $cpos + 1 );
1156 }
1157 }
1158 ++$cpl;
1159 }
1160 $lastPref = $pref2;
1161 }
1162 if ( 0 == $npl ) { # No prefix--go to paragraph mode
1163 if ( preg_match(
1164 "/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6)/i", $t ) ) {
1165 $text .= $this->closeParagraph();
1166 $inBlockElem = true;
1167 }
1168 if ( ! $inBlockElem ) {
1169 if ( " " == $t{0} ) {
1170 $newSection = "pre";
1171 # $t = wfEscapeHTML( $t );
1172 }
1173 else { $newSection = "p"; }
1174
1175 if ( 0 == strcmp( "", trim( $oLine ) ) ) {
1176 $text .= $this->closeParagraph();
1177 $text .= "<" . $newSection . ">";
1178 } else if ( 0 != strcmp( $this->mLastSection,
1179 $newSection ) ) {
1180 $text .= $this->closeParagraph();
1181 if ( 0 != strcmp( "p", $newSection ) ) {
1182 $text .= "<" . $newSection . ">";
1183 }
1184 }
1185 $this->mLastSection = $newSection;
1186 }
1187 if ( $inBlockElem &&
1188 preg_match( "/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6)/i", $t ) ) {
1189 $inBlockElem = false;
1190 }
1191 }
1192 $text .= $t;
1193 }
1194 while ( $npl ) {
1195 $text .= $this->closeList( $pref2{$npl-1} );
1196 --$npl;
1197 }
1198 if ( "" != $this->mLastSection ) {
1199 if ( "p" != $this->mLastSection ) {
1200 $text .= "</" . $this->mLastSection . ">";
1201 }
1202 $this->mLastSection = "";
1203 }
1204 wfProfileOut( $fname );
1205 return $text;
1206 }
1207
1208 /* private */ function replaceVariables( $text )
1209 {
1210 global $wgLang;
1211 $fname = "OutputPage::replaceVariables";
1212 wfProfileIn( $fname );
1213
1214
1215 # Basic variables
1216 # See Language.php for the definition of each magic word
1217
1218 # As with sigs, this uses the server's local time -- ensure
1219 # this is appropriate for your audience!
1220 $v = date( "m" );
1221 $mw =& MagicWord::get( MAG_CURRENTMONTH );
1222 $text = $mw->replace( $v, $text );
1223
1224 $v = $wgLang->getMonthName( date( "n" ) );
1225 $mw =& MagicWord::get( MAG_CURRENTMONTHNAME );
1226 $text = $mw->replace( $v, $text );
1227
1228 $v = $wgLang->getMonthNameGen( date( "n" ) );
1229 $mw =& MagicWord::get( MAG_CURRENTMONTHNAMEGEN );
1230 $text = $mw->replace( $v, $text );
1231
1232 $v = date( "j" );
1233 $mw = MagicWord::get( MAG_CURRENTDAY );
1234 $text = $mw->replace( $v, $text );
1235
1236 $v = $wgLang->getWeekdayName( date( "w" )+1 );
1237 $mw =& MagicWord::get( MAG_CURRENTDAYNAME );
1238 $text = $mw->replace( $v, $text );
1239
1240 $v = date( "Y" );
1241 $mw =& MagicWord::get( MAG_CURRENTYEAR );
1242 $text = $mw->replace( $v, $text );
1243
1244 $v = $wgLang->time( wfTimestampNow(), false );
1245 $mw =& MagicWord::get( MAG_CURRENTTIME );
1246 $text = $mw->replace( $v, $text );
1247
1248 $mw =& MagicWord::get( MAG_NUMBEROFARTICLES );
1249 if ( $mw->match( $text ) ) {
1250 $v = wfNumberOfArticles();
1251 $text = $mw->replace( $v, $text );
1252 }
1253
1254 # "Variables" with an additional parameter e.g. {{MSG:wikipedia}}
1255 # The callbacks are at the bottom of this file
1256 $mw =& MagicWord::get( MAG_MSG );
1257 $text = $mw->substituteCallback( $text, "wfReplaceMsgVar" );
1258
1259 $mw =& MagicWord::get( MAG_MSGNW );
1260 $text = $mw->substituteCallback( $text, "wfReplaceMsgnwVar" );
1261
1262 wfProfileOut( $fname );
1263 return $text;
1264 }
1265
1266 # Cleans up HTML, removes dangerous tags and attributes
1267 /* private */ function removeHTMLtags( $text )
1268 {
1269 $fname = "OutputPage::removeHTMLtags";
1270 wfProfileIn( $fname );
1271 $htmlpairs = array( # Tags that must be closed
1272 "b", "i", "u", "font", "big", "small", "sub", "sup", "h1",
1273 "h2", "h3", "h4", "h5", "h6", "cite", "code", "em", "s",
1274 "strike", "strong", "tt", "var", "div", "center",
1275 "blockquote", "ol", "ul", "dl", "table", "caption", "pre",
1276 "ruby", "rt" , "rb" , "rp"
1277 );
1278 $htmlsingle = array(
1279 "br", "p", "hr", "li", "dt", "dd"
1280 );
1281 $htmlnest = array( # Tags that can be nested--??
1282 "table", "tr", "td", "th", "div", "blockquote", "ol", "ul",
1283 "dl", "font", "big", "small", "sub", "sup"
1284 );
1285 $tabletags = array( # Can only appear inside table
1286 "td", "th", "tr"
1287 );
1288
1289 $htmlsingle = array_merge( $tabletags, $htmlsingle );
1290 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
1291
1292 $htmlattrs = $this->getHTMLattrs () ;
1293
1294 # Remove HTML comments
1295 $text = preg_replace( "/<!--.*-->/sU", "", $text );
1296
1297 $bits = explode( "<", $text );
1298 $text = array_shift( $bits );
1299 $tagstack = array(); $tablestack = array();
1300
1301 foreach ( $bits as $x ) {
1302 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
1303 preg_match( "/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/",
1304 $x, $regs );
1305 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
1306 error_reporting( $prev );
1307
1308 $badtag = 0 ;
1309 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
1310 # Check our stack
1311 if ( $slash ) {
1312 # Closing a tag...
1313 if ( ! in_array( $t, $htmlsingle ) &&
1314 ( $ot = array_pop( $tagstack ) ) != $t ) {
1315 array_push( $tagstack, $ot );
1316 $badtag = 1;
1317 } else {
1318 if ( $t == "table" ) {
1319 $tagstack = array_pop( $tablestack );
1320 }
1321 $newparams = "";
1322 }
1323 } else {
1324 # Keep track for later
1325 if ( in_array( $t, $tabletags ) &&
1326 ! in_array( "table", $tagstack ) ) {
1327 $badtag = 1;
1328 } else if ( in_array( $t, $tagstack ) &&
1329 ! in_array ( $t , $htmlnest ) ) {
1330 $badtag = 1 ;
1331 } else if ( ! in_array( $t, $htmlsingle ) ) {
1332 if ( $t == "table" ) {
1333 array_push( $tablestack, $tagstack );
1334 $tagstack = array();
1335 }
1336 array_push( $tagstack, $t );
1337 }
1338 # Strip non-approved attributes from the tag
1339 $newparams = preg_replace(
1340 "/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e",
1341 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
1342 $params);
1343 }
1344 if ( ! $badtag ) {
1345 $rest = str_replace( ">", "&gt;", $rest );
1346 $text .= "<$slash$t$newparams$brace$rest";
1347 continue;
1348 }
1349 }
1350 $text .= "&lt;" . str_replace( ">", "&gt;", $x);
1351 }
1352 # Close off any remaining tags
1353 while ( $t = array_pop( $tagstack ) ) {
1354 $text .= "</$t>\n";
1355 if ( $t == "table" ) { $tagstack = array_pop( $tablestack ); }
1356 }
1357 wfProfileOut( $fname );
1358 return $text;
1359 }
1360
1361
1362 /*
1363 *
1364 * This function accomplishes several tasks:
1365 * 1) Auto-number headings if that option is enabled
1366 * 2) Add an [edit] link to sections for logged in users who have enabled the option
1367 * 3) Add a Table of contents on the top for users who have enabled the option
1368 * 4) Auto-anchor headings
1369 *
1370 * It loops through all headlines, collects the necessary data, then splits up the
1371 * string and re-inserts the newly formatted headlines.
1372 *
1373 * */
1374 /* private */ function formatHeadings( $text )
1375 {
1376 global $wgUser,$wgArticle,$wgTitle,$wpPreview;
1377 $nh=$wgUser->getOption( "numberheadings" );
1378 $st=$wgUser->getOption( "showtoc" );
1379 if(!$wgTitle->userCanEdit()) {
1380 $es=0;
1381 $esr=0;
1382 } else {
1383 $es=$wgUser->getID() && $wgUser->getOption( "editsection" );
1384 $esr=$wgUser->getID() && $wgUser->getOption( "editsectiononrightclick" );
1385 }
1386
1387 # Inhibit editsection links if requested in the page
1388 if ($es) {
1389 $esw=& MagicWord::get(MAG_NOEDITSECTION);
1390 if ($esw->matchAndRemove( $text )) {
1391 $es=0;
1392 }
1393 }
1394 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
1395 # do not add TOC
1396 $mw =& MagicWord::get( MAG_NOTOC );
1397 if ($mw->matchAndRemove( $text ))
1398 {
1399 $st = 0;
1400 }
1401
1402 # never add the TOC to the Main Page. This is an entry page that should not
1403 # be more than 1-2 screens large anyway
1404 if($wgTitle->getPrefixedText()==wfMsg("mainpage")) {$st=0;}
1405
1406 # We need this to perform operations on the HTML
1407 $sk=$wgUser->getSkin();
1408
1409 # Get all headlines for numbering them and adding funky stuff like [edit]
1410 # links
1411 preg_match_all("/<H([1-6])(.*?>)(.*?)<\/H[1-6]>/i",$text,$matches);
1412
1413 # headline counter
1414 $c=0;
1415
1416 # Ugh .. the TOC should have neat indentation levels which can be
1417 # passed to the skin functions. These are determined here
1418 foreach($matches[3] as $headline) {
1419 if($level) { $prevlevel=$level;}
1420 $level=$matches[1][$c];
1421 if(($nh||$st) && $prevlevel && $level>$prevlevel) {
1422
1423 $h[$level]=0; // reset when we enter a new level
1424 $toc.=$sk->tocIndent($level-$prevlevel);
1425 $toclevel+=$level-$prevlevel;
1426
1427 }
1428 if(($nh||$st) && $level<$prevlevel) {
1429 $h[$level+1]=0; // reset when we step back a level
1430 $toc.=$sk->tocUnindent($prevlevel-$level);
1431 $toclevel-=$prevlevel-$level;
1432
1433 }
1434 $h[$level]++; // count number of headlines for each level
1435
1436 if($nh||$st) {
1437 for($i=1;$i<=$level;$i++) {
1438 if($h[$i]) {
1439 if($dot) {$numbering.=".";}
1440 $numbering.=$h[$i];
1441 $dot=1;
1442 }
1443 }
1444 }
1445
1446 // The canonized header is a version of the header text safe to use for links
1447
1448 $canonized_headline=preg_replace("/<.*?>/","",$headline); // strip out HTML
1449 $tocline=$canonized_headline;
1450 $canonized_headline=str_replace('"',"",$canonized_headline);
1451 $canonized_headline=str_replace(" ","_",trim($canonized_headline));
1452 $refer[$c]=$canonized_headline;
1453 $refers[$canonized_headline]++; // count how many in assoc. array so we can track dupes in anchors
1454 $refcount[$c]=$refers[$canonized_headline];
1455
1456 // Prepend the number to the heading text
1457
1458 if($nh||$st) {
1459 $tocline=$numbering ." ". $tocline;
1460
1461 // Don't number the heading if it is the only one (looks silly)
1462 if($nh && count($matches[3]) > 1) {
1463 $headline=$numbering . " " . $headline; // the two are different if the line contains a link
1464 }
1465 }
1466
1467 // Create the anchor for linking from the TOC to the section
1468
1469 $anchor=$canonized_headline;
1470 if($refcount[$c]>1) {$anchor.="_".$refcount[$c];}
1471 if($st) {
1472 $toc.=$sk->tocLine($anchor,$tocline,$toclevel);
1473 }
1474 if($es && !isset($wpPreview)) {
1475 $head[$c].=$sk->editSectionLink($c+1);
1476 }
1477
1478 // Put it all together
1479
1480 $head[$c].="<h".$level.$matches[2][$c]
1481 ."<a name=\"".$anchor."\">"
1482 .$headline
1483 ."</a>"
1484 ."</h".$level.">";
1485
1486 // Add the edit section link
1487
1488 if($esr && !isset($wpPreview)) {
1489 $head[$c]=$sk->editSectionScript($c+1,$head[$c]);
1490 }
1491
1492 $numbering="";
1493 $c++;
1494 $dot=0;
1495 }
1496
1497 if($st) {
1498 $toclines=$c;
1499 $toc.=$sk->tocUnindent($toclevel);
1500 $toc=$sk->tocTable($toc);
1501 }
1502
1503 // split up and insert constructed headlines
1504
1505 $blocks=preg_split("/<H[1-6].*?>.*?<\/H[1-6]>/i",$text);
1506 $i=0;
1507
1508 foreach($blocks as $block) {
1509 if(($es) && !isset($wpPreview) && $c>0 && $i==0) {
1510 # This is the [edit] link that appears for the top block of text when
1511 # section editing is enabled
1512 $full.=$sk->editSectionLink(0);
1513 }
1514 $full.=$block;
1515 if($st && $toclines>3 && !$i) {
1516 # Let's add a top anchor just in case we want to link to the top of the page
1517 $full="<a name=\"top\"></a>".$full.$toc;
1518 }
1519
1520 $full.=$head[$i];
1521 $i++;
1522 }
1523
1524 return $full;
1525 }
1526
1527 /* private */ function magicISBN( $text )
1528 {
1529 global $wgLang;
1530
1531 $a = split( "ISBN ", " $text" );
1532 if ( count ( $a ) < 2 ) return $text;
1533 $text = substr( array_shift( $a ), 1);
1534 $valid = "0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1535
1536 foreach ( $a as $x ) {
1537 $isbn = $blank = "" ;
1538 while ( " " == $x{0} ) {
1539 $blank .= " ";
1540 $x = substr( $x, 1 );
1541 }
1542 while ( strstr( $valid, $x{0} ) != false ) {
1543 $isbn .= $x{0};
1544 $x = substr( $x, 1 );
1545 }
1546 $num = str_replace( "-", "", $isbn );
1547 $num = str_replace( " ", "", $num );
1548
1549 if ( "" == $num ) {
1550 $text .= "ISBN $blank$x";
1551 } else {
1552 $text .= "<a href=\"" . wfLocalUrlE( $wgLang->specialPage(
1553 "Booksources"), "isbn={$num}" ) . "\" class=\"internal\">ISBN $isbn</a>";
1554 $text .= $x;
1555 }
1556 }
1557 return $text;
1558 }
1559
1560 /* private */ function magicRFC( $text )
1561 {
1562 return $text;
1563 }
1564
1565 /* private */ function headElement()
1566 {
1567 global $wgDocType, $wgDTD, $wgUser, $wgLanguageCode, $wgOutputEncoding, $wgLang;
1568
1569 $ret = "<!DOCTYPE HTML PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1570
1571 if ( "" == $this->mHTMLtitle ) {
1572 $this->mHTMLtitle = $this->mPagetitle;
1573 }
1574 $rtl = $wgLang->isRTL() ? " dir='RTL'" : "";
1575 $ret .= "<html lang=\"$wgLanguageCode\"$rtl><head><title>{$this->mHTMLtitle}</title>\n";
1576 array_push( $this->mMetatags, array( "http:Content-type", "text/html; charset={$wgOutputEncoding}" ) );
1577 foreach ( $this->mMetatags as $tag ) {
1578 if ( 0 == strcasecmp( "http:", substr( $tag[0], 0, 5 ) ) ) {
1579 $a = "http-equiv";
1580 $tag[0] = substr( $tag[0], 5 );
1581 } else {
1582 $a = "name";
1583 }
1584 $ret .= "<meta $a=\"{$tag[0]}\" content=\"{$tag[1]}\">\n";
1585 }
1586 $p = $this->mRobotpolicy;
1587 if ( "" == $p ) { $p = "index,follow"; }
1588 $ret .= "<meta name=\"robots\" content=\"$p\">\n";
1589
1590 if ( count( $this->mKeywords ) > 0 ) {
1591 $ret .= "<meta name=\"keywords\" content=\"" .
1592 implode( ",", $this->mKeywords ) . "\">\n";
1593 }
1594 foreach ( $this->mLinktags as $tag ) {
1595 $ret .= "<link ";
1596 if ( "" != $tag[0] ) { $ret .= "rel=\"{$tag[0]}\" "; }
1597 if ( "" != $tag[1] ) { $ret .= "rev=\"{$tag[1]}\" "; }
1598 $ret .= "href=\"{$tag[2]}\">\n";
1599 }
1600 $sk = $wgUser->getSkin();
1601 $ret .= $sk->getHeadScripts();
1602 $ret .= $sk->getUserStyles();
1603
1604 $ret .= "</head>\n";
1605 return $ret;
1606 }
1607 }
1608
1609 # Regex callbacks, used in OutputPage::replaceVariables
1610
1611 # Just get rid of the dangerous stuff
1612 # Necessary because replaceVariables is called after removeHTMLtags,
1613 # and message text can come from any user
1614 function wfReplaceMsgVar( $matches ) {
1615 global $wgOut;
1616 $text = $wgOut->removeHTMLtags( wfMsg( $matches[1] ) );
1617 return $text;
1618 }
1619
1620 # Effective <nowiki></nowiki>
1621 # Not real <nowiki> because this is called after nowiki sections are processed
1622 function wfReplaceMsgnwVar( $matches ) {
1623 $text = wfEscapeWikiText( wfMsg( $matches[1] ) );
1624 return $text;
1625 }
1626
1627 ?>