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