Merge "Whitelist the <wbr> element."
[mediawiki.git] / tests / parser / parserTest.inc
blob92c03cdc38f436dc2265fab03e4c1d6ef614a72d
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;
438                 // be sure, ParserTest::addArticle has correct language set,
439                 // so that system messages gets into the right language cache
440                 $GLOBALS['wgLanguageCode'] = 'en';
441                 $GLOBALS['wgContLang'] = Language::factory( 'en' );
443                 $this->recorder->start();
444                 try {
445                         $this->setupDatabase();
446                         $ok = true;
448                         foreach ( $filenames as $filename ) {
449                                 $tests = new TestFileIterator( $filename, $this );
450                                 $ok = $this->runTests( $tests ) && $ok;
451                         }
453                         $this->teardownDatabase();
454                         $this->recorder->report();
455                 } catch ( DBError $e ) {
456                         echo $e->getMessage();
457                 }
458                 $this->recorder->end();
460                 return $ok;
461         }
463         function runTests( $tests ) {
464                 $ok = true;
466                 foreach ( $tests as $t ) {
467                         $result =
468                                 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
469                         $ok = $ok && $result;
470                         $this->recorder->record( $t['test'], $result );
471                 }
473                 if ( $this->showProgress ) {
474                         print "\n";
475                 }
477                 return $ok;
478         }
480         /**
481          * Get a Parser object
482          */
483         function getParser( $preprocessor = null ) {
484                 global $wgParserConf;
486                 $class = $wgParserConf['class'];
487                 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
489                 foreach ( $this->hooks as $tag => $callback ) {
490                         $parser->setHook( $tag, $callback );
491                 }
493                 foreach ( $this->functionHooks as $tag => $bits ) {
494                         list( $callback, $flags ) = $bits;
495                         $parser->setFunctionHook( $tag, $callback, $flags );
496                 }
498                 wfRunHooks( 'ParserTestParser', array( &$parser ) );
500                 return $parser;
501         }
503         /**
504          * Run a given wikitext input through a freshly-constructed wiki parser,
505          * and compare the output against the expected results.
506          * Prints status and explanatory messages to stdout.
507          *
508          * @param $desc String: test's description
509          * @param $input String: wikitext to try rendering
510          * @param $result String: result to output
511          * @param $opts Array: test's options
512          * @param $config String: overrides for global variables, one per line
513          * @return Boolean
514          */
515         public function runTest( $desc, $input, $result, $opts, $config ) {
516                 if ( $this->showProgress ) {
517                         $this->showTesting( $desc );
518                 }
520                 $opts = $this->parseOptions( $opts );
521                 $context = $this->setupGlobals( $opts, $config );
523                 $user = $context->getUser();
524                 $options = ParserOptions::newFromContext( $context );
526                 if ( isset( $opts['title'] ) ) {
527                         $titleText = $opts['title'];
528                 } else {
529                         $titleText = 'Parser test';
530                 }
532                 $local = isset( $opts['local'] );
533                 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
534                 $parser = $this->getParser( $preprocessor );
535                 $title = Title::newFromText( $titleText );
537                 if ( isset( $opts['pst'] ) ) {
538                         $out = $parser->preSaveTransform( $input, $title, $user, $options );
539                 } elseif ( isset( $opts['msg'] ) ) {
540                         $out = $parser->transformMsg( $input, $options, $title );
541                 } elseif ( isset( $opts['section'] ) ) {
542                         $section = $opts['section'];
543                         $out = $parser->getSection( $input, $section );
544                 } elseif ( isset( $opts['replace'] ) ) {
545                         $section = $opts['replace'][0];
546                         $replace = $opts['replace'][1];
547                         $out = $parser->replaceSection( $input, $section, $replace );
548                 } elseif ( isset( $opts['comment'] ) ) {
549                         $out = Linker::formatComment( $input, $title, $local );
550                 } elseif ( isset( $opts['preload'] ) ) {
551                         $out = $parser->getPreloadText( $input, $title, $options );
552                 } else {
553                         $output = $parser->parse( $input, $title, $options, true, true, 1337 );
554                         $out = $output->getText();
556                         if ( isset( $opts['showtitle'] ) ) {
557                                 if ( $output->getTitleText() ) {
558                                         $title = $output->getTitleText();
559                                 }
561                                 $out = "$title\n$out";
562                         }
564                         if ( isset( $opts['ill'] ) ) {
565                                 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
566                         } elseif ( isset( $opts['cat'] ) ) {
567                                 $outputPage = $context->getOutput();
568                                 $outputPage->addCategoryLinks( $output->getCategories() );
569                                 $cats = $outputPage->getCategoryLinks();
571                                 if ( isset( $cats['normal'] ) ) {
572                                         $out = $this->tidy( implode( ' ', $cats['normal'] ) );
573                                 } else {
574                                         $out = '';
575                                 }
576                         }
578                         $result = $this->tidy( $result );
579                 }
581                 $this->teardownGlobals();
583                 $testResult = new ParserTestResult( $desc );
584                 $testResult->expected = $result;
585                 $testResult->actual = $out;
587                 return $this->showTestResult( $testResult );
588         }
590         /**
591          * Refactored in 1.22 to use ParserTestResult
592          */
593         function showTestResult( ParserTestResult $testResult ) {
594                 if ( $testResult->isSuccess() ) {
595                         $this->showSuccess( $testResult );
596                         return true;
597                 } else {
598                         $this->showFailure( $testResult );
599                         return false;
600                 }
601         }
603         /**
604          * Use a regex to find out the value of an option
605          * @param $key String: name of option val to retrieve
606          * @param $opts Options array to look in
607          * @param $default Mixed: default value returned if not found
608          */
609         private static function getOptionValue( $key, $opts, $default ) {
610                 $key = strtolower( $key );
612                 if ( isset( $opts[$key] ) ) {
613                         return $opts[$key];
614                 } else {
615                         return $default;
616                 }
617         }
619         private function parseOptions( $instring ) {
620                 $opts = array();
621                 // foo
622                 // foo=bar
623                 // foo="bar baz"
624                 // foo=[[bar baz]]
625                 // foo=bar,"baz quux"
626                 $regex = '/\b
627                         ([\w-]+)                                                # Key
628                         \b
629                         (?:\s*
630                                 =                                               # First sub-value
631                                 \s*
632                                 (
633                                         "
634                                                 [^"]*                   # Quoted val
635                                         "
636                                 |
637                                         \[\[
638                                                 [^]]*                   # Link target
639                                         \]\]
640                                 |
641                                         [\w-]+                          # Plain word
642                                 )
643                                 (?:\s*
644                                         ,                                       # Sub-vals 1..N
645                                         \s*
646                                         (
647                                                 "[^"]*"                 # Quoted val
648                                         |
649                                                 \[\[[^]]*\]\]   # Link target
650                                         |
651                                                 [\w-]+                  # Plain word
652                                         )
653                                 )*
654                         )?
655                         /x';
657                 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
658                         foreach ( $matches as $bits ) {
659                                 array_shift( $bits );
660                                 $key = strtolower( array_shift( $bits ) );
661                                 if ( count( $bits ) == 0 ) {
662                                         $opts[$key] = true;
663                                 } elseif ( count( $bits ) == 1 ) {
664                                         $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
665                                 } else {
666                                         // Array!
667                                         $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
668                                 }
669                         }
670                 }
671                 return $opts;
672         }
674         private function cleanupOption( $opt ) {
675                 if ( substr( $opt, 0, 1 ) == '"' ) {
676                         return substr( $opt, 1, -1 );
677                 }
679                 if ( substr( $opt, 0, 2 ) == '[[' ) {
680                         return substr( $opt, 2, -2 );
681                 }
682                 return $opt;
683         }
685         /**
686          * Set up the global variables for a consistent environment for each test.
687          * Ideally this should replace the global configuration entirely.
688          */
689         private function setupGlobals( $opts = '', $config = '' ) {
690                 # Find out values for some special options.
691                 $lang =
692                         self::getOptionValue( 'language', $opts, 'en' );
693                 $variant =
694                         self::getOptionValue( 'variant', $opts, false );
695                 $maxtoclevel =
696                         self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
697                 $linkHolderBatchSize =
698                         self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
700                 $settings = array(
701                         'wgServer' => 'http://example.org',
702                         'wgScript' => '/index.php',
703                         'wgScriptPath' => '/',
704                         'wgArticlePath' => '/wiki/$1',
705                         'wgActionPaths' => array(),
706                         'wgLockManagers' => array( array(
707                                 'name' => 'fsLockManager',
708                                 'class' => 'FSLockManager',
709                                 'lockDirectory' => $this->uploadDir . '/lockdir',
710                         ), array(
711                                 'name' => 'nullLockManager',
712                                 'class' => 'NullLockManager',
713                         ) ),
714                         'wgLocalFileRepo' => array(
715                                 'class' => 'LocalRepo',
716                                 'name' => 'local',
717                                 'url' => 'http://example.com/images',
718                                 'hashLevels' => 2,
719                                 'transformVia404' => false,
720                                 'backend' => new FSFileBackend( array(
721                                         'name' => 'local-backend',
722                                         'lockManager' => 'fsLockManager',
723                                         'containerPaths' => array(
724                                                 'local-public' => $this->uploadDir,
725                                                 'local-thumb' => $this->uploadDir . '/thumb',
726                                                 'local-temp' => $this->uploadDir . '/temp',
727                                                 'local-deleted' => $this->uploadDir . '/delete',
728                                         )
729                                 ) )
730                         ),
731                         'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
732                         'wgStylePath' => '/skins',
733                         'wgSitename' => 'MediaWiki',
734                         'wgLanguageCode' => $lang,
735                         'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
736                         'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
737                         'wgLang' => null,
738                         'wgContLang' => null,
739                         'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
740                         'wgMaxTocLevel' => $maxtoclevel,
741                         'wgCapitalLinks' => true,
742                         'wgNoFollowLinks' => true,
743                         'wgNoFollowDomainExceptions' => array(),
744                         'wgThumbnailScriptPath' => false,
745                         'wgUseImageResize' => true,
746                         'wgSVGConverter' => 'null',
747                         'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
748                         'wgLocaltimezone' => 'UTC',
749                         'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
750                         'wgUseTidy' => false,
751                         'wgDefaultLanguageVariant' => $variant,
752                         'wgVariantArticlePath' => false,
753                         'wgGroupPermissions' => array( '*' => array(
754                                 'createaccount' => true,
755                                 'read' => true,
756                                 'edit' => true,
757                                 'createpage' => true,
758                                 'createtalk' => true,
759                         ) ),
760                         'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
761                         'wgDefaultExternalStore' => array(),
762                         'wgForeignFileRepos' => array(),
763                         'wgLinkHolderBatchSize' => $linkHolderBatchSize,
764                         'wgExperimentalHtmlIds' => false,
765                         'wgExternalLinkTarget' => false,
766                         'wgAlwaysUseTidy' => false,
767                         'wgHtml5' => true,
768                         'wgWellFormedXml' => true,
769                         'wgAllowMicrodataAttributes' => true,
770                         'wgAdaptiveMessageCache' => true,
771                         'wgDisableLangConversion' => false,
772                         'wgDisableTitleConversion' => false,
773                 );
775                 if ( $config ) {
776                         $configLines = explode( "\n", $config );
778                         foreach ( $configLines as $line ) {
779                                 list( $var, $value ) = explode( '=', $line, 2 );
781                                 $settings[$var] = eval( "return $value;" );
782                         }
783                 }
785                 $this->savedGlobals = array();
787                 /** @since 1.20 */
788                 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
790                 foreach ( $settings as $var => $val ) {
791                         if ( array_key_exists( $var, $GLOBALS ) ) {
792                                 $this->savedGlobals[$var] = $GLOBALS[$var];
793                         }
795                         $GLOBALS[$var] = $val;
796                 }
798                 $GLOBALS['wgContLang'] = Language::factory( $lang );
799                 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
801                 $context = new RequestContext();
802                 $GLOBALS['wgLang'] = $context->getLanguage();
803                 $GLOBALS['wgOut'] = $context->getOutput();
805                 $GLOBALS['wgUser'] = new User();
807                 global $wgHooks;
809                 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
810                 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
812                 MagicWord::clearCache();
814                 return $context;
815         }
817         /**
818          * List of temporary tables to create, without prefix.
819          * Some of these probably aren't necessary.
820          */
821         private function listTables() {
822                 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
823                         'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
824                         'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
825                         'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
826                         'recentchanges', 'watchlist', 'interwiki', 'logging',
827                         'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
828                         'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
829                 );
831                 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
832                         array_push( $tables, 'searchindex' );
833                 }
835                 // Allow extensions to add to the list of tables to duplicate;
836                 // may be necessary if they hook into page save or other code
837                 // which will require them while running tests.
838                 wfRunHooks( 'ParserTestTables', array( &$tables ) );
840                 return $tables;
841         }
843         /**
844          * Set up a temporary set of wiki tables to work with for the tests.
845          * Currently this will only be done once per run, and any changes to
846          * the db will be visible to later tests in the run.
847          */
848         public function setupDatabase() {
849                 global $wgDBprefix;
851                 if ( $this->databaseSetupDone ) {
852                         return;
853                 }
855                 $this->db = wfGetDB( DB_MASTER );
856                 $dbType = $this->db->getType();
858                 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
859                         throw new MWException( 'setupDatabase should be called before setupGlobals' );
860                 }
862                 $this->databaseSetupDone = true;
863                 $this->oldTablePrefix = $wgDBprefix;
865                 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
866                 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
867                 # This works around it for now...
868                 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
870                 # CREATE TEMPORARY TABLE breaks if there is more than one server
871                 if ( wfGetLB()->getServerCount() != 1 ) {
872                         $this->useTemporaryTables = false;
873                 }
875                 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
876                 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
878                 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
879                 $this->dbClone->useTemporaryTables( $temporary );
880                 $this->dbClone->cloneTableStructure();
882                 if ( $dbType == 'oracle' ) {
883                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
884                         # Insert 0 user to prevent FK violations
886                         # Anonymous user
887                         $this->db->insert( 'user', array(
888                                 'user_id' => 0,
889                                 'user_name' => 'Anonymous' ) );
890                 }
892                 # Update certain things in site_stats
893                 $this->db->insert( 'site_stats',
894                         array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
896                 # Reinitialise the LocalisationCache to match the database state
897                 Language::getLocalisationCache()->unloadAll();
899                 # Clear the message cache
900                 MessageCache::singleton()->clear();
902                 // Remember to update newParserTests.php after changing the below
903                 // (and it uses a slightly different syntax just for teh lulz)
904                 $this->uploadDir = $this->setupUploadDir();
905                 $user = User::createNew( 'WikiSysop' );
906                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
907                 # note that the size/width/height/bits/etc of the file
908                 # are actually set by inspecting the file itself; the arguments
909                 # to recordUpload2 have no effect.  That said, we try to make things
910                 # match up so it is less confusing to readers of the code & tests.
911                 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
912                         'size' => 7881,
913                         'width' => 1941,
914                         'height' => 220,
915                         'bits' => 8,
916                         'media_type' => MEDIATYPE_BITMAP,
917                         'mime' => 'image/jpeg',
918                         'metadata' => serialize( array() ),
919                         'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
920                         'fileExists' => true
921                 ), $this->db->timestamp( '20010115123500' ), $user );
923                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
924                 # again, note that size/width/height below are ignored; see above.
925                 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
926                         'size' => 22589,
927                         'width' => 135,
928                         'height' => 135,
929                         'bits' => 8,
930                         'media_type' => MEDIATYPE_BITMAP,
931                         'mime' => 'image/png',
932                         'metadata' => serialize( array() ),
933                         'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
934                         'fileExists' => true
935                 ), $this->db->timestamp( '20130225203040' ), $user );
937                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
938                 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
939                                 'size'        => 12345,
940                                 'width'       => 240,
941                                 'height'      => 180,
942                                 'bits'        => 24,
943                                 'media_type'  => MEDIATYPE_DRAWING,
944                                 'mime'        => 'image/svg+xml',
945                                 'metadata'    => serialize( array() ),
946                                 'sha1'        => wfBaseConvert( '', 16, 36, 31 ),
947                                 'fileExists'  => true
948                 ), $this->db->timestamp( '20010115123500' ), $user );
950                 # This image will be blacklisted in [[MediaWiki:Bad image list]]
951                 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
952                 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
953                         'size' => 12345,
954                         'width' => 320,
955                         'height' => 240,
956                         'bits' => 24,
957                         'media_type' => MEDIATYPE_BITMAP,
958                         'mime' => 'image/jpeg',
959                         'metadata' => serialize( array() ),
960                         'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
961                         'fileExists' => true
962                 ), $this->db->timestamp( '20010115123500' ), $user );
963         }
965         public function teardownDatabase() {
966                 if ( !$this->databaseSetupDone ) {
967                         $this->teardownGlobals();
968                         return;
969                 }
970                 $this->teardownUploadDir( $this->uploadDir );
972                 $this->dbClone->destroy();
973                 $this->databaseSetupDone = false;
975                 if ( $this->useTemporaryTables ) {
976                         if ( $this->db->getType() == 'sqlite' ) {
977                                 # Under SQLite the searchindex table is virtual and need
978                                 # to be explicitly destroyed. See bug 29912
979                                 # See also MediaWikiTestCase::destroyDB()
980                                 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
981                                 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
982                         }
983                         # Don't need to do anything
984                         $this->teardownGlobals();
985                         return;
986                 }
988                 $tables = $this->listTables();
990                 foreach ( $tables as $table ) {
991                         if ( $this->db->getType() == 'oracle' ) {
992                                 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
993                         } else {
994                                 $this->db->query( "DROP TABLE `parsertest_$table`" );
995                         }
996                 }
998                 if ( $this->db->getType() == 'oracle' ) {
999                         $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1000                 }
1002                 $this->teardownGlobals();
1003         }
1005         /**
1006          * Create a dummy uploads directory which will contain a couple
1007          * of files in order to pass existence tests.
1008          *
1009          * @return String: the directory
1010          */
1011         private function setupUploadDir() {
1012                 global $IP;
1014                 if ( $this->keepUploads ) {
1015                         $dir = wfTempDir() . '/mwParser-images';
1017                         if ( is_dir( $dir ) ) {
1018                                 return $dir;
1019                         }
1020                 } else {
1021                         $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1022                 }
1024                 // wfDebug( "Creating upload directory $dir\n" );
1025                 if ( file_exists( $dir ) ) {
1026                         wfDebug( "Already exists!\n" );
1027                         return $dir;
1028                 }
1030                 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1031                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1032                 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1033                 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1034                 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1035                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1036                 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1037                 copy( "$IP/skins/monobook/headbg.jpg", "$dir/f/ff/Foobar.svg" );
1038                 file_put_contents( "$dir/f/ff/Foobar.svg",
1039                         '<?xml version="1.0" encoding="utf-8"?>' .
1040                         '<svg xmlns="http://www.w3.org/2000/svg" />' );
1041                 return $dir;
1042         }
1044         /**
1045          * Restore default values and perform any necessary clean-up
1046          * after each test runs.
1047          */
1048         private function teardownGlobals() {
1049                 RepoGroup::destroySingleton();
1050                 FileBackendGroup::destroySingleton();
1051                 LockManagerGroup::destroySingletons();
1052                 LinkCache::singleton()->clear();
1054                 foreach ( $this->savedGlobals as $var => $val ) {
1055                         $GLOBALS[$var] = $val;
1056                 }
1057         }
1059         /**
1060          * Remove the dummy uploads directory
1061          */
1062         private function teardownUploadDir( $dir ) {
1063                 if ( $this->keepUploads ) {
1064                         return;
1065                 }
1067                 // delete the files first, then the dirs.
1068                 self::deleteFiles(
1069                         array(
1070                                 "$dir/3/3a/Foobar.jpg",
1071                                 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1072                                 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1073                                 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1074                                 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1075                                 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1076                                 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1077                                 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1078                                 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1079                                 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1080                                 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1081                                 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1082                                 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1083                                 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1084                                 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1086                                 "$dir/e/ea/Thumb.png",
1088                                 "$dir/0/09/Bad.jpg",
1090                                 "$dir/f/ff/Foobar.svg",
1091                                 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1092                                 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1093                                 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1094                                 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1095                                 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1096                                 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1098                                 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1099                         )
1100                 );
1102                 self::deleteDirs(
1103                         array(
1104                                 "$dir/3/3a",
1105                                 "$dir/3",
1106                                 "$dir/thumb/6/65",
1107                                 "$dir/thumb/6",
1108                                 "$dir/thumb/3/3a/Foobar.jpg",
1109                                 "$dir/thumb/3/3a",
1110                                 "$dir/thumb/3",
1111                                 "$dir/e/ea",
1112                                 "$dir/e",
1113                                 "$dir/f/ff/",
1114                                 "$dir/f/",
1115                                 "$dir/thumb/f/ff/Foobar.svg",
1116                                 "$dir/thumb/f/ff/",
1117                                 "$dir/thumb/f/",
1118                                 "$dir/0/09/",
1119                                 "$dir/0/",
1120                                 "$dir/thumb",
1121                                 "$dir/math/f/a/5",
1122                                 "$dir/math/f/a",
1123                                 "$dir/math/f",
1124                                 "$dir/math",
1125                                 "$dir",
1126                         )
1127                 );
1128         }
1130         /**
1131          * Delete the specified files, if they exist.
1132          * @param $files Array: full paths to files to delete.
1133          */
1134         private static function deleteFiles( $files ) {
1135                 foreach ( $files as $file ) {
1136                         if ( file_exists( $file ) ) {
1137                                 unlink( $file );
1138                         }
1139                 }
1140         }
1142         /**
1143          * Delete the specified directories, if they exist. Must be empty.
1144          * @param $dirs Array: full paths to directories to delete.
1145          */
1146         private static function deleteDirs( $dirs ) {
1147                 foreach ( $dirs as $dir ) {
1148                         if ( is_dir( $dir ) ) {
1149                                 rmdir( $dir );
1150                         }
1151                 }
1152         }
1154         /**
1155          * "Running test $desc..."
1156          */
1157         protected function showTesting( $desc ) {
1158                 print "Running test $desc... ";
1159         }
1161         /**
1162          * Print a happy success message.
1163          *
1164          * Refactored in 1.22 to use ParserTestResult
1165          *
1166          * @param $testResult ParserTestResult
1167          * @return Boolean
1168          */
1169         protected function showSuccess( ParserTestResult $testResult ) {
1170                 if ( $this->showProgress ) {
1171                         print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1172                 }
1174                 return true;
1175         }
1177         /**
1178          * Print a failure message and provide some explanatory output
1179          * about what went wrong if so configured.
1180          *
1181          * Refactored in 1.22 to use ParserTestResult
1182          *
1183          * @param $testResult ParserTestResult
1184          * @return Boolean
1185          */
1186         protected function showFailure( ParserTestResult $testResult ) {
1187                 if ( $this->showFailure ) {
1188                         if ( !$this->showProgress ) {
1189                                 # In quiet mode we didn't show the 'Testing' message before the
1190                                 # test, in case it succeeded. Show it now:
1191                                 $this->showTesting( $testResult->description );
1192                         }
1194                         print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1196                         if ( $this->showOutput ) {
1197                                 print "--- Expected ---\n{$testResult->expected}\n";
1198                                 print "--- Actual ---\n{$testResult->actual}\n";
1199                         }
1201                         if ( $this->showDiffs ) {
1202                                 print $this->quickDiff( $testResult->expected, $testResult->actual );
1203                                 if ( !$this->wellFormed( $testResult->actual ) ) {
1204                                         print "XML error: $this->mXmlError\n";
1205                                 }
1206                         }
1207                 }
1209                 return false;
1210         }
1212         /**
1213          * Run given strings through a diff and return the (colorized) output.
1214          * Requires writable /tmp directory and a 'diff' command in the PATH.
1215          *
1216          * @param $input String
1217          * @param $output String
1218          * @param $inFileTail String: tailing for the input file name
1219          * @param $outFileTail String: tailing for the output file name
1220          * @return String
1221          */
1222         protected function quickDiff( $input, $output,
1223                 $inFileTail = 'expected', $outFileTail = 'actual'
1224         ) {
1225                 # Windows, or at least the fc utility, is retarded
1226                 $slash = wfIsWindows() ? '\\' : '/';
1227                 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1229                 $infile = "$prefix-$inFileTail";
1230                 $this->dumpToFile( $input, $infile );
1232                 $outfile = "$prefix-$outFileTail";
1233                 $this->dumpToFile( $output, $outfile );
1235                 $shellInfile = wfEscapeShellArg( $infile );
1236                 $shellOutfile = wfEscapeShellArg( $outfile );
1238                 global $wgDiff3;
1239                 // we assume that people with diff3 also have usual diff
1240                 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1242                 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1244                 unlink( $infile );
1245                 unlink( $outfile );
1247                 return $this->colorDiff( $diff );
1248         }
1250         /**
1251          * Write the given string to a file, adding a final newline.
1252          *
1253          * @param $data String
1254          * @param $filename String
1255          */
1256         private function dumpToFile( $data, $filename ) {
1257                 $file = fopen( $filename, "wt" );
1258                 fwrite( $file, $data . "\n" );
1259                 fclose( $file );
1260         }
1262         /**
1263          * Colorize unified diff output if set for ANSI color output.
1264          * Subtractions are colored blue, additions red.
1265          *
1266          * @param $text String
1267          * @return String
1268          */
1269         protected function colorDiff( $text ) {
1270                 return preg_replace(
1271                         array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1272                         array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1273                                 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1274                         $text );
1275         }
1277         /**
1278          * Show "Reading tests from ..."
1279          *
1280          * @param $path String
1281          */
1282         public function showRunFile( $path ) {
1283                 print $this->term->color( 1 ) .
1284                         "Reading tests from \"$path\"..." .
1285                         $this->term->reset() .
1286                         "\n";
1287         }
1289         /**
1290          * Insert a temporary test article
1291          * @param $name String: the title, including any prefix
1292          * @param $text String: the article text
1293          * @param $line Integer: the input line number, for reporting errors
1294          * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1295          */
1296         public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1297                 global $wgCapitalLinks;
1299                 $oldCapitalLinks = $wgCapitalLinks;
1300                 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1302                 $text = self::chomp( $text );
1303                 $name = self::chomp( $name );
1305                 $title = Title::newFromText( $name );
1307                 if ( is_null( $title ) ) {
1308                         throw new MWException( "invalid title '$name' at line $line\n" );
1309                 }
1311                 $page = WikiPage::factory( $title );
1312                 $page->loadPageData( 'fromdbmaster' );
1314                 if ( $page->exists() ) {
1315                         if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1316                                 return;
1317                         } else {
1318                                 throw new MWException( "duplicate article '$name' at line $line\n" );
1319                         }
1320                 }
1322                 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1324                 $wgCapitalLinks = $oldCapitalLinks;
1325         }
1327         /**
1328          * Steal a callback function from the primary parser, save it for
1329          * application to our scary parser. If the hook is not installed,
1330          * abort processing of this file.
1331          *
1332          * @param $name String
1333          * @return Bool true if tag hook is present
1334          */
1335         public function requireHook( $name ) {
1336                 global $wgParser;
1338                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1340                 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1341                         $this->hooks[$name] = $wgParser->mTagHooks[$name];
1342                 } else {
1343                         echo "   This test suite requires the '$name' hook extension, skipping.\n";
1344                         return false;
1345                 }
1347                 return true;
1348         }
1350         /**
1351          * Steal a callback function from the primary parser, save it for
1352          * application to our scary parser. If the hook is not installed,
1353          * abort processing of this file.
1354          *
1355          * @param $name String
1356          * @return Bool true if function hook is present
1357          */
1358         public function requireFunctionHook( $name ) {
1359                 global $wgParser;
1361                 $wgParser->firstCallInit(); // make sure hooks are loaded.
1363                 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1364                         $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1365                 } else {
1366                         echo "   This test suite requires the '$name' function hook extension, skipping.\n";
1367                         return false;
1368                 }
1370                 return true;
1371         }
1373         /**
1374          * Run the "tidy" command on text if the $wgUseTidy
1375          * global is true
1376          *
1377          * @param $text String: the text to tidy
1378          * @return String
1379          */
1380         private function tidy( $text ) {
1381                 global $wgUseTidy;
1383                 if ( $wgUseTidy ) {
1384                         $text = MWTidy::tidy( $text );
1385                 }
1387                 return $text;
1388         }
1390         private function wellFormed( $text ) {
1391                 $html =
1392                         Sanitizer::hackDocType() .
1393                                 '<html>' .
1394                                 $text .
1395                                 '</html>';
1397                 $parser = xml_parser_create( "UTF-8" );
1399                 # case folding violates XML standard, turn it off
1400                 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1402                 if ( !xml_parse( $parser, $html, true ) ) {
1403                         $err = xml_error_string( xml_get_error_code( $parser ) );
1404                         $position = xml_get_current_byte_index( $parser );
1405                         $fragment = $this->extractFragment( $html, $position );
1406                         $this->mXmlError = "$err at byte $position:\n$fragment";
1407                         xml_parser_free( $parser );
1409                         return false;
1410                 }
1412                 xml_parser_free( $parser );
1414                 return true;
1415         }
1417         private function extractFragment( $text, $position ) {
1418                 $start = max( 0, $position - 10 );
1419                 $before = $position - $start;
1420                 $fragment = '...' .
1421                         $this->term->color( 34 ) .
1422                         substr( $text, $start, $before ) .
1423                         $this->term->color( 0 ) .
1424                         $this->term->color( 31 ) .
1425                         $this->term->color( 1 ) .
1426                         substr( $text, $position, 1 ) .
1427                         $this->term->color( 0 ) .
1428                         $this->term->color( 34 ) .
1429                         substr( $text, $position + 1, 9 ) .
1430                         $this->term->color( 0 ) .
1431                         '...';
1432                 $display = str_replace( "\n", ' ', $fragment );
1433                 $caret = '   ' .
1434                         str_repeat( ' ', $before ) .
1435                         $this->term->color( 31 ) .
1436                         '^' .
1437                         $this->term->color( 0 );
1439                 return "$display\n$caret";
1440         }
1442         static function getFakeTimestamp( &$parser, &$ts ) {
1443                 $ts = 123;
1444                 return true;
1445         }