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