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