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