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