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