Remove old maintenance script importTextFile.php
[mediawiki.git] / tests / parser / parserTest.inc
blob24c5aba5134cf430b6c7b288c3d8b3d323370db1
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  * https://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          * @var bool $color whereas output should be colorized
37          */
38         private $color;
40         /**
41          * @var bool $showOutput Show test output
42          */
43         private $showOutput;
45         /**
46          * @var bool $useTemporaryTables Use temporary tables for the temporary database
47          */
48         private $useTemporaryTables = true;
50         /**
51          * @var bool $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          * @var DjVuSupport
69          */
70         private $djVuSupport;
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          * @param array $options
84          */
85         public function __construct( $options = array() ) {
86                 # Only colorize output if stdout is a terminal.
87                 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
89                 if ( isset( $options['color'] ) ) {
90                         switch ( $options['color'] ) {
91                                 case 'no':
92                                         $this->color = false;
93                                         break;
94                                 case 'yes':
95                                 default:
96                                         $this->color = true;
97                                         break;
98                         }
99                 }
101                 $this->term = $this->color
102                         ? new AnsiTermColorer()
103                         : new DummyTermColorer();
105                 $this->showDiffs = !isset( $options['quick'] );
106                 $this->showProgress = !isset( $options['quiet'] );
107                 $this->showFailure = !(
108                         isset( $options['quiet'] )
109                                 && ( isset( $options['record'] )
110                                 || isset( $options['compare'] ) ) ); // redundant output
112                 $this->showOutput = isset( $options['show-output'] );
114                 if ( isset( $options['filter'] ) ) {
115                         $options['regex'] = $options['filter'];
116                 }
118                 if ( isset( $options['regex'] ) ) {
119                         if ( isset( $options['record'] ) ) {
120                                 echo "Warning: --record cannot be used with --regex, disabling --record\n";
121                                 unset( $options['record'] );
122                         }
123                         $this->regex = $options['regex'];
124                 } else {
125                         # Matches anything
126                         $this->regex = '';
127                 }
129                 $this->setupRecorder( $options );
130                 $this->keepUploads = isset( $options['keep-uploads'] );
132                 if ( isset( $options['seed'] ) ) {
133                         $this->fuzzSeed = intval( $options['seed'] ) - 1;
134                 }
136                 $this->runDisabled = isset( $options['run-disabled'] );
137                 $this->runParsoid = isset( $options['run-parsoid'] );
139                 $this->djVuSupport = new DjVuSupport();
141                 $this->hooks = array();
142                 $this->functionHooks = array();
143                 $this->transparentHooks = array();
144                 self::setUp();
145         }
147         static function setUp() {
148                 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
149                         $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
150                         $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
151                         $wgExtraInterlanguageLinkPrefixes,
152                         $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
153                         $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
154                         $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
156                 $wgScript = '/index.php';
157                 $wgScriptPath = '/';
158                 $wgArticlePath = '/wiki/$1';
159                 $wgStylePath = '/skins';
160                 $wgExtensionAssetsPath = '/extensions';
161                 $wgThumbnailScriptPath = false;
162                 $wgLockManagers = array( array(
163                         'name' => 'fsLockManager',
164                         'class' => 'FSLockManager',
165                         'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
166                 ), array(
167                         'name' => 'nullLockManager',
168                         'class' => 'NullLockManager',
169                 ) );
170                 $wgLocalFileRepo = array(
171                         'class' => 'LocalRepo',
172                         'name' => 'local',
173                         'url' => 'http://example.com/images',
174                         'hashLevels' => 2,
175                         'transformVia404' => false,
176                         'backend' => new FSFileBackend( array(
177                                 'name' => 'local-backend',
178                                 'wikiId' => wfWikiId(),
179                                 'containerPaths' => array(
180                                         'local-public' => wfTempDir() . '/test-repo/public',
181                                         'local-thumb' => wfTempDir() . '/test-repo/thumb',
182                                         'local-temp' => wfTempDir() . '/test-repo/temp',
183                                         'local-deleted' => wfTempDir() . '/test-repo/deleted',
184                                 )
185                         ) )
186                 );
187                 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
188                 $wgNamespaceAliases['Image'] = NS_FILE;
189                 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
190                 # add a namespace shadowing a interwiki link, to test
191                 # proper precedence when resolving links. (bug 51680)
192                 $wgExtraNamespaces[100] = 'MemoryAlpha';
194                 // XXX: tests won't run without this (for CACHE_DB)
195                 if ( $wgMainCacheType === CACHE_DB ) {
196                         $wgMainCacheType = CACHE_NONE;
197                 }
198                 if ( $wgMessageCacheType === CACHE_DB ) {
199                         $wgMessageCacheType = CACHE_NONE;
200                 }
201                 if ( $wgParserCacheType === CACHE_DB ) {
202                         $wgParserCacheType = CACHE_NONE;
203                 }
205                 $wgEnableParserCache = false;
206                 DeferredUpdates::clearPendingUpdates();
207                 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
208                 $messageMemc = wfGetMessageCacheStorage();
209                 $parserMemc = wfGetParserCacheStorage();
211                 // $wgContLang = new StubContLang;
212                 $wgUser = new User;
213                 $context = new RequestContext;
214                 $wgLang = $context->getLanguage();
215                 $wgOut = $context->getOutput();
216                 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
217                 $wgRequest = $context->getRequest();
219                 if ( $wgStyleDirectory === false ) {
220                         $wgStyleDirectory = "$IP/skins";
221                 }
222                 // "extra language links"
223                 // see https://gerrit.wikimedia.org/r/111390
224                 array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
226                 self::setupInterwikis();
227         }
229         /**
230          * Insert hardcoded interwiki in the lookup table.
231          *
232          * This function insert a set of well known interwikis that are used in
233          * the parser tests. They can be considered has fixtures are injected in
234          * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
235          * Since we are not interested in looking up interwikis in the database,
236          * the hook completely replace the existing mechanism (hook returns false).
237          */
238         public static function setupInterwikis() {
239                 # Hack: insert a few Wikipedia in-project interwiki prefixes,
240                 # for testing inter-language links
241                 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
242                         static $testInterwikis = array(
243                                 'wikipedia' => array(
244                                         'iw_url' => 'http://en.wikipedia.org/wiki/$1',
245                                         'iw_api' => '',
246                                         'iw_wikiid' => '',
247                                         'iw_local' => 0 ),
248                                 'meatball' => array(
249                                         'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
250                                         'iw_api' => '',
251                                         'iw_wikiid' => '',
252                                         'iw_local' => 0 ),
253                                 'memoryalpha' => array(
254                                         'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
255                                         'iw_api' => '',
256                                         'iw_wikiid' => '',
257                                         'iw_local' => 0 ),
258                                 'zh' => array(
259                                         'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
260                                         'iw_api' => '',
261                                         'iw_wikiid' => '',
262                                         'iw_local' => 1 ),
263                                 'es' => array(
264                                         'iw_url' => 'http://es.wikipedia.org/wiki/$1',
265                                         'iw_api' => '',
266                                         'iw_wikiid' => '',
267                                         'iw_local' => 1 ),
268                                 'fr' => array(
269                                         'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
270                                         'iw_api' => '',
271                                         'iw_wikiid' => '',
272                                         'iw_local' => 1 ),
273                                 'ru' => array(
274                                         'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
275                                         'iw_api' => '',
276                                         'iw_wikiid' => '',
277                                         'iw_local' => 1 ),
278                                 'mul' => array(
279                                         'iw_url' => 'http://wikisource.org/wiki/$1',
280                                         'iw_api' => '',
281                                         'iw_wikiid' => '',
282                                         'iw_local' => 1 ),
283                         );
284                         if ( array_key_exists( $prefix, $testInterwikis ) ) {
285                                 $iwData = $testInterwikis[$prefix];
286                         }
288                         // We only want to rely on the above fixtures
289                         return false;
290                 } );// hooks::register
291         }
293         /**
294          * Remove the hardcoded interwiki lookup table.
295          */
296         public static function tearDownInterwikis() {
297                 Hooks::clear( 'InterwikiLoadPrefix' );
298         }
300         public function setupRecorder( $options ) {
301                 if ( isset( $options['record'] ) ) {
302                         $this->recorder = new DbTestRecorder( $this );
303                         $this->recorder->version = isset( $options['setversion'] ) ?
304                                 $options['setversion'] : SpecialVersion::getVersion();
305                 } elseif ( isset( $options['compare'] ) ) {
306                         $this->recorder = new DbTestPreviewer( $this );
307                 } else {
308                         $this->recorder = new TestRecorder( $this );
309                 }
310         }
312         /**
313          * Remove last character if it is a newline
314          * @group utility
315          * @param string $s
316          */
317         public static function chomp( $s ) {
318                 if ( substr( $s, -1 ) === "\n" ) {
319                         return substr( $s, 0, -1 );
320                 } else {
321                         return $s;
322                 }
323         }
325         /**
326          * Run a fuzz test series
327          * Draw input from a set of test files
328          * @param array $filenames
329          */
330         function fuzzTest( $filenames ) {
331                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
332                 $dict = $this->getFuzzInput( $filenames );
333                 $dictSize = strlen( $dict );
334                 $logMaxLength = log( $this->maxFuzzTestLength );
335                 $this->setupDatabase();
336                 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
338                 $numTotal = 0;
339                 $numSuccess = 0;
340                 $user = new User;
341                 $opts = ParserOptions::newFromUser( $user );
342                 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
344                 while ( true ) {
345                         // Generate test input
346                         mt_srand( ++$this->fuzzSeed );
347                         $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
348                         $input = '';
350                         while ( strlen( $input ) < $totalLength ) {
351                                 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
352                                 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
353                                 $offset = mt_rand( 0, $dictSize - $hairLength );
354                                 $input .= substr( $dict, $offset, $hairLength );
355                         }
357                         $this->setupGlobals();
358                         $parser = $this->getParser();
360                         // Run the test
361                         try {
362                                 $parser->parse( $input, $title, $opts );
363                                 $fail = false;
364                         } catch ( Exception $exception ) {
365                                 $fail = true;
366                         }
368                         if ( $fail ) {
369                                 echo "Test failed with seed {$this->fuzzSeed}\n";
370                                 echo "Input:\n";
371                                 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
372                                 echo "$exception\n";
373                         } else {
374                                 $numSuccess++;
375                         }
377                         $numTotal++;
378                         $this->teardownGlobals();
379                         $parser->__destruct();
381                         if ( $numTotal % 100 == 0 ) {
382                                 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
383                                 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
384                                 if ( $usage > 90 ) {
385                                         echo "Out of memory:\n";
386                                         $memStats = $this->getMemoryBreakdown();
388                                         foreach ( $memStats as $name => $usage ) {
389                                                 echo "$name: $usage\n";
390                                         }
391                                         $this->abort();
392                                 }
393                         }
394                 }
395         }
397         /**
398          * Get an input dictionary from a set of parser test files
399          * @param array $filenames
400          */
401         function getFuzzInput( $filenames ) {
402                 $dict = '';
404                 foreach ( $filenames as $filename ) {
405                         $contents = file_get_contents( $filename );
406                         preg_match_all(
407                                 '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
408                                 $contents,
409                                 $matches
410                         );
412                         foreach ( $matches[1] as $match ) {
413                                 $dict .= $match . "\n";
414                         }
415                 }
417                 return $dict;
418         }
420         /**
421          * Get a memory usage breakdown
422          */
423         function getMemoryBreakdown() {
424                 $memStats = array();
426                 foreach ( $GLOBALS as $name => $value ) {
427                         $memStats['$' . $name] = strlen( serialize( $value ) );
428                 }
430                 $classes = get_declared_classes();
432                 foreach ( $classes as $class ) {
433                         $rc = new ReflectionClass( $class );
434                         $props = $rc->getStaticProperties();
435                         $memStats[$class] = strlen( serialize( $props ) );
436                         $methods = $rc->getMethods();
438                         foreach ( $methods as $method ) {
439                                 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
440                         }
441                 }
443                 $functions = get_defined_functions();
445                 foreach ( $functions['user'] as $function ) {
446                         $rf = new ReflectionFunction( $function );
447                         $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
448                 }
450                 asort( $memStats );
452                 return $memStats;
453         }
455         function abort() {
456                 $this->abort();
457         }
459         /**
460          * Run a series of tests listed in the given text files.
461          * Each test consists of a brief description, wikitext input,
462          * and the expected HTML output.
463          *
464          * Prints status updates on stdout and counts up the total
465          * number and percentage of passed tests.
466          *
467          * @param array $filenames Array of strings
468          * @return bool True if passed all tests, false if any tests failed.
469          */
470         public function runTestsFromFiles( $filenames ) {
471                 $ok = false;
473                 // be sure, ParserTest::addArticle has correct language set,
474                 // so that system messages gets into the right language cache
475                 $GLOBALS['wgLanguageCode'] = 'en';
476                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
478                 $this->recorder->start();
479                 try {
480                         $this->setupDatabase();
481                         $ok = true;
483                         foreach ( $filenames as $filename ) {
484                                 $tests = new TestFileIterator( $filename, $this );
485                                 $ok = $this->runTests( $tests ) && $ok;
486                         }
488                         $this->teardownDatabase();
489                         $this->recorder->report();
490                 } catch ( DBError $e ) {
491                         echo $e->getMessage();
492                 }
493                 $this->recorder->end();
495                 return $ok;
496         }
498         function runTests( $tests ) {
499                 $ok = true;
501                 foreach ( $tests as $t ) {
502                         $result =
503                                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
504                         $ok = $ok && $result;
505                         $this->recorder->record( $t['test'], $result );
506                 }
508                 if ( $this->showProgress ) {
509                         print "\n";
510                 }
512                 return $ok;
513         }
515         /**
516          * Get a Parser object
517          *
518          * @param string $preprocessor
519          * @return Parser
520          */
521         function getParser( $preprocessor = null ) {
522                 global $wgParserConf;
524                 $class = $wgParserConf['class'];
525                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
527                 foreach ( $this->hooks as $tag => $callback ) {
528                         $parser->setHook( $tag, $callback );
529                 }
531                 foreach ( $this->functionHooks as $tag => $bits ) {
532                         list( $callback, $flags ) = $bits;
533                         $parser->setFunctionHook( $tag, $callback, $flags );
534                 }
536                 foreach ( $this->transparentHooks as $tag => $callback ) {
537                         $parser->setTransparentTagHook( $tag, $callback );
538                 }
540                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
542                 return $parser;
543         }
545         /**
546          * Run a given wikitext input through a freshly-constructed wiki parser,
547          * and compare the output against the expected results.
548          * Prints status and explanatory messages to stdout.
549          *
550          * @param string $desc Test's description
551          * @param string $input Wikitext to try rendering
552          * @param string $result Result to output
553          * @param array $opts Test's options
554          * @param string $config Overrides for global variables, one per line
555          * @return bool
556          */
557         public function runTest( $desc, $input, $result, $opts, $config ) {
558                 if ( $this->showProgress ) {
559                         $this->showTesting( $desc );
560                 }
562                 $opts = $this->parseOptions( $opts );
563                 $context = $this->setupGlobals( $opts, $config );
565                 $user = $context->getUser();
566                 $options = ParserOptions::newFromContext( $context );
568                 if ( isset( $opts['djvu'] ) ) {
569                         if ( !$this->djVuSupport->isEnabled() ) {
570                                 return $this->showSkipped();
571                         }
572                 }
574                 if ( isset( $opts['title'] ) ) {
575                         $titleText = $opts['title'];
576                 } else {
577                         $titleText = 'Parser test';
578                 }
580                 $local = isset( $opts['local'] );
581                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
582                 $parser = $this->getParser( $preprocessor );
583                 $title = Title::newFromText( $titleText );
585                 if ( isset( $opts['pst'] ) ) {
586                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
587                 } elseif ( isset( $opts['msg'] ) ) {
588                         $out = $parser->transformMsg( $input, $options, $title );
589                 } elseif ( isset( $opts['section'] ) ) {
590                         $section = $opts['section'];
591                         $out = $parser->getSection( $input, $section );
592                 } elseif ( isset( $opts['replace'] ) ) {
593                         $section = $opts['replace'][0];
594                         $replace = $opts['replace'][1];
595                         $out = $parser->replaceSection( $input, $section, $replace );
596                 } elseif ( isset( $opts['comment'] ) ) {
597                         $out = Linker::formatComment( $input, $title, $local );
598                 } elseif ( isset( $opts['preload'] ) ) {
599                         $out = $parser->getPreloadText( $input, $title, $options );
600                 } else {
601                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
602                         $output->setTOCEnabled( !isset( $opts['notoc'] ) );
603                         $out = $output->getText();
605                         if ( isset( $opts['showtitle'] ) ) {
606                                 if ( $output->getTitleText() ) {
607                                         $title = $output->getTitleText();
608                                 }
610                                 $out = "$title\n$out";
611                         }
613                         if ( isset( $opts['ill'] ) ) {
614                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
615                         } elseif ( isset( $opts['cat'] ) ) {
616                                 $outputPage = $context->getOutput();
617                                 $outputPage->addCategoryLinks( $output->getCategories() );
618                                 $cats = $outputPage->getCategoryLinks();
620                                 if ( isset( $cats['normal'] ) ) {
621                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
622                                 } else {
623                                         $out = '';
624                                 }
625                         }
627                         $result = $this->tidy( $result );
628                 }
630                 $this->teardownGlobals();
632                 $testResult = new ParserTestResult( $desc );
633                 $testResult->expected = $result;
634                 $testResult->actual = $out;
636                 return $this->showTestResult( $testResult );
637         }
639         /**
640          * Refactored in 1.22 to use ParserTestResult
641          * @param ParserTestResult $testResult
642          */
643         function showTestResult( ParserTestResult $testResult ) {
644                 if ( $testResult->isSuccess() ) {
645                         $this->showSuccess( $testResult );
646                         return true;
647                 } else {
648                         $this->showFailure( $testResult );
649                         return false;
650                 }
651         }
653         /**
654          * Use a regex to find out the value of an option
655          * @param string $key Name of option val to retrieve
656          * @param array $opts Options array to look in
657          * @param mixed $default Default value returned if not found
658          */
659         private static function getOptionValue( $key, $opts, $default ) {
660                 $key = strtolower( $key );
662                 if ( isset( $opts[$key] ) ) {
663                         return $opts[$key];
664                 } else {
665                         return $default;
666                 }
667         }
669         private function parseOptions( $instring ) {
670                 $opts = array();
671                 // foo
672                 // foo=bar
673                 // foo="bar baz"
674                 // foo=[[bar baz]]
675                 // foo=bar,"baz quux"
676                 // foo={...json...}
677                 $defs = '(?(DEFINE)
678                         (?<qstr>                                        # Quoted string
679                                 "
680                                 (?:[^\\\\"] | \\\\.)*
681                                 "
682                         )
683                         (?<json>
684                                 \{              # Open bracket
685                                 (?:
686                                         [^"{}] |                                # Not a quoted string or object, or
687                                         (?&qstr) |                              # A quoted string, or
688                                         (?&json)                                # A json object (recursively)
689                                 )*
690                                 \}              # Close bracket
691                         )
692             (?<value>
693                                 (?:
694                                         (?&qstr)                        # Quoted val
695                                 |
696                                         \[\[
697                                                 [^]]*                   # Link target
698                                         \]\]
699                                 |
700                                         [\w-]+                          # Plain word
701                                 |
702                                         (?&json)                        # JSON object
703                                 )
704                         )
705                 )';
706                 $regex = '/' . $defs . '\b
707                         (?<k>[\w-]+)                            # Key
708                         \b
709                         (?:\s*
710                                 =                                               # First sub-value
711                                 \s*
712                                 (?<v>
713                                         (?&value)
714                                         (?:\s*
715                                                 ,                               # Sub-vals 1..N
716                                                 \s*
717                                                 (?&value)
718                                         )*
719                                 )
720                         )?
721                         /x';
722                 $valueregex = '/' . $defs . '(?&value)/x';
724                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
725                         foreach ( $matches as $bits ) {
726                                 $key = strtolower( $bits[ 'k' ] );
727                                 if ( !isset( $bits[ 'v' ] ) ) {
728                                         $opts[$key] = true;
729                                 } else {
730                                         preg_match_all( $valueregex, $bits[ 'v' ], $vmatches );
731                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
732                                         if ( count( $opts[$key] ) == 1 ) {
733                                                 $opts[$key] = $opts[$key][0];
734                                         }
735                                 }
736                         }
737                 }
738                 return $opts;
739         }
741         private function cleanupOption( $opt ) {
742                 if ( substr( $opt, 0, 1 ) == '"' ) {
743                         return stripcslashes( substr( $opt, 1, -1 ) );
744                 }
746                 if ( substr( $opt, 0, 2 ) == '[[' ) {
747                         return substr( $opt, 2, -2 );
748                 }
750                 if ( substr( $opt, 0, 1 ) == '{' ) {
751                         return FormatJson::decode( $opt, true );
752                 }
753                 return $opt;
754         }
756         /**
757          * Set up the global variables for a consistent environment for each test.
758          * Ideally this should replace the global configuration entirely.
759          * @param string $opts
760          * @param string $config
761          */
762         private function setupGlobals( $opts = '', $config = '' ) {
763                 # Find out values for some special options.
764                 $lang =
765                         self::getOptionValue( 'language', $opts, 'en' );
766                 $variant =
767                         self::getOptionValue( 'variant', $opts, false );
768                 $maxtoclevel =
769                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
770                 $linkHolderBatchSize =
771                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
773                 $settings = array(
774                         'wgServer' => 'http://example.org',
775                         'wgServerName' => 'example.org',
776                         'wgScript' => '/index.php',
777                         'wgScriptPath' => '/',
778                         'wgArticlePath' => '/wiki/$1',
779                         'wgActionPaths' => array(),
780                         'wgLockManagers' => array( array(
781                                 'name' => 'fsLockManager',
782                                 'class' => 'FSLockManager',
783                                 'lockDirectory' => $this->uploadDir . '/lockdir',
784                         ), array(
785                                 'name' => 'nullLockManager',
786                                 'class' => 'NullLockManager',
787                         ) ),
788                         'wgLocalFileRepo' => array(
789                                 'class' => 'LocalRepo',
790                                 'name' => 'local',
791                                 'url' => 'http://example.com/images',
792                                 'hashLevels' => 2,
793                                 'transformVia404' => false,
794                                 'backend' => new FSFileBackend( array(
795                                         'name' => 'local-backend',
796                                         'wikiId' => wfWikiId(),
797                                         'containerPaths' => array(
798                                                 'local-public' => $this->uploadDir,
799                                                 'local-thumb' => $this->uploadDir . '/thumb',
800                                                 'local-temp' => $this->uploadDir . '/temp',
801                                                 'local-deleted' => $this->uploadDir . '/delete',
802                                         )
803                                 ) )
804                         ),
805                         'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
806                         'wgStylePath' => '/skins',
807                         'wgSitename' => 'MediaWiki',
808                         'wgLanguageCode' => $lang,
809                         'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
810                         'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
811                         'wgLang' => null,
812                         'wgContLang' => null,
813                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
814                         'wgMaxTocLevel' => $maxtoclevel,
815                         'wgCapitalLinks' => true,
816                         'wgNoFollowLinks' => true,
817                         'wgNoFollowDomainExceptions' => array(),
818                         'wgThumbnailScriptPath' => false,
819                         'wgUseImageResize' => true,
820                         'wgSVGConverter' => 'null',
821                         'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
822                         'wgLocaltimezone' => 'UTC',
823                         'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
824                         'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
825                         'wgUseTidy' => false,
826                         'wgDefaultLanguageVariant' => $variant,
827                         'wgVariantArticlePath' => false,
828                         'wgGroupPermissions' => array( '*' => array(
829                                 'createaccount' => true,
830                                 'read' => true,
831                                 'edit' => true,
832                                 'createpage' => true,
833                                 'createtalk' => true,
834                         ) ),
835                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
836                         'wgDefaultExternalStore' => array(),
837                         'wgForeignFileRepos' => array(),
838                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
839                         'wgExperimentalHtmlIds' => false,
840                         'wgExternalLinkTarget' => false,
841                         'wgAlwaysUseTidy' => false,
842                         'wgHtml5' => true,
843                         'wgWellFormedXml' => true,
844                         'wgAllowMicrodataAttributes' => true,
845                         'wgAdaptiveMessageCache' => true,
846                         'wgDisableLangConversion' => false,
847                         'wgDisableTitleConversion' => false,
848                 );
850                 if ( $config ) {
851                         $configLines = explode( "\n", $config );
853                         foreach ( $configLines as $line ) {
854                                 list( $var, $value ) = explode( '=', $line, 2 );
856                                 $settings[$var] = eval( "return $value;" );
857                         }
858                 }
860                 $this->savedGlobals = array();
862                 /** @since 1.20 */
863                 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
865                 foreach ( $settings as $var => $val ) {
866                         if ( array_key_exists( $var, $GLOBALS ) ) {
867                                 $this->savedGlobals[$var] = $GLOBALS[$var];
868                         }
870                         $GLOBALS[$var] = $val;
871                 }
873                 $GLOBALS['wgContLang'] = Language::factory( $lang );
874                 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
876                 $context = new RequestContext();
877                 $GLOBALS['wgLang'] = $context->getLanguage();
878                 $GLOBALS['wgOut'] = $context->getOutput();
879                 $GLOBALS['wgUser'] = $context->getUser();
881                 // We (re)set $wgThumbLimits to a single-element array above.
882                 $context->getUser()->setOption( 'thumbsize', 0 );
884                 global $wgHooks;
886                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
887                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
889                 MagicWord::clearCache();
891                 return $context;
892         }
894         /**
895          * List of temporary tables to create, without prefix.
896          * Some of these probably aren't necessary.
897          */
898         private function listTables() {
899                 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
900                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
901                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
902                         'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
903                         'recentchanges', 'watchlist', 'interwiki', 'logging',
904                         'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
905                         'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
906                 );
908                 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
909                         array_push( $tables, 'searchindex' );
910                 }
912                 // Allow extensions to add to the list of tables to duplicate;
913                 // may be necessary if they hook into page save or other code
914                 // which will require them while running tests.
915                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
917                 return $tables;
918         }
920         /**
921          * Set up a temporary set of wiki tables to work with for the tests.
922          * Currently this will only be done once per run, and any changes to
923          * the db will be visible to later tests in the run.
924          */
925         public function setupDatabase() {
926                 global $wgDBprefix;
928                 if ( $this->databaseSetupDone ) {
929                         return;
930                 }
932                 $this->db = wfGetDB( DB_MASTER );
933                 $dbType = $this->db->getType();
935                 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
936                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
937                 }
939                 $this->databaseSetupDone = true;
941                 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
942                 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
943                 # This works around it for now...
944                 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
946                 # CREATE TEMPORARY TABLE breaks if there is more than one server
947                 if ( wfGetLB()->getServerCount() != 1 ) {
948                         $this->useTemporaryTables = false;
949                 }
951                 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
952                 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
954                 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
955                 $this->dbClone->useTemporaryTables( $temporary );
956                 $this->dbClone->cloneTableStructure();
958                 if ( $dbType == 'oracle' ) {
959                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
960                         # Insert 0 user to prevent FK violations
962                         # Anonymous user
963                         $this->db->insert( 'user', array(
964                                 'user_id' => 0,
965                                 'user_name' => 'Anonymous' ) );
966                 }
968                 # Update certain things in site_stats
969                 $this->db->insert( 'site_stats',
970                         array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
972                 # Reinitialise the LocalisationCache to match the database state
973                 Language::getLocalisationCache()->unloadAll();
975                 # Clear the message cache
976                 MessageCache::singleton()->clear();
978                 // Remember to update newParserTests.php after changing the below
979                 // (and it uses a slightly different syntax just for teh lulz)
980                 $this->uploadDir = $this->setupUploadDir();
981                 $user = User::createNew( 'WikiSysop' );
982                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
983                 # note that the size/width/height/bits/etc of the file
984                 # are actually set by inspecting the file itself; the arguments
985                 # to recordUpload2 have no effect.  That said, we try to make things
986                 # match up so it is less confusing to readers of the code & tests.
987                 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
988                         'size' => 7881,
989                         'width' => 1941,
990                         'height' => 220,
991                         'bits' => 8,
992                         'media_type' => MEDIATYPE_BITMAP,
993                         'mime' => 'image/jpeg',
994                         'metadata' => serialize( array() ),
995                         'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
996                         'fileExists' => true
997                 ), $this->db->timestamp( '20010115123500' ), $user );
999                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1000                 # again, note that size/width/height below are ignored; see above.
1001                 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
1002                         'size' => 22589,
1003                         'width' => 135,
1004                         'height' => 135,
1005                         'bits' => 8,
1006                         'media_type' => MEDIATYPE_BITMAP,
1007                         'mime' => 'image/png',
1008                         'metadata' => serialize( array() ),
1009                         'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
1010                         'fileExists' => true
1011                 ), $this->db->timestamp( '20130225203040' ), $user );
1013                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1014                 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
1015                                 'size'        => 12345,
1016                                 'width'       => 240,
1017                                 'height'      => 180,
1018                                 'bits'        => 0,
1019                                 'media_type'  => MEDIATYPE_DRAWING,
1020                                 'mime'        => 'image/svg+xml',
1021                                 'metadata'    => serialize( array() ),
1022                                 'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
1023                                 'fileExists'  => true
1024                 ), $this->db->timestamp( '20010115123500' ), $user );
1026                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
1027                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1028                 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
1029                         'size' => 12345,
1030                         'width' => 320,
1031                         'height' => 240,
1032                         'bits' => 24,
1033                         'media_type' => MEDIATYPE_BITMAP,
1034                         'mime' => 'image/jpeg',
1035                         'metadata' => serialize( array() ),
1036                         'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1037                         'fileExists' => true
1038                 ), $this->db->timestamp( '20010115123500' ), $user );
1040                 # A DjVu file
1041                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1042                 $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', array(
1043                         'size' => 3249,
1044                         'width' => 2480,
1045                         'height' => 3508,
1046                         'bits' => 0,
1047                         'media_type' => MEDIATYPE_BITMAP,
1048                         'mime' => 'image/vnd.djvu',
1049                         'metadata' => '<?xml version="1.0" ?>
1050 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1051 <DjVuXML>
1052 <HEAD></HEAD>
1053 <BODY><OBJECT height="3508" width="2480">
1054 <PARAM name="DPI" value="300" />
1055 <PARAM name="GAMMA" value="2.2" />
1056 </OBJECT>
1057 <OBJECT height="3508" width="2480">
1058 <PARAM name="DPI" value="300" />
1059 <PARAM name="GAMMA" value="2.2" />
1060 </OBJECT>
1061 <OBJECT height="3508" width="2480">
1062 <PARAM name="DPI" value="300" />
1063 <PARAM name="GAMMA" value="2.2" />
1064 </OBJECT>
1065 <OBJECT height="3508" width="2480">
1066 <PARAM name="DPI" value="300" />
1067 <PARAM name="GAMMA" value="2.2" />
1068 </OBJECT>
1069 <OBJECT height="3508" width="2480">
1070 <PARAM name="DPI" value="300" />
1071 <PARAM name="GAMMA" value="2.2" />
1072 </OBJECT>
1073 </BODY>
1074 </DjVuXML>',
1075                         'sha1' => wfBaseConvert( '', 16, 36, 31 ),
1076                         'fileExists' => true
1077                 ), $this->db->timestamp( '20010115123600' ), $user );
1078         }
1080         public function teardownDatabase() {
1081                 if ( !$this->databaseSetupDone ) {
1082                         $this->teardownGlobals();
1083                         return;
1084                 }
1085                 $this->teardownUploadDir( $this->uploadDir );
1087                 $this->dbClone->destroy();
1088                 $this->databaseSetupDone = false;
1090                 if ( $this->useTemporaryTables ) {
1091                         if ( $this->db->getType() == 'sqlite' ) {
1092                                 # Under SQLite the searchindex table is virtual and need
1093                                 # to be explicitly destroyed. See bug 29912
1094                                 # See also MediaWikiTestCase::destroyDB()
1095                                 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1096                                 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1097                         }
1098                         # Don't need to do anything
1099                         $this->teardownGlobals();
1100                         return;
1101                 }
1103                 $tables = $this->listTables();
1105                 foreach ( $tables as $table ) {
1106                         if ( $this->db->getType() == 'oracle' ) {
1107                                 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1108                         } else {
1109                                 $this->db->query( "DROP TABLE `parsertest_$table`" );
1110                         }
1111                 }
1113                 if ( $this->db->getType() == 'oracle' ) {
1114                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1115                 }
1117                 $this->teardownGlobals();
1118         }
1120         /**
1121          * Create a dummy uploads directory which will contain a couple
1122          * of files in order to pass existence tests.
1123          *
1124          * @return string The directory
1125          */
1126         private function setupUploadDir() {
1127                 global $IP;
1129                 if ( $this->keepUploads ) {
1130                         $dir = wfTempDir() . '/mwParser-images';
1132                         if ( is_dir( $dir ) ) {
1133                                 return $dir;
1134                         }
1135                 } else {
1136                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1137                 }
1139                 // wfDebug( "Creating upload directory $dir\n" );
1140                 if ( file_exists( $dir ) ) {
1141                         wfDebug( "Already exists!\n" );
1142                         return $dir;
1143                 }
1145                 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1146                 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1147                 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1148                 copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1149                 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1150                 copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1151                 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1152                 file_put_contents( "$dir/f/ff/Foobar.svg",
1153                         '<?xml version="1.0" encoding="utf-8"?>' .
1154                         '<svg xmlns="http://www.w3.org/2000/svg"' .
1155                         ' version="1.1" width="240" height="180"/>' );
1156                 wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1157                 copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1159                 return $dir;
1160         }
1162         /**
1163          * Restore default values and perform any necessary clean-up
1164          * after each test runs.
1165          */
1166         private function teardownGlobals() {
1167                 RepoGroup::destroySingleton();
1168                 FileBackendGroup::destroySingleton();
1169                 LockManagerGroup::destroySingletons();
1170                 LinkCache::singleton()->clear();
1172                 foreach ( $this->savedGlobals as $var => $val ) {
1173                         $GLOBALS[$var] = $val;
1174                 }
1175         }
1177         /**
1178          * Remove the dummy uploads directory
1179          * @param string $dir
1180          */
1181         private function teardownUploadDir( $dir ) {
1182                 if ( $this->keepUploads ) {
1183                         return;
1184                 }
1186                 // delete the files first, then the dirs.
1187                 self::deleteFiles(
1188                         array(
1189                                 "$dir/3/3a/Foobar.jpg",
1190                                 "$dir/thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
1191                                 "$dir/thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
1192                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1193                                 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1194                                 "$dir/thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
1195                                 "$dir/thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
1196                                 "$dir/thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
1197                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1198                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1199                                 "$dir/thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
1200                                 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1201                                 "$dir/thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
1202                                 "$dir/thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
1203                                 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1204                                 "$dir/thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
1205                                 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1206                                 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1207                                 "$dir/thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
1208                                 "$dir/thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
1209                                 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1210                                 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1211                                 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1212                                 "$dir/thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
1213                                 "$dir/thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
1214                                 "$dir/thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
1215                                 "$dir/thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
1216                                 "$dir/thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
1217                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1218                                 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1219                                 "$dir/thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
1220                                 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1222                                 "$dir/e/ea/Thumb.png",
1224                                 "$dir/0/09/Bad.jpg",
1226                                 "$dir/5/5f/LoremIpsum.djvu",
1227                                 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
1228                                 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
1229                                 "$dir/thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
1231                                 "$dir/f/ff/Foobar.svg",
1232                                 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1233                                 "$dir/thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
1234                                 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1235                                 "$dir/thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
1236                                 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1237                                 "$dir/thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
1238                                 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1239                                 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1240                                 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1242                                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1243                         )
1244                 );
1246                 self::deleteDirs(
1247                         array(
1248                                 "$dir/3/3a",
1249                                 "$dir/3",
1250                                 "$dir/thumb/3/3a/Foobar.jpg",
1251                                 "$dir/thumb/3/3a",
1252                                 "$dir/thumb/3",
1253                                 "$dir/e/ea",
1254                                 "$dir/e",
1255                                 "$dir/f/ff/",
1256                                 "$dir/f/",
1257                                 "$dir/thumb/f/ff/Foobar.svg",
1258                                 "$dir/thumb/f/ff/",
1259                                 "$dir/thumb/f/",
1260                                 "$dir/0/09/",
1261                                 "$dir/0/",
1262                                 "$dir/5/5f",
1263                                 "$dir/5",
1264                                 "$dir/thumb/5/5f/LoremIpsum.djvu",
1265                                 "$dir/thumb/5/5f",
1266                                 "$dir/thumb/5",
1267                                 "$dir/thumb",
1268                                 "$dir/math/f/a/5",
1269                                 "$dir/math/f/a",
1270                                 "$dir/math/f",
1271                                 "$dir/math",
1272                                 "$dir",
1273                         )
1274                 );
1275         }
1277         /**
1278          * Delete the specified files, if they exist.
1279          * @param array $files Full paths to files to delete.
1280          */
1281         private static function deleteFiles( $files ) {
1282                 foreach ( $files as $file ) {
1283                         if ( file_exists( $file ) ) {
1284                                 unlink( $file );
1285                         }
1286                 }
1287         }
1289         /**
1290          * Delete the specified directories, if they exist. Must be empty.
1291          * @param array $dirs Full paths to directories to delete.
1292          */
1293         private static function deleteDirs( $dirs ) {
1294                 foreach ( $dirs as $dir ) {
1295                         if ( is_dir( $dir ) ) {
1296                                 rmdir( $dir );
1297                         }
1298                 }
1299         }
1301         /**
1302          * "Running test $desc..."
1303          * @param string $desc
1304          */
1305         protected function showTesting( $desc ) {
1306                 print "Running test $desc... ";
1307         }
1309         /**
1310          * Print a happy success message.
1311          *
1312          * Refactored in 1.22 to use ParserTestResult
1313          *
1314          * @param ParserTestResult $testResult
1315          * @return bool
1316          */
1317         protected function showSuccess( ParserTestResult $testResult ) {
1318                 if ( $this->showProgress ) {
1319                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1320                 }
1322                 return true;
1323         }
1325         /**
1326          * Print a failure message and provide some explanatory output
1327          * about what went wrong if so configured.
1328          *
1329          * Refactored in 1.22 to use ParserTestResult
1330          *
1331          * @param ParserTestResult $testResult
1332          * @return bool
1333          */
1334         protected function showFailure( ParserTestResult $testResult ) {
1335                 if ( $this->showFailure ) {
1336                         if ( !$this->showProgress ) {
1337                                 # In quiet mode we didn't show the 'Testing' message before the
1338                                 # test, in case it succeeded. Show it now:
1339                                 $this->showTesting( $testResult->description );
1340                         }
1342                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1344                         if ( $this->showOutput ) {
1345                                 print "--- Expected ---\n{$testResult->expected}\n";
1346                                 print "--- Actual ---\n{$testResult->actual}\n";
1347                         }
1349                         if ( $this->showDiffs ) {
1350                                 print $this->quickDiff( $testResult->expected, $testResult->actual );
1351                                 if ( !$this->wellFormed( $testResult->actual ) ) {
1352                                         print "XML error: $this->mXmlError\n";
1353                                 }
1354                         }
1355                 }
1357                 return false;
1358         }
1360         /**
1361          * Print a skipped message.
1362          *
1363          * @return boolean
1364          */
1365         protected function showSkipped() {
1366                 if ( $this->showProgress ) {
1367                         print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1368                 }
1370                 return true;
1371         }
1373         /**
1374          * Run given strings through a diff and return the (colorized) output.
1375          * Requires writable /tmp directory and a 'diff' command in the PATH.
1376          *
1377          * @param string $input
1378          * @param string $output
1379          * @param string $inFileTail Tailing for the input file name
1380          * @param string $outFileTail Tailing for the output file name
1381          * @return string
1382          */
1383         protected function quickDiff( $input, $output,
1384                 $inFileTail = 'expected', $outFileTail = 'actual'
1385         ) {
1386                 # Windows, or at least the fc utility, is retarded
1387                 $slash = wfIsWindows() ? '\\' : '/';
1388                 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1390                 $infile = "$prefix-$inFileTail";
1391                 $this->dumpToFile( $input, $infile );
1393                 $outfile = "$prefix-$outFileTail";
1394                 $this->dumpToFile( $output, $outfile );
1396                 $shellInfile = wfEscapeShellArg( $infile );
1397                 $shellOutfile = wfEscapeShellArg( $outfile );
1399                 global $wgDiff3;
1400                 // we assume that people with diff3 also have usual diff
1401                 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1403                 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1405                 unlink( $infile );
1406                 unlink( $outfile );
1408                 return $this->colorDiff( $diff );
1409         }
1411         /**
1412          * Write the given string to a file, adding a final newline.
1413          *
1414          * @param string $data
1415          * @param string $filename
1416          */
1417         private function dumpToFile( $data, $filename ) {
1418                 $file = fopen( $filename, "wt" );
1419                 fwrite( $file, $data . "\n" );
1420                 fclose( $file );
1421         }
1423         /**
1424          * Colorize unified diff output if set for ANSI color output.
1425          * Subtractions are colored blue, additions red.
1426          *
1427          * @param string $text
1428          * @return string
1429          */
1430         protected function colorDiff( $text ) {
1431                 return preg_replace(
1432                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1433                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1434                                 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1435                         $text );
1436         }
1438         /**
1439          * Show "Reading tests from ..."
1440          *
1441          * @param string $path
1442          */
1443         public function showRunFile( $path ) {
1444                 print $this->term->color( 1 ) .
1445                         "Reading tests from \"$path\"..." .
1446                         $this->term->reset() .
1447                         "\n";
1448         }
1450         /**
1451          * Insert a temporary test article
1452          * @param string $name The title, including any prefix
1453          * @param string $text The article text
1454          * @param int $line The input line number, for reporting errors
1455          * @param bool $ignoreDuplicate Whether to silently ignore duplicate pages
1456          */
1457         public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1458                 global $wgCapitalLinks;
1460                 $oldCapitalLinks = $wgCapitalLinks;
1461                 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1463                 $text = self::chomp( $text );
1464                 $name = self::chomp( $name );
1466                 $title = Title::newFromText( $name );
1468                 if ( is_null( $title ) ) {
1469                         throw new MWException( "invalid title '$name' at line $line\n" );
1470                 }
1472                 $page = WikiPage::factory( $title );
1473                 $page->loadPageData( 'fromdbmaster' );
1475                 if ( $page->exists() ) {
1476                         if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1477                                 return;
1478                         } else {
1479                                 throw new MWException( "duplicate article '$name' at line $line\n" );
1480                         }
1481                 }
1483                 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1485                 $wgCapitalLinks = $oldCapitalLinks;
1486         }
1488         /**
1489          * Steal a callback function from the primary parser, save it for
1490          * application to our scary parser. If the hook is not installed,
1491          * abort processing of this file.
1492          *
1493          * @param string $name
1494          * @return bool True if tag hook is present
1495          */
1496         public function requireHook( $name ) {
1497                 global $wgParser;
1499                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1501                 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1502                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
1503                 } else {
1504                         echo "   This test suite requires the '$name' hook extension, skipping.\n";
1505                         return false;
1506                 }
1508                 return true;
1509         }
1511         /**
1512          * Steal a callback function from the primary parser, save it for
1513          * application to our scary parser. If the hook is not installed,
1514          * abort processing of this file.
1515          *
1516          * @param string $name
1517          * @return bool True if function hook is present
1518          */
1519         public function requireFunctionHook( $name ) {
1520                 global $wgParser;
1522                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1524                 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1525                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1526                 } else {
1527                         echo "   This test suite requires the '$name' function hook extension, skipping.\n";
1528                         return false;
1529                 }
1531                 return true;
1532         }
1534         /**
1535          * Steal a callback function from the primary parser, save it for
1536          * application to our scary parser. If the hook is not installed,
1537          * abort processing of this file.
1538          *
1539          * @param string $name
1540          * @return bool True if function hook is present
1541          */
1542         public function requireTransparentHook( $name ) {
1543                 global $wgParser;
1545                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1547                 if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1548                         $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1549                 } else {
1550                         echo "   This test suite requires the '$name' transparent hook extension, skipping.\n";
1551                         return false;
1552                 }
1554                 return true;
1555         }
1557         /**
1558          * Run the "tidy" command on text if the $wgUseTidy
1559          * global is true
1560          *
1561          * @param string $text The text to tidy
1562          * @return string
1563          */
1564         private function tidy( $text ) {
1565                 global $wgUseTidy;
1567                 if ( $wgUseTidy ) {
1568                         $text = MWTidy::tidy( $text );
1569                 }
1571                 return $text;
1572         }
1574         private function wellFormed( $text ) {
1575                 $html =
1576                         Sanitizer::hackDocType() .
1577                                 '<html>' .
1578                                 $text .
1579                                 '</html>';
1581                 $parser = xml_parser_create( "UTF-8" );
1583                 # case folding violates XML standard, turn it off
1584                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1586                 if ( !xml_parse( $parser, $html, true ) ) {
1587                         $err = xml_error_string( xml_get_error_code( $parser ) );
1588                         $position = xml_get_current_byte_index( $parser );
1589                         $fragment = $this->extractFragment( $html, $position );
1590                         $this->mXmlError = "$err at byte $position:\n$fragment";
1591                         xml_parser_free( $parser );
1593                         return false;
1594                 }
1596                 xml_parser_free( $parser );
1598                 return true;
1599         }
1601         private function extractFragment( $text, $position ) {
1602                 $start = max( 0, $position - 10 );
1603                 $before = $position - $start;
1604                 $fragment = '...' .
1605                         $this->term->color( 34 ) .
1606                         substr( $text, $start, $before ) .
1607                         $this->term->color( 0 ) .
1608                         $this->term->color( 31 ) .
1609                         $this->term->color( 1 ) .
1610                         substr( $text, $position, 1 ) .
1611                         $this->term->color( 0 ) .
1612                         $this->term->color( 34 ) .
1613                         substr( $text, $position + 1, 9 ) .
1614                         $this->term->color( 0 ) .
1615                         '...';
1616                 $display = str_replace( "\n", ' ', $fragment );
1617                 $caret = '   ' .
1618                         str_repeat( ' ', $before ) .
1619                         $this->term->color( 31 ) .
1620                         '^' .
1621                         $this->term->color( 0 );
1623                 return "$display\n$caret";
1624         }
1626         static function getFakeTimestamp( &$parser, &$ts ) {
1627                 $ts = 123; //parsed as '1970-01-01T00:02:03Z'
1628                 return true;
1629         }