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