1c3ba1dcaf876c1ed1a13ab80bde4ebab22fc508
[lhc/web/wiklou.git] / tests / parser / parserTest.inc
1 <?php
2 /**
3 * Helper code for the MediaWiki parser test suite. Some code is duplicated
4 * in PHPUnit's NewParserTests.php, so you'll probably want to update both
5 * at the same time.
6 *
7 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
8 * http://www.mediawiki.org/
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @todo Make this more independent of the configuration (and if possible the database)
26 * @todo document
27 * @file
28 * @ingroup Testing
29 */
30
31 /**
32 * @ingroup Testing
33 */
34 class ParserTest {
35 /**
36 * boolean $color whereas output should be colorized
37 */
38 private $color;
39
40 /**
41 * boolean $showOutput Show test output
42 */
43 private $showOutput;
44
45 /**
46 * boolean $useTemporaryTables Use temporary tables for the temporary database
47 */
48 private $useTemporaryTables = true;
49
50 /**
51 * boolean $databaseSetupDone True if the database has been set up
52 */
53 private $databaseSetupDone = false;
54
55 /**
56 * Our connection to the database
57 * @var DatabaseBase
58 */
59 private $db;
60
61 /**
62 * Database clone helper
63 * @var CloneDatabase
64 */
65 private $dbClone;
66
67 /**
68 * string $oldTablePrefix Original table prefix
69 */
70 private $oldTablePrefix;
71
72 private $maxFuzzTestLength = 300;
73 private $fuzzSeed = 0;
74 private $memoryLimit = 50;
75 private $uploadDir = null;
76
77 public $regex = "";
78 private $savedGlobals = array();
79
80 /**
81 * Sets terminal colorization and diff/quick modes depending on OS and
82 * command-line options (--color and --quick).
83 */
84 public function __construct( $options = array() ) {
85 # Only colorize output if stdout is a terminal.
86 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
87
88 if ( isset( $options['color'] ) ) {
89 switch ( $options['color'] ) {
90 case 'no':
91 $this->color = false;
92 break;
93 case 'yes':
94 default:
95 $this->color = true;
96 break;
97 }
98 }
99
100 $this->term = $this->color
101 ? new AnsiTermColorer()
102 : new DummyTermColorer();
103
104 $this->showDiffs = !isset( $options['quick'] );
105 $this->showProgress = !isset( $options['quiet'] );
106 $this->showFailure = !(
107 isset( $options['quiet'] )
108 && ( isset( $options['record'] )
109 || isset( $options['compare'] ) ) ); // redundant output
110
111 $this->showOutput = isset( $options['show-output'] );
112
113 if ( isset( $options['filter'] ) ) {
114 $options['regex'] = $options['filter'];
115 }
116
117 if ( isset( $options['regex'] ) ) {
118 if ( isset( $options['record'] ) ) {
119 echo "Warning: --record cannot be used with --regex, disabling --record\n";
120 unset( $options['record'] );
121 }
122 $this->regex = $options['regex'];
123 } else {
124 # Matches anything
125 $this->regex = '';
126 }
127
128 $this->setupRecorder( $options );
129 $this->keepUploads = isset( $options['keep-uploads'] );
130
131 if ( isset( $options['seed'] ) ) {
132 $this->fuzzSeed = intval( $options['seed'] ) - 1;
133 }
134
135 $this->runDisabled = isset( $options['run-disabled'] );
136 $this->runParsoid = isset( $options['run-parsoid'] );
137
138 $this->hooks = array();
139 $this->functionHooks = array();
140 self::setUp();
141 }
142
143 static function setUp() {
144 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
145 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
146 $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
147 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
148 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
149 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
150
151 $wgScript = '/index.php';
152 $wgScriptPath = '/';
153 $wgArticlePath = '/wiki/$1';
154 $wgStylePath = '/skins';
155 $wgExtensionAssetsPath = '/extensions';
156 $wgThumbnailScriptPath = false;
157 $wgLockManagers = array( array(
158 'name' => 'fsLockManager',
159 'class' => 'FSLockManager',
160 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
161 ), array(
162 'name' => 'nullLockManager',
163 'class' => 'NullLockManager',
164 ) );
165 $wgLocalFileRepo = array(
166 'class' => 'LocalRepo',
167 'name' => 'local',
168 'url' => 'http://example.com/images',
169 'hashLevels' => 2,
170 'transformVia404' => false,
171 'backend' => new FSFileBackend( array(
172 'name' => 'local-backend',
173 'lockManager' => 'fsLockManager',
174 'containerPaths' => array(
175 'local-public' => wfTempDir() . '/test-repo/public',
176 'local-thumb' => wfTempDir() . '/test-repo/thumb',
177 'local-temp' => wfTempDir() . '/test-repo/temp',
178 'local-deleted' => wfTempDir() . '/test-repo/deleted',
179 )
180 ) )
181 );
182 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
183 $wgNamespaceAliases['Image'] = NS_FILE;
184 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
185
186 // XXX: tests won't run without this (for CACHE_DB)
187 if ( $wgMainCacheType === CACHE_DB ) {
188 $wgMainCacheType = CACHE_NONE;
189 }
190 if ( $wgMessageCacheType === CACHE_DB ) {
191 $wgMessageCacheType = CACHE_NONE;
192 }
193 if ( $wgParserCacheType === CACHE_DB ) {
194 $wgParserCacheType = CACHE_NONE;
195 }
196
197 $wgEnableParserCache = false;
198 DeferredUpdates::clearPendingUpdates();
199 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
200 $messageMemc = wfGetMessageCacheStorage();
201 $parserMemc = wfGetParserCacheStorage();
202
203 // $wgContLang = new StubContLang;
204 $wgUser = new User;
205 $context = new RequestContext;
206 $wgLang = $context->getLanguage();
207 $wgOut = $context->getOutput();
208 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
209 $wgRequest = $context->getRequest();
210
211 if ( $wgStyleDirectory === false ) {
212 $wgStyleDirectory = "$IP/skins";
213 }
214
215 }
216
217 public function setupRecorder( $options ) {
218 if ( isset( $options['record'] ) ) {
219 $this->recorder = new DbTestRecorder( $this );
220 $this->recorder->version = isset( $options['setversion'] ) ?
221 $options['setversion'] : SpecialVersion::getVersion();
222 } elseif ( isset( $options['compare'] ) ) {
223 $this->recorder = new DbTestPreviewer( $this );
224 } else {
225 $this->recorder = new TestRecorder( $this );
226 }
227 }
228
229 /**
230 * Remove last character if it is a newline
231 * @group utility
232 */
233 public static function chomp( $s ) {
234 if ( substr( $s, -1 ) === "\n" ) {
235 return substr( $s, 0, -1 );
236 } else {
237 return $s;
238 }
239 }
240
241 /**
242 * Run a fuzz test series
243 * Draw input from a set of test files
244 */
245 function fuzzTest( $filenames ) {
246 $GLOBALS['wgContLang'] = Language::factory( 'en' );
247 $dict = $this->getFuzzInput( $filenames );
248 $dictSize = strlen( $dict );
249 $logMaxLength = log( $this->maxFuzzTestLength );
250 $this->setupDatabase();
251 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
252
253 $numTotal = 0;
254 $numSuccess = 0;
255 $user = new User;
256 $opts = ParserOptions::newFromUser( $user );
257 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
258
259 while ( true ) {
260 // Generate test input
261 mt_srand( ++$this->fuzzSeed );
262 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
263 $input = '';
264
265 while ( strlen( $input ) < $totalLength ) {
266 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
267 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
268 $offset = mt_rand( 0, $dictSize - $hairLength );
269 $input .= substr( $dict, $offset, $hairLength );
270 }
271
272 $this->setupGlobals();
273 $parser = $this->getParser();
274
275 // Run the test
276 try {
277 $parser->parse( $input, $title, $opts );
278 $fail = false;
279 } catch ( Exception $exception ) {
280 $fail = true;
281 }
282
283 if ( $fail ) {
284 echo "Test failed with seed {$this->fuzzSeed}\n";
285 echo "Input:\n";
286 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
287 echo "$exception\n";
288 } else {
289 $numSuccess++;
290 }
291
292 $numTotal++;
293 $this->teardownGlobals();
294 $parser->__destruct();
295
296 if ( $numTotal % 100 == 0 ) {
297 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
298 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
299 if ( $usage > 90 ) {
300 echo "Out of memory:\n";
301 $memStats = $this->getMemoryBreakdown();
302
303 foreach ( $memStats as $name => $usage ) {
304 echo "$name: $usage\n";
305 }
306 $this->abort();
307 }
308 }
309 }
310 }
311
312 /**
313 * Get an input dictionary from a set of parser test files
314 */
315 function getFuzzInput( $filenames ) {
316 $dict = '';
317
318 foreach ( $filenames as $filename ) {
319 $contents = file_get_contents( $filename );
320 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
321
322 foreach ( $matches[1] as $match ) {
323 $dict .= $match . "\n";
324 }
325 }
326
327 return $dict;
328 }
329
330 /**
331 * Get a memory usage breakdown
332 */
333 function getMemoryBreakdown() {
334 $memStats = array();
335
336 foreach ( $GLOBALS as $name => $value ) {
337 $memStats['$' . $name] = strlen( serialize( $value ) );
338 }
339
340 $classes = get_declared_classes();
341
342 foreach ( $classes as $class ) {
343 $rc = new ReflectionClass( $class );
344 $props = $rc->getStaticProperties();
345 $memStats[$class] = strlen( serialize( $props ) );
346 $methods = $rc->getMethods();
347
348 foreach ( $methods as $method ) {
349 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
350 }
351 }
352
353 $functions = get_defined_functions();
354
355 foreach ( $functions['user'] as $function ) {
356 $rf = new ReflectionFunction( $function );
357 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
358 }
359
360 asort( $memStats );
361
362 return $memStats;
363 }
364
365 function abort() {
366 $this->abort();
367 }
368
369 /**
370 * Run a series of tests listed in the given text files.
371 * Each test consists of a brief description, wikitext input,
372 * and the expected HTML output.
373 *
374 * Prints status updates on stdout and counts up the total
375 * number and percentage of passed tests.
376 *
377 * @param $filenames Array of strings
378 * @return Boolean: true if passed all tests, false if any tests failed.
379 */
380 public function runTestsFromFiles( $filenames ) {
381 $ok = false;
382 $GLOBALS['wgContLang'] = Language::factory( 'en' );
383 $this->recorder->start();
384 try {
385 $this->setupDatabase();
386 $ok = true;
387
388 foreach ( $filenames as $filename ) {
389 $tests = new TestFileIterator( $filename, $this );
390 $ok = $this->runTests( $tests ) && $ok;
391 }
392
393 $this->teardownDatabase();
394 $this->recorder->report();
395 } catch ( DBError $e ) {
396 echo $e->getMessage();
397 }
398 $this->recorder->end();
399
400 return $ok;
401 }
402
403 function runTests( $tests ) {
404 $ok = true;
405
406 foreach ( $tests as $t ) {
407 $result =
408 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
409 $ok = $ok && $result;
410 $this->recorder->record( $t['test'], $result );
411 }
412
413 if ( $this->showProgress ) {
414 print "\n";
415 }
416
417 return $ok;
418 }
419
420 /**
421 * Get a Parser object
422 */
423 function getParser( $preprocessor = null ) {
424 global $wgParserConf;
425
426 $class = $wgParserConf['class'];
427 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
428
429 foreach ( $this->hooks as $tag => $callback ) {
430 $parser->setHook( $tag, $callback );
431 }
432
433 foreach ( $this->functionHooks as $tag => $bits ) {
434 list( $callback, $flags ) = $bits;
435 $parser->setFunctionHook( $tag, $callback, $flags );
436 }
437
438 wfRunHooks( 'ParserTestParser', array( &$parser ) );
439
440 return $parser;
441 }
442
443 /**
444 * Run a given wikitext input through a freshly-constructed wiki parser,
445 * and compare the output against the expected results.
446 * Prints status and explanatory messages to stdout.
447 *
448 * @param $desc String: test's description
449 * @param $input String: wikitext to try rendering
450 * @param $result String: result to output
451 * @param $opts Array: test's options
452 * @param $config String: overrides for global variables, one per line
453 * @return Boolean
454 */
455 public function runTest( $desc, $input, $result, $opts, $config ) {
456 if ( $this->showProgress ) {
457 $this->showTesting( $desc );
458 }
459
460 $opts = $this->parseOptions( $opts );
461 $context = $this->setupGlobals( $opts, $config );
462
463 $user = $context->getUser();
464 $options = ParserOptions::newFromContext( $context );
465
466 if ( isset( $opts['title'] ) ) {
467 $titleText = $opts['title'];
468 } else {
469 $titleText = 'Parser test';
470 }
471
472 $local = isset( $opts['local'] );
473 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
474 $parser = $this->getParser( $preprocessor );
475 $title = Title::newFromText( $titleText );
476
477 if ( isset( $opts['pst'] ) ) {
478 $out = $parser->preSaveTransform( $input, $title, $user, $options );
479 } elseif ( isset( $opts['msg'] ) ) {
480 $out = $parser->transformMsg( $input, $options, $title );
481 } elseif ( isset( $opts['section'] ) ) {
482 $section = $opts['section'];
483 $out = $parser->getSection( $input, $section );
484 } elseif ( isset( $opts['replace'] ) ) {
485 $section = $opts['replace'][0];
486 $replace = $opts['replace'][1];
487 $out = $parser->replaceSection( $input, $section, $replace );
488 } elseif ( isset( $opts['comment'] ) ) {
489 $out = Linker::formatComment( $input, $title, $local );
490 } elseif ( isset( $opts['preload'] ) ) {
491 $out = $parser->getPreloadText( $input, $title, $options );
492 } else {
493 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
494 $out = $output->getText();
495
496 if ( isset( $opts['showtitle'] ) ) {
497 if ( $output->getTitleText() ) {
498 $title = $output->getTitleText();
499 }
500
501 $out = "$title\n$out";
502 }
503
504 if ( isset( $opts['ill'] ) ) {
505 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
506 } elseif ( isset( $opts['cat'] ) ) {
507 $outputPage = $context->getOutput();
508 $outputPage->addCategoryLinks( $output->getCategories() );
509 $cats = $outputPage->getCategoryLinks();
510
511 if ( isset( $cats['normal'] ) ) {
512 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
513 } else {
514 $out = '';
515 }
516 }
517
518 $result = $this->tidy( $result );
519 }
520
521 $this->teardownGlobals();
522
523 $testResult = new ParserTestResult( $desc );
524 $testResult->expected = $result;
525 $testResult->actual = $out;
526
527 return $this->showTestResult( $testResult );
528 }
529
530 /**
531 * Refactored in 1.22 to use ParserTestResult
532 */
533 function showTestResult( ParserTestResult $testResult ) {
534 if ( $testResult->isSuccess() ) {
535 $this->showSuccess( $testResult );
536 return true;
537 } else {
538 $this->showFailure( $testResult );
539 return false;
540 }
541 }
542
543 /**
544 * Use a regex to find out the value of an option
545 * @param $key String: name of option val to retrieve
546 * @param $opts Options array to look in
547 * @param $default Mixed: default value returned if not found
548 */
549 private static function getOptionValue( $key, $opts, $default ) {
550 $key = strtolower( $key );
551
552 if ( isset( $opts[$key] ) ) {
553 return $opts[$key];
554 } else {
555 return $default;
556 }
557 }
558
559 private function parseOptions( $instring ) {
560 $opts = array();
561 // foo
562 // foo=bar
563 // foo="bar baz"
564 // foo=[[bar baz]]
565 // foo=bar,"baz quux"
566 $regex = '/\b
567 ([\w-]+) # Key
568 \b
569 (?:\s*
570 = # First sub-value
571 \s*
572 (
573 "
574 [^"]* # Quoted val
575 "
576 |
577 \[\[
578 [^]]* # Link target
579 \]\]
580 |
581 [\w-]+ # Plain word
582 )
583 (?:\s*
584 , # Sub-vals 1..N
585 \s*
586 (
587 "[^"]*" # Quoted val
588 |
589 \[\[[^]]*\]\] # Link target
590 |
591 [\w-]+ # Plain word
592 )
593 )*
594 )?
595 /x';
596
597 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
598 foreach ( $matches as $bits ) {
599 array_shift( $bits );
600 $key = strtolower( array_shift( $bits ) );
601 if ( count( $bits ) == 0 ) {
602 $opts[$key] = true;
603 } elseif ( count( $bits ) == 1 ) {
604 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
605 } else {
606 // Array!
607 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
608 }
609 }
610 }
611 return $opts;
612 }
613
614 private function cleanupOption( $opt ) {
615 if ( substr( $opt, 0, 1 ) == '"' ) {
616 return substr( $opt, 1, -1 );
617 }
618
619 if ( substr( $opt, 0, 2 ) == '[[' ) {
620 return substr( $opt, 2, -2 );
621 }
622 return $opt;
623 }
624
625 /**
626 * Set up the global variables for a consistent environment for each test.
627 * Ideally this should replace the global configuration entirely.
628 */
629 private function setupGlobals( $opts = '', $config = '' ) {
630 # Find out values for some special options.
631 $lang =
632 self::getOptionValue( 'language', $opts, 'en' );
633 $variant =
634 self::getOptionValue( 'variant', $opts, false );
635 $maxtoclevel =
636 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
637 $linkHolderBatchSize =
638 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
639
640 $settings = array(
641 'wgServer' => 'http://example.org',
642 'wgScript' => '/index.php',
643 'wgScriptPath' => '/',
644 'wgArticlePath' => '/wiki/$1',
645 'wgActionPaths' => array(),
646 'wgLockManagers' => array( array(
647 'name' => 'fsLockManager',
648 'class' => 'FSLockManager',
649 'lockDirectory' => $this->uploadDir . '/lockdir',
650 ), array(
651 'name' => 'nullLockManager',
652 'class' => 'NullLockManager',
653 ) ),
654 'wgLocalFileRepo' => array(
655 'class' => 'LocalRepo',
656 'name' => 'local',
657 'url' => 'http://example.com/images',
658 'hashLevels' => 2,
659 'transformVia404' => false,
660 'backend' => new FSFileBackend( array(
661 'name' => 'local-backend',
662 'lockManager' => 'fsLockManager',
663 'containerPaths' => array(
664 'local-public' => $this->uploadDir,
665 'local-thumb' => $this->uploadDir . '/thumb',
666 'local-temp' => $this->uploadDir . '/temp',
667 'local-deleted' => $this->uploadDir . '/delete',
668 )
669 ) )
670 ),
671 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
672 'wgStylePath' => '/skins',
673 'wgSitename' => 'MediaWiki',
674 'wgLanguageCode' => $lang,
675 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
676 'wgRawHtml' => isset( $opts['rawhtml'] ),
677 'wgLang' => null,
678 'wgContLang' => null,
679 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
680 'wgMaxTocLevel' => $maxtoclevel,
681 'wgCapitalLinks' => true,
682 'wgNoFollowLinks' => true,
683 'wgNoFollowDomainExceptions' => array(),
684 'wgThumbnailScriptPath' => false,
685 'wgUseImageResize' => true,
686 'wgSVGConverter' => 'null',
687 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
688 'wgLocaltimezone' => 'UTC',
689 'wgAllowExternalImages' => true,
690 'wgUseTidy' => false,
691 'wgDefaultLanguageVariant' => $variant,
692 'wgVariantArticlePath' => false,
693 'wgGroupPermissions' => array( '*' => array(
694 'createaccount' => true,
695 'read' => true,
696 'edit' => true,
697 'createpage' => true,
698 'createtalk' => true,
699 ) ),
700 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
701 'wgDefaultExternalStore' => array(),
702 'wgForeignFileRepos' => array(),
703 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
704 'wgExperimentalHtmlIds' => false,
705 'wgExternalLinkTarget' => false,
706 'wgAlwaysUseTidy' => false,
707 'wgHtml5' => true,
708 'wgWellFormedXml' => true,
709 'wgAllowMicrodataAttributes' => true,
710 'wgAdaptiveMessageCache' => true,
711 'wgDisableLangConversion' => false,
712 'wgDisableTitleConversion' => false,
713 );
714
715 if ( $config ) {
716 $configLines = explode( "\n", $config );
717
718 foreach ( $configLines as $line ) {
719 list( $var, $value ) = explode( '=', $line, 2 );
720
721 $settings[$var] = eval( "return $value;" );
722 }
723 }
724
725 $this->savedGlobals = array();
726
727 /** @since 1.20 */
728 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
729
730 foreach ( $settings as $var => $val ) {
731 if ( array_key_exists( $var, $GLOBALS ) ) {
732 $this->savedGlobals[$var] = $GLOBALS[$var];
733 }
734
735 $GLOBALS[$var] = $val;
736 }
737
738 $GLOBALS['wgContLang'] = Language::factory( $lang );
739 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
740
741 $context = new RequestContext();
742 $GLOBALS['wgLang'] = $context->getLanguage();
743 $GLOBALS['wgOut'] = $context->getOutput();
744
745 $GLOBALS['wgUser'] = new User();
746
747 global $wgHooks;
748
749 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
750 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
751
752 MagicWord::clearCache();
753
754 return $context;
755 }
756
757 /**
758 * List of temporary tables to create, without prefix.
759 * Some of these probably aren't necessary.
760 */
761 private function listTables() {
762 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
763 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
764 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
765 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
766 'recentchanges', 'watchlist', 'interwiki', 'logging',
767 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
768 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
769 );
770
771 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
772 array_push( $tables, 'searchindex' );
773 }
774
775 // Allow extensions to add to the list of tables to duplicate;
776 // may be necessary if they hook into page save or other code
777 // which will require them while running tests.
778 wfRunHooks( 'ParserTestTables', array( &$tables ) );
779
780 return $tables;
781 }
782
783 /**
784 * Set up a temporary set of wiki tables to work with for the tests.
785 * Currently this will only be done once per run, and any changes to
786 * the db will be visible to later tests in the run.
787 */
788 public function setupDatabase() {
789 global $wgDBprefix;
790
791 if ( $this->databaseSetupDone ) {
792 return;
793 }
794
795 $this->db = wfGetDB( DB_MASTER );
796 $dbType = $this->db->getType();
797
798 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
799 throw new MWException( 'setupDatabase should be called before setupGlobals' );
800 }
801
802 $this->databaseSetupDone = true;
803 $this->oldTablePrefix = $wgDBprefix;
804
805 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
806 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
807 # This works around it for now...
808 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
809
810 # CREATE TEMPORARY TABLE breaks if there is more than one server
811 if ( wfGetLB()->getServerCount() != 1 ) {
812 $this->useTemporaryTables = false;
813 }
814
815 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
816 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
817
818 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
819 $this->dbClone->useTemporaryTables( $temporary );
820 $this->dbClone->cloneTableStructure();
821
822 if ( $dbType == 'oracle' ) {
823 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
824 # Insert 0 user to prevent FK violations
825
826 # Anonymous user
827 $this->db->insert( 'user', array(
828 'user_id' => 0,
829 'user_name' => 'Anonymous' ) );
830 }
831
832 # Hack: insert a few Wikipedia in-project interwiki prefixes,
833 # for testing inter-language links
834 $this->db->insert( 'interwiki', array(
835 array( 'iw_prefix' => 'wikipedia',
836 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
837 'iw_api' => '',
838 'iw_wikiid' => '',
839 'iw_local' => 0 ),
840 array( 'iw_prefix' => 'meatball',
841 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
842 'iw_api' => '',
843 'iw_wikiid' => '',
844 'iw_local' => 0 ),
845 array( 'iw_prefix' => 'zh',
846 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
847 'iw_api' => '',
848 'iw_wikiid' => '',
849 'iw_local' => 1 ),
850 array( 'iw_prefix' => 'es',
851 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
852 'iw_api' => '',
853 'iw_wikiid' => '',
854 'iw_local' => 1 ),
855 array( 'iw_prefix' => 'fr',
856 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
857 'iw_api' => '',
858 'iw_wikiid' => '',
859 'iw_local' => 1 ),
860 array( 'iw_prefix' => 'ru',
861 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
862 'iw_api' => '',
863 'iw_wikiid' => '',
864 'iw_local' => 1 ),
865 ) );
866
867 # Update certain things in site_stats
868 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
869
870 # Reinitialise the LocalisationCache to match the database state
871 Language::getLocalisationCache()->unloadAll();
872
873 # Clear the message cache
874 MessageCache::singleton()->clear();
875
876 // Remember to update newParserTests.php after changing the below
877 // (and it uses a slightly different syntax just for teh lulz)
878 $this->uploadDir = $this->setupUploadDir();
879 $user = User::createNew( 'WikiSysop' );
880 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
881 # note that the size/width/height/bits/etc of the file
882 # are actually set by inspecting the file itself; the arguments
883 # to recordUpload2 have no effect. That said, we try to make things
884 # match up so it is less confusing to readers of the code & tests.
885 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
886 'size' => 7881,
887 'width' => 1941,
888 'height' => 220,
889 'bits' => 8,
890 'media_type' => MEDIATYPE_BITMAP,
891 'mime' => 'image/jpeg',
892 'metadata' => serialize( array() ),
893 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
894 'fileExists' => true
895 ), $this->db->timestamp( '20010115123500' ), $user );
896
897 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
898 # again, note that size/width/height below are ignored; see above.
899 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
900 'size' => 22589,
901 'width' => 135,
902 'height' => 135,
903 'bits' => 8,
904 'media_type' => MEDIATYPE_BITMAP,
905 'mime' => 'image/png',
906 'metadata' => serialize( array() ),
907 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
908 'fileExists' => true
909 ), $this->db->timestamp( '20130225203040' ), $user );
910
911 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
912 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
913 'size' => 12345,
914 'width' => 240,
915 'height' => 180,
916 'bits' => 24,
917 'media_type' => MEDIATYPE_DRAWING,
918 'mime' => 'image/svg+xml',
919 'metadata' => serialize( array() ),
920 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
921 'fileExists' => true
922 ), $this->db->timestamp( '20010115123500' ), $user );
923
924 # This image will be blacklisted in [[MediaWiki:Bad image list]]
925 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
926 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
927 'size' => 12345,
928 'width' => 320,
929 'height' => 240,
930 'bits' => 24,
931 'media_type' => MEDIATYPE_BITMAP,
932 'mime' => 'image/jpeg',
933 'metadata' => serialize( array() ),
934 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
935 'fileExists' => true
936 ), $this->db->timestamp( '20010115123500' ), $user );
937 }
938
939 public function teardownDatabase() {
940 if ( !$this->databaseSetupDone ) {
941 $this->teardownGlobals();
942 return;
943 }
944 $this->teardownUploadDir( $this->uploadDir );
945
946 $this->dbClone->destroy();
947 $this->databaseSetupDone = false;
948
949 if ( $this->useTemporaryTables ) {
950 if ( $this->db->getType() == 'sqlite' ) {
951 # Under SQLite the searchindex table is virtual and need
952 # to be explicitly destroyed. See bug 29912
953 # See also MediaWikiTestCase::destroyDB()
954 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
955 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
956 }
957 # Don't need to do anything
958 $this->teardownGlobals();
959 return;
960 }
961
962 $tables = $this->listTables();
963
964 foreach ( $tables as $table ) {
965 $sql = $this->db->getType() == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
966 $this->db->query( $sql );
967 }
968
969 if ( $this->db->getType() == 'oracle' ) {
970 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
971 }
972
973 $this->teardownGlobals();
974 }
975
976 /**
977 * Create a dummy uploads directory which will contain a couple
978 * of files in order to pass existence tests.
979 *
980 * @return String: the directory
981 */
982 private function setupUploadDir() {
983 global $IP;
984
985 if ( $this->keepUploads ) {
986 $dir = wfTempDir() . '/mwParser-images';
987
988 if ( is_dir( $dir ) ) {
989 return $dir;
990 }
991 } else {
992 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
993 }
994
995 // wfDebug( "Creating upload directory $dir\n" );
996 if ( file_exists( $dir ) ) {
997 wfDebug( "Already exists!\n" );
998 return $dir;
999 }
1000
1001 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1002 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1003 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1004 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1005 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1006 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1007 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1008 copy( "$IP/skins/monobook/headbg.jpg", "$dir/f/ff/Foobar.svg" );
1009 file_put_contents( "$dir/f/ff/Foobar.svg",
1010 '<?xml version="1.0" encoding="utf-8"?>' .
1011 '<svg xmlns="http://www.w3.org/2000/svg" />' );
1012 return $dir;
1013 }
1014
1015 /**
1016 * Restore default values and perform any necessary clean-up
1017 * after each test runs.
1018 */
1019 private function teardownGlobals() {
1020 RepoGroup::destroySingleton();
1021 FileBackendGroup::destroySingleton();
1022 LockManagerGroup::destroySingletons();
1023 LinkCache::singleton()->clear();
1024
1025 foreach ( $this->savedGlobals as $var => $val ) {
1026 $GLOBALS[$var] = $val;
1027 }
1028 }
1029
1030 /**
1031 * Remove the dummy uploads directory
1032 */
1033 private function teardownUploadDir( $dir ) {
1034 if ( $this->keepUploads ) {
1035 return;
1036 }
1037
1038 // delete the files first, then the dirs.
1039 self::deleteFiles(
1040 array(
1041 "$dir/3/3a/Foobar.jpg",
1042 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1043 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1044 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1045 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1046 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1047 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1048 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1049 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1050 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1051 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1052 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1053 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1054 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1055 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1056
1057 "$dir/e/ea/Thumb.png",
1058
1059 "$dir/0/09/Bad.jpg",
1060
1061 "$dir/f/ff/Foobar.svg",
1062 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1063 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1064 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1065 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1066 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1067 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1068
1069 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1070 )
1071 );
1072
1073 self::deleteDirs(
1074 array(
1075 "$dir/3/3a",
1076 "$dir/3",
1077 "$dir/thumb/6/65",
1078 "$dir/thumb/6",
1079 "$dir/thumb/3/3a/Foobar.jpg",
1080 "$dir/thumb/3/3a",
1081 "$dir/thumb/3",
1082 "$dir/e/ea",
1083 "$dir/e",
1084 "$dir/f/ff/",
1085 "$dir/f/",
1086 "$dir/thumb/f/ff/Foobar.svg",
1087 "$dir/thumb/f/ff/",
1088 "$dir/thumb/f/",
1089 "$dir/0/09/",
1090 "$dir/0/",
1091 "$dir/thumb",
1092 "$dir/math/f/a/5",
1093 "$dir/math/f/a",
1094 "$dir/math/f",
1095 "$dir/math",
1096 "$dir",
1097 )
1098 );
1099 }
1100
1101 /**
1102 * Delete the specified files, if they exist.
1103 * @param $files Array: full paths to files to delete.
1104 */
1105 private static function deleteFiles( $files ) {
1106 foreach ( $files as $file ) {
1107 if ( file_exists( $file ) ) {
1108 unlink( $file );
1109 }
1110 }
1111 }
1112
1113 /**
1114 * Delete the specified directories, if they exist. Must be empty.
1115 * @param $dirs Array: full paths to directories to delete.
1116 */
1117 private static function deleteDirs( $dirs ) {
1118 foreach ( $dirs as $dir ) {
1119 if ( is_dir( $dir ) ) {
1120 rmdir( $dir );
1121 }
1122 }
1123 }
1124
1125 /**
1126 * "Running test $desc..."
1127 */
1128 protected function showTesting( $desc ) {
1129 print "Running test $desc... ";
1130 }
1131
1132 /**
1133 * Print a happy success message.
1134 *
1135 * Refactored in 1.22 to use ParserTestResult
1136 *
1137 * @param $testResult ParserTestResult
1138 * @return Boolean
1139 */
1140 protected function showSuccess( ParserTestResult $testResult ) {
1141 if ( $this->showProgress ) {
1142 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1143 }
1144
1145 return true;
1146 }
1147
1148 /**
1149 * Print a failure message and provide some explanatory output
1150 * about what went wrong if so configured.
1151 *
1152 * Refactored in 1.22 to use ParserTestResult
1153 *
1154 * @param $testResult ParserTestResult
1155 * @return Boolean
1156 */
1157 protected function showFailure( ParserTestResult $testResult ) {
1158 if ( $this->showFailure ) {
1159 if ( !$this->showProgress ) {
1160 # In quiet mode we didn't show the 'Testing' message before the
1161 # test, in case it succeeded. Show it now:
1162 $this->showTesting( $testResult->description );
1163 }
1164
1165 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1166
1167 if ( $this->showOutput ) {
1168 print "--- Expected ---\n{$testResult->expected}\n";
1169 print "--- Actual ---\n{$testResult->actual}\n";
1170 }
1171
1172 if ( $this->showDiffs ) {
1173 print $this->quickDiff( $testResult->expected, $testResult->actual );
1174 if ( !$this->wellFormed( $testResult->actual ) ) {
1175 print "XML error: $this->mXmlError\n";
1176 }
1177 }
1178 }
1179
1180 return false;
1181 }
1182
1183 /**
1184 * Run given strings through a diff and return the (colorized) output.
1185 * Requires writable /tmp directory and a 'diff' command in the PATH.
1186 *
1187 * @param $input String
1188 * @param $output String
1189 * @param $inFileTail String: tailing for the input file name
1190 * @param $outFileTail String: tailing for the output file name
1191 * @return String
1192 */
1193 protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
1194 # Windows, or at least the fc utility, is retarded
1195 $slash = wfIsWindows() ? '\\' : '/';
1196 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1197
1198 $infile = "$prefix-$inFileTail";
1199 $this->dumpToFile( $input, $infile );
1200
1201 $outfile = "$prefix-$outFileTail";
1202 $this->dumpToFile( $output, $outfile );
1203
1204 $shellInfile = wfEscapeShellArg( $infile );
1205 $shellOutfile = wfEscapeShellArg( $outfile );
1206
1207 global $wgDiff3;
1208 // we assume that people with diff3 also have usual diff
1209 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1210
1211 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1212
1213 unlink( $infile );
1214 unlink( $outfile );
1215
1216 return $this->colorDiff( $diff );
1217 }
1218
1219 /**
1220 * Write the given string to a file, adding a final newline.
1221 *
1222 * @param $data String
1223 * @param $filename String
1224 */
1225 private function dumpToFile( $data, $filename ) {
1226 $file = fopen( $filename, "wt" );
1227 fwrite( $file, $data . "\n" );
1228 fclose( $file );
1229 }
1230
1231 /**
1232 * Colorize unified diff output if set for ANSI color output.
1233 * Subtractions are colored blue, additions red.
1234 *
1235 * @param $text String
1236 * @return String
1237 */
1238 protected function colorDiff( $text ) {
1239 return preg_replace(
1240 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1241 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1242 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1243 $text );
1244 }
1245
1246 /**
1247 * Show "Reading tests from ..."
1248 *
1249 * @param $path String
1250 */
1251 public function showRunFile( $path ) {
1252 print $this->term->color( 1 ) .
1253 "Reading tests from \"$path\"..." .
1254 $this->term->reset() .
1255 "\n";
1256 }
1257
1258 /**
1259 * Insert a temporary test article
1260 * @param $name String: the title, including any prefix
1261 * @param $text String: the article text
1262 * @param $line Integer: the input line number, for reporting errors
1263 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1264 */
1265 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1266 global $wgCapitalLinks;
1267
1268 $oldCapitalLinks = $wgCapitalLinks;
1269 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1270
1271 $text = self::chomp( $text );
1272 $name = self::chomp( $name );
1273
1274 $title = Title::newFromText( $name );
1275
1276 if ( is_null( $title ) ) {
1277 throw new MWException( "invalid title '$name' at line $line\n" );
1278 }
1279
1280 $page = WikiPage::factory( $title );
1281 $page->loadPageData( 'fromdbmaster' );
1282
1283 if ( $page->exists() ) {
1284 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1285 return;
1286 } else {
1287 throw new MWException( "duplicate article '$name' at line $line\n" );
1288 }
1289 }
1290
1291 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1292
1293 $wgCapitalLinks = $oldCapitalLinks;
1294 }
1295
1296 /**
1297 * Steal a callback function from the primary parser, save it for
1298 * application to our scary parser. If the hook is not installed,
1299 * abort processing of this file.
1300 *
1301 * @param $name String
1302 * @return Bool true if tag hook is present
1303 */
1304 public function requireHook( $name ) {
1305 global $wgParser;
1306
1307 $wgParser->firstCallInit(); // make sure hooks are loaded.
1308
1309 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1310 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1311 } else {
1312 echo " This test suite requires the '$name' hook extension, skipping.\n";
1313 return false;
1314 }
1315
1316 return true;
1317 }
1318
1319 /**
1320 * Steal a callback function from the primary parser, save it for
1321 * application to our scary parser. If the hook is not installed,
1322 * abort processing of this file.
1323 *
1324 * @param $name String
1325 * @return Bool true if function hook is present
1326 */
1327 public function requireFunctionHook( $name ) {
1328 global $wgParser;
1329
1330 $wgParser->firstCallInit(); // make sure hooks are loaded.
1331
1332 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1333 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1334 } else {
1335 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1336 return false;
1337 }
1338
1339 return true;
1340 }
1341
1342 /**
1343 * Run the "tidy" command on text if the $wgUseTidy
1344 * global is true
1345 *
1346 * @param $text String: the text to tidy
1347 * @return String
1348 */
1349 private function tidy( $text ) {
1350 global $wgUseTidy;
1351
1352 if ( $wgUseTidy ) {
1353 $text = MWTidy::tidy( $text );
1354 }
1355
1356 return $text;
1357 }
1358
1359 private function wellFormed( $text ) {
1360 $html =
1361 Sanitizer::hackDocType() .
1362 '<html>' .
1363 $text .
1364 '</html>';
1365
1366 $parser = xml_parser_create( "UTF-8" );
1367
1368 # case folding violates XML standard, turn it off
1369 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1370
1371 if ( !xml_parse( $parser, $html, true ) ) {
1372 $err = xml_error_string( xml_get_error_code( $parser ) );
1373 $position = xml_get_current_byte_index( $parser );
1374 $fragment = $this->extractFragment( $html, $position );
1375 $this->mXmlError = "$err at byte $position:\n$fragment";
1376 xml_parser_free( $parser );
1377
1378 return false;
1379 }
1380
1381 xml_parser_free( $parser );
1382
1383 return true;
1384 }
1385
1386 private function extractFragment( $text, $position ) {
1387 $start = max( 0, $position - 10 );
1388 $before = $position - $start;
1389 $fragment = '...' .
1390 $this->term->color( 34 ) .
1391 substr( $text, $start, $before ) .
1392 $this->term->color( 0 ) .
1393 $this->term->color( 31 ) .
1394 $this->term->color( 1 ) .
1395 substr( $text, $position, 1 ) .
1396 $this->term->color( 0 ) .
1397 $this->term->color( 34 ) .
1398 substr( $text, $position + 1, 9 ) .
1399 $this->term->color( 0 ) .
1400 '...';
1401 $display = str_replace( "\n", ' ', $fragment );
1402 $caret = ' ' .
1403 str_repeat( ' ', $before ) .
1404 $this->term->color( 31 ) .
1405 '^' .
1406 $this->term->color( 0 );
1407
1408 return "$display\n$caret";
1409 }
1410
1411 static function getFakeTimestamp( &$parser, &$ts ) {
1412 $ts = 123;
1413 return true;
1414 }
1415 }