Change some search index update code to do two regexps backwards.
[mediawiki.git] / includes / Parser.php
blob79c9c1eec2be8b2ecd3e0f9e67001089af8b9431
1 <?php
3 // require_once('Tokenizer.php');
5 # PHP Parser
7 # Processes wiki markup
9 # There are two main entry points into the Parser class:
10 # parse()
11 # produces HTML output
12 # preSaveTransform().
13 # produces altered wiki markup.
15 # Globals used:
16 # objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
18 # NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
20 # settings:
21 # $wgUseTex*, $wgUseCategoryMagic*, $wgUseDynamicDates*, $wgInterwikiMagic*,
22 # $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
23 # $wgLocaltimezone
25 # * only within ParserOptions
27 #----------------------------------------
28 # Variable substitution O(N^2) attack
29 #-----------------------------------------
30 # Without countermeasures, it would be possible to attack the parser by saving
31 # a page filled with a large number of inclusions of large pages. The size of
32 # the generated page would be proportional to the square of the input size.
33 # Hence, we limit the number of inclusions of any given page, thus bringing any
34 # attack back to O(N).
35 define( "MAX_INCLUDE_REPEAT", 100 );
36 define( "MAX_INCLUDE_SIZE", 1000000 ); // 1 Million
38 # Allowed values for $mOutputType
39 define( "OT_HTML", 1 );
40 define( "OT_WIKI", 2 );
41 define( "OT_MSG" , 3 );
43 # string parameter for extractTags which will cause it
44 # to strip HTML comments in addition to regular
45 # <XML>-style tags. This should not be anything we
46 # may want to use in wikisyntax
47 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
49 # prefix for escaping, used in two functions at least
50 define( 'UNIQ_PREFIX', 'NaodW29');
52 # Constants needed for external link processing
53 define( 'URL_PROTOCOLS', 'http|https|ftp|irc|gopher|news|mailto' );
54 define( 'HTTP_PROTOCOLS', 'http|https' );
55 # Everything except bracket, space, or control characters
56 define( 'EXT_LINK_URL_CLASS', '[^]\\x00-\\x20\\x7F]' );
57 define( 'INVERSE_EXT_LINK_URL_CLASS', '[\]\\x00-\\x20\\x7F]' );
58 # Including space
59 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
60 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
61 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
62 define( 'EXT_LINK_BRACKETED', '/\[(('.URL_PROTOCOLS.'):'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
63 define( 'EXT_IMAGE_REGEX',
64 '/^('.HTTP_PROTOCOLS.':)'. # Protocol
65 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
66 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
69 class Parser
71 # Persistent:
72 var $mTagHooks;
74 # Cleared with clearState():
75 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
76 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
78 # Temporary:
79 var $mOptions, $mTitle, $mOutputType,
80 $mTemplates, // cache of already loaded templates, avoids
81 // multiple SQL queries for the same string
82 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
83 // in this path. Used for loop detection.
85 function Parser() {
86 $this->mTemplates = array();
87 $this->mTemplatePath = array();
88 $this->mTagHooks = array();
89 $this->clearState();
92 function clearState() {
93 $this->mOutput = new ParserOutput;
94 $this->mAutonumber = 0;
95 $this->mLastSection = "";
96 $this->mDTopen = false;
97 $this->mVariables = false;
98 $this->mIncludeCount = array();
99 $this->mStripState = array();
100 $this->mArgStack = array();
101 $this->mInPre = false;
104 # First pass--just handle <nowiki> sections, pass the rest off
105 # to internalParse() which does all the real work.
107 # Returns a ParserOutput
109 function parse( $text, &$title, $options, $linestart = true, $clearState = true ) {
110 global $wgUseTidy;
111 $fname = "Parser::parse";
112 wfProfileIn( $fname );
114 if ( $clearState ) {
115 $this->clearState();
118 $this->mOptions = $options;
119 $this->mTitle =& $title;
120 $this->mOutputType = OT_HTML;
122 $stripState = NULL;
123 $text = $this->strip( $text, $this->mStripState );
124 $text = $this->internalParse( $text, $linestart );
125 $text = $this->unstrip( $text, $this->mStripState );
126 # Clean up special characters, only run once, next-to-last before doBlockLevels
127 if(!$wgUseTidy) {
128 $fixtags = array(
129 # french spaces, last one Guillemet-left
130 # only if there is something before the space
131 '/(.) (?=\\?|:|;|!|\\302\\273)/i' => '\\1&nbsp;\\2',
132 # french spaces, Guillemet-right
133 "/(\\302\\253) /i"=>"\\1&nbsp;",
134 '/<hr *>/i' => '<hr />',
135 '/<br *>/i' => '<br />',
136 '/<center *>/i' => '<div class="center">',
137 '/<\\/center *>/i' => '</div>',
138 # Clean up spare ampersands; note that we probably ought to be
139 # more careful about named entities.
140 '/&(?!:amp;|#[Xx][0-9A-fa-f]+;|#[0-9]+;|[a-zA-Z0-9]+;)/' => '&amp;'
142 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
143 } else {
144 $fixtags = array(
145 # french spaces, last one Guillemet-left
146 '/ (\\?|:|;|!|\\302\\273)/i' => '&nbsp;\\1',
147 # french spaces, Guillemet-right
148 '/(\\302\\253) /i' => '\\1&nbsp;',
149 '/([^> ]+(&#x30(1|3|9);)[^< ]*)/i' => '<span class="diacrit">\\1</span>',
150 '/<center *>/i' => '<div class="center">',
151 '/<\\/center *>/i' => '</div>'
153 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
155 # only once and last
156 $text = $this->doBlockLevels( $text, $linestart );
157 $text = $this->unstripNoWiki( $text, $this->mStripState );
158 if($wgUseTidy) {
159 $text = $this->tidy($text);
161 $this->mOutput->setText( $text );
162 wfProfileOut( $fname );
163 return $this->mOutput;
166 /* static */ function getRandomString() {
167 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
170 # Replaces all occurrences of <$tag>content</$tag> in the text
171 # with a random marker and returns the new text. the output parameter
172 # $content will be an associative array filled with data on the form
173 # $unique_marker => content.
175 # If $content is already set, the additional entries will be appended
177 # If $tag is set to STRIP_COMMENTS, the function will extract
178 # <!-- HTML comments -->
180 /* static */ function extractTags($tag, $text, &$content, $uniq_prefix = ""){
181 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
182 if ( !$content ) {
183 $content = array( );
185 $n = 1;
186 $stripped = '';
188 while ( '' != $text ) {
189 if($tag==STRIP_COMMENTS) {
190 $p = preg_split( '/<!--/i', $text, 2 );
191 } else {
192 $p = preg_split( "/<\\s*$tag\\s*>/i", $text, 2 );
194 $stripped .= $p[0];
195 if ( ( count( $p ) < 2 ) || ( '' == $p[1] ) ) {
196 $text = '';
197 } else {
198 if($tag==STRIP_COMMENTS) {
199 $q = preg_split( '/-->/i', $p[1], 2 );
200 } else {
201 $q = preg_split( "/<\\/\\s*$tag\\s*>/i", $p[1], 2 );
203 $marker = $rnd . sprintf('%08X', $n++);
204 $content[$marker] = $q[0];
205 $stripped .= $marker;
206 $text = $q[1];
209 return $stripped;
212 # Strips and renders <nowiki>, <pre>, <math>, <hiero>
213 # If $render is set, performs necessary rendering operations on plugins
214 # Returns the text, and fills an array with data needed in unstrip()
215 # If the $state is already a valid strip state, it adds to the state
217 # When $stripcomments is set, HTML comments <!-- like this -->
218 # will be stripped in addition to other tags. This is important
219 # for section editing, where these comments cause confusion when
220 # counting the sections in the wikisource
221 function strip( $text, &$state, $stripcomments = false ) {
222 $render = ($this->mOutputType == OT_HTML);
223 $html_content = array();
224 $nowiki_content = array();
225 $math_content = array();
226 $pre_content = array();
227 $comment_content = array();
228 $ext_content = array();
230 # Replace any instances of the placeholders
231 $uniq_prefix = UNIQ_PREFIX;
232 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
234 # html
235 global $wgRawHtml;
236 if( $wgRawHtml ) {
237 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
238 foreach( $html_content as $marker => $content ) {
239 if ($render ) {
240 # Raw and unchecked for validity.
241 $html_content[$marker] = $content;
242 } else {
243 $html_content[$marker] = "<html>$content</html>";
248 # nowiki
249 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
250 foreach( $nowiki_content as $marker => $content ) {
251 if( $render ){
252 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
253 } else {
254 $nowiki_content[$marker] = "<nowiki>$content</nowiki>";
258 # math
259 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
260 foreach( $math_content as $marker => $content ){
261 if( $render ) {
262 if( $this->mOptions->getUseTeX() ) {
263 $math_content[$marker] = renderMath( $content );
264 } else {
265 $math_content[$marker] = "&lt;math&gt;$content&lt;math&gt;";
267 } else {
268 $math_content[$marker] = "<math>$content</math>";
272 # pre
273 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
274 foreach( $pre_content as $marker => $content ){
275 if( $render ){
276 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
277 } else {
278 $pre_content[$marker] = "<pre>$content</pre>";
282 # Comments
283 if($stripcomments) {
284 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
285 foreach( $comment_content as $marker => $content ){
286 $comment_content[$marker] = "<!--$content-->";
290 # Extensions
291 foreach ( $this->mTagHooks as $tag => $callback ) {
292 $ext_contents[$tag] = array();
293 $text = Parser::extractTags( $tag, $text, $ext_content[$tag], $uniq_prefix );
294 foreach( $ext_content[$tag] as $marker => $content ) {
295 if ( $render ) {
296 $ext_content[$tag][$marker] = $callback( $content );
297 } else {
298 $ext_content[$tag][$marker] = "<$tag>$content</$tag>";
303 # Merge state with the pre-existing state, if there is one
304 if ( $state ) {
305 $state['html'] = $state['html'] + $html_content;
306 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
307 $state['math'] = $state['math'] + $math_content;
308 $state['pre'] = $state['pre'] + $pre_content;
309 $state['comment'] = $state['comment'] + $comment_content;
311 foreach( $ext_content as $tag => $array ) {
312 if ( array_key_exists( $tag, $state ) ) {
313 $state[$tag] = $state[$tag] + $array;
316 } else {
317 $state = array(
318 'html' => $html_content,
319 'nowiki' => $nowiki_content,
320 'math' => $math_content,
321 'pre' => $pre_content,
322 'comment' => $comment_content,
323 ) + $ext_content;
325 return $text;
328 # always call unstripNoWiki() after this one
329 function unstrip( $text, &$state ) {
330 # Must expand in reverse order, otherwise nested tags will be corrupted
331 $contentDict = end( $state );
332 for ( $contentDict = end( $state ); $contentDict !== false; $contentDict = prev( $state ) ) {
333 if( key($state) != 'nowiki' && key($state) != 'html') {
334 for ( $content = end( $contentDict ); $content !== false; $content = prev( $contentDict ) ) {
335 $text = str_replace( key( $contentDict ), $content, $text );
340 return $text;
342 # always call this after unstrip() to preserve the order
343 function unstripNoWiki( $text, &$state ) {
344 # Must expand in reverse order, otherwise nested tags will be corrupted
345 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
346 $text = str_replace( key( $state['nowiki'] ), $content, $text );
349 global $wgRawHtml;
350 if ($wgRawHtml) {
351 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
352 $text = str_replace( key( $state['html'] ), $content, $text );
356 return $text;
359 # Add an item to the strip state
360 # Returns the unique tag which must be inserted into the stripped text
361 # The tag will be replaced with the original text in unstrip()
362 function insertStripItem( $text, &$state ) {
363 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
364 if ( !$state ) {
365 $state = array(
366 'html' => array(),
367 'nowiki' => array(),
368 'math' => array(),
369 'pre' => array()
372 $state['item'][$rnd] = $text;
373 return $rnd;
376 # categoryMagic
377 # generate a list of subcategories and pages for a category
378 # depending on wfMsg("usenewcategorypage") it either calls the new
379 # or the old code. The new code will not work properly for some
380 # languages due to sorting issues, so they might want to turn it
381 # off.
382 function categoryMagic() {
383 $msg = wfMsg('usenewcategorypage');
384 if ( '0' == @$msg[0] )
386 return $this->oldCategoryMagic();
387 } else {
388 return $this->newCategoryMagic();
392 # This method generates the list of subcategories and pages for a category
393 function oldCategoryMagic () {
394 global $wgLang ;
395 $fname = 'Parser::oldCategoryMagic';
397 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
399 if ( $this->mTitle->getNamespace() != NS_CATEGORY ) return "" ; # This ain't a category page
401 $r = "<br style=\"clear:both;\"/>\n";
404 $sk =& $this->mOptions->getSkin() ;
406 $articles = array() ;
407 $children = array() ;
408 $data = array () ;
409 $id = $this->mTitle->getArticleID() ;
411 # FIXME: add limits
412 $dbr =& wfGetDB( DB_SLAVE );
413 $cur = $dbr->tableName( 'cur' );
414 $categorylinks = $dbr->tableName( 'categorylinks' );
416 $t = $dbr->strencode( $this->mTitle->getDBKey() );
417 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM $cur,$categorylinks " .
418 "WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
419 $res = $dbr->query( $sql, $fname ) ;
420 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
422 # For all pages that link to this category
423 foreach ( $data AS $x )
425 $t = $wgLang->getNsText ( $x->cur_namespace ) ;
426 if ( $t != '' ) $t .= ':' ;
427 $t .= $x->cur_title ;
429 if ( $x->cur_namespace == NS_CATEGORY ) {
430 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
431 } else {
432 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
435 $dbr->freeResult ( $res ) ;
437 # Showing subcategories
438 if ( count ( $children ) > 0 ) {
439 $r .= '<h2>'.wfMsg('subcategories')."</h2>\n" ;
440 $r .= implode ( ', ' , $children ) ;
443 # Showing pages in this category
444 if ( count ( $articles ) > 0 ) {
445 $ti = $this->mTitle->getText() ;
446 $h = wfMsg( 'category_header', $ti );
447 $r .= "<h2>$h</h2>\n" ;
448 $r .= implode ( ', ' , $articles ) ;
451 return $r ;
454 function newCategoryMagic () {
455 global $wgLang;
456 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
458 if ( $this->mTitle->getNamespace() != NS_CATEGORY ) return '' ; # This ain't a category page
460 $r = "<br style=\"clear:both;\"/>\n";
463 $sk =& $this->mOptions->getSkin() ;
465 $articles = array() ;
466 $articles_start_char = array();
467 $children = array() ;
468 $children_start_char = array();
469 $data = array () ;
470 $id = $this->mTitle->getArticleID() ;
472 # FIXME: add limits
473 $dbr =& wfGetDB( DB_SLAVE );
474 $cur = $dbr->tableName( 'cur' );
475 $categorylinks = $dbr->tableName( 'categorylinks' );
477 $t = $dbr->strencode( $this->mTitle->getDBKey() );
478 $sql = "SELECT DISTINCT cur_title,cur_namespace,cl_sortkey FROM " .
479 "$cur,$categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
480 $res = $dbr->query ( $sql ) ;
481 while ( $x = $dbr->fetchObject ( $res ) )
483 $t = $ns = $wgLang->getNsText ( $x->cur_namespace ) ;
484 if ( $t != '' ) $t .= ':' ;
485 $t .= $x->cur_title ;
487 if ( $x->cur_namespace == NS_CATEGORY ) {
488 $ctitle = str_replace( '_',' ',$x->cur_title );
489 array_push ( $children, $sk->makeKnownLink ( $t, $ctitle ) ) ; # Subcategory
491 // If there's a link from Category:A to Category:B, the sortkey of the resulting
492 // entry in the categorylinks table is Category:A, not A, which it SHOULD be.
493 // Workaround: If sortkey == "Category:".$title, than use $title for sorting,
494 // else use sortkey...
495 if ( ($ns.':'.$ctitle) == $x->cl_sortkey ) {
496 array_push ( $children_start_char, $wgLang->firstChar( $x->cur_title ) );
497 } else {
498 array_push ( $children_start_char, $wgLang->firstChar( $x->cl_sortkey ) ) ;
500 } else {
501 array_push ( $articles , $sk->makeKnownLink ( $t ) ) ; # Page in this category
502 array_push ( $articles_start_char, $wgLang->firstChar( $x->cl_sortkey ) ) ;
505 $dbr->freeResult ( $res ) ;
507 $ti = $this->mTitle->getText() ;
509 # Don't show subcategories section if there are none.
510 if ( count ( $children ) > 0 )
512 # Showing subcategories
513 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
515 $numchild = count( $children );
516 if($numchild == 1) {
517 $r .= wfMsg( 'subcategorycount1', 1 );
518 } else {
519 $r .= wfMsg( 'subcategorycount' , $numchild );
521 unset($numchild);
523 if ( count ( $children ) > 6 ) {
525 // divide list into three equal chunks
526 $chunk = (int) (count ( $children ) / 3);
528 // get and display header
529 $r .= '<table width="100%"><tr valign="top">';
531 $startChunk = 0;
532 $endChunk = $chunk;
534 // loop through the chunks
535 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
536 $chunkIndex < 3;
537 $chunkIndex++, $startChunk = $endChunk, $endChunk += $chunk + 1)
540 $r .= '<td><ul>';
541 // output all subcategories to category
542 for ($index = $startChunk ;
543 $index < $endChunk && $index < count($children);
544 $index++ )
546 // check for change of starting letter or begging of chunk
547 if ( ($children_start_char[$index] != $children_start_char[$index - 1])
548 || ($index == $startChunk) )
550 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
553 $r .= "<li>{$children[$index]}</li>";
555 $r .= '</ul></td>';
559 $r .= '</tr></table>';
560 } else {
561 // for short lists of subcategories to category.
563 $r .= "<h3>{$children_start_char[0]}</h3>\n";
564 $r .= '<ul><li>'.$children[0].'</li>';
565 for ($index = 1; $index < count($children); $index++ )
567 if ($children_start_char[$index] != $children_start_char[$index - 1])
569 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
572 $r .= "<li>{$children[$index]}</li>";
574 $r .= '</ul>';
576 } # END of if ( count($children) > 0 )
578 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
580 $numart = count( $articles );
581 if($numart == 1) {
582 $r .= wfMsg( 'categoryarticlecount1', 1 );
583 } else {
584 $r .= wfMsg( 'categoryarticlecount' , $numart );
586 unset($numart);
588 # Showing articles in this category
589 if ( count ( $articles ) > 6) {
590 $ti = $this->mTitle->getText() ;
592 // divide list into three equal chunks
593 $chunk = (int) (count ( $articles ) / 3);
595 // get and display header
596 $r .= '<table width="100%"><tr valign="top">';
598 // loop through the chunks
599 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
600 $chunkIndex < 3;
601 $chunkIndex++, $startChunk = $endChunk, $endChunk += $chunk + 1)
604 $r .= '<td><ul>';
606 // output all articles in category
607 for ($index = $startChunk ;
608 $index < $endChunk && $index < count($articles);
609 $index++ )
611 // check for change of starting letter or begging of chunk
612 if ( ($index == $startChunk) ||
613 ($articles_start_char[$index] != $articles_start_char[$index - 1]) )
616 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
619 $r .= "<li>{$articles[$index]}</li>";
621 $r .= '</ul></td>';
625 $r .= '</tr></table>';
626 } elseif ( count($articles) > 0) {
627 // for short lists of articles in categories.
628 $ti = $this->mTitle->getText() ;
630 $r .= '<h3>'.$articles_start_char[0]."</h3>\n";
631 $r .= '<ul><li>'.$articles[0].'</li>';
632 for ($index = 1; $index < count($articles); $index++ )
634 if ($articles_start_char[$index] != $articles_start_char[$index - 1])
636 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
639 $r .= "<li>{$articles[$index]}</li>";
641 $r .= '</ul>';
645 return $r ;
648 # Return allowed HTML attributes
649 function getHTMLattrs () {
650 $htmlattrs = array( # Allowed attributes--no scripting, etc.
651 'title', 'align', 'lang', 'dir', 'width', 'height',
652 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
653 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
654 /* FONT */ 'type', 'start', 'value', 'compact',
655 /* For various lists, mostly deprecated but safe */
656 'summary', 'width', 'border', 'frame', 'rules',
657 'cellspacing', 'cellpadding', 'valign', 'char',
658 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
659 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
660 'id', 'class', 'name', 'style' /* For CSS */
662 return $htmlattrs ;
665 # Remove non approved attributes and javascript in css
666 function fixTagAttributes ( $t ) {
667 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
668 $htmlattrs = $this->getHTMLattrs() ;
670 # Strip non-approved attributes from the tag
671 $t = preg_replace(
672 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
673 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
674 $t);
676 $t = str_replace ( "<></>" , "" , $t ) ; # This should fix bug 980557
678 # Strip javascript "expression" from stylesheets. Brute force approach:
679 # If anythin offensive is found, all attributes of the HTML tag are dropped
681 if( preg_match(
682 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
683 wfMungeToUtf8( $t ) ) )
685 $t='';
688 return trim ( $t ) ;
691 # interface with html tidy, used if $wgUseTidy = true
692 function tidy ( $text ) {
693 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
694 global $wgInputEncoding, $wgOutputEncoding;
695 $fname = 'Parser::tidy';
696 wfProfileIn( $fname );
698 $cleansource = '';
699 switch(strtoupper($wgOutputEncoding)) {
700 case 'ISO-8859-1':
701 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -latin1':' -raw';
702 break;
703 case 'UTF-8':
704 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -utf8':' -raw';
705 break;
706 default:
707 $wgTidyOpts .= ' -raw';
710 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
711 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
712 '<head><title>test</title></head><body>'.$text.'</body></html>';
713 $descriptorspec = array(
714 0 => array('pipe', 'r'),
715 1 => array('pipe', 'w'),
716 2 => array('file', '/dev/null', 'a')
718 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
719 if (is_resource($process)) {
720 fwrite($pipes[0], $wrappedtext);
721 fclose($pipes[0]);
722 while (!feof($pipes[1])) {
723 $cleansource .= fgets($pipes[1], 1024);
725 fclose($pipes[1]);
726 $return_value = proc_close($process);
729 wfProfileOut( $fname );
731 if( $cleansource == '' && $text != '') {
732 wfDebug( "Tidy error detected!\n" );
733 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
734 } else {
735 return $cleansource;
739 # parse the wiki syntax used to render tables
740 function doTableStuff ( $t ) {
741 $fname = 'Parser::doTableStuff';
742 wfProfileIn( $fname );
744 $t = explode ( "\n" , $t ) ;
745 $td = array () ; # Is currently a td tag open?
746 $ltd = array () ; # Was it TD or TH?
747 $tr = array () ; # Is currently a tr tag open?
748 $ltr = array () ; # tr attributes
749 $indent_level = 0; # indent level of the table
750 foreach ( $t AS $k => $x )
752 $x = trim ( $x ) ;
753 $fc = substr ( $x , 0 , 1 ) ;
754 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
755 $indent_level = strlen( $matches[1] );
756 $t[$k] = "\n" .
757 str_repeat( "<dl><dd>", $indent_level ) .
758 "<table " . $this->fixTagAttributes ( $matches[2] ) . '>' ;
759 array_push ( $td , false ) ;
760 array_push ( $ltd , '' ) ;
761 array_push ( $tr , false ) ;
762 array_push ( $ltr , '' ) ;
764 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
765 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
766 $z = "</table>\n" ;
767 $l = array_pop ( $ltd ) ;
768 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
769 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
770 array_pop ( $ltr ) ;
771 $t[$k] = $z . str_repeat( "</dd></dl>", $indent_level );
773 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
774 $x = substr ( $x , 1 ) ;
775 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
776 $z = '' ;
777 $l = array_pop ( $ltd ) ;
778 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
779 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
780 array_pop ( $ltr ) ;
781 $t[$k] = $z ;
782 array_push ( $tr , false ) ;
783 array_push ( $td , false ) ;
784 array_push ( $ltd , '' ) ;
785 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
787 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
788 if ( '|+' == substr ( $x , 0 , 2 ) ) {
789 $fc = '+' ;
790 $x = substr ( $x , 1 ) ;
792 $after = substr ( $x , 1 ) ;
793 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
794 $after = explode ( '||' , $after ) ;
795 $t[$k] = '' ;
796 foreach ( $after AS $theline )
798 $z = '' ;
799 if ( $fc != '+' )
801 $tra = array_pop ( $ltr ) ;
802 if ( !array_pop ( $tr ) ) $z = '<tr '.$tra.">\n" ;
803 array_push ( $tr , true ) ;
804 array_push ( $ltr , '' ) ;
807 $l = array_pop ( $ltd ) ;
808 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
809 if ( $fc == '|' ) $l = 'td' ;
810 else if ( $fc == '!' ) $l = 'th' ;
811 else if ( $fc == '+' ) $l = 'caption' ;
812 else $l = '' ;
813 array_push ( $ltd , $l ) ;
814 $y = explode ( '|' , $theline , 2 ) ;
815 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
816 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
817 $t[$k] .= $y ;
818 array_push ( $td , true ) ;
823 # Closing open td, tr && table
824 while ( count ( $td ) > 0 )
826 if ( array_pop ( $td ) ) $t[] = '</td>' ;
827 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
828 $t[] = '</table>' ;
831 $t = implode ( "\n" , $t ) ;
832 # $t = $this->removeHTMLtags( $t );
833 wfProfileOut( $fname );
834 return $t ;
837 # Parses the text and adds the result to the strip state
838 # Returns the strip tag
839 function stripParse( $text, $newline, $args ) {
840 $text = $this->strip( $text, $this->mStripState );
841 $text = $this->internalParse( $text, (bool)$newline, $args, false );
842 return $newline.$this->insertStripItem( $text, $this->mStripState );
845 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
846 $fname = 'Parser::internalParse';
847 wfProfileIn( $fname );
849 $text = $this->removeHTMLtags( $text );
850 $text = $this->replaceVariables( $text, $args );
852 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
854 $text = $this->doHeadings( $text );
855 if($this->mOptions->getUseDynamicDates()) {
856 global $wgDateFormatter;
857 $text = $wgDateFormatter->reformat( $this->mOptions->getDateFormat(), $text );
859 $text = $this->doAllQuotes( $text );
860 $text = $this->replaceExternalLinks( $text );
861 $text = $this->doMagicLinks( $text );
862 $text = $this->replaceInternalLinks ( $text );
863 $text = $this->replaceInternalLinks ( $text );
865 $text = $this->unstrip( $text, $this->mStripState );
866 $text = $this->unstripNoWiki( $text, $this->mStripState );
868 $text = $this->doTableStuff( $text );
869 $text = $this->formatHeadings( $text, $isMain );
870 $sk =& $this->mOptions->getSkin();
871 $text = $sk->transformContent( $text );
873 if ( $isMain && !isset ( $this->categoryMagicDone ) ) {
874 $text .= $this->categoryMagic () ;
875 $this->categoryMagicDone = true ;
878 wfProfileOut( $fname );
879 return $text;
882 /* private */ function &doMagicLinks( &$text ) {
883 global $wgUseGeoMode;
884 $text = $this->magicISBN( $text );
885 if ( isset( $wgUseGeoMode ) && $wgUseGeoMode ) {
886 $text = $this->magicGEO( $text );
888 $text = $this->magicRFC( $text );
889 return $text;
892 # Parse ^^ tokens and return html
893 /* private */ function doExponent ( $text ) {
894 $fname = 'Parser::doExponent';
895 wfProfileIn( $fname);
896 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
897 wfProfileOut( $fname);
898 return $text;
901 # Parse headers and return html
902 /* private */ function doHeadings( $text ) {
903 $fname = 'Parser::doHeadings';
904 wfProfileIn( $fname );
905 for ( $i = 6; $i >= 1; --$i ) {
906 $h = substr( '======', 0, $i );
907 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
908 "<h{$i}>\\1</h{$i}>\\2", $text );
910 wfProfileOut( $fname );
911 return $text;
914 /* private */ function doAllQuotes( $text ) {
915 $fname = 'Parser::doAllQuotes';
916 wfProfileIn( $fname );
917 $outtext = '';
918 $lines = explode( "\n", $text );
919 foreach ( $lines as $line ) {
920 $outtext .= $this->doQuotes ( $line ) . "\n";
922 $outtext = substr($outtext, 0,-1);
923 wfProfileOut( $fname );
924 return $outtext;
927 /* private */ function doQuotes( $text ) {
928 $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
929 if (count ($arr) == 1)
930 return $text;
931 else
933 # First, do some preliminary work. This may shift some apostrophes from
934 # being mark-up to being text. It also counts the number of occurrences
935 # of bold and italics mark-ups.
936 $i = 0;
937 $numbold = 0;
938 $numitalics = 0;
939 foreach ($arr as $r)
941 if (($i % 2) == 1)
943 # If there are ever four apostrophes, assume the first is supposed to
944 # be text, and the remaining three constitute mark-up for bold text.
945 if (strlen ($arr[$i]) == 4)
947 $arr[$i-1] .= "'";
948 $arr[$i] = "'''";
950 # If there are more than 5 apostrophes in a row, assume they're all
951 # text except for the last 5.
952 else if (strlen ($arr[$i]) > 5)
954 $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
955 $arr[$i] = "'''''";
957 # Count the number of occurrences of bold and italics mark-ups.
958 # We are not counting sequences of five apostrophes.
959 if (strlen ($arr[$i]) == 2) $numitalics++; else
960 if (strlen ($arr[$i]) == 3) $numbold++; else
961 if (strlen ($arr[$i]) == 5) { $numitalics++; $numbold++; }
963 $i++;
966 # If there is an odd number of both bold and italics, it is likely
967 # that one of the bold ones was meant to be an apostrophe followed
968 # by italics. Which one we cannot know for certain, but it is more
969 # likely to be one that has a single-letter word before it.
970 if (($numbold % 2 == 1) && ($numitalics % 2 == 1))
972 $i = 0;
973 $firstsingleletterword = -1;
974 $firstmultiletterword = -1;
975 $firstspace = -1;
976 foreach ($arr as $r)
978 if (($i % 2 == 1) and (strlen ($r) == 3))
980 $x1 = substr ($arr[$i-1], -1);
981 $x2 = substr ($arr[$i-1], -2, 1);
982 if ($x1 == " ") {
983 if ($firstspace == -1) $firstspace = $i;
984 } else if ($x2 == " ") {
985 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
986 } else {
987 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
990 $i++;
993 # If there is a single-letter word, use it!
994 if ($firstsingleletterword > -1)
996 $arr [ $firstsingleletterword ] = "''";
997 $arr [ $firstsingleletterword-1 ] .= "'";
999 # If not, but there's a multi-letter word, use that one.
1000 else if ($firstmultiletterword > -1)
1002 $arr [ $firstmultiletterword ] = "''";
1003 $arr [ $firstmultiletterword-1 ] .= "'";
1005 # ... otherwise use the first one that has neither.
1006 # (notice that it is possible for all three to be -1 if, for example,
1007 # there is only one pentuple-apostrophe in the line)
1008 else if ($firstspace > -1)
1010 $arr [ $firstspace ] = "''";
1011 $arr [ $firstspace-1 ] .= "'";
1015 # Now let's actually convert our apostrophic mush to HTML!
1016 $output = '';
1017 $buffer = '';
1018 $state = '';
1019 $i = 0;
1020 foreach ($arr as $r)
1022 if (($i % 2) == 0)
1024 if ($state == 'both')
1025 $buffer .= $r;
1026 else
1027 $output .= $r;
1029 else
1031 if (strlen ($r) == 2)
1033 if ($state == 'em')
1034 { $output .= "</em>"; $state = ''; }
1035 else if ($state == 'strongem')
1036 { $output .= "</em>"; $state = 'strong'; }
1037 else if ($state == 'emstrong')
1038 { $output .= "</strong></em><strong>"; $state = 'strong'; }
1039 else if ($state == 'both')
1040 { $output .= "<strong><em>{$buffer}</em>"; $state = 'strong'; }
1041 else # $state can be 'strong' or ''
1042 { $output .= "<em>"; $state .= 'em'; }
1044 else if (strlen ($r) == 3)
1046 if ($state == 'strong')
1047 { $output .= "</strong>"; $state = ''; }
1048 else if ($state == 'strongem')
1049 { $output .= "</em></strong><em>"; $state = 'em'; }
1050 else if ($state == 'emstrong')
1051 { $output .= "</strong>"; $state = 'em'; }
1052 else if ($state == 'both')
1053 { $output .= "<em><strong>{$buffer}</strong>"; $state = 'em'; }
1054 else # $state can be 'em' or ''
1055 { $output .= "<strong>"; $state .= 'strong'; }
1057 else if (strlen ($r) == 5)
1059 if ($state == 'strong')
1060 { $output .= "</strong><em>"; $state = 'em'; }
1061 else if ($state == 'em')
1062 { $output .= "</em><strong>"; $state = 'strong'; }
1063 else if ($state == 'strongem')
1064 { $output .= "</em></strong>"; $state = ''; }
1065 else if ($state == 'emstrong')
1066 { $output .= "</strong></em>"; $state = ''; }
1067 else if ($state == 'both')
1068 { $output .= "<em><strong>{$buffer}</strong></em>"; $state = ''; }
1069 else # ($state == '')
1070 { $buffer = ''; $state = 'both'; }
1073 $i++;
1075 # Now close all remaining tags. Notice that the order is important.
1076 if ($state == 'strong' || $state == 'emstrong')
1077 $output .= '</strong>';
1078 if ($state == 'em' || $state == 'strongem' || $state == 'emstrong')
1079 $output .= '</em>';
1080 if ($state == 'strongem')
1081 $output .= '</strong>';
1082 if ($state == 'both')
1083 $output .= "<strong><em>{$buffer}</em></strong>";
1084 return $output;
1088 # Note: we have to do external links before the internal ones,
1089 # and otherwise take great care in the order of things here, so
1090 # that we don't end up interpreting some URLs twice.
1092 /* private */ function replaceExternalLinks( $text ) {
1093 $fname = 'Parser::replaceExternalLinks';
1094 wfProfileIn( $fname );
1096 $sk =& $this->mOptions->getSkin();
1097 $linktrail = wfMsg('linktrail');
1098 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1100 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1102 $i = 0;
1103 while ( $i<count( $bits ) ) {
1104 $url = $bits[$i++];
1105 $protocol = $bits[$i++];
1106 $text = $bits[$i++];
1107 $trail = $bits[$i++];
1109 # If the link text is an image URL, replace it with an <img> tag
1110 # This happened by accident in the original parser, but some people used it extensively
1111 $img = $this->maybeMakeImageLink( $text );
1112 if ( $img !== false ) {
1113 $text = $img;
1116 $dtrail = '';
1118 # No link text, e.g. [http://domain.tld/some.link]
1119 if ( $text == '' ) {
1120 # Autonumber if allowed
1121 if ( strpos( HTTP_PROTOCOLS, $protocol ) !== false ) {
1122 $text = "[" . ++$this->mAutonumber . "]";
1123 } else {
1124 # Otherwise just use the URL
1125 $text = htmlspecialchars( $url );
1127 } else {
1128 # Have link text, e.g. [http://domain.tld/some.link text]s
1129 # Check for trail
1130 if ( preg_match( $linktrail, $trail, $m2 ) ) {
1131 $dtrail = $m2[1];
1132 $trail = $m2[2];
1136 $encUrl = htmlspecialchars( $url );
1137 # Bit in parentheses showing the URL for the printable version
1138 if( $url == $text || preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $url ) ) {
1139 $paren = '';
1140 } else {
1141 # Expand the URL for printable version
1142 if ( ! $sk->suppressUrlExpansion() ) {
1143 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
1144 } else {
1145 $paren = '';
1149 # Process the trail (i.e. everything after this link up until start of the next link),
1150 # replacing any non-bracketed links
1151 $trail = $this->replaceFreeExternalLinks( $trail );
1153 $la = $sk->getExternalLinkAttributes( $url, $text );
1155 # Use the encoded URL
1156 # This means that users can paste URLs directly into the text
1157 # Funny characters like &ouml; aren't valid in URLs anyway
1158 # This was changed in August 2004
1159 $s .= "<a href=\"{$url}\" {$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
1162 wfProfileOut( $fname );
1163 return $s;
1166 # Replace anything that looks like a URL with a link
1167 function replaceFreeExternalLinks( $text ) {
1168 $bits = preg_split( '/((?:'.URL_PROTOCOLS.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1169 $s = array_shift( $bits );
1170 $i = 0;
1172 $sk =& $this->mOptions->getSkin();
1174 while ( $i < count( $bits ) ){
1175 $protocol = $bits[$i++];
1176 $remainder = $bits[$i++];
1178 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1179 # Found some characters after the protocol that look promising
1180 $url = $protocol . $m[1];
1181 $trail = $m[2];
1183 # Move trailing punctuation to $trail
1184 $sep = ',;\.:!?';
1185 # If there is no left bracket, then consider right brackets fair game too
1186 if ( strpos( $url, '(' ) === false ) {
1187 $sep .= ')';
1190 $numSepChars = strspn( strrev( $url ), $sep );
1191 if ( $numSepChars ) {
1192 $trail = substr( $url, -$numSepChars ) . $trail;
1193 $url = substr( $url, 0, -$numSepChars );
1196 # Replace &amp; from obsolete syntax with &
1197 $url = str_replace( '&amp;', '&', $url );
1199 # Is this an external image?
1200 $text = $this->maybeMakeImageLink( $url );
1201 if ( $text === false ) {
1202 # Not an image, make a link
1203 $text = $sk->makeExternalLink( $url, $url );
1205 $s .= $text . $trail;
1206 } else {
1207 $s .= $protocol . $remainder;
1210 return $s;
1213 # make an image if it's allowed
1214 function maybeMakeImageLink( $url ) {
1215 $sk =& $this->mOptions->getSkin();
1216 $text = false;
1217 if ( $this->mOptions->getAllowExternalImages() ) {
1218 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1219 # Image found
1220 $text = $sk->makeImage( htmlspecialchars( $url ) );
1223 return $text;
1226 # The wikilinks [[ ]] are procedeed here.
1227 /* private */ function replaceInternalLinks( $s ) {
1228 global $wgLang, $wgLinkCache;
1229 global $wgNamespacesWithSubpages, $wgLanguageCode;
1230 static $fname = 'Parser::replaceInternalLinks' ;
1231 wfProfileIn( $fname );
1233 wfProfileIn( $fname.'-setup' );
1234 static $tc = FALSE;
1235 # the % is needed to support urlencoded titles as well
1236 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1237 $sk =& $this->mOptions->getSkin();
1239 $redirect = MagicWord::get ( MAG_REDIRECT ) ;
1241 $a = explode( '[[', ' ' . $s );
1242 $s = array_shift( $a );
1243 $s = substr( $s, 1 );
1245 # Match a link having the form [[namespace:link|alternate]]trail
1246 static $e1 = FALSE;
1247 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1248 # Match the end of a line for a word that's not followed by whitespace,
1249 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1250 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1252 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
1253 # Special and Media are pseudo-namespaces; no pages actually exist in them
1255 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
1257 if ( $useLinkPrefixExtension ) {
1258 if ( preg_match( $e2, $s, $m ) ) {
1259 $first_prefix = $m[2];
1260 $s = $m[1];
1261 } else {
1262 $first_prefix = false;
1264 } else {
1265 $prefix = '';
1268 wfProfileOut( $fname.'-setup' );
1270 # start procedeeding each line
1271 foreach ( $a as $line ) {
1272 wfProfileIn( $fname.'-prefixhandling' );
1273 if ( $useLinkPrefixExtension ) {
1274 if ( preg_match( $e2, $s, $m ) ) {
1275 $prefix = $m[2];
1276 $s = $m[1];
1277 } else {
1278 $prefix='';
1280 # first link
1281 if($first_prefix) {
1282 $prefix = $first_prefix;
1283 $first_prefix = false;
1286 wfProfileOut( $fname.'-prefixhandling' );
1288 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1289 $text = $m[2];
1290 # fix up urlencoded title texts
1291 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1292 $trail = $m[3];
1293 } else { # Invalid form; output directly
1294 $s .= $prefix . '[[' . $line ;
1295 continue;
1298 # Valid link forms:
1299 # Foobar -- normal
1300 # :Foobar -- override special treatment of prefix (images, language links)
1301 # /Foobar -- convert to CurrentPage/Foobar
1302 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1304 # Look at the first character
1305 $c = substr($m[1],0,1);
1306 $noforce = ($c != ':');
1308 # subpage
1309 if( $c == '/' ) {
1310 # / at end means we don't want the slash to be shown
1311 if(substr($m[1],-1,1)=='/') {
1312 $m[1]=substr($m[1],1,strlen($m[1])-2);
1313 $noslash=$m[1];
1314 } else {
1315 $noslash=substr($m[1],1);
1318 # Some namespaces don't allow subpages
1319 if(!empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()])) {
1320 # subpages allowed here
1321 $link = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1322 if( '' == $text ) {
1323 $text= $m[1];
1324 } # this might be changed for ugliness reasons
1325 } else {
1326 # no subpage allowed, use standard link
1327 $link = $noslash;
1330 } elseif( $noforce ) { # no subpage
1331 $link = $m[1];
1332 } else {
1333 # We don't want to keep the first character
1334 $link = substr( $m[1], 1 );
1337 $wasblank = ( '' == $text );
1338 if( $wasblank ) $text = $link;
1340 $nt = Title::newFromText( $link );
1341 if( !$nt ) {
1342 $s .= $prefix . '[[' . $line;
1343 continue;
1346 $ns = $nt->getNamespace();
1347 $iw = $nt->getInterWiki();
1349 # Link not escaped by : , create the various objects
1350 if( $noforce ) {
1352 # Interwikis
1353 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1354 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1355 $tmp = $prefix . $trail ;
1356 $s .= (trim($tmp) == '')? '': $tmp;
1357 continue;
1360 if ( $ns == NS_IMAGE ) {
1361 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1362 $wgLinkCache->addImageLinkObj( $nt );
1363 continue;
1366 if ( $ns == NS_CATEGORY ) {
1367 $t = $nt->getText() ;
1368 $nnt = Title::newFromText ( Namespace::getCanonicalName(NS_CATEGORY).":".$t ) ;
1370 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1371 $pPLC=$sk->postParseLinkColour();
1372 $sk->postParseLinkColour( false );
1373 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1374 $sk->postParseLinkColour( $pPLC );
1375 $wgLinkCache->resume();
1377 $sortkey = $wasblank ? $this->mTitle->getPrefixedText() : $text;
1378 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1379 $this->mOutput->mCategoryLinks[] = $t ;
1380 $s .= $prefix . $trail ;
1381 continue;
1385 if( ( $nt->getPrefixedText() == $this->mTitle->getPrefixedText() ) &&
1386 ( strpos( $link, '#' ) == FALSE ) ) {
1387 # Self-links are handled specially; generally de-link and change to bold.
1388 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1389 continue;
1392 if( $ns == NS_MEDIA ) {
1393 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1394 $wgLinkCache->addImageLinkObj( $nt );
1395 continue;
1396 } elseif( $ns == NS_SPECIAL ) {
1397 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1398 continue;
1400 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1402 wfProfileOut( $fname );
1403 return $s;
1406 # Some functions here used by doBlockLevels()
1408 /* private */ function closeParagraph() {
1409 $result = '';
1410 if ( '' != $this->mLastSection ) {
1411 $result = '</' . $this->mLastSection . ">\n";
1413 $this->mInPre = false;
1414 $this->mLastSection = '';
1415 return $result;
1417 # getCommon() returns the length of the longest common substring
1418 # of both arguments, starting at the beginning of both.
1420 /* private */ function getCommon( $st1, $st2 ) {
1421 $fl = strlen( $st1 );
1422 $shorter = strlen( $st2 );
1423 if ( $fl < $shorter ) { $shorter = $fl; }
1425 for ( $i = 0; $i < $shorter; ++$i ) {
1426 if ( $st1{$i} != $st2{$i} ) { break; }
1428 return $i;
1430 # These next three functions open, continue, and close the list
1431 # element appropriate to the prefix character passed into them.
1433 /* private */ function openList( $char ) {
1434 $result = $this->closeParagraph();
1436 if ( '*' == $char ) { $result .= '<ul><li>'; }
1437 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1438 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1439 else if ( ';' == $char ) {
1440 $result .= '<dl><dt>';
1441 $this->mDTopen = true;
1443 else { $result = '<!-- ERR 1 -->'; }
1445 return $result;
1448 /* private */ function nextItem( $char ) {
1449 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1450 else if ( ':' == $char || ';' == $char ) {
1451 $close = '</dd>';
1452 if ( $this->mDTopen ) { $close = '</dt>'; }
1453 if ( ';' == $char ) {
1454 $this->mDTopen = true;
1455 return $close . '<dt>';
1456 } else {
1457 $this->mDTopen = false;
1458 return $close . '<dd>';
1461 return '<!-- ERR 2 -->';
1464 /* private */ function closeList( $char ) {
1465 if ( '*' == $char ) { $text = '</li></ul>'; }
1466 else if ( '#' == $char ) { $text = '</li></ol>'; }
1467 else if ( ':' == $char ) {
1468 if ( $this->mDTopen ) {
1469 $this->mDTopen = false;
1470 $text = '</dt></dl>';
1471 } else {
1472 $text = '</dd></dl>';
1475 else { return '<!-- ERR 3 -->'; }
1476 return $text."\n";
1479 /* private */ function doBlockLevels( $text, $linestart ) {
1480 $fname = 'Parser::doBlockLevels';
1481 wfProfileIn( $fname );
1483 # Parsing through the text line by line. The main thing
1484 # happening here is handling of block-level elements p, pre,
1485 # and making lists from lines starting with * # : etc.
1487 $textLines = explode( "\n", $text );
1489 $lastPrefix = $output = $lastLine = '';
1490 $this->mDTopen = $inBlockElem = false;
1491 $prefixLength = 0;
1492 $paragraphStack = false;
1494 if ( !$linestart ) {
1495 $output .= array_shift( $textLines );
1497 foreach ( $textLines as $oLine ) {
1498 $lastPrefixLength = strlen( $lastPrefix );
1499 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1500 $preOpenMatch = preg_match('/<pre/i', $oLine );
1501 if ( !$this->mInPre ) {
1502 # Multiple prefixes may abut each other for nested lists.
1503 $prefixLength = strspn( $oLine, '*#:;' );
1504 $pref = substr( $oLine, 0, $prefixLength );
1506 # eh?
1507 $pref2 = str_replace( ';', ':', $pref );
1508 $t = substr( $oLine, $prefixLength );
1509 $this->mInPre = !empty($preOpenMatch);
1510 } else {
1511 # Don't interpret any other prefixes in preformatted text
1512 $prefixLength = 0;
1513 $pref = $pref2 = '';
1514 $t = $oLine;
1517 # List generation
1518 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1519 # Same as the last item, so no need to deal with nesting or opening stuff
1520 $output .= $this->nextItem( substr( $pref, -1 ) );
1521 $paragraphStack = false;
1523 if ( substr( $pref, -1 ) == ';') {
1524 # The one nasty exception: definition lists work like this:
1525 # ; title : definition text
1526 # So we check for : in the remainder text to split up the
1527 # title and definition, without b0rking links.
1528 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1529 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1530 $term = $match[1];
1531 $output .= $term . $this->nextItem( ':' );
1532 $t = $match[2];
1535 } elseif( $prefixLength || $lastPrefixLength ) {
1536 # Either open or close a level...
1537 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1538 $paragraphStack = false;
1540 while( $commonPrefixLength < $lastPrefixLength ) {
1541 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1542 --$lastPrefixLength;
1544 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1545 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1547 while ( $prefixLength > $commonPrefixLength ) {
1548 $char = substr( $pref, $commonPrefixLength, 1 );
1549 $output .= $this->openList( $char );
1551 if ( ';' == $char ) {
1552 # FIXME: This is dupe of code above
1553 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1554 $term = $match[1];
1555 $output .= $term . $this->nextItem( ":" );
1556 $t = $match[2];
1559 ++$commonPrefixLength;
1561 $lastPrefix = $pref2;
1563 if( 0 == $prefixLength ) {
1564 # No prefix (not in list)--go to paragraph mode
1565 $uniq_prefix = UNIQ_PREFIX;
1566 // XXX: use a stack for nestable elements like span, table and div
1567 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1568 $closematch = preg_match(
1569 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1570 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1571 if ( $openmatch or $closematch ) {
1572 $paragraphStack = false;
1573 $output .= $this->closeParagraph();
1574 if($preOpenMatch and !$preCloseMatch) {
1575 $this->mInPre = true;
1577 if ( $closematch ) {
1578 $inBlockElem = false;
1579 } else {
1580 $inBlockElem = true;
1582 } else if ( !$inBlockElem && !$this->mInPre ) {
1583 if ( " " == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1584 // pre
1585 if ($this->mLastSection != 'pre') {
1586 $paragraphStack = false;
1587 $output .= $this->closeParagraph().'<pre>';
1588 $this->mLastSection = 'pre';
1590 } else {
1591 // paragraph
1592 if ( '' == trim($t) ) {
1593 if ( $paragraphStack ) {
1594 $output .= $paragraphStack.'<br />';
1595 $paragraphStack = false;
1596 $this->mLastSection = 'p';
1597 } else {
1598 if ($this->mLastSection != 'p' ) {
1599 $output .= $this->closeParagraph();
1600 $this->mLastSection = '';
1601 $paragraphStack = '<p>';
1602 } else {
1603 $paragraphStack = '</p><p>';
1606 } else {
1607 if ( $paragraphStack ) {
1608 $output .= $paragraphStack;
1609 $paragraphStack = false;
1610 $this->mLastSection = 'p';
1611 } else if ($this->mLastSection != 'p') {
1612 $output .= $this->closeParagraph().'<p>';
1613 $this->mLastSection = 'p';
1619 if ($paragraphStack === false) {
1620 $output .= $t."\n";
1623 while ( $prefixLength ) {
1624 $output .= $this->closeList( $pref2{$prefixLength-1} );
1625 --$prefixLength;
1627 if ( '' != $this->mLastSection ) {
1628 $output .= '</' . $this->mLastSection . '>';
1629 $this->mLastSection = '';
1632 wfProfileOut( $fname );
1633 return $output;
1636 # Return value of a magic variable (like PAGENAME)
1637 function getVariableValue( $index ) {
1638 global $wgLang, $wgSitename, $wgServer;
1640 switch ( $index ) {
1641 case MAG_CURRENTMONTH:
1642 return $wgLang->formatNum( date( 'm' ) );
1643 case MAG_CURRENTMONTHNAME:
1644 return $wgLang->getMonthName( date('n') );
1645 case MAG_CURRENTMONTHNAMEGEN:
1646 return $wgLang->getMonthNameGen( date('n') );
1647 case MAG_CURRENTDAY:
1648 return $wgLang->formatNum( date('j') );
1649 case MAG_PAGENAME:
1650 return $this->mTitle->getText();
1651 case MAG_PAGENAMEE:
1652 return $this->mTitle->getPartialURL();
1653 case MAG_NAMESPACE:
1654 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1655 return $wgLang->getNsText($this->mTitle->getNamespace()); # Patch by Dori
1656 case MAG_CURRENTDAYNAME:
1657 return $wgLang->getWeekdayName( date('w')+1 );
1658 case MAG_CURRENTYEAR:
1659 return $wgLang->formatNum( date( 'Y' ) );
1660 case MAG_CURRENTTIME:
1661 return $wgLang->time( wfTimestampNow(), false );
1662 case MAG_NUMBEROFARTICLES:
1663 return $wgLang->formatNum( wfNumberOfArticles() );
1664 case MAG_SITENAME:
1665 return $wgSitename;
1666 case MAG_SERVER:
1667 return $wgServer;
1668 default:
1669 return NULL;
1673 # initialise the magic variables (like CURRENTMONTHNAME)
1674 function initialiseVariables() {
1675 global $wgVariableIDs;
1676 $this->mVariables = array();
1677 foreach ( $wgVariableIDs as $id ) {
1678 $mw =& MagicWord::get( $id );
1679 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1683 /* private */ function replaceVariables( $text, $args = array() ) {
1684 global $wgLang, $wgScript, $wgArticlePath;
1686 # Prevent too big inclusions
1687 if(strlen($text)> MAX_INCLUDE_SIZE)
1688 return $text;
1690 $fname = 'Parser::replaceVariables';
1691 wfProfileIn( $fname );
1693 $bail = false;
1694 $titleChars = Title::legalChars();
1695 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1697 # This function is called recursively. To keep track of arguments we need a stack:
1698 array_push( $this->mArgStack, $args );
1700 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1701 $GLOBALS['wgCurParser'] =& $this;
1704 if ( $this->mOutputType == OT_HTML ) {
1705 # Variable substitution
1706 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1708 # Argument substitution
1709 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1711 # Template substitution
1712 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1713 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1715 array_pop( $this->mArgStack );
1717 wfProfileOut( $fname );
1718 return $text;
1721 function variableSubstitution( $matches ) {
1722 if ( !$this->mVariables ) {
1723 $this->initialiseVariables();
1725 if ( array_key_exists( $matches[1], $this->mVariables ) ) {
1726 $text = $this->mVariables[$matches[1]];
1727 $this->mOutput->mContainsOldMagic = true;
1728 } else {
1729 $text = $matches[0];
1731 return $text;
1734 # Split template arguments
1735 function getTemplateArgs( $argsString ) {
1736 if ( $argsString === '' ) {
1737 return array();
1740 $args = explode( '|', substr( $argsString, 1 ) );
1742 # If any of the arguments contains a '[[' but no ']]', it needs to be
1743 # merged with the next arg because the '|' character between belongs
1744 # to the link syntax and not the template parameter syntax.
1745 $argc = count($args);
1746 $i = 0;
1747 for ( $i = 0; $i < $argc-1; $i++ ) {
1748 if ( substr_count ( $args[$i], "[[" ) != substr_count ( $args[$i], "]]" ) ) {
1749 $args[$i] .= "|".$args[$i+1];
1750 array_splice($args, $i+1, 1);
1751 $i--;
1752 $argc--;
1756 return $args;
1759 function braceSubstitution( $matches ) {
1760 global $wgLinkCache, $wgLang;
1761 $fname = 'Parser::braceSubstitution';
1762 $found = false;
1763 $nowiki = false;
1764 $noparse = false;
1766 $title = NULL;
1768 # $newline is an optional newline character before the braces
1769 # $part1 is the bit before the first |, and must contain only title characters
1770 # $args is a list of arguments, starting from index 0, not including $part1
1772 $newline = $matches[1];
1773 $part1 = $matches[2];
1774 # If the third subpattern matched anything, it will start with |
1776 $args = $this->getTemplateArgs($matches[3]);
1777 $argc = count( $args );
1779 # {{{}}}
1780 if ( strpos( $matches[0], '{{{' ) !== false ) {
1781 $text = $matches[0];
1782 $found = true;
1783 $noparse = true;
1786 # SUBST
1787 if ( !$found ) {
1788 $mwSubst =& MagicWord::get( MAG_SUBST );
1789 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1790 if ( $this->mOutputType != OT_WIKI ) {
1791 # Invalid SUBST not replaced at PST time
1792 # Return without further processing
1793 $text = $matches[0];
1794 $found = true;
1795 $noparse= true;
1797 } elseif ( $this->mOutputType == OT_WIKI ) {
1798 # SUBST not found in PST pass, do nothing
1799 $text = $matches[0];
1800 $found = true;
1804 # MSG, MSGNW and INT
1805 if ( !$found ) {
1806 # Check for MSGNW:
1807 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1808 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1809 $nowiki = true;
1810 } else {
1811 # Remove obsolete MSG:
1812 $mwMsg =& MagicWord::get( MAG_MSG );
1813 $mwMsg->matchStartAndRemove( $part1 );
1816 # Check if it is an internal message
1817 $mwInt =& MagicWord::get( MAG_INT );
1818 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1819 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1820 $text = wfMsgReal( $part1, $args, true );
1821 $found = true;
1826 # NS
1827 if ( !$found ) {
1828 # Check for NS: (namespace expansion)
1829 $mwNs = MagicWord::get( MAG_NS );
1830 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1831 if ( intval( $part1 ) ) {
1832 $text = $wgLang->getNsText( intval( $part1 ) );
1833 $found = true;
1834 } else {
1835 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1836 if ( !is_null( $index ) ) {
1837 $text = $wgLang->getNsText( $index );
1838 $found = true;
1844 # LOCALURL and LOCALURLE
1845 if ( !$found ) {
1846 $mwLocal = MagicWord::get( MAG_LOCALURL );
1847 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1849 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1850 $func = 'getLocalURL';
1851 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1852 $func = 'escapeLocalURL';
1853 } else {
1854 $func = '';
1857 if ( $func !== '' ) {
1858 $title = Title::newFromText( $part1 );
1859 if ( !is_null( $title ) ) {
1860 if ( $argc > 0 ) {
1861 $text = $title->$func( $args[0] );
1862 } else {
1863 $text = $title->$func();
1865 $found = true;
1870 # Internal variables
1871 if ( !$this->mVariables ) {
1872 $this->initialiseVariables();
1874 if ( !$found && array_key_exists( $part1, $this->mVariables ) ) {
1875 $text = $this->mVariables[$part1];
1876 $found = true;
1877 $this->mOutput->mContainsOldMagic = true;
1880 # Template table test
1882 # Did we encounter this template already? If yes, it is in the cache
1883 # and we need to check for loops.
1884 if ( isset( $this->mTemplates[$part1] ) ) {
1885 # Infinite loop test
1886 if ( isset( $this->mTemplatePath[$part1] ) ) {
1887 $noparse = true;
1888 $found = true;
1890 # set $text to cached message.
1891 $text = $this->mTemplates[$part1];
1892 $found = true;
1895 # Load from database
1896 if ( !$found ) {
1897 $title = Title::newFromText( $part1, NS_TEMPLATE );
1898 if ( !is_null( $title ) && !$title->isExternal() ) {
1899 # Check for excessive inclusion
1900 $dbk = $title->getPrefixedDBkey();
1901 if ( $this->incrementIncludeCount( $dbk ) ) {
1902 # This should never be reached.
1903 $article = new Article( $title );
1904 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1905 if ( $articleContent !== false ) {
1906 $found = true;
1907 $text = $articleContent;
1911 # If the title is valid but undisplayable, make a link to it
1912 if ( $this->mOutputType == OT_HTML && !$found ) {
1913 $text = '[['.$title->getPrefixedText().']]';
1914 $found = true;
1917 # Template cache array insertion
1918 $this->mTemplates[$part1] = $text;
1922 # Recursive parsing, escaping and link table handling
1923 # Only for HTML output
1924 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
1925 $text = wfEscapeWikiText( $text );
1926 } elseif ( $this->mOutputType == OT_HTML && $found && !$noparse) {
1927 # Clean up argument array
1928 $assocArgs = array();
1929 $index = 1;
1930 foreach( $args as $arg ) {
1931 $eqpos = strpos( $arg, '=' );
1932 if ( $eqpos === false ) {
1933 $assocArgs[$index++] = $arg;
1934 } else {
1935 $name = trim( substr( $arg, 0, $eqpos ) );
1936 $value = trim( substr( $arg, $eqpos+1 ) );
1937 if ( $value === false ) {
1938 $value = '';
1940 if ( $name !== false ) {
1941 $assocArgs[$name] = $value;
1946 # Do not enter included links in link table
1947 if ( !is_null( $title ) ) {
1948 $wgLinkCache->suspend();
1951 # Add a new element to the templace recursion path
1952 $this->mTemplatePath[$part1] = 1;
1954 $text = $this->stripParse( $text, $newline, $assocArgs );
1956 # Resume the link cache and register the inclusion as a link
1957 if ( !is_null( $title ) ) {
1958 $wgLinkCache->resume();
1959 $wgLinkCache->addLinkObj( $title );
1962 # Empties the template path
1963 $this->mTemplatePath = array();
1965 if ( !$found ) {
1966 return $matches[0];
1967 } else {
1968 return $text;
1972 # Triple brace replacement -- used for template arguments
1973 function argSubstitution( $matches ) {
1974 $newline = $matches[1];
1975 $arg = trim( $matches[2] );
1976 $text = $matches[0];
1977 $inputArgs = end( $this->mArgStack );
1979 if ( array_key_exists( $arg, $inputArgs ) ) {
1980 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1983 return $text;
1986 # Returns true if the function is allowed to include this entity
1987 function incrementIncludeCount( $dbk ) {
1988 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
1989 $this->mIncludeCount[$dbk] = 0;
1991 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
1992 return true;
1993 } else {
1994 return false;
1999 # Cleans up HTML, removes dangerous tags and attributes
2000 /* private */ function removeHTMLtags( $text ) {
2001 global $wgUseTidy, $wgUserHtml;
2002 $fname = 'Parser::removeHTMLtags';
2003 wfProfileIn( $fname );
2005 if( $wgUserHtml ) {
2006 $htmlpairs = array( # Tags that must be closed
2007 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
2008 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
2009 'strike', 'strong', 'tt', 'var', 'div', 'center',
2010 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
2011 'ruby', 'rt' , 'rb' , 'rp', 'p'
2013 $htmlsingle = array(
2014 'br', 'hr', 'li', 'dt', 'dd'
2016 $htmlnest = array( # Tags that can be nested--??
2017 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
2018 'dl', 'font', 'big', 'small', 'sub', 'sup'
2020 $tabletags = array( # Can only appear inside table
2021 'td', 'th', 'tr'
2023 } else {
2024 $htmlpairs = array();
2025 $htmlsingle = array();
2026 $htmlnest = array();
2027 $tabletags = array();
2030 $htmlsingle = array_merge( $tabletags, $htmlsingle );
2031 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
2033 $htmlattrs = $this->getHTMLattrs () ;
2035 # Remove HTML comments
2036 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
2038 $bits = explode( '<', $text );
2039 $text = array_shift( $bits );
2040 if(!$wgUseTidy) {
2041 $tagstack = array(); $tablestack = array();
2042 foreach ( $bits as $x ) {
2043 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
2044 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2045 $x, $regs );
2046 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2047 error_reporting( $prev );
2049 $badtag = 0 ;
2050 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2051 # Check our stack
2052 if ( $slash ) {
2053 # Closing a tag...
2054 if ( ! in_array( $t, $htmlsingle ) &&
2055 ( $ot = @array_pop( $tagstack ) ) != $t ) {
2056 @array_push( $tagstack, $ot );
2057 $badtag = 1;
2058 } else {
2059 if ( $t == 'table' ) {
2060 $tagstack = array_pop( $tablestack );
2062 $newparams = '';
2064 } else {
2065 # Keep track for later
2066 if ( in_array( $t, $tabletags ) &&
2067 ! in_array( 'table', $tagstack ) ) {
2068 $badtag = 1;
2069 } else if ( in_array( $t, $tagstack ) &&
2070 ! in_array ( $t , $htmlnest ) ) {
2071 $badtag = 1 ;
2072 } else if ( ! in_array( $t, $htmlsingle ) ) {
2073 if ( $t == 'table' ) {
2074 array_push( $tablestack, $tagstack );
2075 $tagstack = array();
2077 array_push( $tagstack, $t );
2079 # Strip non-approved attributes from the tag
2080 $newparams = $this->fixTagAttributes($params);
2083 if ( ! $badtag ) {
2084 $rest = str_replace( '>', '&gt;', $rest );
2085 $text .= "<$slash$t $newparams$brace$rest";
2086 continue;
2089 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
2091 # Close off any remaining tags
2092 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2093 $text .= "</$t>\n";
2094 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2096 } else {
2097 # this might be possible using tidy itself
2098 foreach ( $bits as $x ) {
2099 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2100 $x, $regs );
2101 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2102 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2103 $newparams = $this->fixTagAttributes($params);
2104 $rest = str_replace( '>', '&gt;', $rest );
2105 $text .= "<$slash$t $newparams$brace$rest";
2106 } else {
2107 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
2111 wfProfileOut( $fname );
2112 return $text;
2116 # This function accomplishes several tasks:
2117 # 1) Auto-number headings if that option is enabled
2118 # 2) Add an [edit] link to sections for logged in users who have enabled the option
2119 # 3) Add a Table of contents on the top for users who have enabled the option
2120 # 4) Auto-anchor headings
2122 # It loops through all headlines, collects the necessary data, then splits up the
2123 # string and re-inserts the newly formatted headlines.
2124 /* private */ function formatHeadings( $text, $isMain=true ) {
2125 global $wgInputEncoding, $wgMaxTocLevel;
2127 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2128 $doShowToc = $this->mOptions->getShowToc();
2129 $forceTocHere = false;
2130 if( !$this->mTitle->userCanEdit() ) {
2131 $showEditLink = 0;
2132 $rightClickHack = 0;
2133 } else {
2134 $showEditLink = $this->mOptions->getEditSection();
2135 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
2138 # Inhibit editsection links if requested in the page
2139 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2140 if( $esw->matchAndRemove( $text ) ) {
2141 $showEditLink = 0;
2143 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2144 # do not add TOC
2145 $mw =& MagicWord::get( MAG_NOTOC );
2146 if( $mw->matchAndRemove( $text ) ) {
2147 $doShowToc = 0;
2150 # never add the TOC to the Main Page. This is an entry page that should not
2151 # be more than 1-2 screens large anyway
2152 if( $this->mTitle->getPrefixedText() == wfMsg('mainpage') ) {
2153 $doShowToc = 0;
2156 # Get all headlines for numbering them and adding funky stuff like [edit]
2157 # links - this is for later, but we need the number of headlines right now
2158 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2160 # if there are fewer than 4 headlines in the article, do not show TOC
2161 if( $numMatches < 4 ) {
2162 $doShowToc = 0;
2165 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2166 # override above conditions and always show TOC at that place
2167 $mw =& MagicWord::get( MAG_TOC );
2168 if ($mw->match( $text ) ) {
2169 $doShowToc = 1;
2170 $forceTocHere = true;
2171 } else {
2172 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2173 # override above conditions and always show TOC above first header
2174 $mw =& MagicWord::get( MAG_FORCETOC );
2175 if ($mw->matchAndRemove( $text ) ) {
2176 $doShowToc = 1;
2182 # We need this to perform operations on the HTML
2183 $sk =& $this->mOptions->getSkin();
2185 # headline counter
2186 $headlineCount = 0;
2188 # Ugh .. the TOC should have neat indentation levels which can be
2189 # passed to the skin functions. These are determined here
2190 $toclevel = 0;
2191 $toc = '';
2192 $full = '';
2193 $head = array();
2194 $sublevelCount = array();
2195 $level = 0;
2196 $prevlevel = 0;
2197 foreach( $matches[3] as $headline ) {
2198 $numbering = '';
2199 if( $level ) {
2200 $prevlevel = $level;
2202 $level = $matches[1][$headlineCount];
2203 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
2204 # reset when we enter a new level
2205 $sublevelCount[$level] = 0;
2206 $toc .= $sk->tocIndent( $level - $prevlevel );
2207 $toclevel += $level - $prevlevel;
2209 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
2210 # reset when we step back a level
2211 $sublevelCount[$level+1]=0;
2212 $toc .= $sk->tocUnindent( $prevlevel - $level );
2213 $toclevel -= $prevlevel - $level;
2215 # count number of headlines for each level
2216 @$sublevelCount[$level]++;
2217 if( $doNumberHeadings || $doShowToc ) {
2218 $dot = 0;
2219 for( $i = 1; $i <= $level; $i++ ) {
2220 if( !empty( $sublevelCount[$i] ) ) {
2221 if( $dot ) {
2222 $numbering .= '.';
2224 $numbering .= $sublevelCount[$i];
2225 $dot = 1;
2230 # The canonized header is a version of the header text safe to use for links
2231 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2232 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2233 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState );
2235 # strip out HTML
2236 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2237 $tocline = trim( $canonized_headline );
2238 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2239 $replacearray = array(
2240 '%3A' => ':',
2241 '%' => '.'
2243 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2244 $refer[$headlineCount] = $canonized_headline;
2246 # count how many in assoc. array so we can track dupes in anchors
2247 @$refers[$canonized_headline]++;
2248 $refcount[$headlineCount]=$refers[$canonized_headline];
2250 # Prepend the number to the heading text
2252 if( $doNumberHeadings || $doShowToc ) {
2253 $tocline = $numbering . ' ' . $tocline;
2255 # Don't number the heading if it is the only one (looks silly)
2256 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2257 # the two are different if the line contains a link
2258 $headline=$numbering . ' ' . $headline;
2262 # Create the anchor for linking from the TOC to the section
2263 $anchor = $canonized_headline;
2264 if($refcount[$headlineCount] > 1 ) {
2265 $anchor .= '_' . $refcount[$headlineCount];
2267 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2268 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2270 if( $showEditLink ) {
2271 if ( empty( $head[$headlineCount] ) ) {
2272 $head[$headlineCount] = '';
2274 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+1);
2277 # Add the edit section span
2278 if( $rightClickHack ) {
2279 $headline = $sk->editSectionScript($headlineCount+1,$headline);
2282 # give headline the correct <h#> tag
2283 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
2285 $headlineCount++;
2288 if( $doShowToc ) {
2289 $toclines = $headlineCount;
2290 $toc .= $sk->tocUnindent( $toclevel );
2291 $toc = $sk->tocTable( $toc );
2294 # split up and insert constructed headlines
2296 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2297 $i = 0;
2299 foreach( $blocks as $block ) {
2300 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2301 # This is the [edit] link that appears for the top block of text when
2302 # section editing is enabled
2304 # Disabled because it broke block formatting
2305 # For example, a bullet point in the top line
2306 # $full .= $sk->editSectionLink(0);
2308 $full .= $block;
2309 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2310 # Top anchor now in skin
2311 $full = $full.$toc;
2314 if( !empty( $head[$i] ) ) {
2315 $full .= $head[$i];
2317 $i++;
2319 if($forceTocHere) {
2320 $mw =& MagicWord::get( MAG_TOC );
2321 return $mw->replace( $toc, $full );
2322 } else {
2323 return $full;
2327 # Return an HTML link for the "ISBN 123456" text
2328 /* private */ function magicISBN( $text ) {
2329 global $wgLang;
2330 $fname = 'Parser::magicISBN';
2331 wfProfileIn( $fname );
2333 $a = split( 'ISBN ', " $text" );
2334 if ( count ( $a ) < 2 ) {
2335 wfProfileOut( $fname );
2336 return $text;
2338 $text = substr( array_shift( $a ), 1);
2339 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2341 foreach ( $a as $x ) {
2342 $isbn = $blank = '' ;
2343 while ( ' ' == $x{0} ) {
2344 $blank .= ' ';
2345 $x = substr( $x, 1 );
2347 while ( strstr( $valid, $x{0} ) != false ) {
2348 $isbn .= $x{0};
2349 $x = substr( $x, 1 );
2351 $num = str_replace( '-', '', $isbn );
2352 $num = str_replace( ' ', '', $num );
2354 if ( '' == $num ) {
2355 $text .= "ISBN $blank$x";
2356 } else {
2357 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2358 $text .= '<a href="' .
2359 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
2360 "\" class=\"internal\">ISBN $isbn</a>";
2361 $text .= $x;
2364 wfProfileOut( $fname );
2365 return $text;
2368 # Return an HTML link for the "GEO ..." text
2369 /* private */ function magicGEO( $text ) {
2370 global $wgLang, $wgUseGeoMode;
2371 $fname = 'Parser::magicGEO';
2372 wfProfileIn( $fname );
2374 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2375 $directions = array ( "N" => "North" , "S" => "South" , "E" => "East" , "W" => "West" ) ;
2376 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2377 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2378 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2379 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2381 $a = split( 'GEO ', " $text" );
2382 if ( count ( $a ) < 2 ) {
2383 wfProfileOut( $fname );
2384 return $text;
2386 $text = substr( array_shift( $a ), 1);
2387 $valid = '0123456789.+-:';
2389 foreach ( $a as $x ) {
2390 $geo = $blank = '' ;
2391 while ( ' ' == $x{0} ) {
2392 $blank .= ' ';
2393 $x = substr( $x, 1 );
2395 while ( strstr( $valid, $x{0} ) != false ) {
2396 $geo .= $x{0};
2397 $x = substr( $x, 1 );
2399 $num = str_replace( '+', '', $geo );
2400 $num = str_replace( ' ', '', $num );
2402 if ( '' == $num || count ( explode ( ":" , $num , 3 ) ) < 2 ) {
2403 $text .= "GEO $blank$x";
2404 } else {
2405 $titleObj = Title::makeTitle( NS_SPECIAL, 'Geo' );
2406 $text .= '<a href="' .
2407 $titleObj->escapeLocalUrl( "coordinates={$num}" ) .
2408 "\" class=\"internal\">GEO $geo</a>";
2409 $text .= $x;
2412 wfProfileOut( $fname );
2413 return $text;
2416 # Return an HTML link for the "RFC 1234" text
2417 /* private */ function magicRFC( $text ) {
2418 global $wgLang;
2420 $a = split( 'RFC ', ' '.$text );
2421 if ( count ( $a ) < 2 ) return $text;
2422 $text = substr( array_shift( $a ), 1);
2423 $valid = '0123456789';
2425 foreach ( $a as $x ) {
2426 $rfc = $blank = '' ;
2427 while ( ' ' == $x{0} ) {
2428 $blank .= ' ';
2429 $x = substr( $x, 1 );
2431 while ( strstr( $valid, $x{0} ) != false ) {
2432 $rfc .= $x{0};
2433 $x = substr( $x, 1 );
2436 if ( '' == $rfc ) {
2437 $text .= "RFC $blank$x";
2438 } else {
2439 $url = wfmsg( 'rfcurl' );
2440 $url = str_replace( '$1', $rfc, $url);
2441 $sk =& $this->mOptions->getSkin();
2442 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2443 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2446 return $text;
2449 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2450 $this->mOptions = $options;
2451 $this->mTitle =& $title;
2452 $this->mOutputType = OT_WIKI;
2454 if ( $clearState ) {
2455 $this->clearState();
2458 $stripState = false;
2459 $pairs = array(
2460 "\r\n" => "\n",
2462 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2463 // now with regexes
2465 $pairs = array(
2466 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2467 "/<br *?>/i" => "<br />",
2469 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2471 $text = $this->strip( $text, $stripState, false );
2472 $text = $this->pstPass2( $text, $user );
2473 $text = $this->unstrip( $text, $stripState );
2474 $text = $this->unstripNoWiki( $text, $stripState );
2475 return $text;
2478 /* private */ function pstPass2( $text, &$user ) {
2479 global $wgLang, $wgLocaltimezone, $wgCurParser;
2481 # Variable replacement
2482 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2483 $text = $this->replaceVariables( $text );
2485 # Signatures
2487 $n = $user->getName();
2488 $k = $user->getOption( 'nickname' );
2489 if ( '' == $k ) { $k = $n; }
2490 if(isset($wgLocaltimezone)) {
2491 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2493 /* Note: this is an ugly timezone hack for the European wikis */
2494 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2495 ' (' . date( 'T' ) . ')';
2496 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2498 $text = preg_replace( '/~~~~~/', $d, $text );
2499 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText( NS_USER ) . ":$n|$k]] $d", $text );
2500 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText( NS_USER ) . ":$n|$k]]", $text );
2502 # Context links: [[|name]] and [[name (context)|]]
2504 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2505 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2506 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2507 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2509 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2510 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2511 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2512 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2513 # [[ns:page (cont)|]]
2514 $context = '';
2515 $t = $this->mTitle->getText();
2516 if ( preg_match( $conpat, $t, $m ) ) {
2517 $context = $m[2];
2519 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2520 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2521 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2523 if ( '' == $context ) {
2524 $text = preg_replace( $p2, '[[\\1]]', $text );
2525 } else {
2526 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2530 $mw =& MagicWord::get( MAG_SUBST );
2531 $wgCurParser = $this->fork();
2532 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2533 $this->merge( $wgCurParser );
2536 # Trim trailing whitespace
2537 # MAG_END (__END__) tag allows for trailing
2538 # whitespace to be deliberately included
2539 $text = rtrim( $text );
2540 $mw =& MagicWord::get( MAG_END );
2541 $mw->matchAndRemove( $text );
2543 return $text;
2546 # Set up some variables which are usually set up in parse()
2547 # so that an external function can call some class members with confidence
2548 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2549 $this->mTitle =& $title;
2550 $this->mOptions = $options;
2551 $this->mOutputType = $outputType;
2552 if ( $clearState ) {
2553 $this->clearState();
2557 function transformMsg( $text, $options ) {
2558 global $wgTitle;
2559 static $executing = false;
2561 # Guard against infinite recursion
2562 if ( $executing ) {
2563 return $text;
2565 $executing = true;
2567 $this->mTitle = $wgTitle;
2568 $this->mOptions = $options;
2569 $this->mOutputType = OT_MSG;
2570 $this->clearState();
2571 $text = $this->replaceVariables( $text );
2573 $executing = false;
2574 return $text;
2577 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2578 # Callback will be called with the text within
2579 # Transform and return the text within
2580 function setHook( $tag, $callback ) {
2581 $oldVal = @$this->mTagHooks[$tag];
2582 $this->mTagHooks[$tag] = $callback;
2583 return $oldVal;
2587 class ParserOutput
2589 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2590 var $mCacheTime; # Used in ParserCache
2592 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2593 $containsOldMagic = false )
2595 $this->mText = $text;
2596 $this->mLanguageLinks = $languageLinks;
2597 $this->mCategoryLinks = $categoryLinks;
2598 $this->mContainsOldMagic = $containsOldMagic;
2599 $this->mCacheTime = "";
2602 function getText() { return $this->mText; }
2603 function getLanguageLinks() { return $this->mLanguageLinks; }
2604 function getCategoryLinks() { return $this->mCategoryLinks; }
2605 function getCacheTime() { return $this->mCacheTime; }
2606 function containsOldMagic() { return $this->mContainsOldMagic; }
2607 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2608 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2609 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2610 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2611 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2613 function merge( $other ) {
2614 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2615 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2616 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2621 class ParserOptions
2623 # All variables are private
2624 var $mUseTeX; # Use texvc to expand <math> tags
2625 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2626 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2627 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2628 var $mAllowExternalImages; # Allow external images inline
2629 var $mSkin; # Reference to the preferred skin
2630 var $mDateFormat; # Date format index
2631 var $mEditSection; # Create "edit section" links
2632 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2633 var $mNumberHeadings; # Automatically number headings
2634 var $mShowToc; # Show table of contents
2636 function getUseTeX() { return $this->mUseTeX; }
2637 function getUseCategoryMagic() { return $this->mUseCategoryMagic; }
2638 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2639 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2640 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2641 function getSkin() { return $this->mSkin; }
2642 function getDateFormat() { return $this->mDateFormat; }
2643 function getEditSection() { return $this->mEditSection; }
2644 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
2645 function getNumberHeadings() { return $this->mNumberHeadings; }
2646 function getShowToc() { return $this->mShowToc; }
2648 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
2649 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic, $x ); }
2650 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
2651 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
2652 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
2653 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
2654 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
2655 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
2656 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
2657 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
2659 function setSkin( &$x ) { $this->mSkin =& $x; }
2661 # Get parser options
2662 /* static */ function newFromUser( &$user ) {
2663 $popts = new ParserOptions;
2664 $popts->initialiseFromUser( $user );
2665 return $popts;
2668 # Get user options
2669 function initialiseFromUser( &$userInput ) {
2670 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2672 $fname = "ParserOptions::initialiseFromUser";
2673 wfProfileIn( $fname );
2674 if ( !$userInput ) {
2675 $user = new User;
2676 $user->setLoaded( true );
2677 } else {
2678 $user =& $userInput;
2681 $this->mUseTeX = $wgUseTeX;
2682 $this->mUseCategoryMagic = $wgUseCategoryMagic;
2683 $this->mUseDynamicDates = $wgUseDynamicDates;
2684 $this->mInterwikiMagic = $wgInterwikiMagic;
2685 $this->mAllowExternalImages = $wgAllowExternalImages;
2686 wfProfileIn( "$fname-skin" );
2687 $this->mSkin =& $user->getSkin();
2688 wfProfileOut( "$fname-skin" );
2689 $this->mDateFormat = $user->getOption( 'date' );
2690 $this->mEditSection = $user->getOption( 'editsection' );
2691 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
2692 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
2693 $this->mShowToc = $user->getOption( 'showtoc' );
2694 wfProfileOut( $fname );
2700 # Regex callbacks, used in Parser::replaceVariables
2701 function wfBraceSubstitution( $matches ) {
2702 global $wgCurParser;
2703 return $wgCurParser->braceSubstitution( $matches );
2706 function wfArgSubstitution( $matches ) {
2707 global $wgCurParser;
2708 return $wgCurParser->argSubstitution( $matches );
2711 function wfVariableSubstitution( $matches ) {
2712 global $wgCurParser;
2713 return $wgCurParser->variableSubstitution( $matches );
2716 # Return the total number of articles
2717 function wfNumberOfArticles() {
2718 global $wgNumberOfArticles;
2720 wfLoadSiteStats();
2721 return $wgNumberOfArticles;
2724 # Get various statistics from the database
2725 /* private */ function wfLoadSiteStats() {
2726 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
2727 $fname = 'wfLoadSiteStats';
2729 if ( -1 != $wgNumberOfArticles ) return;
2730 $dbr =& wfGetDB( DB_SLAVE );
2731 $s = $dbr->getArray( 'site_stats',
2732 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
2733 array( 'ss_row_id' => 1 ), $fname
2736 if ( $s === false ) {
2737 return;
2738 } else {
2739 $wgTotalViews = $s->ss_total_views;
2740 $wgTotalEdits = $s->ss_total_edits;
2741 $wgNumberOfArticles = $s->ss_good_articles;
2745 function wfEscapeHTMLTagsOnly( $in ) {
2746 return str_replace(
2747 array( '"', '>', '<' ),
2748 array( '&quot;', '&gt;', '&lt;' ),
2749 $in );