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