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