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