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