Antiglobalization!
[mediawiki.git] / includes / Parser.php
bloba3d285794f6280f752c51d49ee9baf00e9a5c019
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: parse() and preSaveTransform().
10 # The parse() function produces HTML output, preSaveTransform() produces altered wiki markup.
12 # Globals used:
13 # objects: $wgLang, $wgDateFormatter, $wgLinkCache, $wgCurParser
15 # NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
17 # settings: $wgUseTex*, $wgUseCategoryMagic*, $wgUseDynamicDates*, $wgInterwikiMagic*,
18 # $wgNamespacesWithSubpages, $wgLanguageCode, $wgAllowExternalImages*,
19 # $wgLocaltimezone
21 # * only within ParserOptions
24 #----------------------------------------
25 # Variable substitution O(N^2) attack
26 #-----------------------------------------
27 # Without countermeasures, it would be possible to attack the parser by saving a page
28 # filled with a large number of inclusions of large pages. The size of the generated
29 # page would be proportional to the square of the input size. Hence, we limit the number
30 # of inclusions of any given page, thus bringing any attack back to O(N).
33 define( "MAX_INCLUDE_REPEAT", 20 );
34 define( "MAX_INCLUDE_SIZE", 1000000 ); // 1 Million
36 # Allowed values for $mOutputType
37 define( "OT_HTML", 1 );
38 define( "OT_WIKI", 2 );
39 define( "OT_MSG", 3 );
41 # string parameter for extractTags which will cause it
42 # to strip HTML comments in addition to regular
43 # <XML>-style tags. This should not be anything we
44 # may want to use in wikisyntax
45 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
47 # prefix for escaping, used in two functions at least
48 define( 'UNIQ_PREFIX', 'NaodW29');
51 # 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()
363 function insertStripItem( $text, &$state ) {
364 $rnd = UNIQ_PREFIX . '-item' . Parser::getRandomString();
365 if ( !$state ) {
366 $state = array(
367 'html' => array(),
368 'nowiki' => array(),
369 'math' => array(),
370 'pre' => array()
373 $state['item'][$rnd] = $text;
374 return $rnd;
377 # categoryMagic
378 # generate a list of subcategories and pages for a category
379 # depending on wfMsg("usenewcategorypage") it either calls the new
380 # or the old code. The new code will not work properly for some
381 # languages due to sorting issues, so they might want to turn it
382 # off.
383 function categoryMagic() {
384 $msg = wfMsg('usenewcategorypage');
385 if ( '0' == @$msg[0] )
387 return $this->oldCategoryMagic();
388 } else {
389 return $this->newCategoryMagic();
393 # This method generates the list of subcategories and pages for a category
394 function oldCategoryMagic () {
395 global $wgLang ;
396 $fname = 'Parser::oldCategoryMagic';
398 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
400 if ( $this->mTitle->getNamespace() != NS_CATEGORY ) return "" ; # This ain't a category page
402 $r = "<br style=\"clear:both;\"/>\n";
405 $sk =& $this->mOptions->getSkin() ;
407 $articles = array() ;
408 $children = array() ;
409 $data = array () ;
410 $id = $this->mTitle->getArticleID() ;
412 # FIXME: add limits
413 $dbr =& wfGetDB( DB_SLAVE );
414 $cur = $dbr->tableName( 'cur' );
415 $categorylinks = $dbr->tableName( 'categorylinks' );
417 $t = $dbr->strencode( $this->mTitle->getDBKey() );
418 $sql = "SELECT DISTINCT cur_title,cur_namespace FROM $cur,$categorylinks " .
419 "WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
420 $res = $dbr->query( $sql, $fname ) ;
421 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
423 # For all pages that link to this category
424 foreach ( $data AS $x )
426 $t = $wgLang->getNsText ( $x->cur_namespace ) ;
427 if ( $t != "" ) $t .= ":" ;
428 $t .= $x->cur_title ;
430 if ( $x->cur_namespace == NS_CATEGORY ) {
431 array_push ( $children , $sk->makeLink ( $t ) ) ; # Subcategory
432 } else {
433 array_push ( $articles , $sk->makeLink ( $t ) ) ; # Page in this category
436 $dbr->freeResult ( $res ) ;
438 # Showing subcategories
439 if ( count ( $children ) > 0 ) {
440 $r .= '<h2>'.wfMsg('subcategories')."</h2>\n" ;
441 $r .= implode ( ', ' , $children ) ;
444 # Showing pages in this category
445 if ( count ( $articles ) > 0 ) {
446 $ti = $this->mTitle->getText() ;
447 $h = wfMsg( 'category_header', $ti );
448 $r .= "<h2>{$h}</h2>\n" ;
449 $r .= implode ( ', ' , $articles ) ;
452 return $r ;
457 function newCategoryMagic () {
458 global $wgLang;
459 if ( !$this->mOptions->getUseCategoryMagic() ) return ; # Doesn't use categories at all
461 if ( $this->mTitle->getNamespace() != NS_CATEGORY ) return '' ; # This ain't a category page
463 $r = "<br style=\"clear:both;\"/>\n";
466 $sk =& $this->mOptions->getSkin() ;
468 $articles = array() ;
469 $articles_start_char = array();
470 $children = array() ;
471 $children_start_char = array();
472 $data = array () ;
473 $id = $this->mTitle->getArticleID() ;
475 # FIXME: add limits
476 $dbr =& wfGetDB( DB_SLAVE );
477 $cur = $dbr->tableName( 'cur' );
478 $categorylinks = $dbr->tableName( 'categorylinks' );
480 $t = $dbr->strencode( $this->mTitle->getDBKey() );
481 $sql = "SELECT DISTINCT cur_title,cur_namespace,cl_sortkey FROM " .
482 "$cur,$categorylinks WHERE cl_to='$t' AND cl_from=cur_id ORDER BY cl_sortkey" ;
483 $res = $dbr->query ( $sql ) ;
484 while ( $x = $dbr->fetchObject ( $res ) )
486 $t = $ns = $wgLang->getNsText ( $x->cur_namespace ) ;
487 if ( $t != '' ) $t .= ':' ;
488 $t .= $x->cur_title ;
490 if ( $x->cur_namespace == NS_CATEGORY ) {
491 $ctitle = str_replace( '_',' ',$x->cur_title );
492 array_push ( $children, $sk->makeKnownLink ( $t, $ctitle ) ) ; # Subcategory
494 // If there's a link from Category:A to Category:B, the sortkey of the resulting
495 // entry in the categorylinks table is Category:A, not A, which it SHOULD be.
496 // Workaround: If sortkey == "Category:".$title, than use $title for sorting,
497 // else use sortkey...
498 if ( ($ns.":".$ctitle) == $x->cl_sortkey ) {
499 array_push ( $children_start_char, $wgLang->firstChar( $x->cur_title ) );
500 } else {
501 array_push ( $children_start_char, $wgLang->firstChar( $x->cl_sortkey ) ) ;
503 } else {
504 array_push ( $articles , $sk->makeKnownLink ( $t ) ) ; # Page in this category
505 array_push ( $articles_start_char, $wgLang->firstChar( $x->cl_sortkey ) ) ;
508 $dbr->freeResult ( $res ) ;
510 $ti = $this->mTitle->getText() ;
512 # Don't show subcategories section if there are none.
513 if ( count ( $children ) > 0 )
515 # Showing subcategories
516 $r .= '<h2>' . wfMsg( 'subcategories' ) . "</h2>\n";
518 $numchild = count( $children );
519 if($numchild == 1) {
520 $r .= wfMsg( 'subcategorycount1', 1 );
521 } else {
522 $r .= wfMsg( 'subcategorycount' , $numchild );
524 unset($numchild);
526 if ( count ( $children ) > 6 ) {
528 // divide list into three equal chunks
529 $chunk = (int) (count ( $children ) / 3);
531 // get and display header
532 $r .= '<table width="100%"><tr valign="top">';
534 $startChunk = 0;
535 $endChunk = $chunk;
537 // loop through the chunks
538 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
539 $chunkIndex < 3;
540 $chunkIndex++, $startChunk = $endChunk, $endChunk += $chunk + 1)
543 $r .= '<td><ul>';
544 // output all subcategories to category
545 for ($index = $startChunk ;
546 $index < $endChunk && $index < count($children);
547 $index++ )
549 // check for change of starting letter or begging of chunk
550 if ( ($children_start_char[$index] != $children_start_char[$index - 1])
551 || ($index == $startChunk) )
553 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
556 $r .= "<li>{$children[$index]}</li>";
558 $r .= '</ul></td>';
562 $r .= '</tr></table>';
563 } else {
564 // for short lists of subcategories to category.
566 $r .= "<h3>{$children_start_char[0]}</h3>\n";
567 $r .= '<ul><li>'.$children[0].'</li>';
568 for ($index = 1; $index < count($children); $index++ )
570 if ($children_start_char[$index] != $children_start_char[$index - 1])
572 $r .= "</ul><h3>{$children_start_char[$index]}</h3>\n<ul>";
575 $r .= "<li>{$children[$index]}</li>";
577 $r .= '</ul>';
579 } # END of if ( count($children) > 0 )
581 $r .= '<h2>' . wfMsg( 'category_header', $ti ) . "</h2>\n";
583 $numart = count( $articles );
584 if($numart == 1) {
585 $r .= wfMsg( 'categoryarticlecount1', 1 );
586 } else {
587 $r .= wfMsg( 'categoryarticlecount' , $numart );
589 unset($numart);
591 # Showing articles in this category
592 if ( count ( $articles ) > 6) {
593 $ti = $this->mTitle->getText() ;
595 // divide list into three equal chunks
596 $chunk = (int) (count ( $articles ) / 3);
598 // get and display header
599 $r .= '<table width="100%"><tr valign="top">';
601 // loop through the chunks
602 for($startChunk = 0, $endChunk = $chunk, $chunkIndex = 0;
603 $chunkIndex < 3;
604 $chunkIndex++, $startChunk = $endChunk, $endChunk += $chunk + 1)
607 $r .= '<td><ul>';
609 // output all articles in category
610 for ($index = $startChunk ;
611 $index < $endChunk && $index < count($articles);
612 $index++ )
614 // check for change of starting letter or begging of chunk
615 if ( ($articles_start_char[$index] != $articles_start_char[$index - 1])
616 || ($index == $startChunk) )
618 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
621 $r .= "<li>{$articles[$index]}</li>";
623 $r .= '</ul></td>';
627 $r .= '</tr></table>';
628 } elseif ( count ( $articles ) > 0) {
629 // for short lists of articles in categories.
630 $ti = $this->mTitle->getText() ;
632 $r .= '<h3>'.$articles_start_char[0]."</h3>\n";
633 $r .= '<ul><li>'.$articles[0].'</li>';
634 for ($index = 1; $index < count($articles); $index++ )
636 if ($articles_start_char[$index] != $articles_start_char[$index - 1])
638 $r .= "</ul><h3>{$articles_start_char[$index]}</h3>\n<ul>";
641 $r .= "<li>{$articles[$index]}</li>";
643 $r .= '</ul>';
647 return $r ;
650 # Return allowed HTML attributes
651 function getHTMLattrs () {
652 $htmlattrs = array( # Allowed attributes--no scripting, etc.
653 'title', 'align', 'lang', 'dir', 'width', 'height',
654 'bgcolor', 'clear', /* BR */ 'noshade', /* HR */
655 'cite', /* BLOCKQUOTE, Q */ 'size', 'face', 'color',
656 /* FONT */ 'type', 'start', 'value', 'compact',
657 /* For various lists, mostly deprecated but safe */
658 'summary', 'width', 'border', 'frame', 'rules',
659 'cellspacing', 'cellpadding', 'valign', 'char',
660 'charoff', 'colgroup', 'col', 'span', 'abbr', 'axis',
661 'headers', 'scope', 'rowspan', 'colspan', /* Tables */
662 'id', 'class', 'name', 'style' /* For CSS */
664 return $htmlattrs ;
667 # Remove non approved attributes and javascript in css
668 function fixTagAttributes ( $t ) {
669 if ( trim ( $t ) == '' ) return '' ; # Saves runtime ;-)
670 $htmlattrs = $this->getHTMLattrs() ;
672 # Strip non-approved attributes from the tag
673 $t = preg_replace(
674 '/(\\w+)(\\s*=\\s*([^\\s\">]+|\"[^\">]*\"))?/e',
675 "(in_array(strtolower(\"\$1\"),\$htmlattrs)?(\"\$1\".((\"x\$3\" != \"x\")?\"=\$3\":'')):'')",
676 $t);
678 $t = str_replace ( "<></>" , "" , $t ) ; # This should fix bug 980557
680 # Strip javascript "expression" from stylesheets. Brute force approach:
681 # If anythin offensive is found, all attributes of the HTML tag are dropped
683 if( preg_match(
684 '/style\\s*=.*(expression|tps*:\/\/|url\\s*\().*/is',
685 wfMungeToUtf8( $t ) ) )
687 $t='';
690 return trim ( $t ) ;
693 # interface with html tidy, used if $wgUseTidy = true
694 function tidy ( $text ) {
695 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
696 global $wgInputEncoding, $wgOutputEncoding;
697 $fname = 'Parser::tidy';
698 wfProfileIn( $fname );
700 $cleansource = '';
701 switch(strtoupper($wgOutputEncoding)) {
702 case 'ISO-8859-1':
703 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -latin1':' -raw';
704 break;
705 case 'UTF-8':
706 $wgTidyOpts .= ($wgInputEncoding == $wgOutputEncoding)? ' -utf8':' -raw';
707 break;
708 default:
709 $wgTidyOpts .= ' -raw';
712 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
713 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
714 '<head><title>test</title></head><body>'.$text.'</body></html>';
715 $descriptorspec = array(
716 0 => array('pipe', 'r'),
717 1 => array('pipe', 'w'),
718 2 => array('file', '/dev/null', 'a')
720 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts", $descriptorspec, $pipes);
721 if (is_resource($process)) {
722 fwrite($pipes[0], $wrappedtext);
723 fclose($pipes[0]);
724 while (!feof($pipes[1])) {
725 $cleansource .= fgets($pipes[1], 1024);
727 fclose($pipes[1]);
728 $return_value = proc_close($process);
731 wfProfileOut( $fname );
733 if( $cleansource == '' && $text != '') {
734 wfDebug( "Tidy error detected!\n" );
735 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
736 } else {
737 return $cleansource;
741 # parse the wiki syntax used to render tables
742 function doTableStuff ( $t ) {
743 $fname = 'Parser::doTableStuff';
744 wfProfileIn( $fname );
746 $t = explode ( "\n" , $t ) ;
747 $td = array () ; # Is currently a td tag open?
748 $ltd = array () ; # Was it TD or TH?
749 $tr = array () ; # Is currently a tr tag open?
750 $ltr = array () ; # tr attributes
751 $indent_level = 0; # indent level of the table
752 foreach ( $t AS $k => $x )
754 $x = trim ( $x ) ;
755 $fc = substr ( $x , 0 , 1 ) ;
756 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) )
758 $indent_level = strlen( $matches[1] );
759 $t[$k] = "\n" .
760 str_repeat( "<dl><dd>", $indent_level ) .
761 "<table " . $this->fixTagAttributes ( $matches[2] ) . '>' ;
762 array_push ( $td , false ) ;
763 array_push ( $ltd , '' ) ;
764 array_push ( $tr , false ) ;
765 array_push ( $ltr , '' ) ;
767 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
768 else if ( '|}' == substr ( $x , 0 , 2 ) )
770 $z = "</table>\n" ;
771 $l = array_pop ( $ltd ) ;
772 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
773 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
774 array_pop ( $ltr ) ;
775 $t[$k] = $z . str_repeat( "</dd></dl>", $indent_level );
777 else if ( '|-' == substr ( $x , 0 , 2 ) ) # Allows for |---------------
779 $x = substr ( $x , 1 ) ;
780 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
781 $z = '' ;
782 $l = array_pop ( $ltd ) ;
783 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
784 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
785 array_pop ( $ltr ) ;
786 $t[$k] = $z ;
787 array_push ( $tr , false ) ;
788 array_push ( $td , false ) ;
789 array_push ( $ltd , '' ) ;
790 array_push ( $ltr , $this->fixTagAttributes ( $x ) ) ;
792 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) # Caption
794 if ( '|+' == substr ( $x , 0 , 2 ) )
796 $fc = '+' ;
797 $x = substr ( $x , 1 ) ;
799 $after = substr ( $x , 1 ) ;
800 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
801 $after = explode ( '||' , $after ) ;
802 $t[$k] = '' ;
803 foreach ( $after AS $theline )
805 $z = '' ;
806 if ( $fc != '+' )
808 $tra = array_pop ( $ltr ) ;
809 if ( !array_pop ( $tr ) ) $z = "<tr {$tra}>\n" ;
810 array_push ( $tr , true ) ;
811 array_push ( $ltr , '' ) ;
814 $l = array_pop ( $ltd ) ;
815 if ( array_pop ( $td ) ) $z = "</{$l}>" . $z ;
816 if ( $fc == '|' ) $l = 'td' ;
817 else if ( $fc == '!' ) $l = 'th' ;
818 else if ( $fc == '+' ) $l = 'caption' ;
819 else $l = '' ;
820 array_push ( $ltd , $l ) ;
821 $y = explode ( '|' , $theline , 2 ) ;
822 if ( count ( $y ) == 1 ) $y = "{$z}<{$l}>{$y[0]}" ;
823 else $y = $y = "{$z}<{$l} ".$this->fixTagAttributes($y[0]).">{$y[1]}" ;
824 $t[$k] .= $y ;
825 array_push ( $td , true ) ;
830 # Closing open td, tr && table
831 while ( count ( $td ) > 0 )
833 if ( array_pop ( $td ) ) $t[] = '</td>' ;
834 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
835 $t[] = '</table>' ;
838 $t = implode ( "\n" , $t ) ;
839 # $t = $this->removeHTMLtags( $t );
840 wfProfileOut( $fname );
841 return $t ;
844 # Parses the text and adds the result to the strip state
845 # Returns the strip tag
846 function stripParse( $text, $newline, $args )
848 $text = $this->strip( $text, $this->mStripState );
849 $text = $this->internalParse( $text, (bool)$newline, $args, false );
850 return $newline.$this->insertStripItem( $text, $this->mStripState );
853 function internalParse( $text, $linestart, $args = array(), $isMain=true ) {
854 $fname = 'Parser::internalParse';
855 wfProfileIn( $fname );
857 $text = $this->removeHTMLtags( $text );
858 $text = $this->replaceVariables( $text, $args );
860 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
862 $text = $this->doHeadings( $text );
863 if($this->mOptions->getUseDynamicDates()) {
864 global $wgDateFormatter;
865 $text = $wgDateFormatter->reformat( $this->mOptions->getDateFormat(), $text );
867 $text = $this->doAllQuotes( $text );
868 $text = $this->replaceExternalLinks( $text );
869 $text = $this->doMagicLinks( $text );
870 $text = $this->replaceInternalLinks ( $text );
871 $text = $this->replaceInternalLinks ( $text );
873 $text = $this->unstrip( $text, $this->mStripState );
874 $text = $this->unstripNoWiki( $text, $this->mStripState );
876 $text = $this->doTableStuff( $text );
877 $text = $this->formatHeadings( $text, $isMain );
878 $sk =& $this->mOptions->getSkin();
879 $text = $sk->transformContent( $text );
881 if ( $isMain && !isset ( $this->categoryMagicDone ) ) {
882 $text .= $this->categoryMagic () ;
883 $this->categoryMagicDone = true ;
886 wfProfileOut( $fname );
887 return $text;
890 /* private */ function &doMagicLinks( &$text ) {
891 $text = $this->magicISBN( $text );
892 $text = $this->magicGEO( $text );
893 $text = $this->magicRFC( $text );
894 return $text;
897 # Parse ^^ tokens and return html
898 /* private */ function doExponent ( $text )
900 $fname = 'Parser::doExponent';
901 wfProfileIn( $fname);
902 $text = preg_replace('/\^\^(.*)\^\^/','<small><sup>\\1</sup></small>', $text);
903 wfProfileOut( $fname);
904 return $text;
907 # Parse headers and return html
908 /* private */ function doHeadings( $text ) {
909 $fname = 'Parser::doHeadings';
910 wfProfileIn( $fname );
911 for ( $i = 6; $i >= 1; --$i ) {
912 $h = substr( '======', 0, $i );
913 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
914 "<h{$i}>\\1</h{$i}>\\2", $text );
916 wfProfileOut( $fname );
917 return $text;
920 /* private */ function doAllQuotes( $text ) {
921 $fname = 'Parser::doAllQuotes';
922 wfProfileIn( $fname );
923 $outtext = '';
924 $lines = explode( "\n", $text );
925 foreach ( $lines as $line ) {
926 $outtext .= $this->doQuotes ( $line ) . "\n";
928 $outtext = substr($outtext, 0,-1);
929 wfProfileOut( $fname );
930 return $outtext;
933 /* private */ function doQuotes( $text ) {
934 $arr = preg_split ("/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
935 if (count ($arr) == 1)
936 return $text;
937 else
939 # First, do some preliminary work. This may shift some apostrophes from
940 # being mark-up to being text. It also counts the number of occurrences
941 # of bold and italics mark-ups.
942 $i = 0;
943 $numbold = 0;
944 $numitalics = 0;
945 foreach ($arr as $r)
947 if (($i % 2) == 1)
949 # If there are ever four apostrophes, assume the first is supposed to
950 # be text, and the remaining three constitute mark-up for bold text.
951 if (strlen ($arr[$i]) == 4)
953 $arr[$i-1] .= "'";
954 $arr[$i] = "'''";
956 # If there are more than 5 apostrophes in a row, assume they're all
957 # text except for the last 5.
958 else if (strlen ($arr[$i]) > 5)
960 $arr[$i-1] .= str_repeat ("'", strlen ($arr[$i]) - 5);
961 $arr[$i] = "'''''";
963 # Count the number of occurrences of bold and italics mark-ups.
964 # We are not counting sequences of five apostrophes.
965 if (strlen ($arr[$i]) == 2) $numitalics++; else
966 if (strlen ($arr[$i]) == 3) $numbold++;
968 $i++;
971 # If there is an odd number of both bold and italics, it is likely
972 # that one of the bold ones was meant to be an apostrophe followed
973 # by italics. Which one we cannot know for certain, but it is more
974 # likely to be one that has a single-letter word before it.
975 if (($numbold % 2 == 1) && ($numitalics % 2 == 1))
977 $i = 0;
978 $firstsingleletterword = -1;
979 $firstmultiletterword = -1;
980 $firstspace = -1;
981 foreach ($arr as $r)
983 if (($i % 2 == 1) and (strlen ($r) == 3))
985 $x1 = substr ($arr[$i-1], -1);
986 $x2 = substr ($arr[$i-1], -2, 1);
987 if ($x1 == " ") {
988 if ($firstspace == -1) $firstspace = $i;
989 } else if ($x2 == " ") {
990 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
991 } else {
992 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
995 $i++;
998 # If there is a single-letter word, use it!
999 if ($firstsingleletterword > -1)
1001 $arr [ $firstsingleletterword ] = "''";
1002 $arr [ $firstsingleletterword-1 ] .= "'";
1004 # If not, but there's a multi-letter word, use that one.
1005 else if ($firstmultiletterword > -1)
1007 $arr [ $firstmultiletterword ] = "''";
1008 $arr [ $firstmultiletterword-1 ] .= "'";
1010 # ... otherwise use the first one that has neither.
1011 else
1013 $arr [ $firstspace ] = "''";
1014 $arr [ $firstspace-1 ] .= "'";
1018 # Now let's actually convert our apostrophic mush to HTML!
1019 $output = '';
1020 $buffer = '';
1021 $state = '';
1022 $i = 0;
1023 foreach ($arr as $r)
1025 if (($i % 2) == 0)
1027 if ($state == 'both')
1028 $buffer .= $r;
1029 else
1030 $output .= $r;
1032 else
1034 if (strlen ($r) == 2)
1036 if ($state == 'em')
1037 { $output .= "</em>"; $state = ''; }
1038 else if ($state == 'strongem')
1039 { $output .= "</em>"; $state = 'strong'; }
1040 else if ($state == 'emstrong')
1041 { $output .= "</strong></em><strong>"; $state = 'strong'; }
1042 else if ($state == 'both')
1043 { $output .= "<strong><em>{$buffer}</em>"; $state = 'strong'; }
1044 else # $state can be 'strong' or ''
1045 { $output .= "<em>"; $state .= 'em'; }
1047 else if (strlen ($r) == 3)
1049 if ($state == 'strong')
1050 { $output .= "</strong>"; $state = ''; }
1051 else if ($state == 'strongem')
1052 { $output .= "</em></strong><em>"; $state = 'em'; }
1053 else if ($state == 'emstrong')
1054 { $output .= "</strong>"; $state = 'em'; }
1055 else if ($state == 'both')
1056 { $output .= "<em><strong>{$buffer}</strong>"; $state = 'em'; }
1057 else # $state can be 'em' or ''
1058 { $output .= "<strong>"; $state .= 'strong'; }
1060 else if (strlen ($r) == 5)
1062 if ($state == 'strong')
1063 { $output .= "</strong><em>"; $state = 'em'; }
1064 else if ($state == 'em')
1065 { $output .= "</em><strong>"; $state = 'strong'; }
1066 else if ($state == 'strongem')
1067 { $output .= "</em></strong>"; $state = ''; }
1068 else if ($state == 'emstrong')
1069 { $output .= "</strong></em>"; $state = ''; }
1070 else if ($state == 'both')
1071 { $output .= "<em><strong>{$buffer}</strong></em>"; $state = ''; }
1072 else # ($state == '')
1073 { $buffer = ''; $state = 'both'; }
1076 $i++;
1078 # Now close all remaining tags. Notice that the order is important.
1079 if ($state == 'strong' || $state == 'emstrong')
1080 $output .= "</strong>";
1081 if ($state == 'em' || $state == 'strongem' || $state == 'emstrong')
1082 $output .= "</em>";
1083 if ($state == 'strongem')
1084 $output .= "</strong>";
1085 if ($state == 'both')
1086 $output .= "<strong><em>{$buffer}</em></strong>";
1087 return $output;
1091 # Note: we have to do external links before the internal ones,
1092 # and otherwise take great care in the order of things here, so
1093 # that we don't end up interpreting some URLs twice.
1095 /* private */ function replaceExternalLinks( $text ) {
1096 $fname = 'Parser::replaceExternalLinks';
1097 wfProfileIn( $fname );
1099 $sk =& $this->mOptions->getSkin();
1100 $linktrail = wfMsg('linktrail');
1101 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1103 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1105 $i = 0;
1106 while ( $i<count( $bits ) ) {
1107 $url = $bits[$i++];
1108 $protocol = $bits[$i++];
1109 $text = $bits[$i++];
1110 $trail = $bits[$i++];
1112 # If the link text is an image URL, replace it with an <img> tag
1113 # This happened by accident in the original parser, but some people used it extensively
1114 $img = $this->maybeMakeImageLink( $text );
1115 if ( $img !== false ) {
1116 $text = $img;
1119 $dtrail = '';
1121 # No link text, e.g. [http://domain.tld/some.link]
1122 if ( $text == '' ) {
1123 # Autonumber if allowed
1124 if ( strpos( HTTP_PROTOCOLS, $protocol ) !== false ) {
1125 $text = "[" . ++$this->mAutonumber . "]";
1126 } else {
1127 # Otherwise just use the URL
1128 $text = htmlspecialchars( $url );
1130 } else {
1131 # Have link text, e.g. [http://domain.tld/some.link text]s
1132 # Check for trail
1133 if ( preg_match( $linktrail, $trail, $m2 ) ) {
1134 $dtrail = $m2[1];
1135 $trail = $m2[2];
1139 $encUrl = htmlspecialchars( $url );
1140 # Bit in parentheses showing the URL for the printable version
1141 if( $url == $text || preg_match( "!$protocol://" . preg_quote( $text, "/" ) . "/?$!", $url ) ) {
1142 $paren = '';
1143 } else {
1144 # Expand the URL for printable version
1145 $paren = "<span class='urlexpansion'> (<i>" . htmlspecialchars ( $encUrl ) . "</i>)</span>";
1148 # Process the trail (i.e. everything after this link up until start of the next link),
1149 # replacing any non-bracketed links
1150 $trail = $this->replaceFreeExternalLinks( $trail );
1152 $la = $sk->getExternalLinkAttributes( $url, $text );
1154 # Use the encoded URL
1155 # This means that users can paste URLs directly into the text
1156 # Funny characters like &ouml; aren't valid in URLs anyway
1157 # This was changed in August 2004
1158 $s .= "<a href=\"{$url}\" {$la}>{$text}</a>{$dtrail}{$paren}{$trail}";
1161 wfProfileOut( $fname );
1162 return $s;
1165 # Replace anything that looks like a URL with a link
1166 function replaceFreeExternalLinks( $text ) {
1167 $bits = preg_split( '/((?:'.URL_PROTOCOLS.'):)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1168 $s = array_shift( $bits );
1169 $i = 0;
1171 $sk =& $this->mOptions->getSkin();
1173 while ( $i < count( $bits ) ){
1174 $protocol = $bits[$i++];
1175 $remainder = $bits[$i++];
1177 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1178 # Found some characters after the protocol that look promising
1179 $url = $protocol . $m[1];
1180 $trail = $m[2];
1182 # Move trailing punctuation to $trail
1183 $sep = ',;\.:!?';
1184 # If there is no left bracket, then consider right brackets fair game too
1185 if ( strpos( $url, '(' ) === false ) {
1186 $sep .= ')';
1189 $numSepChars = strspn( strrev( $url ), $sep );
1190 if ( $numSepChars ) {
1191 $trail = substr( $url, -$numSepChars ) . $trail;
1192 $url = substr( $url, 0, -$numSepChars );
1195 # Replace &amp; from obsolete syntax with &
1196 $url = str_replace( '&amp;', '&', $url );
1198 # Is this an external image?
1199 $text = $this->maybeMakeImageLink( $url );
1200 if ( $text === false ) {
1201 # Not an image, make a link
1202 $text = $sk->makeExternalLink( $url, $url );
1204 $s .= $text . $trail;
1205 } else {
1206 $s .= $protocol . $remainder;
1209 return $s;
1212 function maybeMakeImageLink( $url ) {
1213 $sk =& $this->mOptions->getSkin();
1214 $text = false;
1215 if ( $this->mOptions->getAllowExternalImages() ) {
1216 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1217 # Image found
1218 $text = $sk->makeImage( htmlspecialchars( $url ) );
1221 return $text;
1224 /* private */ function replaceInternalLinks( $s ) {
1225 global $wgLang, $wgLinkCache;
1226 global $wgNamespacesWithSubpages, $wgLanguageCode;
1227 static $fname = 'Parser::replaceInternalLinks' ;
1228 wfProfileIn( $fname );
1230 wfProfileIn( $fname.'-setup' );
1231 static $tc = FALSE;
1232 # the % is needed to support urlencoded titles as well
1233 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1234 $sk =& $this->mOptions->getSkin();
1236 $redirect = MagicWord::get ( MAG_REDIRECT ) ;
1238 $a = explode( '[[', ' ' . $s );
1239 $s = array_shift( $a );
1240 $s = substr( $s, 1 );
1242 # Match a link having the form [[namespace:link|alternate]]trail
1243 static $e1 = FALSE;
1244 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|([^]]+))?]](.*)\$/sD"; }
1245 # Match the end of a line for a word that's not followed by whitespace,
1246 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1247 static $e2 = '/^(.*?)([a-zA-Z\x80-\xff]+)$/sD';
1249 $useLinkPrefixExtension = $wgLang->linkPrefixExtension();
1250 # Special and Media are pseudo-namespaces; no pages actually exist in them
1252 $nottalk = !Namespace::isTalk( $this->mTitle->getNamespace() );
1254 if ( $useLinkPrefixExtension ) {
1255 if ( preg_match( $e2, $s, $m ) ) {
1256 $first_prefix = $m[2];
1257 $s = $m[1];
1258 } else {
1259 $first_prefix = false;
1261 } else {
1262 $prefix = '';
1265 wfProfileOut( $fname.'-setup' );
1267 foreach ( $a as $line ) {
1268 wfProfileIn( $fname.'-prefixhandling' );
1269 if ( $useLinkPrefixExtension ) {
1270 if ( preg_match( $e2, $s, $m ) ) {
1271 $prefix = $m[2];
1272 $s = $m[1];
1273 } else {
1274 $prefix='';
1276 # first link
1277 if($first_prefix) {
1278 $prefix = $first_prefix;
1279 $first_prefix = false;
1282 wfProfileOut( $fname.'-prefixhandling' );
1284 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1285 $text = $m[2];
1286 # fix up urlencoded title texts
1287 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1288 $trail = $m[3];
1289 } else { # Invalid form; output directly
1290 $s .= $prefix . '[[' . $line ;
1291 continue;
1294 /* Valid link forms:
1295 Foobar -- normal
1296 :Foobar -- override special treatment of prefix (images, language links)
1297 /Foobar -- convert to CurrentPage/Foobar
1298 /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1300 $c = substr($m[1],0,1);
1301 $noforce = ($c != ':');
1302 if( $c == '/' ) { # subpage
1303 if(substr($m[1],-1,1)=='/') { # / at end means we don't want the slash to be shown
1304 $m[1]=substr($m[1],1,strlen($m[1])-2);
1305 $noslash=$m[1];
1306 } else {
1307 $noslash=substr($m[1],1);
1309 if(!empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()])) { # subpages allowed here
1310 $link = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1311 if( '' == $text ) {
1312 $text= $m[1];
1313 } # this might be changed for ugliness reasons
1314 } else {
1315 $link = $noslash; # no subpage allowed, use standard link
1317 } elseif( $noforce ) { # no subpage
1318 $link = $m[1];
1319 } else {
1320 $link = substr( $m[1], 1 );
1322 $wasblank = ( '' == $text );
1323 if( $wasblank )
1324 $text = $link;
1326 $nt = Title::newFromText( $link );
1327 if( !$nt ) {
1328 $s .= $prefix . '[[' . $line;
1329 continue;
1331 $ns = $nt->getNamespace();
1332 $iw = $nt->getInterWiki();
1333 if( $noforce ) {
1334 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgLang->getLanguageName( $iw ) ) {
1335 array_push( $this->mOutput->mLanguageLinks, $nt->getFullText() );
1336 $tmp = $prefix . $trail ;
1337 $s .= (trim($tmp) == '')? '': $tmp;
1338 continue;
1340 if ( $ns == NS_IMAGE ) {
1341 $s .= $prefix . $sk->makeImageLinkObj( $nt, $text ) . $trail;
1342 $wgLinkCache->addImageLinkObj( $nt );
1343 continue;
1345 if ( $ns == NS_CATEGORY ) {
1346 $t = $nt->getText() ;
1347 $nnt = Title::newFromText ( Namespace::getCanonicalName(NS_CATEGORY).":".$t ) ;
1349 $wgLinkCache->suspend(); # Don't save in links/brokenlinks
1350 $pPLC=$sk->postParseLinkColour();
1351 $sk->postParseLinkColour( false );
1352 $t = $sk->makeLinkObj( $nnt, $t, '', '' , $prefix );
1353 $sk->postParseLinkColour( $pPLC );
1354 $wgLinkCache->resume();
1356 $sortkey = $wasblank ? $this->mTitle->getPrefixedText() : $text;
1357 $wgLinkCache->addCategoryLinkObj( $nt, $sortkey );
1358 $this->mOutput->mCategoryLinks[] = $t ;
1359 $s .= $prefix . $trail ;
1360 continue;
1363 if( ( $nt->getPrefixedText() == $this->mTitle->getPrefixedText() ) &&
1364 ( strpos( $link, '#' ) == FALSE ) ) {
1365 # Self-links are handled specially; generally de-link and change to bold.
1366 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1367 continue;
1370 if( $ns == NS_MEDIA ) {
1371 $s .= $prefix . $sk->makeMediaLinkObj( $nt, $text ) . $trail;
1372 $wgLinkCache->addImageLinkObj( $nt );
1373 continue;
1374 } elseif( $ns == NS_SPECIAL ) {
1375 $s .= $prefix . $sk->makeKnownLinkObj( $nt, $text, '', $trail );
1376 continue;
1378 $s .= $sk->makeLinkObj( $nt, $text, '', $trail, $prefix );
1380 wfProfileOut( $fname );
1381 return $s;
1384 # Some functions here used by doBlockLevels()
1386 /* private */ function closeParagraph() {
1387 $result = '';
1388 if ( '' != $this->mLastSection ) {
1389 $result = '</' . $this->mLastSection . ">\n";
1391 $this->mInPre = false;
1392 $this->mLastSection = '';
1393 return $result;
1395 # getCommon() returns the length of the longest common substring
1396 # of both arguments, starting at the beginning of both.
1398 /* private */ function getCommon( $st1, $st2 ) {
1399 $fl = strlen( $st1 );
1400 $shorter = strlen( $st2 );
1401 if ( $fl < $shorter ) { $shorter = $fl; }
1403 for ( $i = 0; $i < $shorter; ++$i ) {
1404 if ( $st1{$i} != $st2{$i} ) { break; }
1406 return $i;
1408 # These next three functions open, continue, and close the list
1409 # element appropriate to the prefix character passed into them.
1411 /* private */ function openList( $char )
1413 $result = $this->closeParagraph();
1415 if ( '*' == $char ) { $result .= '<ul><li>'; }
1416 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1417 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1418 else if ( ';' == $char ) {
1419 $result .= '<dl><dt>';
1420 $this->mDTopen = true;
1422 else { $result = '<!-- ERR 1 -->'; }
1424 return $result;
1427 /* private */ function nextItem( $char ) {
1428 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1429 else if ( ':' == $char || ';' == $char ) {
1430 $close = "</dd>";
1431 if ( $this->mDTopen ) { $close = '</dt>'; }
1432 if ( ';' == $char ) {
1433 $this->mDTopen = true;
1434 return $close . '<dt>';
1435 } else {
1436 $this->mDTopen = false;
1437 return $close . '<dd>';
1440 return '<!-- ERR 2 -->';
1443 /* private */function closeList( $char ) {
1444 if ( '*' == $char ) { $text = '</li></ul>'; }
1445 else if ( '#' == $char ) { $text = '</li></ol>'; }
1446 else if ( ':' == $char ) {
1447 if ( $this->mDTopen ) {
1448 $this->mDTopen = false;
1449 $text = '</dt></dl>';
1450 } else {
1451 $text = '</dd></dl>';
1454 else { return '<!-- ERR 3 -->'; }
1455 return $text."\n";
1458 /* private */ function doBlockLevels( $text, $linestart ) {
1459 $fname = 'Parser::doBlockLevels';
1460 wfProfileIn( $fname );
1462 # Parsing through the text line by line. The main thing
1463 # happening here is handling of block-level elements p, pre,
1464 # and making lists from lines starting with * # : etc.
1466 $textLines = explode( "\n", $text );
1468 $lastPrefix = $output = $lastLine = '';
1469 $this->mDTopen = $inBlockElem = false;
1470 $prefixLength = 0;
1471 $paragraphStack = false;
1473 if ( !$linestart ) {
1474 $output .= array_shift( $textLines );
1476 foreach ( $textLines as $oLine ) {
1477 $lastPrefixLength = strlen( $lastPrefix );
1478 $preCloseMatch = preg_match("/<\\/pre/i", $oLine );
1479 $preOpenMatch = preg_match("/<pre/i", $oLine );
1480 if ( !$this->mInPre ) {
1481 # Multiple prefixes may abut each other for nested lists.
1482 $prefixLength = strspn( $oLine, '*#:;' );
1483 $pref = substr( $oLine, 0, $prefixLength );
1485 # eh?
1486 $pref2 = str_replace( ';', ':', $pref );
1487 $t = substr( $oLine, $prefixLength );
1488 $this->mInPre = !empty($preOpenMatch);
1489 } else {
1490 # Don't interpret any other prefixes in preformatted text
1491 $prefixLength = 0;
1492 $pref = $pref2 = '';
1493 $t = $oLine;
1496 # List generation
1497 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1498 # Same as the last item, so no need to deal with nesting or opening stuff
1499 $output .= $this->nextItem( substr( $pref, -1 ) );
1500 $paragraphStack = false;
1502 if ( ";" == substr( $pref, -1 ) ) {
1503 # The one nasty exception: definition lists work like this:
1504 # ; title : definition text
1505 # So we check for : in the remainder text to split up the
1506 # title and definition, without b0rking links.
1507 # FIXME: This is not foolproof. Something better in Tokenizer might help.
1508 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1509 $term = $match[1];
1510 $output .= $term . $this->nextItem( ':' );
1511 $t = $match[2];
1514 } elseif( $prefixLength || $lastPrefixLength ) {
1515 # Either open or close a level...
1516 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1517 $paragraphStack = false;
1519 while( $commonPrefixLength < $lastPrefixLength ) {
1520 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1521 --$lastPrefixLength;
1523 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1524 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1526 while ( $prefixLength > $commonPrefixLength ) {
1527 $char = substr( $pref, $commonPrefixLength, 1 );
1528 $output .= $this->openList( $char );
1530 if ( ';' == $char ) {
1531 # FIXME: This is dupe of code above
1532 if( preg_match( '/^(.*?(?:\s|&nbsp;)):(.*)$/', $t, $match ) ) {
1533 $term = $match[1];
1534 $output .= $term . $this->nextItem( ":" );
1535 $t = $match[2];
1538 ++$commonPrefixLength;
1540 $lastPrefix = $pref2;
1542 if( 0 == $prefixLength ) {
1543 # No prefix (not in list)--go to paragraph mode
1544 $uniq_prefix = UNIQ_PREFIX;
1545 // XXX: use a stack for nestable elements like span, table and div
1546 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/i', $t );
1547 $closematch = preg_match(
1548 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1549 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$uniq_prefix.'-pre|<\\/li|<\\/ul)/i', $t );
1550 if ( $openmatch or $closematch ) {
1551 $paragraphStack = false;
1552 $output .= $this->closeParagraph();
1553 if($preOpenMatch and !$preCloseMatch) {
1554 $this->mInPre = true;
1556 if ( $closematch ) {
1557 $inBlockElem = false;
1558 } else {
1559 $inBlockElem = true;
1561 } else if ( !$inBlockElem && !$this->mInPre ) {
1562 if ( " " == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1563 // pre
1564 if ($this->mLastSection != 'pre') {
1565 $paragraphStack = false;
1566 $output .= $this->closeParagraph().'<pre>';
1567 $this->mLastSection = 'pre';
1569 } else {
1570 // paragraph
1571 if ( '' == trim($t) ) {
1572 if ( $paragraphStack ) {
1573 $output .= $paragraphStack.'<br />';
1574 $paragraphStack = false;
1575 $this->mLastSection = 'p';
1576 } else {
1577 if ($this->mLastSection != 'p' ) {
1578 $output .= $this->closeParagraph();
1579 $this->mLastSection = '';
1580 $paragraphStack = '<p>';
1581 } else {
1582 $paragraphStack = '</p><p>';
1585 } else {
1586 if ( $paragraphStack ) {
1587 $output .= $paragraphStack;
1588 $paragraphStack = false;
1589 $this->mLastSection = 'p';
1590 } else if ($this->mLastSection != 'p') {
1591 $output .= $this->closeParagraph().'<p>';
1592 $this->mLastSection = 'p';
1598 if ($paragraphStack === false) {
1599 $output .= $t."\n";
1602 while ( $prefixLength ) {
1603 $output .= $this->closeList( $pref2{$prefixLength-1} );
1604 --$prefixLength;
1606 if ( '' != $this->mLastSection ) {
1607 $output .= '</' . $this->mLastSection . '>';
1608 $this->mLastSection = '';
1611 wfProfileOut( $fname );
1612 return $output;
1615 # Return value of a magic variable (like PAGENAME)
1616 function getVariableValue( $index ) {
1617 global $wgLang, $wgSitename, $wgServer;
1619 switch ( $index ) {
1620 case MAG_CURRENTMONTH:
1621 return $wgLang->formatNum( date( 'm' ) );
1622 case MAG_CURRENTMONTHNAME:
1623 return $wgLang->getMonthName( date('n') );
1624 case MAG_CURRENTMONTHNAMEGEN:
1625 return $wgLang->getMonthNameGen( date('n') );
1626 case MAG_CURRENTDAY:
1627 return $wgLang->formatNum( date('j') );
1628 case MAG_PAGENAME:
1629 return $this->mTitle->getText();
1630 case MAG_PAGENAMEE:
1631 return $this->mTitle->getPartialURL();
1632 case MAG_NAMESPACE:
1633 # return Namespace::getCanonicalName($this->mTitle->getNamespace());
1634 return $wgLang->getNsText($this->mTitle->getNamespace()); // Patch by Dori
1635 case MAG_CURRENTDAYNAME:
1636 return $wgLang->getWeekdayName( date('w')+1 );
1637 case MAG_CURRENTYEAR:
1638 return $wgLang->formatNum( date( 'Y' ) );
1639 case MAG_CURRENTTIME:
1640 return $wgLang->time( wfTimestampNow(), false );
1641 case MAG_NUMBEROFARTICLES:
1642 return $wgLang->formatNum( wfNumberOfArticles() );
1643 case MAG_SITENAME:
1644 return $wgSitename;
1645 case MAG_SERVER:
1646 return $wgServer;
1647 default:
1648 return NULL;
1652 # initialise the magic variables (like CURRENTMONTHNAME)
1653 function initialiseVariables() {
1654 global $wgVariableIDs;
1655 $this->mVariables = array();
1656 foreach ( $wgVariableIDs as $id ) {
1657 $mw =& MagicWord::get( $id );
1658 $mw->addToArray( $this->mVariables, $this->getVariableValue( $id ) );
1662 /* private */ function replaceVariables( $text, $args = array() ) {
1663 global $wgLang, $wgScript, $wgArticlePath;
1665 # Prevent too big inclusions
1666 if(strlen($text)> MAX_INCLUDE_SIZE)
1667 return $text;
1669 $fname = 'Parser::replaceVariables';
1670 wfProfileIn( $fname );
1672 $bail = false;
1673 $titleChars = Title::legalChars();
1674 $nonBraceChars = str_replace( array( '{', '}' ), array( '', '' ), $titleChars );
1676 # This function is called recursively. To keep track of arguments we need a stack:
1677 array_push( $this->mArgStack, $args );
1679 # PHP global rebinding syntax is a bit weird, need to use the GLOBALS array
1680 $GLOBALS['wgCurParser'] =& $this;
1683 if ( $this->mOutputType == OT_HTML ) {
1684 # Variable substitution
1685 $text = preg_replace_callback( "/{{([$nonBraceChars]*?)}}/", 'wfVariableSubstitution', $text );
1687 # Argument substitution
1688 $text = preg_replace_callback( "/(\\n?){{{([$titleChars]*?)}}}/", 'wfArgSubstitution', $text );
1690 # Template substitution
1691 $regex = '/(\\n?){{(['.$nonBraceChars.']*)(\\|.*?|)}}/s';
1692 $text = preg_replace_callback( $regex, 'wfBraceSubstitution', $text );
1694 array_pop( $this->mArgStack );
1696 wfProfileOut( $fname );
1697 return $text;
1700 function variableSubstitution( $matches ) {
1701 if ( !$this->mVariables ) {
1702 $this->initialiseVariables();
1704 if ( array_key_exists( $matches[1], $this->mVariables ) ) {
1705 $text = $this->mVariables[$matches[1]];
1706 $this->mOutput->mContainsOldMagic = true;
1707 } else {
1708 $text = $matches[0];
1710 return $text;
1713 # Split template arguments
1714 function getTemplateArgs( $argsString ) {
1715 if ( $argsString === '' ) {
1716 return array();
1719 $args = explode( '|', substr( $argsString, 1 ) );
1721 # If any of the arguments contains a '[[' but no ']]', it needs to be
1722 # merged with the next arg because the '|' character between belongs
1723 # to the link syntax and not the template parameter syntax.
1724 $argc = count($args);
1725 $i = 0;
1726 for ( $i = 0; $i < $argc-1; $i++ ) {
1727 if ( substr_count ( $args[$i], "[[" ) != substr_count ( $args[$i], "]]" ) ) {
1728 $args[$i] .= "|".$args[$i+1];
1729 array_splice($args, $i+1, 1);
1730 $i--;
1731 $argc--;
1735 return $args;
1738 function braceSubstitution( $matches ) {
1739 global $wgLinkCache, $wgLang;
1740 $fname = 'Parser::braceSubstitution';
1741 $found = false;
1742 $nowiki = false;
1743 $noparse = false;
1745 $title = NULL;
1747 # $newline is an optional newline character before the braces
1748 # $part1 is the bit before the first |, and must contain only title characters
1749 # $args is a list of arguments, starting from index 0, not including $part1
1751 $newline = $matches[1];
1752 $part1 = $matches[2];
1753 # If the third subpattern matched anything, it will start with |
1755 $args = $this->getTemplateArgs($matches[3]);
1756 $argc = count( $args );
1758 # {{{}}}
1759 if ( strpos( $matches[0], '{{{' ) !== false ) {
1760 $text = $matches[0];
1761 $found = true;
1762 $noparse = true;
1765 # SUBST
1766 if ( !$found ) {
1767 $mwSubst =& MagicWord::get( MAG_SUBST );
1768 if ( $mwSubst->matchStartAndRemove( $part1 ) ) {
1769 if ( $this->mOutputType != OT_WIKI ) {
1770 # Invalid SUBST not replaced at PST time
1771 # Return without further processing
1772 $text = $matches[0];
1773 $found = true;
1774 $noparse= true;
1776 } elseif ( $this->mOutputType == OT_WIKI ) {
1777 # SUBST not found in PST pass, do nothing
1778 $text = $matches[0];
1779 $found = true;
1783 # MSG, MSGNW and INT
1784 if ( !$found ) {
1785 # Check for MSGNW:
1786 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
1787 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
1788 $nowiki = true;
1789 } else {
1790 # Remove obsolete MSG:
1791 $mwMsg =& MagicWord::get( MAG_MSG );
1792 $mwMsg->matchStartAndRemove( $part1 );
1795 # Check if it is an internal message
1796 $mwInt =& MagicWord::get( MAG_INT );
1797 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
1798 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
1799 $text = wfMsgReal( $part1, $args, true );
1800 $found = true;
1805 # NS
1806 if ( !$found ) {
1807 # Check for NS: (namespace expansion)
1808 $mwNs = MagicWord::get( MAG_NS );
1809 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
1810 if ( intval( $part1 ) ) {
1811 $text = $wgLang->getNsText( intval( $part1 ) );
1812 $found = true;
1813 } else {
1814 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
1815 if ( !is_null( $index ) ) {
1816 $text = $wgLang->getNsText( $index );
1817 $found = true;
1823 # LOCALURL and LOCALURLE
1824 if ( !$found ) {
1825 $mwLocal = MagicWord::get( MAG_LOCALURL );
1826 $mwLocalE = MagicWord::get( MAG_LOCALURLE );
1828 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
1829 $func = 'getLocalURL';
1830 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
1831 $func = 'escapeLocalURL';
1832 } else {
1833 $func = '';
1836 if ( $func !== '' ) {
1837 $title = Title::newFromText( $part1 );
1838 if ( !is_null( $title ) ) {
1839 if ( $argc > 0 ) {
1840 $text = $title->$func( $args[0] );
1841 } else {
1842 $text = $title->$func();
1844 $found = true;
1849 # Internal variables
1850 if ( !$this->mVariables ) {
1851 $this->initialiseVariables();
1853 if ( !$found && array_key_exists( $part1, $this->mVariables ) ) {
1854 $text = $this->mVariables[$part1];
1855 $found = true;
1856 $this->mOutput->mContainsOldMagic = true;
1859 # Template table test
1861 # Did we encounter this template already? If yes, it is in the cache
1862 # and we need to check for loops.
1863 if ( isset( $this->mTemplates[$part1] ) ) {
1864 # Infinite loop test
1865 if ( isset( $this->mTemplatePath[$part1] ) ) {
1866 $noparse = true;
1867 $found = true;
1869 # set $text to cached message.
1870 $text = $this->mTemplates[$part1];
1871 $found = true;
1874 # Load from database
1875 if ( !$found ) {
1876 $title = Title::newFromText( $part1, NS_TEMPLATE );
1877 if ( !is_null( $title ) && !$title->isExternal() ) {
1878 # Check for excessive inclusion
1879 $dbk = $title->getPrefixedDBkey();
1880 if ( $this->incrementIncludeCount( $dbk ) ) {
1881 # This should never be reached.
1882 $article = new Article( $title );
1883 $articleContent = $article->getContentWithoutUsingSoManyDamnGlobals();
1884 if ( $articleContent !== false ) {
1885 $found = true;
1886 $text = $articleContent;
1891 # If the title is valid but undisplayable, make a link to it
1892 if ( $this->mOutputType == OT_HTML && !$found ) {
1893 $text = '[[' . $title->getPrefixedText() . ']]';
1894 $found = true;
1897 # Template cache array insertion
1898 $this->mTemplates[$part1] = $text;
1902 # Recursive parsing, escaping and link table handling
1903 # Only for HTML output
1904 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
1905 $text = wfEscapeWikiText( $text );
1906 } elseif ( $this->mOutputType == OT_HTML && $found && !$noparse) {
1907 # Clean up argument array
1908 $assocArgs = array();
1909 $index = 1;
1910 foreach( $args as $arg ) {
1911 $eqpos = strpos( $arg, '=' );
1912 if ( $eqpos === false ) {
1913 $assocArgs[$index++] = $arg;
1914 } else {
1915 $name = trim( substr( $arg, 0, $eqpos ) );
1916 $value = trim( substr( $arg, $eqpos+1 ) );
1917 if ( $value === false ) {
1918 $value = '';
1920 if ( $name !== false ) {
1921 $assocArgs[$name] = $value;
1926 # Do not enter included links in link table
1927 if ( !is_null( $title ) ) {
1928 $wgLinkCache->suspend();
1931 # Add a new element to the templace recursion path
1932 $this->mTemplatePath[$part1] = 1;
1934 $text = $this->stripParse( $text, $newline, $assocArgs );
1936 # Resume the link cache and register the inclusion as a link
1937 if ( !is_null( $title ) ) {
1938 $wgLinkCache->resume();
1939 $wgLinkCache->addLinkObj( $title );
1942 # Empties the template path
1943 $this->mTemplatePath = array();
1945 if ( !$found ) {
1946 return $matches[0];
1947 } else {
1948 return $text;
1952 # Triple brace replacement -- used for template arguments
1953 function argSubstitution( $matches ) {
1954 $newline = $matches[1];
1955 $arg = trim( $matches[2] );
1956 $text = $matches[0];
1957 $inputArgs = end( $this->mArgStack );
1959 if ( array_key_exists( $arg, $inputArgs ) ) {
1960 $text = $this->stripParse( $inputArgs[$arg], $newline, array() );
1963 return $text;
1966 # Returns true if the function is allowed to include this entity
1967 function incrementIncludeCount( $dbk ) {
1968 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
1969 $this->mIncludeCount[$dbk] = 0;
1971 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
1972 return true;
1973 } else {
1974 return false;
1979 # Cleans up HTML, removes dangerous tags and attributes
1980 /* private */ function removeHTMLtags( $text ) {
1981 global $wgUseTidy, $wgUserHtml;
1982 $fname = 'Parser::removeHTMLtags';
1983 wfProfileIn( $fname );
1985 if( $wgUserHtml ) {
1986 $htmlpairs = array( # Tags that must be closed
1987 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
1988 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
1989 'strike', 'strong', 'tt', 'var', 'div', 'center',
1990 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
1991 'ruby', 'rt' , 'rb' , 'rp', 'p'
1993 $htmlsingle = array(
1994 'br', 'hr', 'li', 'dt', 'dd'
1996 $htmlnest = array( # Tags that can be nested--??
1997 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
1998 'dl', 'font', 'big', 'small', 'sub', 'sup'
2000 $tabletags = array( # Can only appear inside table
2001 'td', 'th', 'tr'
2003 } else {
2004 $htmlpairs = array();
2005 $htmlsingle = array();
2006 $htmlnest = array();
2007 $tabletags = array();
2010 $htmlsingle = array_merge( $tabletags, $htmlsingle );
2011 $htmlelements = array_merge( $htmlsingle, $htmlpairs );
2013 $htmlattrs = $this->getHTMLattrs () ;
2015 # Remove HTML comments
2016 $text = preg_replace( '/(\\n *<!--.*--> *(?=\\n)|<!--.*-->)/sU', '$2', $text );
2018 $bits = explode( '<', $text );
2019 $text = array_shift( $bits );
2020 if(!$wgUseTidy) {
2021 $tagstack = array(); $tablestack = array();
2022 foreach ( $bits as $x ) {
2023 $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
2024 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2025 $x, $regs );
2026 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2027 error_reporting( $prev );
2029 $badtag = 0 ;
2030 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2031 # Check our stack
2032 if ( $slash ) {
2033 # Closing a tag...
2034 if ( ! in_array( $t, $htmlsingle ) &&
2035 ( $ot = @array_pop( $tagstack ) ) != $t ) {
2036 @array_push( $tagstack, $ot );
2037 $badtag = 1;
2038 } else {
2039 if ( $t == 'table' ) {
2040 $tagstack = array_pop( $tablestack );
2042 $newparams = '';
2044 } else {
2045 # Keep track for later
2046 if ( in_array( $t, $tabletags ) &&
2047 ! in_array( 'table', $tagstack ) ) {
2048 $badtag = 1;
2049 } else if ( in_array( $t, $tagstack ) &&
2050 ! in_array ( $t , $htmlnest ) ) {
2051 $badtag = 1 ;
2052 } else if ( ! in_array( $t, $htmlsingle ) ) {
2053 if ( $t == 'table' ) {
2054 array_push( $tablestack, $tagstack );
2055 $tagstack = array();
2057 array_push( $tagstack, $t );
2059 # Strip non-approved attributes from the tag
2060 $newparams = $this->fixTagAttributes($params);
2063 if ( ! $badtag ) {
2064 $rest = str_replace( '>', '&gt;', $rest );
2065 $text .= "<$slash$t $newparams$brace$rest";
2066 continue;
2069 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
2071 # Close off any remaining tags
2072 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
2073 $text .= "</$t>\n";
2074 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
2076 } else {
2077 # this might be possible using tidy itself
2078 foreach ( $bits as $x ) {
2079 preg_match( '/^(\\/?)(\\w+)([^>]*)(\\/{0,1}>)([^<]*)$/',
2080 $x, $regs );
2081 @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
2082 if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
2083 $newparams = $this->fixTagAttributes($params);
2084 $rest = str_replace( '>', '&gt;', $rest );
2085 $text .= "<$slash$t $newparams$brace$rest";
2086 } else {
2087 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
2091 wfProfileOut( $fname );
2092 return $text;
2098 * This function accomplishes several tasks:
2099 * 1) Auto-number headings if that option is enabled
2100 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2101 * 3) Add a Table of contents on the top for users who have enabled the option
2102 * 4) Auto-anchor headings
2104 * It loops through all headlines, collects the necessary data, then splits up the
2105 * string and re-inserts the newly formatted headlines.
2109 /* private */ function formatHeadings( $text, $isMain=true ) {
2110 global $wgInputEncoding, $wgMaxTocLevel;
2112 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2113 $doShowToc = $this->mOptions->getShowToc();
2114 $forceTocHere = false;
2115 if( !$this->mTitle->userCanEdit() ) {
2116 $showEditLink = 0;
2117 $rightClickHack = 0;
2118 } else {
2119 $showEditLink = $this->mOptions->getEditSection();
2120 $rightClickHack = $this->mOptions->getEditSectionOnRightClick();
2123 # Inhibit editsection links if requested in the page
2124 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2125 if( $esw->matchAndRemove( $text ) ) {
2126 $showEditLink = 0;
2128 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2129 # do not add TOC
2130 $mw =& MagicWord::get( MAG_NOTOC );
2131 if( $mw->matchAndRemove( $text ) ) {
2132 $doShowToc = 0;
2135 # never add the TOC to the Main Page. This is an entry page that should not
2136 # be more than 1-2 screens large anyway
2137 if( $this->mTitle->getPrefixedText() == wfMsg('mainpage') ) {
2138 $doShowToc = 0;
2141 # Get all headlines for numbering them and adding funky stuff like [edit]
2142 # links - this is for later, but we need the number of headlines right now
2143 $numMatches = preg_match_all( '/<H([1-6])(.*?' . '>)(.*?)<\/H[1-6]>/i', $text, $matches );
2145 # if there are fewer than 4 headlines in the article, do not show TOC
2146 if( $numMatches < 4 ) {
2147 $doShowToc = 0;
2150 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2151 # override above conditions and always show TOC at that place
2152 $mw =& MagicWord::get( MAG_TOC );
2153 if ($mw->match( $text ) ) {
2154 $doShowToc = 1;
2155 $forceTocHere = true;
2156 } else {
2157 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2158 # override above conditions and always show TOC above first header
2159 $mw =& MagicWord::get( MAG_FORCETOC );
2160 if ($mw->matchAndRemove( $text ) ) {
2161 $doShowToc = 1;
2167 # We need this to perform operations on the HTML
2168 $sk =& $this->mOptions->getSkin();
2170 # headline counter
2171 $headlineCount = 0;
2173 # Ugh .. the TOC should have neat indentation levels which can be
2174 # passed to the skin functions. These are determined here
2175 $toclevel = 0;
2176 $toc = '';
2177 $full = '';
2178 $head = array();
2179 $sublevelCount = array();
2180 $level = 0;
2181 $prevlevel = 0;
2182 foreach( $matches[3] as $headline ) {
2183 $numbering = '';
2184 if( $level ) {
2185 $prevlevel = $level;
2187 $level = $matches[1][$headlineCount];
2188 if( ( $doNumberHeadings || $doShowToc ) && $prevlevel && $level > $prevlevel ) {
2189 # reset when we enter a new level
2190 $sublevelCount[$level] = 0;
2191 $toc .= $sk->tocIndent( $level - $prevlevel );
2192 $toclevel += $level - $prevlevel;
2194 if( ( $doNumberHeadings || $doShowToc ) && $level < $prevlevel ) {
2195 # reset when we step back a level
2196 $sublevelCount[$level+1]=0;
2197 $toc .= $sk->tocUnindent( $prevlevel - $level );
2198 $toclevel -= $prevlevel - $level;
2200 # count number of headlines for each level
2201 @$sublevelCount[$level]++;
2202 if( $doNumberHeadings || $doShowToc ) {
2203 $dot = 0;
2204 for( $i = 1; $i <= $level; $i++ ) {
2205 if( !empty( $sublevelCount[$i] ) ) {
2206 if( $dot ) {
2207 $numbering .= '.';
2209 $numbering .= $sublevelCount[$i];
2210 $dot = 1;
2215 # The canonized header is a version of the header text safe to use for links
2216 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2217 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2218 $canonized_headline = $this->unstripNoWiki( $headline, $this->mStripState );
2220 # strip out HTML
2221 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
2222 $tocline = trim( $canonized_headline );
2223 $canonized_headline = urlencode( do_html_entity_decode( str_replace(' ', '_', $tocline), ENT_COMPAT, $wgInputEncoding ) );
2224 $replacearray = array(
2225 '%3A' => ':',
2226 '%' => '.'
2228 $canonized_headline = str_replace(array_keys($replacearray),array_values($replacearray),$canonized_headline);
2229 $refer[$headlineCount] = $canonized_headline;
2231 # count how many in assoc. array so we can track dupes in anchors
2232 @$refers[$canonized_headline]++;
2233 $refcount[$headlineCount]=$refers[$canonized_headline];
2235 # Prepend the number to the heading text
2237 if( $doNumberHeadings || $doShowToc ) {
2238 $tocline = $numbering . ' ' . $tocline;
2240 # Don't number the heading if it is the only one (looks silly)
2241 if( $doNumberHeadings && count( $matches[3] ) > 1) {
2242 # the two are different if the line contains a link
2243 $headline=$numbering . ' ' . $headline;
2247 # Create the anchor for linking from the TOC to the section
2248 $anchor = $canonized_headline;
2249 if($refcount[$headlineCount] > 1 ) {
2250 $anchor .= '_' . $refcount[$headlineCount];
2252 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
2253 $toc .= $sk->tocLine($anchor,$tocline,$toclevel);
2255 if( $showEditLink ) {
2256 if ( empty( $head[$headlineCount] ) ) {
2257 $head[$headlineCount] = '';
2259 $head[$headlineCount] .= $sk->editSectionLink($headlineCount+1);
2262 # Add the edit section span
2263 if( $rightClickHack ) {
2264 $headline = $sk->editSectionScript($headlineCount+1,$headline);
2267 # give headline the correct <h#> tag
2268 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline."</h".$level.">";
2270 $headlineCount++;
2273 if( $doShowToc ) {
2274 $toclines = $headlineCount;
2275 $toc .= $sk->tocUnindent( $toclevel );
2276 $toc = $sk->tocTable( $toc );
2279 # split up and insert constructed headlines
2281 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
2282 $i = 0;
2284 foreach( $blocks as $block ) {
2285 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
2286 # This is the [edit] link that appears for the top block of text when
2287 # section editing is enabled
2289 # Disabled because it broke block formatting
2290 # For example, a bullet point in the top line
2291 # $full .= $sk->editSectionLink(0);
2293 $full .= $block;
2294 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
2295 # Top anchor now in skin
2296 $full = $full.$toc;
2299 if( !empty( $head[$i] ) ) {
2300 $full .= $head[$i];
2302 $i++;
2304 if($forceTocHere) {
2305 $mw =& MagicWord::get( MAG_TOC );
2306 return $mw->replace( $toc, $full );
2307 } else {
2308 return $full;
2312 # Return an HTML link for the "ISBN 123456" text
2313 /* private */ function magicISBN( $text ) {
2314 global $wgLang;
2315 $fname = 'Parser::magicISBN';
2316 wfProfileIn( $fname );
2318 $a = split( 'ISBN ', " $text" );
2319 if ( count ( $a ) < 2 ) {
2320 wfProfileOut( $fname );
2321 return $text;
2323 $text = substr( array_shift( $a ), 1);
2324 $valid = '0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2326 foreach ( $a as $x ) {
2327 $isbn = $blank = '' ;
2328 while ( ' ' == $x{0} ) {
2329 $blank .= ' ';
2330 $x = substr( $x, 1 );
2332 while ( strstr( $valid, $x{0} ) != false ) {
2333 $isbn .= $x{0};
2334 $x = substr( $x, 1 );
2336 $num = str_replace( '-', '', $isbn );
2337 $num = str_replace( ' ', '', $num );
2339 if ( '' == $num ) {
2340 $text .= "ISBN $blank$x";
2341 } else {
2342 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
2343 $text .= '<a href="' .
2344 $titleObj->escapeLocalUrl( "isbn={$num}" ) .
2345 "\" class=\"internal\">ISBN $isbn</a>";
2346 $text .= $x;
2349 wfProfileOut( $fname );
2350 return $text;
2353 # Return an HTML link for the "GEO ..." text
2354 /* private */ function magicGEO( $text ) {
2355 global $wgLang, $wgUseGeoMode;
2356 if ( !isset ( $wgUseGeoMode ) || !$wgUseGeoMode ) return $text ;
2357 $fname = 'Parser::magicGEO';
2358 wfProfileIn( $fname );
2360 # These next five lines are only for the ~35000 U.S. Census Rambot pages...
2361 $directions = array ( "N" => "North" , "S" => "South" , "E" => "East" , "W" => "West" ) ;
2362 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2363 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['N']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2364 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['W']}/" , "(GEO +\$1.\$2.\$3:-\$4.\$5.\$6)" , $text ) ;
2365 $text = preg_replace ( "/(\d+)&deg;(\d+)'(\d+)\" {$directions['S']}, (\d+)&deg;(\d+)'(\d+)\" {$directions['E']}/" , "(GEO +\$1.\$2.\$3:+\$4.\$5.\$6)" , $text ) ;
2367 $a = split( 'GEO ', " $text" );
2368 if ( count ( $a ) < 2 ) {
2369 wfProfileOut( $fname );
2370 return $text;
2372 $text = substr( array_shift( $a ), 1);
2373 $valid = '0123456789.+-:';
2375 foreach ( $a as $x ) {
2376 $geo = $blank = '' ;
2377 while ( ' ' == $x{0} ) {
2378 $blank .= ' ';
2379 $x = substr( $x, 1 );
2381 while ( strstr( $valid, $x{0} ) != false ) {
2382 $geo .= $x{0};
2383 $x = substr( $x, 1 );
2385 $num = str_replace( '+', '', $geo );
2386 $num = str_replace( ' ', '', $num );
2388 if ( '' == $num || count ( explode ( ":" , $num , 3 ) ) < 2 ) {
2389 $text .= "GEO $blank$x";
2390 } else {
2391 $titleObj = Title::makeTitle( NS_SPECIAL, 'Geo' );
2392 $text .= '<a href="' .
2393 $titleObj->escapeLocalUrl( "coordinates={$num}" ) .
2394 "\" class=\"internal\">GEO $geo</a>";
2395 $text .= $x;
2398 wfProfileOut( $fname );
2399 return $text;
2402 # Return an HTML link for the "RFC 1234" text
2403 /* private */ function magicRFC( $text ) {
2404 global $wgLang;
2406 $a = split( 'RFC ', ' '.$text );
2407 if ( count ( $a ) < 2 ) return $text;
2408 $text = substr( array_shift( $a ), 1);
2409 $valid = '0123456789';
2411 foreach ( $a as $x ) {
2412 $rfc = $blank = '' ;
2413 while ( ' ' == $x{0} ) {
2414 $blank .= ' ';
2415 $x = substr( $x, 1 );
2417 while ( strstr( $valid, $x{0} ) != false ) {
2418 $rfc .= $x{0};
2419 $x = substr( $x, 1 );
2422 if ( '' == $rfc ) {
2423 $text .= "RFC $blank$x";
2424 } else {
2425 $url = wfmsg( 'rfcurl' );
2426 $url = str_replace( '$1', $rfc, $url);
2427 $sk =& $this->mOptions->getSkin();
2428 $la = $sk->getExternalLinkAttributes( $url, "RFC {$rfc}" );
2429 $text .= "<a href='{$url}'{$la}>RFC {$rfc}</a>{$x}";
2432 return $text;
2435 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
2436 $this->mOptions = $options;
2437 $this->mTitle =& $title;
2438 $this->mOutputType = OT_WIKI;
2440 if ( $clearState ) {
2441 $this->clearState();
2444 $stripState = false;
2445 $pairs = array(
2446 "\r\n" => "\n",
2448 $text = str_replace(array_keys($pairs), array_values($pairs), $text);
2449 // now with regexes
2451 $pairs = array(
2452 "/<br.+(clear|break)=[\"']?(all|both)[\"']?\\/?>/i" => '<br style="clear:both;"/>',
2453 "/<br *?>/i" => "<br />",
2455 $text = preg_replace(array_keys($pairs), array_values($pairs), $text);
2457 $text = $this->strip( $text, $stripState, false );
2458 $text = $this->pstPass2( $text, $user );
2459 $text = $this->unstrip( $text, $stripState );
2460 $text = $this->unstripNoWiki( $text, $stripState );
2461 return $text;
2464 /* private */ function pstPass2( $text, &$user ) {
2465 global $wgLang, $wgLocaltimezone, $wgCurParser;
2467 # Variable replacement
2468 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
2469 $text = $this->replaceVariables( $text );
2471 # Signatures
2473 $n = $user->getName();
2474 $k = $user->getOption( 'nickname' );
2475 if ( '' == $k ) { $k = $n; }
2476 if(isset($wgLocaltimezone)) {
2477 $oldtz = getenv('TZ'); putenv('TZ='.$wgLocaltimezone);
2479 /* Note: this is an ugly timezone hack for the European wikis */
2480 $d = $wgLang->timeanddate( date( 'YmdHis' ), false ) .
2481 ' (' . date( 'T' ) . ')';
2482 if(isset($wgLocaltimezone)) putenv('TZ='.$oldtzs);
2484 $text = preg_replace( '/~~~~~/', $d, $text );
2485 $text = preg_replace( '/~~~~/', '[[' . $wgLang->getNsText( NS_USER ) . ":$n|$k]] $d", $text );
2486 $text = preg_replace( '/~~~/', '[[' . $wgLang->getNsText( NS_USER ) . ":$n|$k]]", $text );
2488 # Context links: [[|name]] and [[name (context)|]]
2490 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
2491 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
2492 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
2493 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
2495 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
2496 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
2497 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
2498 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
2499 # [[ns:page (cont)|]]
2500 $context = "";
2501 $t = $this->mTitle->getText();
2502 if ( preg_match( $conpat, $t, $m ) ) {
2503 $context = $m[2];
2505 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
2506 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
2507 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
2509 if ( '' == $context ) {
2510 $text = preg_replace( $p2, '[[\\1]]', $text );
2511 } else {
2512 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
2516 $mw =& MagicWord::get( MAG_SUBST );
2517 $wgCurParser = $this->fork();
2518 $text = $mw->substituteCallback( $text, "wfBraceSubstitution" );
2519 $this->merge( $wgCurParser );
2522 # Trim trailing whitespace
2523 # MAG_END (__END__) tag allows for trailing
2524 # whitespace to be deliberately included
2525 $text = rtrim( $text );
2526 $mw =& MagicWord::get( MAG_END );
2527 $mw->matchAndRemove( $text );
2529 return $text;
2532 # Set up some variables which are usually set up in parse()
2533 # so that an external function can call some class members with confidence
2534 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
2535 $this->mTitle =& $title;
2536 $this->mOptions = $options;
2537 $this->mOutputType = $outputType;
2538 if ( $clearState ) {
2539 $this->clearState();
2543 function transformMsg( $text, $options ) {
2544 global $wgTitle;
2545 static $executing = false;
2547 # Guard against infinite recursion
2548 if ( $executing ) {
2549 return $text;
2551 $executing = true;
2553 $this->mTitle = $wgTitle;
2554 $this->mOptions = $options;
2555 $this->mOutputType = OT_MSG;
2556 $this->clearState();
2557 $text = $this->replaceVariables( $text );
2559 $executing = false;
2560 return $text;
2563 # Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
2564 # Callback will be called with the text within
2565 # Transform and return the text within
2566 function setHook( $tag, $callback ) {
2567 $oldVal = @$this->mTagHooks[$tag];
2568 $this->mTagHooks[$tag] = $callback;
2569 return $oldVal;
2573 class ParserOutput
2575 var $mText, $mLanguageLinks, $mCategoryLinks, $mContainsOldMagic;
2576 var $mCacheTime; # Used in ParserCache
2578 function ParserOutput( $text = "", $languageLinks = array(), $categoryLinks = array(),
2579 $containsOldMagic = false )
2581 $this->mText = $text;
2582 $this->mLanguageLinks = $languageLinks;
2583 $this->mCategoryLinks = $categoryLinks;
2584 $this->mContainsOldMagic = $containsOldMagic;
2585 $this->mCacheTime = "";
2588 function getText() { return $this->mText; }
2589 function getLanguageLinks() { return $this->mLanguageLinks; }
2590 function getCategoryLinks() { return $this->mCategoryLinks; }
2591 function getCacheTime() { return $this->mCacheTime; }
2592 function containsOldMagic() { return $this->mContainsOldMagic; }
2593 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
2594 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
2595 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategoryLinks, $cl ); }
2596 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
2597 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
2599 function merge( $other ) {
2600 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
2601 $this->mCategoryLinks = array_merge( $this->mCategoryLinks, $this->mLanguageLinks );
2602 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
2607 class ParserOptions
2609 # All variables are private
2610 var $mUseTeX; # Use texvc to expand <math> tags
2611 var $mUseCategoryMagic; # Treat [[Category:xxxx]] tags specially
2612 var $mUseDynamicDates; # Use $wgDateFormatter to format dates
2613 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
2614 var $mAllowExternalImages; # Allow external images inline
2615 var $mSkin; # Reference to the preferred skin
2616 var $mDateFormat; # Date format index
2617 var $mEditSection; # Create "edit section" links
2618 var $mEditSectionOnRightClick; # Generate JavaScript to edit section on right click
2619 var $mNumberHeadings; # Automatically number headings
2620 var $mShowToc; # Show table of contents
2622 function getUseTeX() { return $this->mUseTeX; }
2623 function getUseCategoryMagic() { return $this->mUseCategoryMagic; }
2624 function getUseDynamicDates() { return $this->mUseDynamicDates; }
2625 function getInterwikiMagic() { return $this->mInterwikiMagic; }
2626 function getAllowExternalImages() { return $this->mAllowExternalImages; }
2627 function getSkin() { return $this->mSkin; }
2628 function getDateFormat() { return $this->mDateFormat; }
2629 function getEditSection() { return $this->mEditSection; }
2630 function getEditSectionOnRightClick() { return $this->mEditSectionOnRightClick; }
2631 function getNumberHeadings() { return $this->mNumberHeadings; }
2632 function getShowToc() { return $this->mShowToc; }
2634 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
2635 function setUseCategoryMagic( $x ) { return wfSetVar( $this->mUseCategoryMagic, $x ); }
2636 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
2637 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
2638 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
2639 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
2640 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
2641 function setEditSectionOnRightClick( $x ) { return wfSetVar( $this->mEditSectionOnRightClick, $x ); }
2642 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
2643 function setShowToc( $x ) { return wfSetVar( $this->mShowToc, $x ); }
2645 function setSkin( &$x ) { $this->mSkin =& $x; }
2647 /* static */ function newFromUser( &$user ) {
2648 $popts = new ParserOptions;
2649 $popts->initialiseFromUser( $user );
2650 return $popts;
2653 function initialiseFromUser( &$userInput ) {
2654 global $wgUseTeX, $wgUseCategoryMagic, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages;
2656 if ( !$userInput ) {
2657 $user = new User;
2658 $user->setLoaded( true );
2659 } else {
2660 $user =& $userInput;
2663 $this->mUseTeX = $wgUseTeX;
2664 $this->mUseCategoryMagic = $wgUseCategoryMagic;
2665 $this->mUseDynamicDates = $wgUseDynamicDates;
2666 $this->mInterwikiMagic = $wgInterwikiMagic;
2667 $this->mAllowExternalImages = $wgAllowExternalImages;
2668 $this->mSkin =& $user->getSkin();
2669 $this->mDateFormat = $user->getOption( 'date' );
2670 $this->mEditSection = $user->getOption( 'editsection' );
2671 $this->mEditSectionOnRightClick = $user->getOption( 'editsectiononrightclick' );
2672 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
2673 $this->mShowToc = $user->getOption( 'showtoc' );
2679 # Regex callbacks, used in Parser::replaceVariables
2680 function wfBraceSubstitution( $matches )
2682 global $wgCurParser;
2683 return $wgCurParser->braceSubstitution( $matches );
2686 function wfArgSubstitution( $matches )
2688 global $wgCurParser;
2689 return $wgCurParser->argSubstitution( $matches );
2692 function wfVariableSubstitution( $matches )
2694 global $wgCurParser;
2695 return $wgCurParser->variableSubstitution( $matches );
2698 function wfNumberOfArticles()
2700 global $wgNumberOfArticles;
2702 wfLoadSiteStats();
2703 return $wgNumberOfArticles;
2706 /* private */ function wfLoadSiteStats()
2708 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
2709 $fname = 'wfLoadSiteStats';
2711 if ( -1 != $wgNumberOfArticles ) return;
2712 $dbr =& wfGetDB( DB_SLAVE );
2713 $s = $dbr->getArray( 'site_stats',
2714 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
2715 array( 'ss_row_id' => 1 ), $fname
2718 if ( $s === false ) {
2719 return;
2720 } else {
2721 $wgTotalViews = $s->ss_total_views;
2722 $wgTotalEdits = $s->ss_total_edits;
2723 $wgNumberOfArticles = $s->ss_good_articles;
2727 function wfEscapeHTMLTagsOnly( $in ) {
2728 return str_replace(
2729 array( '"', '>', '<' ),
2730 array( '&quot;', '&gt;', '&lt;' ),
2731 $in );