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