Added --show-output option to parserTests.php, to allow capture of complete output...
[lhc/web/wiklou.git] / maintenance / parserTests.inc
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * @todo Make this more independent of the configuration (and if possible the database)
22 * @todo document
23 * @package MediaWiki
24 * @subpackage Maintenance
25 */
26
27 /** */
28 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output' );
29 $optionsWithArgs = array( 'regex' );
30
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/includes/ObjectCache.php" );
33 require_once( "$IP/includes/BagOStuff.php" );
34 require_once( "$IP/includes/Hooks.php" );
35 require_once( "$IP/maintenance/parserTestsParserHook.php" );
36 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
37 require_once( "$IP/maintenance/parserTestsParserTime.php" );
38
39 /**
40 * @package MediaWiki
41 * @subpackage Maintenance
42 */
43 class ParserTest {
44 /**
45 * boolean $color whereas output should be colorized
46 * @private
47 */
48 var $color;
49
50 /**
51 * boolean $lightcolor whereas output should use light colors
52 * @private
53 */
54 var $lightcolor;
55
56 /**
57 * boolean $showOutput Show test output
58 */
59 var $showOutput;
60
61 /**
62 * Sets terminal colorization and diff/quick modes depending on OS and
63 * command-line options (--color and --quick).
64 *
65 * @public
66 */
67 function ParserTest() {
68 global $options;
69
70 # Only colorize output if stdout is a terminal.
71 $this->lightcolor = false;
72 $this->color = !wfIsWindows() && posix_isatty(1);
73
74 if( isset( $options['color'] ) ) {
75 switch( $options['color'] ) {
76 case 'no':
77 $this->color = false;
78 break;
79 case 'light':
80 $this->lightcolor = true;
81 # Fall through
82 case 'yes':
83 default:
84 $this->color = true;
85 break;
86 }
87 }
88
89 $this->showDiffs = !isset( $options['quick'] );
90 $this->quiet = isset( $options['quiet'] );
91 $this->showOutput = isset( $options['show-output'] );
92
93
94 if (isset($options['regex'])) {
95 $this->regex = $options['regex'];
96 } else {
97 # Matches anything
98 $this->regex = '';
99 }
100
101 $this->hooks = array();
102 }
103
104 /**
105 * Remove last character if it is a newline
106 * @private
107 */
108 function chomp($s) {
109 if (substr($s, -1) === "\n") {
110 return substr($s, 0, -1);
111 }
112 else {
113 return $s;
114 }
115 }
116
117 /**
118 * Run a series of tests listed in the given text file.
119 * Each test consists of a brief description, wikitext input,
120 * and the expected HTML output.
121 *
122 * Prints status updates on stdout and counts up the total
123 * number and percentage of passed tests.
124 *
125 * @param string $filename
126 * @return bool True if passed all tests, false if any tests failed.
127 * @public
128 */
129 function runTestsFromFile( $filename ) {
130 $infile = fopen( $filename, 'rt' );
131 if( !$infile ) {
132 wfDie( "Couldn't open $filename\n" );
133 }
134
135 $data = array();
136 $section = null;
137 $success = 0;
138 $total = 0;
139 $n = 0;
140 while( false !== ($line = fgets( $infile ) ) ) {
141 $n++;
142 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
143 $section = strtolower( $matches[1] );
144 if( $section == 'endarticle') {
145 if( !isset( $data['text'] ) ) {
146 wfDie( "'endarticle' without 'text' at line $n\n" );
147 }
148 if( !isset( $data['article'] ) ) {
149 wfDie( "'endarticle' without 'article' at line $n\n" );
150 }
151 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
152 $data = array();
153 $section = null;
154 continue;
155 }
156 if( $section == 'endhooks' ) {
157 if( !isset( $data['hooks'] ) ) {
158 wfDie( "'endhooks' without 'hooks' at line $n\n" );
159 }
160 foreach( explode( "\n", $data['hooks'] ) as $line ) {
161 $line = trim( $line );
162 if( $line ) {
163 $this->requireHook( $line );
164 }
165 }
166 $data = array();
167 $section = null;
168 continue;
169 }
170 if( $section == 'end' ) {
171 if( !isset( $data['test'] ) ) {
172 wfDie( "'end' without 'test' at line $n\n" );
173 }
174 if( !isset( $data['input'] ) ) {
175 wfDie( "'end' without 'input' at line $n\n" );
176 }
177 if( !isset( $data['result'] ) ) {
178 wfDie( "'end' without 'result' at line $n\n" );
179 }
180 if( !isset( $data['options'] ) ) {
181 $data['options'] = '';
182 }
183 else {
184 $data['options'] = $this->chomp( $data['options'] );
185 }
186 if (preg_match('/\\bdisabled\\b/i', $data['options'])
187 || !preg_match("/{$this->regex}/i", $data['test'])) {
188 # disabled test
189 $data = array();
190 $section = null;
191 continue;
192 }
193 if( $this->runTest(
194 $this->chomp( $data['test'] ),
195 $this->chomp( $data['input'] ),
196 $this->chomp( $data['result'] ),
197 $this->chomp( $data['options'] ) ) ) {
198 $success++;
199 }
200 $total++;
201 $data = array();
202 $section = null;
203 continue;
204 }
205 if ( isset ($data[$section] ) ) {
206 wfDie( "duplicate section '$section' at line $n\n" );
207 }
208 $data[$section] = '';
209 continue;
210 }
211 if( $section ) {
212 $data[$section] .= $line;
213 }
214 }
215 if( $total > 0 ) {
216 $ratio = wfPercent( 100 * $success / $total );
217 print $this->termColor( 1 ) . "\nPassed $success of $total tests ($ratio) ";
218 if( $success == $total ) {
219 print $this->termColor( 32 ) . "PASSED!";
220 } else {
221 print $this->termColor( 31 ) . "FAILED!";
222 }
223 print $this->termReset() . "\n";
224 return ($success == $total);
225 } else {
226 wfDie( "No tests found.\n" );
227 }
228 }
229
230 /**
231 * Run a given wikitext input through a freshly-constructed wiki parser,
232 * and compare the output against the expected results.
233 * Prints status and explanatory messages to stdout.
234 *
235 * @param string $input Wikitext to try rendering
236 * @param string $result Result to output
237 * @return bool
238 */
239 function runTest( $desc, $input, $result, $opts ) {
240 if( !$this->quiet ) {
241 $this->showTesting( $desc );
242 }
243
244 $this->setupGlobals($opts);
245
246 $user = new User();
247 $options = ParserOptions::newFromUser( $user );
248
249 if (preg_match('/\\bmath\\b/i', $opts)) {
250 # XXX this should probably be done by the ParserOptions
251 $options->setUseTex(true);
252 }
253
254 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
255 $titleText = $m[1];
256 }
257 else {
258 $titleText = 'Parser test';
259 }
260
261 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
262
263 $parser = new Parser();
264 foreach( $this->hooks as $tag => $callback ) {
265 $parser->setHook( $tag, $callback );
266 }
267 wfRunHooks( 'ParserTestParser', array( &$parser ) );
268
269 $title =& Title::makeTitle( NS_MAIN, $titleText );
270
271 if (preg_match('/\\bpst\\b/i', $opts)) {
272 $out = $parser->preSaveTransform( $input, $title, $user, $options );
273 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
274 $out = $parser->transformMsg( $input, $options );
275 } elseif( preg_match( '/\\bsection=(\d+)\b/i', $opts, $matches ) ) {
276 $section = intval( $matches[1] );
277 $out = $parser->getSection( $input, $section );
278 } elseif( preg_match( '/\\breplace=(\d+),"(.*?)"/i', $opts, $matches ) ) {
279 $section = intval( $matches[1] );
280 $replace = $matches[2];
281 $out = $parser->replaceSection( $input, $section, $replace );
282 } else {
283 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
284 $out = $output->getText();
285
286 if (preg_match('/\\bill\\b/i', $opts)) {
287 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
288 } else if (preg_match('/\\bcat\\b/i', $opts)) {
289 global $wgOut;
290 $wgOut->addCategoryLinks($output->getCategories());
291 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
292 }
293
294 $result = $this->tidy($result);
295 }
296
297 $this->teardownGlobals();
298
299 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
300 return $this->showSuccess( $desc );
301 } else {
302 return $this->showFailure( $desc, $result, $out );
303 }
304 }
305
306 /**
307 * Set up the global variables for a consistent environment for each test.
308 * Ideally this should replace the global configuration entirely.
309 *
310 * @private
311 */
312 function setupGlobals($opts = '') {
313 # Save the prefixed / quoted table names for later use when we make the temporaries.
314 $db =& wfGetDB( DB_READ );
315 $this->oldTableNames = array();
316 foreach( $this->listTables() as $table ) {
317 $this->oldTableNames[$table] = $db->tableName( $table );
318 }
319 if( !isset( $this->uploadDir ) ) {
320 $this->uploadDir = $this->setupUploadDir();
321 }
322
323 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
324 $lang = $m[1];
325 } else {
326 $lang = 'en';
327 }
328
329 $settings = array(
330 'wgServer' => 'http://localhost',
331 'wgScript' => '/index.php',
332 'wgScriptPath' => '/',
333 'wgArticlePath' => '/wiki/$1',
334 'wgActionPaths' => array(),
335 'wgUploadPath' => 'http://example.com/images',
336 'wgUploadDirectory' => $this->uploadDir,
337 'wgStyleSheetPath' => '/skins',
338 'wgSitename' => 'MediaWiki',
339 'wgServerName' => 'Britney Spears',
340 'wgLanguageCode' => $lang,
341 'wgContLanguageCode' => $lang,
342 'wgDBprefix' => 'parsertest_',
343
344 'wgLang' => null,
345 'wgContLang' => null,
346 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
347 'wgMaxTocLevel' => 999,
348 'wgCapitalLinks' => true,
349 'wgNoFollowLinks' => true,
350 'wgThumbnailScriptPath' => false,
351 'wgUseTeX' => false,
352 'wgLocaltimezone' => 'UTC',
353 'wgAllowExternalImages' => true,
354 );
355 $this->savedGlobals = array();
356 foreach( $settings as $var => $val ) {
357 $this->savedGlobals[$var] = $GLOBALS[$var];
358 $GLOBALS[$var] = $val;
359 }
360 $langObj = Language::factory( $lang );
361 $GLOBALS['wgLang'] = $langObj;
362 $GLOBALS['wgContLang'] = $langObj;
363
364 $GLOBALS['wgLoadBalancer']->loadMasterPos();
365 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
366 $this->setupDatabase();
367
368 global $wgUser;
369 $wgUser = new User();
370 }
371
372 # List of temporary tables to create, without prefix
373 # Some of these probably aren't necessary
374 function listTables() {
375 $tables = array('user', 'page', 'revision', 'text',
376 'pagelinks', 'imagelinks', 'categorylinks',
377 'templatelinks', 'externallinks', 'langlinks',
378 'site_stats', 'hitcounter',
379 'ipblocks', 'image', 'oldimage',
380 'recentchanges',
381 'watchlist', 'math', 'searchindex',
382 'interwiki', 'querycache',
383 'objectcache', 'job'
384 );
385
386 // FIXME manually adding additional table for the tasks extension
387 // we probably need a better software wide system to register new
388 // tables.
389 global $wgExtensionFunctions;
390 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
391 $tables[] = 'tasks';
392 }
393
394 return $tables;
395 }
396
397 /**
398 * Set up a temporary set of wiki tables to work with for the tests.
399 * Currently this will only be done once per run, and any changes to
400 * the db will be visible to later tests in the run.
401 *
402 * @private
403 */
404 function setupDatabase() {
405 static $setupDB = false;
406 global $wgDBprefix;
407
408 # Make sure we don't mess with the live DB
409 if (!$setupDB && $wgDBprefix === 'parsertest_') {
410 # oh teh horror
411 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
412 $db =& wfGetDB( DB_MASTER );
413
414 $tables = $this->listTables();
415
416 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
417 # Database that supports CREATE TABLE ... LIKE
418 global $wgDBtype;
419 if( $wgDBtype == 'postgres' ) {
420 $def = 'INCLUDING DEFAULTS';
421 } else {
422 $def = '';
423 }
424 foreach ($tables as $tbl) {
425 $newTableName = $db->tableName( $tbl );
426 $tableName = $this->oldTableNames[$tbl];
427 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
428 }
429 } else {
430 # Hack for MySQL versions < 4.1, which don't support
431 # "CREATE TABLE ... LIKE". Note that
432 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
433 # would not create the indexes we need....
434 foreach ($tables as $tbl) {
435 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
436 $row = $db->fetchRow($res);
437 $create = $row[1];
438 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
439 . $wgDBprefix . $tbl .'`', $create);
440 if ($create === $create_tmp) {
441 # Couldn't do replacement
442 wfDie("could not create temporary table $tbl");
443 }
444 $db->query($create_tmp);
445 }
446
447 }
448
449 # Hack: insert a few Wikipedia in-project interwiki prefixes,
450 # for testing inter-language links
451 $db->insert( 'interwiki', array(
452 array( 'iw_prefix' => 'Wikipedia',
453 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
454 'iw_local' => 0 ),
455 array( 'iw_prefix' => 'MeatBall',
456 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
457 'iw_local' => 0 ),
458 array( 'iw_prefix' => 'zh',
459 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
460 'iw_local' => 1 ),
461 array( 'iw_prefix' => 'es',
462 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
463 'iw_local' => 1 ),
464 array( 'iw_prefix' => 'fr',
465 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
466 'iw_local' => 1 ),
467 array( 'iw_prefix' => 'ru',
468 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
469 'iw_local' => 1 ),
470 ) );
471
472 # Hack: Insert an image to work with
473 $db->insert( 'image', array(
474 'img_name' => 'Foobar.jpg',
475 'img_size' => 12345,
476 'img_description' => 'Some lame file',
477 'img_user' => 1,
478 'img_user_text' => 'WikiSysop',
479 'img_timestamp' => $db->timestamp( '20010115123500' ),
480 'img_width' => 1941,
481 'img_height' => 220,
482 'img_bits' => 24,
483 'img_media_type' => MEDIATYPE_BITMAP,
484 'img_major_mime' => "image",
485 'img_minor_mime' => "jpeg",
486 ) );
487
488 # Update certain things in site_stats
489 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
490
491 $setupDB = true;
492 }
493 }
494
495 /**
496 * Create a dummy uploads directory which will contain a couple
497 * of files in order to pass existence tests.
498 * @return string The directory
499 * @private
500 */
501 function setupUploadDir() {
502 global $IP;
503
504 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
505 mkdir( $dir );
506 mkdir( $dir . '/3' );
507 mkdir( $dir . '/3/3a' );
508
509 $img = "$IP/skins/monobook/headbg.jpg";
510 $h = fopen($img, 'r');
511 $c = fread($h, filesize($img));
512 fclose($h);
513
514 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
515 fwrite( $f, $c );
516 fclose( $f );
517 return $dir;
518 }
519
520 /**
521 * Restore default values and perform any necessary clean-up
522 * after each test runs.
523 *
524 * @private
525 */
526 function teardownGlobals() {
527 foreach( $this->savedGlobals as $var => $val ) {
528 $GLOBALS[$var] = $val;
529 }
530 if( isset( $this->uploadDir ) ) {
531 $this->teardownUploadDir( $this->uploadDir );
532 unset( $this->uploadDir );
533 }
534 }
535
536 /**
537 * Remove the dummy uploads directory
538 * @private
539 */
540 function teardownUploadDir( $dir ) {
541 unlink( "$dir/3/3a/Foobar.jpg" );
542 rmdir( "$dir/3/3a" );
543 rmdir( "$dir/3" );
544 @rmdir( "$dir/thumb/6/65" );
545 @rmdir( "$dir/thumb/6" );
546
547 @unlink( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
548 @rmdir( "$dir/thumb/3/3a/Foobar.jpg" );
549 @rmdir( "$dir/thumb/3/3a" );
550 @rmdir( "$dir/thumb/3/39" ); # wtf?
551 @rmdir( "$dir/thumb/3" );
552 @rmdir( "$dir/thumb" );
553 @rmdir( "$dir" );
554 }
555
556 /**
557 * "Running test $desc..."
558 * @private
559 */
560 function showTesting( $desc ) {
561 print "Running test $desc... ";
562 }
563
564 /**
565 * Print a happy success message.
566 *
567 * @param string $desc The test name
568 * @return bool
569 * @private
570 */
571 function showSuccess( $desc ) {
572 if( !$this->quiet ) {
573 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
574 }
575 return true;
576 }
577
578 /**
579 * Print a failure message and provide some explanatory output
580 * about what went wrong if so configured.
581 *
582 * @param string $desc The test name
583 * @param string $result Expected HTML output
584 * @param string $html Actual HTML output
585 * @return bool
586 * @private
587 */
588 function showFailure( $desc, $result, $html ) {
589 if( $this->quiet ) {
590 # In quiet mode we didn't show the 'Testing' message before the
591 # test, in case it succeeded. Show it now:
592 $this->showTesting( $desc );
593 }
594 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
595 if ( $this->showOutput ) {
596 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
597 }
598 if( $this->showDiffs ) {
599 print $this->quickDiff( $result, $html );
600 if( !$this->wellFormed( $html ) ) {
601 print "XML error: $this->mXmlError\n";
602 }
603 }
604 return false;
605 }
606
607 /**
608 * Run given strings through a diff and return the (colorized) output.
609 * Requires writable /tmp directory and a 'diff' command in the PATH.
610 *
611 * @param string $input
612 * @param string $output
613 * @param string $inFileTail Tailing for the input file name
614 * @param string $outFileTail Tailing for the output file name
615 * @return string
616 * @private
617 */
618 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
619 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
620
621 $infile = "$prefix-$inFileTail";
622 $this->dumpToFile( $input, $infile );
623
624 $outfile = "$prefix-$outFileTail";
625 $this->dumpToFile( $output, $outfile );
626
627 $diff = `diff -au $infile $outfile`;
628 unlink( $infile );
629 unlink( $outfile );
630
631 return $this->colorDiff( $diff );
632 }
633
634 /**
635 * Write the given string to a file, adding a final newline.
636 *
637 * @param string $data
638 * @param string $filename
639 * @private
640 */
641 function dumpToFile( $data, $filename ) {
642 $file = fopen( $filename, "wt" );
643 fwrite( $file, $data . "\n" );
644 fclose( $file );
645 }
646
647 /**
648 * Return ANSI terminal escape code for changing text attribs/color,
649 * or empty string if color output is disabled.
650 *
651 * @param string $color Semicolon-separated list of attribute/color codes
652 * @return string
653 * @private
654 */
655 function termColor( $color ) {
656 if($this->lightcolor) {
657 return $this->color ? "\x1b[1;{$color}m" : '';
658 } else {
659 return $this->color ? "\x1b[{$color}m" : '';
660 }
661 }
662
663 /**
664 * Return ANSI terminal escape code for restoring default text attributes,
665 * or empty string if color output is disabled.
666 *
667 * @return string
668 * @private
669 */
670 function termReset() {
671 return $this->color ? "\x1b[0m" : '';
672 }
673
674 /**
675 * Colorize unified diff output if set for ANSI color output.
676 * Subtractions are colored blue, additions red.
677 *
678 * @param string $text
679 * @return string
680 * @private
681 */
682 function colorDiff( $text ) {
683 return preg_replace(
684 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
685 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
686 $this->termColor( 31 ) . '$1' . $this->termReset() ),
687 $text );
688 }
689
690 /**
691 * Insert a temporary test article
692 * @param string $name the title, including any prefix
693 * @param string $text the article text
694 * @param int $line the input line number, for reporting errors
695 * @private
696 */
697 function addArticle($name, $text, $line) {
698 $this->setupGlobals();
699 $title = Title::newFromText( $name );
700 if ( is_null($title) ) {
701 wfDie( "invalid title at line $line\n" );
702 }
703
704 $aid = $title->getArticleID( GAID_FOR_UPDATE );
705 if ($aid != 0) {
706 wfDie( "duplicate article at line $line\n" );
707 }
708
709 $art = new Article($title);
710 $art->insertNewArticle($text, '', false, false );
711 $this->teardownGlobals();
712 }
713
714 /**
715 * Steal a callback function from the primary parser, save it for
716 * application to our scary parser. If the hook is not installed,
717 * die a painful dead to warn the others.
718 * @param string $name
719 */
720 private function requireHook( $name ) {
721 global $wgParser;
722 if( isset( $wgParser->mTagHooks[$name] ) ) {
723 $this->hooks[$name] = $wgParser->mTagHooks[$name];
724 } else {
725 wfDie( "This test suite requires the '$name' hook extension.\n" );
726 }
727 }
728
729 /*
730 * Run the "tidy" command on text if the $wgUseTidy
731 * global is true
732 *
733 * @param string $text the text to tidy
734 * @return string
735 * @static
736 * @private
737 */
738 function tidy( $text ) {
739 global $wgUseTidy;
740 if ($wgUseTidy) {
741 $text = Parser::tidy($text);
742 }
743 return $text;
744 }
745
746 function wellFormed( $text ) {
747 $html =
748 Sanitizer::hackDocType() .
749 '<html>' .
750 $text .
751 '</html>';
752
753 $parser = xml_parser_create( "UTF-8" );
754
755 # case folding violates XML standard, turn it off
756 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
757
758 if( !xml_parse( $parser, $html, true ) ) {
759 $err = xml_error_string( xml_get_error_code( $parser ) );
760 $position = xml_get_current_byte_index( $parser );
761 $fragment = $this->extractFragment( $html, $position );
762 $this->mXmlError = "$err at byte $position:\n$fragment";
763 xml_parser_free( $parser );
764 return false;
765 }
766 xml_parser_free( $parser );
767 return true;
768 }
769
770 function extractFragment( $text, $position ) {
771 $start = max( 0, $position - 10 );
772 $before = $position - $start;
773 $fragment = '...' .
774 $this->termColor( 34 ) .
775 substr( $text, $start, $before ) .
776 $this->termColor( 0 ) .
777 $this->termColor( 31 ) .
778 $this->termColor( 1 ) .
779 substr( $text, $position, 1 ) .
780 $this->termColor( 0 ) .
781 $this->termColor( 34 ) .
782 substr( $text, $position + 1, 9 ) .
783 $this->termColor( 0 ) .
784 '...';
785 $display = str_replace( "\n", ' ', $fragment );
786 $caret = ' ' .
787 str_repeat( ' ', $before ) .
788 $this->termColor( 31 ) .
789 '^' .
790 $this->termColor( 0 );
791 return "$display\n$caret";
792 }
793
794 }
795
796 ?>