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