Add some basic regression tests on extraction for section editing
[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/', $opts, $matches ) ) {
273 $section = intval( $matches[1] );
274 $out = Article::getSection( $input, $section );
275 } else {
276 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
277 $out = $output->getText();
278
279 if (preg_match('/\\bill\\b/i', $opts)) {
280 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
281 } else if (preg_match('/\\bcat\\b/i', $opts)) {
282 global $wgOut;
283 $wgOut->addCategoryLinks($output->getCategories());
284 $out = $this->tidy ( implode( ' ', $wgOut->getCategoryLinks() ) );
285 }
286
287 $result = $this->tidy($result);
288 }
289
290 $this->teardownGlobals();
291
292 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
293 return $this->showSuccess( $desc );
294 } else {
295 return $this->showFailure( $desc, $result, $out );
296 }
297 }
298
299 /**
300 * Set up the global variables for a consistent environment for each test.
301 * Ideally this should replace the global configuration entirely.
302 *
303 * @private
304 */
305 function setupGlobals($opts = '') {
306 # Save the prefixed / quoted table names for later use when we make the temporaries.
307 $db =& wfGetDB( DB_READ );
308 $this->oldTableNames = array();
309 foreach( $this->listTables() as $table ) {
310 $this->oldTableNames[$table] = $db->tableName( $table );
311 }
312 if( !isset( $this->uploadDir ) ) {
313 $this->uploadDir = $this->setupUploadDir();
314 }
315
316 if( preg_match( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, $m ) ) {
317 $lang = $m[1];
318 } else {
319 $lang = 'en';
320 }
321 $langClass = 'Language' . str_replace( '-', '_', ucfirst( $lang ) );
322 $langObj = setupLangObj( $langClass );
323
324 $settings = array(
325 'wgServer' => 'http://localhost',
326 'wgScript' => '/index.php',
327 'wgScriptPath' => '/',
328 'wgArticlePath' => '/wiki/$1',
329 'wgActionPaths' => array(),
330 'wgUploadPath' => 'http://example.com/images',
331 'wgUploadDirectory' => $this->uploadDir,
332 'wgStyleSheetPath' => '/skins',
333 'wgSitename' => 'MediaWiki',
334 'wgServerName' => 'Britney Spears',
335 'wgLanguageCode' => $lang,
336 'wgContLanguageCode' => $lang,
337 'wgDBprefix' => 'parsertest_',
338 'wgDefaultUserOptions' => array(),
339
340 'wgLang' => $langObj,
341 'wgContLang' => $langObj,
342 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
343 'wgMaxTocLevel' => 999,
344 'wgCapitalLinks' => true,
345 'wgDefaultUserOptions' => array(),
346 'wgNoFollowLinks' => true,
347 'wgThumbnailScriptPath' => false,
348 'wgUseTeX' => false,
349 'wgLocaltimezone' => 'UTC',
350 );
351 $this->savedGlobals = array();
352 foreach( $settings as $var => $val ) {
353 $this->savedGlobals[$var] = $GLOBALS[$var];
354 $GLOBALS[$var] = $val;
355 }
356 $GLOBALS['wgLoadBalancer']->loadMasterPos();
357 $GLOBALS['wgMessageCache']->initialise( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
358 $this->setupDatabase();
359
360 global $wgUser;
361 $wgUser = new User();
362 }
363
364 # List of temporary tables to create, without prefix
365 # Some of these probably aren't necessary
366 function listTables() {
367 $tables = array('user', 'page', 'revision', 'text',
368 'pagelinks', 'imagelinks', 'categorylinks',
369 'templatelinks', 'externallinks', 'langlinks',
370 'site_stats', 'hitcounter',
371 'ipblocks', 'image', 'oldimage',
372 'recentchanges',
373 'watchlist', 'math', 'searchindex',
374 'interwiki', 'querycache',
375 'objectcache', 'job'
376 );
377
378 // FIXME manually adding additional table for the tasks extension
379 // we probably need a better software wide system to register new
380 // tables.
381 global $wgExtensionFunctions;
382 if( in_array('wfTasksExtension' , $wgExtensionFunctions ) ) {
383 $tables[] = 'tasks';
384 }
385
386 return $tables;
387 }
388
389 /**
390 * Set up a temporary set of wiki tables to work with for the tests.
391 * Currently this will only be done once per run, and any changes to
392 * the db will be visible to later tests in the run.
393 *
394 * @private
395 */
396 function setupDatabase() {
397 static $setupDB = false;
398 global $wgDBprefix;
399
400 # Make sure we don't mess with the live DB
401 if (!$setupDB && $wgDBprefix === 'parsertest_') {
402 # oh teh horror
403 $GLOBALS['wgLoadBalancer'] = LoadBalancer::newFromParams( $GLOBALS['wgDBservers'] );
404 $db =& wfGetDB( DB_MASTER );
405
406 $tables = $this->listTables();
407
408 if (!(strcmp($db->getServerVersion(), '4.1') < 0 and stristr($db->getSoftwareLink(), 'MySQL'))) {
409 # Database that supports CREATE TABLE ... LIKE
410 global $wgDBtype;
411 if( $wgDBtype == 'PostgreSQL' ) {
412 $def = 'INCLUDING DEFAULTS';
413 } else {
414 $def = '';
415 }
416 foreach ($tables as $tbl) {
417 $newTableName = $db->tableName( $tbl );
418 $tableName = $this->oldTableNames[$tbl];
419 $db->query("CREATE TEMPORARY TABLE $newTableName (LIKE $tableName $def)");
420 }
421 } else {
422 # Hack for MySQL versions < 4.1, which don't support
423 # "CREATE TABLE ... LIKE". Note that
424 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
425 # would not create the indexes we need....
426 foreach ($tables as $tbl) {
427 $res = $db->query("SHOW CREATE TABLE {$this->oldTableNames[$tbl]}");
428 $row = $db->fetchRow($res);
429 $create = $row[1];
430 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/', 'CREATE TEMPORARY TABLE `'
431 . $wgDBprefix . $tbl .'`', $create);
432 if ($create === $create_tmp) {
433 # Couldn't do replacement
434 wfDie("could not create temporary table $tbl");
435 }
436 $db->query($create_tmp);
437 }
438
439 }
440
441 # Hack: insert a few Wikipedia in-project interwiki prefixes,
442 # for testing inter-language links
443 $db->insert( 'interwiki', array(
444 array( 'iw_prefix' => 'Wikipedia',
445 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
446 'iw_local' => 0 ),
447 array( 'iw_prefix' => 'MeatBall',
448 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
449 'iw_local' => 0 ),
450 array( 'iw_prefix' => 'zh',
451 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
452 'iw_local' => 1 ),
453 array( 'iw_prefix' => 'es',
454 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
455 'iw_local' => 1 ),
456 array( 'iw_prefix' => 'fr',
457 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
458 'iw_local' => 1 ),
459 array( 'iw_prefix' => 'ru',
460 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
461 'iw_local' => 1 ),
462 ) );
463
464 # Hack: Insert an image to work with
465 $db->insert( 'image', array(
466 'img_name' => 'Foobar.jpg',
467 'img_size' => 12345,
468 'img_description' => 'Some lame file',
469 'img_user' => 1,
470 'img_user_text' => 'WikiSysop',
471 'img_timestamp' => $db->timestamp( '20010115123500' ),
472 'img_width' => 1941,
473 'img_height' => 220,
474 'img_bits' => 24,
475 'img_media_type' => MEDIATYPE_BITMAP,
476 'img_major_mime' => "image",
477 'img_minor_mime' => "jpeg",
478 ) );
479
480 # Update certain things in site_stats
481 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
482
483 $setupDB = true;
484 }
485 }
486
487 /**
488 * Create a dummy uploads directory which will contain a couple
489 * of files in order to pass existence tests.
490 * @return string The directory
491 * @private
492 */
493 function setupUploadDir() {
494 global $IP;
495
496 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
497 mkdir( $dir );
498 mkdir( $dir . '/3' );
499 mkdir( $dir . '/3/3a' );
500
501 $img = "$IP/skins/monobook/headbg.jpg";
502 $h = fopen($img, 'r');
503 $c = fread($h, filesize($img));
504 fclose($h);
505
506 $f = fopen( $dir . '/3/3a/Foobar.jpg', 'wb' );
507 fwrite( $f, $c );
508 fclose( $f );
509 return $dir;
510 }
511
512 /**
513 * Restore default values and perform any necessary clean-up
514 * after each test runs.
515 *
516 * @private
517 */
518 function teardownGlobals() {
519 foreach( $this->savedGlobals as $var => $val ) {
520 $GLOBALS[$var] = $val;
521 }
522 if( isset( $this->uploadDir ) ) {
523 $this->teardownUploadDir( $this->uploadDir );
524 unset( $this->uploadDir );
525 }
526 }
527
528 /**
529 * Remove the dummy uploads directory
530 * @private
531 */
532 function teardownUploadDir( $dir ) {
533 unlink( "$dir/3/3a/Foobar.jpg" );
534 rmdir( "$dir/3/3a" );
535 rmdir( "$dir/3" );
536 @rmdir( "$dir/thumb/6/65" );
537 @rmdir( "$dir/thumb/6" );
538
539 @unlink( "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg" );
540 @rmdir( "$dir/thumb/3/3a/Foobar.jpg" );
541 @rmdir( "$dir/thumb/3/3a" );
542 @rmdir( "$dir/thumb/3/39" ); # wtf?
543 @rmdir( "$dir/thumb/3" );
544 @rmdir( "$dir/thumb" );
545 @rmdir( "$dir" );
546 }
547
548 /**
549 * "Running test $desc..."
550 * @private
551 */
552 function showTesting( $desc ) {
553 print "Running test $desc... ";
554 }
555
556 /**
557 * Print a happy success message.
558 *
559 * @param string $desc The test name
560 * @return bool
561 * @private
562 */
563 function showSuccess( $desc ) {
564 if( !$this->quiet ) {
565 print $this->termColor( '1;32' ) . 'PASSED' . $this->termReset() . "\n";
566 }
567 return true;
568 }
569
570 /**
571 * Print a failure message and provide some explanatory output
572 * about what went wrong if so configured.
573 *
574 * @param string $desc The test name
575 * @param string $result Expected HTML output
576 * @param string $html Actual HTML output
577 * @return bool
578 * @private
579 */
580 function showFailure( $desc, $result, $html ) {
581 if( $this->quiet ) {
582 # In quiet mode we didn't show the 'Testing' message before the
583 # test, in case it succeeded. Show it now:
584 $this->showTesting( $desc );
585 }
586 print $this->termColor( '1;31' ) . 'FAILED!' . $this->termReset() . "\n";
587 if( $this->showDiffs ) {
588 print $this->quickDiff( $result, $html );
589 if( !$this->wellFormed( $html ) ) {
590 print "XML error: $this->mXmlError\n";
591 }
592 }
593 return false;
594 }
595
596 /**
597 * Run given strings through a diff and return the (colorized) output.
598 * Requires writable /tmp directory and a 'diff' command in the PATH.
599 *
600 * @param string $input
601 * @param string $output
602 * @param string $inFileTail Tailing for the input file name
603 * @param string $outFileTail Tailing for the output file name
604 * @return string
605 * @private
606 */
607 function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
608 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
609
610 $infile = "$prefix-$inFileTail";
611 $this->dumpToFile( $input, $infile );
612
613 $outfile = "$prefix-$outFileTail";
614 $this->dumpToFile( $output, $outfile );
615
616 $diff = `diff -au $infile $outfile`;
617 unlink( $infile );
618 unlink( $outfile );
619
620 return $this->colorDiff( $diff );
621 }
622
623 /**
624 * Write the given string to a file, adding a final newline.
625 *
626 * @param string $data
627 * @param string $filename
628 * @private
629 */
630 function dumpToFile( $data, $filename ) {
631 $file = fopen( $filename, "wt" );
632 fwrite( $file, $data . "\n" );
633 fclose( $file );
634 }
635
636 /**
637 * Return ANSI terminal escape code for changing text attribs/color,
638 * or empty string if color output is disabled.
639 *
640 * @param string $color Semicolon-separated list of attribute/color codes
641 * @return string
642 * @private
643 */
644 function termColor( $color ) {
645 if($this->lightcolor) {
646 return $this->color ? "\x1b[1;{$color}m" : '';
647 } else {
648 return $this->color ? "\x1b[{$color}m" : '';
649 }
650 }
651
652 /**
653 * Return ANSI terminal escape code for restoring default text attributes,
654 * or empty string if color output is disabled.
655 *
656 * @return string
657 * @private
658 */
659 function termReset() {
660 return $this->color ? "\x1b[0m" : '';
661 }
662
663 /**
664 * Colorize unified diff output if set for ANSI color output.
665 * Subtractions are colored blue, additions red.
666 *
667 * @param string $text
668 * @return string
669 * @private
670 */
671 function colorDiff( $text ) {
672 return preg_replace(
673 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
674 array( $this->termColor( 34 ) . '$1' . $this->termReset(),
675 $this->termColor( 31 ) . '$1' . $this->termReset() ),
676 $text );
677 }
678
679 /**
680 * Insert a temporary test article
681 * @param string $name the title, including any prefix
682 * @param string $text the article text
683 * @param int $line the input line number, for reporting errors
684 * @private
685 */
686 function addArticle($name, $text, $line) {
687 $this->setupGlobals();
688 $title = Title::newFromText( $name );
689 if ( is_null($title) ) {
690 wfDie( "invalid title at line $line\n" );
691 }
692
693 $aid = $title->getArticleID( GAID_FOR_UPDATE );
694 if ($aid != 0) {
695 wfDie( "duplicate article at line $line\n" );
696 }
697
698 $art = new Article($title);
699 $art->insertNewArticle($text, '', false, false );
700 $this->teardownGlobals();
701 }
702
703 /**
704 * Steal a callback function from the primary parser, save it for
705 * application to our scary parser. If the hook is not installed,
706 * die a painful dead to warn the others.
707 * @param string $name
708 */
709 private function requireHook( $name ) {
710 global $wgParser;
711 if( isset( $wgParser->mTagHooks[$name] ) ) {
712 $this->hooks[$name] = $wgParser->mTagHooks[$name];
713 } else {
714 wfDie( "This test suite requires the '$name' hook extension.\n" );
715 }
716 }
717
718 /*
719 * Run the "tidy" command on text if the $wgUseTidy
720 * global is true
721 *
722 * @param string $text the text to tidy
723 * @return string
724 * @static
725 * @private
726 */
727 function tidy( $text ) {
728 global $wgUseTidy;
729 if ($wgUseTidy) {
730 $text = Parser::tidy($text);
731 }
732 return $text;
733 }
734
735 function wellFormed( $text ) {
736 $html =
737 Sanitizer::hackDocType() .
738 '<html>' .
739 $text .
740 '</html>';
741
742 $parser = xml_parser_create( "UTF-8" );
743
744 # case folding violates XML standard, turn it off
745 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
746
747 if( !xml_parse( $parser, $html, true ) ) {
748 $err = xml_error_string( xml_get_error_code( $parser ) );
749 $position = xml_get_current_byte_index( $parser );
750 $fragment = $this->extractFragment( $html, $position );
751 $this->mXmlError = "$err at byte $position:\n$fragment";
752 xml_parser_free( $parser );
753 return false;
754 }
755 xml_parser_free( $parser );
756 return true;
757 }
758
759 function extractFragment( $text, $position ) {
760 $start = max( 0, $position - 10 );
761 $before = $position - $start;
762 $fragment = '...' .
763 $this->termColor( 34 ) .
764 substr( $text, $start, $before ) .
765 $this->termColor( 0 ) .
766 $this->termColor( 31 ) .
767 $this->termColor( 1 ) .
768 substr( $text, $position, 1 ) .
769 $this->termColor( 0 ) .
770 $this->termColor( 34 ) .
771 substr( $text, $position + 1, 9 ) .
772 $this->termColor( 0 ) .
773 '...';
774 $display = str_replace( "\n", ' ', $fragment );
775 $caret = ' ' .
776 str_repeat( ' ', $before ) .
777 $this->termColor( 31 ) .
778 '^' .
779 $this->termColor( 0 );
780 return "$display\n$caret";
781 }
782
783 }
784
785 ?>