MediaWiki  master
parserTest.inc
Go to the documentation of this file.
1 <?php
31 
35 class ParserTest {
39  private $color;
40 
44  private $showOutput;
45 
49  private $useTemporaryTables = true;
50 
54  private $databaseSetupDone = false;
55 
60  private $db;
61 
66  private $dbClone;
67 
71  private $djVuSupport;
72 
76  private $tidySupport;
77 
81  private $recorder;
82 
83  private $maxFuzzTestLength = 300;
84  private $fuzzSeed = 0;
85  private $memoryLimit = 50;
86  private $uploadDir = null;
87 
88  public $regex = "";
89  private $savedGlobals = [];
90  private $useDwdiff = false;
91  private $markWhitespace = false;
93 
99  public function __construct( $options = [] ) {
100  # Only colorize output if stdout is a terminal.
101  $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
102 
103  if ( isset( $options['color'] ) ) {
104  switch ( $options['color'] ) {
105  case 'no':
106  $this->color = false;
107  break;
108  case 'yes':
109  default:
110  $this->color = true;
111  break;
112  }
113  }
114 
115  $this->term = $this->color
116  ? new AnsiTermColorer()
117  : new DummyTermColorer();
118 
119  $this->showDiffs = !isset( $options['quick'] );
120  $this->showProgress = !isset( $options['quiet'] );
121  $this->showFailure = !(
122  isset( $options['quiet'] )
123  && ( isset( $options['record'] )
124  || isset( $options['compare'] ) ) ); // redundant output
125 
126  $this->showOutput = isset( $options['show-output'] );
127  $this->useDwdiff = isset( $options['dwdiff'] );
128  $this->markWhitespace = isset( $options['mark-ws'] );
129 
130  if ( isset( $options['norm'] ) ) {
131  foreach ( explode( ',', $options['norm'] ) as $func ) {
132  if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
133  $this->normalizationFunctions[] = $func;
134  } else {
135  echo "Warning: unknown normalization option \"$func\"\n";
136  }
137  }
138  }
139 
140  if ( isset( $options['filter'] ) ) {
141  $options['regex'] = $options['filter'];
142  }
143 
144  if ( isset( $options['regex'] ) ) {
145  if ( isset( $options['record'] ) ) {
146  echo "Warning: --record cannot be used with --regex, disabling --record\n";
147  unset( $options['record'] );
148  }
149  $this->regex = $options['regex'];
150  } else {
151  # Matches anything
152  $this->regex = '';
153  }
154 
155  $this->setupRecorder( $options );
156  $this->keepUploads = isset( $options['keep-uploads'] );
157 
158  if ( $this->keepUploads ) {
159  $this->uploadDir = wfTempDir() . '/mwParser-images';
160  } else {
161  $this->uploadDir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
162  }
163 
164  if ( isset( $options['seed'] ) ) {
165  $this->fuzzSeed = intval( $options['seed'] ) - 1;
166  }
167 
168  $this->runDisabled = isset( $options['run-disabled'] );
169  $this->runParsoid = isset( $options['run-parsoid'] );
170 
171  $this->djVuSupport = new DjVuSupport();
172  $this->tidySupport = new TidySupport( isset( $options['use-tidy-config'] ) );
173  if ( !$this->tidySupport->isEnabled() ) {
174  echo "Warning: tidy is not installed, skipping some tests\n";
175  }
176 
177  if ( !extension_loaded( 'gd' ) ) {
178  echo "Warning: GD extension is not present, thumbnailing tests will probably fail\n";
179  }
180 
181  $this->hooks = [];
182  $this->functionHooks = [];
183  $this->transparentHooks = [];
184  $this->setUp();
185  }
186 
187  function setUp() {
188  global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
195 
196  $wgScriptPath = '';
197  $wgScript = '/index.php';
198  $wgStylePath = '/skins';
199  $wgResourceBasePath = '';
200  $wgExtensionAssetsPath = '/extensions';
201  $wgArticlePath = '/wiki/$1';
202  $wgThumbnailScriptPath = false;
203  $wgLockManagers = [ [
204  'name' => 'fsLockManager',
205  'class' => 'FSLockManager',
206  'lockDirectory' => $this->uploadDir . '/lockdir',
207  ], [
208  'name' => 'nullLockManager',
209  'class' => 'NullLockManager',
210  ] ];
211  $wgLocalFileRepo = [
212  'class' => 'LocalRepo',
213  'name' => 'local',
214  'url' => 'http://example.com/images',
215  'hashLevels' => 2,
216  'transformVia404' => false,
217  'backend' => new FSFileBackend( [
218  'name' => 'local-backend',
219  'wikiId' => wfWikiID(),
220  'containerPaths' => [
221  'local-public' => $this->uploadDir . '/public',
222  'local-thumb' => $this->uploadDir . '/thumb',
223  'local-temp' => $this->uploadDir . '/temp',
224  'local-deleted' => $this->uploadDir . '/deleted',
225  ]
226  ] )
227  ];
228  $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
229  $wgNamespaceAliases['Image'] = NS_FILE;
230  $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
231  # add a namespace shadowing a interwiki link, to test
232  # proper precedence when resolving links. (bug 51680)
233  $wgExtraNamespaces[100] = 'MemoryAlpha';
234  $wgExtraNamespaces[101] = 'MemoryAlpha talk';
235 
236  // XXX: tests won't run without this (for CACHE_DB)
237  if ( $wgMainCacheType === CACHE_DB ) {
238  $wgMainCacheType = CACHE_NONE;
239  }
240  if ( $wgMessageCacheType === CACHE_DB ) {
241  $wgMessageCacheType = CACHE_NONE;
242  }
243  if ( $wgParserCacheType === CACHE_DB ) {
244  $wgParserCacheType = CACHE_NONE;
245  }
246 
248  $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
249  $messageMemc = wfGetMessageCacheStorage();
250  $parserMemc = wfGetParserCacheStorage();
251 
253  $context = new RequestContext;
254  $wgUser = new User;
255  $wgLang = $context->getLanguage();
256  $wgOut = $context->getOutput();
257  $wgRequest = $context->getRequest();
258  $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], [ $wgParserConf ] );
259 
260  if ( $wgStyleDirectory === false ) {
261  $wgStyleDirectory = "$IP/skins";
262  }
263 
264  self::setupInterwikis();
265  $wgLocalInterwikis = [ 'local', 'mi' ];
266  // "extra language links"
267  // see https://gerrit.wikimedia.org/r/111390
268  array_push( $wgExtraInterlanguageLinkPrefixes, 'mul' );
269 
270  // Reset namespace cache
272  Language::factory( 'en' )->resetNamespaces();
273  }
274 
284  public static function setupInterwikis() {
285  # Hack: insert a few Wikipedia in-project interwiki prefixes,
286  # for testing inter-language links
287  Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
288  static $testInterwikis = [
289  'local' => [
290  'iw_url' => 'http://doesnt.matter.org/$1',
291  'iw_api' => '',
292  'iw_wikiid' => '',
293  'iw_local' => 0 ],
294  'wikipedia' => [
295  'iw_url' => 'http://en.wikipedia.org/wiki/$1',
296  'iw_api' => '',
297  'iw_wikiid' => '',
298  'iw_local' => 0 ],
299  'meatball' => [
300  'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
301  'iw_api' => '',
302  'iw_wikiid' => '',
303  'iw_local' => 0 ],
304  'memoryalpha' => [
305  'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
306  'iw_api' => '',
307  'iw_wikiid' => '',
308  'iw_local' => 0 ],
309  'zh' => [
310  'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
311  'iw_api' => '',
312  'iw_wikiid' => '',
313  'iw_local' => 1 ],
314  'es' => [
315  'iw_url' => 'http://es.wikipedia.org/wiki/$1',
316  'iw_api' => '',
317  'iw_wikiid' => '',
318  'iw_local' => 1 ],
319  'fr' => [
320  'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
321  'iw_api' => '',
322  'iw_wikiid' => '',
323  'iw_local' => 1 ],
324  'ru' => [
325  'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
326  'iw_api' => '',
327  'iw_wikiid' => '',
328  'iw_local' => 1 ],
329  'mi' => [
330  'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
331  'iw_api' => '',
332  'iw_wikiid' => '',
333  'iw_local' => 1 ],
334  'mul' => [
335  'iw_url' => 'http://wikisource.org/wiki/$1',
336  'iw_api' => '',
337  'iw_wikiid' => '',
338  'iw_local' => 1 ],
339  ];
340  if ( array_key_exists( $prefix, $testInterwikis ) ) {
341  $iwData = $testInterwikis[$prefix];
342  }
343 
344  // We only want to rely on the above fixtures
345  return false;
346  } );// hooks::register
347  }
348 
352  public static function tearDownInterwikis() {
353  Hooks::clear( 'InterwikiLoadPrefix' );
354  }
355 
360  public static function resetTitleServices() {
361  $services = MediaWikiServices::getInstance();
362  $services->resetServiceForTesting( 'TitleFormatter' );
363  $services->resetServiceForTesting( 'TitleParser' );
364  $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
365  $services->resetServiceForTesting( 'LinkRenderer' );
366  $services->resetServiceForTesting( 'LinkRendererFactory' );
367  }
368 
369  public function setupRecorder( $options ) {
370  if ( isset( $options['record'] ) ) {
371  $this->recorder = new DbTestRecorder( $this );
372  $this->recorder->version = isset( $options['setversion'] ) ?
373  $options['setversion'] : SpecialVersion::getVersion();
374  } elseif ( isset( $options['compare'] ) ) {
375  $this->recorder = new DbTestPreviewer( $this );
376  } else {
377  $this->recorder = new TestRecorder( $this );
378  }
379  }
380 
387  public static function chomp( $s ) {
388  if ( substr( $s, -1 ) === "\n" ) {
389  return substr( $s, 0, -1 );
390  } else {
391  return $s;
392  }
393  }
394 
400  function fuzzTest( $filenames ) {
401  $GLOBALS['wgContLang'] = Language::factory( 'en' );
402  $dict = $this->getFuzzInput( $filenames );
403  $dictSize = strlen( $dict );
404  $logMaxLength = log( $this->maxFuzzTestLength );
405  $this->setupDatabase();
406  ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
407 
408  $numTotal = 0;
409  $numSuccess = 0;
410  $user = new User;
412  $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
413 
414  while ( true ) {
415  // Generate test input
416  mt_srand( ++$this->fuzzSeed );
417  $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
418  $input = '';
419 
420  while ( strlen( $input ) < $totalLength ) {
421  $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
422  $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
423  $offset = mt_rand( 0, $dictSize - $hairLength );
424  $input .= substr( $dict, $offset, $hairLength );
425  }
426 
427  $this->setupGlobals();
428  $parser = $this->getParser();
429 
430  // Run the test
431  try {
432  $parser->parse( $input, $title, $opts );
433  $fail = false;
434  } catch ( Exception $exception ) {
435  $fail = true;
436  }
437 
438  if ( $fail ) {
439  echo "Test failed with seed {$this->fuzzSeed}\n";
440  echo "Input:\n";
441  printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
442  echo "$exception\n";
443  } else {
444  $numSuccess++;
445  }
446 
447  $numTotal++;
448  $this->teardownGlobals();
449  $parser->__destruct();
450 
451  if ( $numTotal % 100 == 0 ) {
452  $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
453  echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
454  if ( $usage > 90 ) {
455  echo "Out of memory:\n";
456  $memStats = $this->getMemoryBreakdown();
457 
458  foreach ( $memStats as $name => $usage ) {
459  echo "$name: $usage\n";
460  }
461  $this->abort();
462  }
463  }
464  }
465  }
466 
472  function getFuzzInput( $filenames ) {
473  $dict = '';
474 
475  foreach ( $filenames as $filename ) {
476  $contents = file_get_contents( $filename );
477  preg_match_all(
478  '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s',
479  $contents,
480  $matches
481  );
482 
483  foreach ( $matches[1] as $match ) {
484  $dict .= $match . "\n";
485  }
486  }
487 
488  return $dict;
489  }
490 
495  function getMemoryBreakdown() {
496  $memStats = [];
497 
498  foreach ( $GLOBALS as $name => $value ) {
499  $memStats['$' . $name] = strlen( serialize( $value ) );
500  }
501 
502  $classes = get_declared_classes();
503 
504  foreach ( $classes as $class ) {
505  $rc = new ReflectionClass( $class );
506  $props = $rc->getStaticProperties();
507  $memStats[$class] = strlen( serialize( $props ) );
508  $methods = $rc->getMethods();
509 
510  foreach ( $methods as $method ) {
511  $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
512  }
513  }
514 
515  $functions = get_defined_functions();
516 
517  foreach ( $functions['user'] as $function ) {
518  $rf = new ReflectionFunction( $function );
519  $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
520  }
521 
522  asort( $memStats );
523 
524  return $memStats;
525  }
526 
527  function abort() {
528  $this->abort();
529  }
530 
542  public function runTestsFromFiles( $filenames ) {
543  $ok = false;
544 
545  // be sure, ParserTest::addArticle has correct language set,
546  // so that system messages gets into the right language cache
547  $GLOBALS['wgLanguageCode'] = 'en';
548  $GLOBALS['wgContLang'] = Language::factory( 'en' );
549 
550  $this->recorder->start();
551  try {
552  $this->setupDatabase();
553  $ok = true;
554 
555  foreach ( $filenames as $filename ) {
556  echo "Running parser tests from: $filename\n";
557  $tests = new TestFileIterator( $filename, $this );
558  $ok = $this->runTests( $tests ) && $ok;
559  }
560 
561  $this->teardownDatabase();
562  $this->recorder->report();
563  } catch ( DBError $e ) {
564  echo $e->getMessage();
565  }
566  $this->recorder->end();
567 
568  return $ok;
569  }
570 
571  function runTests( $tests ) {
572  $ok = true;
573 
574  foreach ( $tests as $t ) {
575  $result =
576  $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
577  $ok = $ok && $result;
578  $this->recorder->record( $t['test'], $t['subtest'], $result );
579  }
580 
581  if ( $this->showProgress ) {
582  print "\n";
583  }
584 
585  return $ok;
586  }
587 
594  function getParser( $preprocessor = null ) {
595  global $wgParserConf;
596 
597  $class = $wgParserConf['class'];
598  $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
599 
600  foreach ( $this->hooks as $tag => $callback ) {
601  $parser->setHook( $tag, $callback );
602  }
603 
604  foreach ( $this->functionHooks as $tag => $bits ) {
605  list( $callback, $flags ) = $bits;
606  $parser->setFunctionHook( $tag, $callback, $flags );
607  }
608 
609  foreach ( $this->transparentHooks as $tag => $callback ) {
610  $parser->setTransparentTagHook( $tag, $callback );
611  }
612 
613  Hooks::run( 'ParserTestParser', [ &$parser ] );
614 
615  return $parser;
616  }
617 
630  public function runTest( $desc, $input, $result, $opts, $config ) {
631  if ( $this->showProgress ) {
632  $this->showTesting( $desc );
633  }
634 
635  $opts = $this->parseOptions( $opts );
636  $context = $this->setupGlobals( $opts, $config );
637 
638  $user = $context->getUser();
640 
641  if ( isset( $opts['djvu'] ) ) {
642  if ( !$this->djVuSupport->isEnabled() ) {
643  return $this->showSkipped();
644  }
645  }
646 
647  if ( isset( $opts['tidy'] ) ) {
648  if ( !$this->tidySupport->isEnabled() ) {
649  return $this->showSkipped();
650  } else {
651  $options->setTidy( true );
652  }
653  }
654 
655  if ( isset( $opts['title'] ) ) {
656  $titleText = $opts['title'];
657  } else {
658  $titleText = 'Parser test';
659  }
660 
661  ObjectCache::getMainWANInstance()->clearProcessCache();
662  $local = isset( $opts['local'] );
663  $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
664  $parser = $this->getParser( $preprocessor );
665  $title = Title::newFromText( $titleText );
666 
667  if ( isset( $opts['pst'] ) ) {
668  $out = $parser->preSaveTransform( $input, $title, $user, $options );
669  } elseif ( isset( $opts['msg'] ) ) {
670  $out = $parser->transformMsg( $input, $options, $title );
671  } elseif ( isset( $opts['section'] ) ) {
672  $section = $opts['section'];
673  $out = $parser->getSection( $input, $section );
674  } elseif ( isset( $opts['replace'] ) ) {
675  $section = $opts['replace'][0];
676  $replace = $opts['replace'][1];
677  $out = $parser->replaceSection( $input, $section, $replace );
678  } elseif ( isset( $opts['comment'] ) ) {
679  $out = Linker::formatComment( $input, $title, $local );
680  } elseif ( isset( $opts['preload'] ) ) {
681  $out = $parser->getPreloadText( $input, $title, $options );
682  } else {
683  $output = $parser->parse( $input, $title, $options, true, true, 1337 );
684  $output->setTOCEnabled( !isset( $opts['notoc'] ) );
685  $out = $output->getText();
686  if ( isset( $opts['tidy'] ) ) {
687  $out = preg_replace( '/\s+$/', '', $out );
688  }
689 
690  if ( isset( $opts['showtitle'] ) ) {
691  if ( $output->getTitleText() ) {
693  }
694 
695  $out = "$title\n$out";
696  }
697 
698  if ( isset( $opts['showindicators'] ) ) {
699  $indicators = '';
700  foreach ( $output->getIndicators() as $id => $content ) {
701  $indicators .= "$id=$content\n";
702  }
703  $out = $indicators . $out;
704  }
705 
706  if ( isset( $opts['ill'] ) ) {
707  $out = implode( ' ', $output->getLanguageLinks() );
708  } elseif ( isset( $opts['cat'] ) ) {
709  $outputPage = $context->getOutput();
710  $outputPage->addCategoryLinks( $output->getCategories() );
711  $cats = $outputPage->getCategoryLinks();
712 
713  if ( isset( $cats['normal'] ) ) {
714  $out = implode( ' ', $cats['normal'] );
715  } else {
716  $out = '';
717  }
718  }
719  }
720 
721  $this->teardownGlobals();
722 
723  if ( count( $this->normalizationFunctions ) ) {
724  $result = ParserTestResultNormalizer::normalize( $result, $this->normalizationFunctions );
725  $out = ParserTestResultNormalizer::normalize( $out, $this->normalizationFunctions );
726  }
727 
728  $testResult = new ParserTestResult( $desc );
729  $testResult->expected = $result;
730  $testResult->actual = $out;
731 
732  return $this->showTestResult( $testResult );
733  }
734 
740  function showTestResult( ParserTestResult $testResult ) {
741  if ( $testResult->isSuccess() ) {
742  $this->showSuccess( $testResult );
743  return true;
744  } else {
745  $this->showFailure( $testResult );
746  return false;
747  }
748  }
749 
757  private static function getOptionValue( $key, $opts, $default ) {
758  $key = strtolower( $key );
759 
760  if ( isset( $opts[$key] ) ) {
761  return $opts[$key];
762  } else {
763  return $default;
764  }
765  }
766 
767  private function parseOptions( $instring ) {
768  $opts = [];
769  // foo
770  // foo=bar
771  // foo="bar baz"
772  // foo=[[bar baz]]
773  // foo=bar,"baz quux"
774  // foo={...json...}
775  $defs = '(?(DEFINE)
776  (?<qstr> # Quoted string
777  "
778  (?:[^\\\\"] | \\\\.)*
779  "
780  )
781  (?<json>
782  \{ # Open bracket
783  (?:
784  [^"{}] | # Not a quoted string or object, or
785  (?&qstr) | # A quoted string, or
786  (?&json) # A json object (recursively)
787  )*
788  \} # Close bracket
789  )
790  (?<value>
791  (?:
792  (?&qstr) # Quoted val
793  |
794  \[\[
795  [^]]* # Link target
796  \]\]
797  |
798  [\w-]+ # Plain word
799  |
800  (?&json) # JSON object
801  )
802  )
803  )';
804  $regex = '/' . $defs . '\b
805  (?<k>[\w-]+) # Key
806  \b
807  (?:\s*
808  = # First sub-value
809  \s*
810  (?<v>
811  (?&value)
812  (?:\s*
813  , # Sub-vals 1..N
814  \s*
815  (?&value)
816  )*
817  )
818  )?
819  /x';
820  $valueregex = '/' . $defs . '(?&value)/x';
821 
822  if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
823  foreach ( $matches as $bits ) {
824  $key = strtolower( $bits['k'] );
825  if ( !isset( $bits['v'] ) ) {
826  $opts[$key] = true;
827  } else {
828  preg_match_all( $valueregex, $bits['v'], $vmatches );
829  $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
830  if ( count( $opts[$key] ) == 1 ) {
831  $opts[$key] = $opts[$key][0];
832  }
833  }
834  }
835  }
836  return $opts;
837  }
838 
839  private function cleanupOption( $opt ) {
840  if ( substr( $opt, 0, 1 ) == '"' ) {
841  return stripcslashes( substr( $opt, 1, -1 ) );
842  }
843 
844  if ( substr( $opt, 0, 2 ) == '[[' ) {
845  return substr( $opt, 2, -2 );
846  }
847 
848  if ( substr( $opt, 0, 1 ) == '{' ) {
849  return FormatJson::decode( $opt, true );
850  }
851  return $opt;
852  }
853 
861  private function setupGlobals( $opts = '', $config = '' ) {
862  # Find out values for some special options.
863  $lang =
864  self::getOptionValue( 'language', $opts, 'en' );
865  $variant =
866  self::getOptionValue( 'variant', $opts, false );
867  $maxtoclevel =
868  self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
869  $linkHolderBatchSize =
870  self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
871 
872  $settings = [
873  'wgServer' => 'http://example.org',
874  'wgServerName' => 'example.org',
875  'wgScript' => '/index.php',
876  'wgScriptPath' => '',
877  'wgArticlePath' => '/wiki/$1',
878  'wgActionPaths' => [],
879  'wgLockManagers' => [ [
880  'name' => 'fsLockManager',
881  'class' => 'FSLockManager',
882  'lockDirectory' => $this->uploadDir . '/lockdir',
883  ], [
884  'name' => 'nullLockManager',
885  'class' => 'NullLockManager',
886  ] ],
887  'wgLocalFileRepo' => [
888  'class' => 'LocalRepo',
889  'name' => 'local',
890  'url' => 'http://example.com/images',
891  'hashLevels' => 2,
892  'transformVia404' => false,
893  'backend' => new FSFileBackend( [
894  'name' => 'local-backend',
895  'wikiId' => wfWikiID(),
896  'containerPaths' => [
897  'local-public' => $this->uploadDir,
898  'local-thumb' => $this->uploadDir . '/thumb',
899  'local-temp' => $this->uploadDir . '/temp',
900  'local-deleted' => $this->uploadDir . '/delete',
901  ]
902  ] )
903  ],
904  'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
905  'wgUploadNavigationUrl' => false,
906  'wgStylePath' => '/skins',
907  'wgSitename' => 'MediaWiki',
908  'wgLanguageCode' => $lang,
909  'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
910  'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
911  'wgLang' => null,
912  'wgContLang' => null,
913  'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
914  'wgMaxTocLevel' => $maxtoclevel,
915  'wgCapitalLinks' => true,
916  'wgNoFollowLinks' => true,
917  'wgNoFollowDomainExceptions' => [ 'no-nofollow.org' ],
918  'wgThumbnailScriptPath' => false,
919  'wgUseImageResize' => true,
920  'wgSVGConverter' => 'null',
921  'wgSVGConverters' => [ 'null' => 'echo "1">$output' ],
922  'wgLocaltimezone' => 'UTC',
923  'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
924  'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
925  'wgDefaultLanguageVariant' => $variant,
926  'wgVariantArticlePath' => false,
927  'wgGroupPermissions' => [ '*' => [
928  'createaccount' => true,
929  'read' => true,
930  'edit' => true,
931  'createpage' => true,
932  'createtalk' => true,
933  ] ],
934  'wgNamespaceProtection' => [ NS_MEDIAWIKI => 'editinterface' ],
935  'wgDefaultExternalStore' => [],
936  'wgForeignFileRepos' => [],
937  'wgLinkHolderBatchSize' => $linkHolderBatchSize,
938  'wgExperimentalHtmlIds' => false,
939  'wgExternalLinkTarget' => false,
940  'wgHtml5' => true,
941  'wgAdaptiveMessageCache' => true,
942  'wgDisableLangConversion' => false,
943  'wgDisableTitleConversion' => false,
944  // Tidy options.
945  'wgUseTidy' => false,
946  'wgTidyConfig' => isset( $opts['tidy'] ) ? $this->tidySupport->getConfig() : null
947  ];
948 
949  if ( $config ) {
950  $configLines = explode( "\n", $config );
951 
952  foreach ( $configLines as $line ) {
953  list( $var, $value ) = explode( '=', $line, 2 );
954 
955  $settings[$var] = eval( "return $value;" );
956  }
957  }
958 
959  $this->savedGlobals = [];
960 
962  Hooks::run( 'ParserTestGlobals', [ &$settings ] );
963 
964  foreach ( $settings as $var => $val ) {
965  if ( array_key_exists( $var, $GLOBALS ) ) {
966  $this->savedGlobals[$var] = $GLOBALS[$var];
967  }
968 
969  $GLOBALS[$var] = $val;
970  }
971 
972  // Must be set before $context as user language defaults to $wgContLang
973  $GLOBALS['wgContLang'] = Language::factory( $lang );
974  $GLOBALS['wgMemc'] = new EmptyBagOStuff;
975 
978  $GLOBALS['wgLang'] = $context->getLanguage();
979  $GLOBALS['wgOut'] = $context->getOutput();
980  $GLOBALS['wgUser'] = $context->getUser();
981 
982  // We (re)set $wgThumbLimits to a single-element array above.
983  $context->getUser()->setOption( 'thumbsize', 0 );
984 
986 
987  $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
988  $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
989 
993 
994  self::resetTitleServices();
995 
996  return $context;
997  }
998 
1004  private function listTables() {
1005  $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1006  'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1007  'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1008  'site_stats', 'ipblocks', 'image', 'oldimage',
1009  'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1010  'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1011  'archive', 'user_groups', 'page_props', 'category'
1012  ];
1013 
1014  if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1015  array_push( $tables, 'searchindex' );
1016  }
1017 
1018  // Allow extensions to add to the list of tables to duplicate;
1019  // may be necessary if they hook into page save or other code
1020  // which will require them while running tests.
1021  Hooks::run( 'ParserTestTables', [ &$tables ] );
1022 
1023  return $tables;
1024  }
1025 
1031  public function setupDatabase() {
1033 
1034  if ( $this->databaseSetupDone ) {
1035  return;
1036  }
1037 
1038  $this->db = wfGetDB( DB_MASTER );
1039  $dbType = $this->db->getType();
1040 
1041  if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
1042  throw new MWException( 'setupDatabase should be called before setupGlobals' );
1043  }
1044 
1045  $this->databaseSetupDone = true;
1046 
1047  # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
1048  # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
1049  # This works around it for now...
1051 
1052  # CREATE TEMPORARY TABLE breaks if there is more than one server
1053  if ( wfGetLB()->getServerCount() != 1 ) {
1054  $this->useTemporaryTables = false;
1055  }
1056 
1057  $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1058  $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1059 
1060  $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1061  $this->dbClone->useTemporaryTables( $temporary );
1062  $this->dbClone->cloneTableStructure();
1063 
1064  if ( $dbType == 'oracle' ) {
1065  $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1066  # Insert 0 user to prevent FK violations
1067 
1068  # Anonymous user
1069  $this->db->insert( 'user', [
1070  'user_id' => 0,
1071  'user_name' => 'Anonymous' ] );
1072  }
1073 
1074  # Update certain things in site_stats
1075  $this->db->insert( 'site_stats',
1076  [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ] );
1077 
1078  # Reinitialise the LocalisationCache to match the database state
1079  Language::getLocalisationCache()->unloadAll();
1080 
1081  # Clear the message cache
1082  MessageCache::singleton()->clear();
1083 
1084  // Remember to update newParserTests.php after changing the below
1085  // (and it uses a slightly different syntax just for teh lulz)
1086  $this->setupUploadDir();
1087  $user = User::createNew( 'WikiSysop' );
1088  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1089  # note that the size/width/height/bits/etc of the file
1090  # are actually set by inspecting the file itself; the arguments
1091  # to recordUpload2 have no effect. That said, we try to make things
1092  # match up so it is less confusing to readers of the code & tests.
1093  $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1094  'size' => 7881,
1095  'width' => 1941,
1096  'height' => 220,
1097  'bits' => 8,
1098  'media_type' => MEDIATYPE_BITMAP,
1099  'mime' => 'image/jpeg',
1100  'metadata' => serialize( [] ),
1101  'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1102  'fileExists' => true
1103  ], $this->db->timestamp( '20010115123500' ), $user );
1104 
1105  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1106  # again, note that size/width/height below are ignored; see above.
1107  $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1108  'size' => 22589,
1109  'width' => 135,
1110  'height' => 135,
1111  'bits' => 8,
1112  'media_type' => MEDIATYPE_BITMAP,
1113  'mime' => 'image/png',
1114  'metadata' => serialize( [] ),
1115  'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1116  'fileExists' => true
1117  ], $this->db->timestamp( '20130225203040' ), $user );
1118 
1119  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1120  $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1121  'size' => 12345,
1122  'width' => 240,
1123  'height' => 180,
1124  'bits' => 0,
1125  'media_type' => MEDIATYPE_DRAWING,
1126  'mime' => 'image/svg+xml',
1127  'metadata' => serialize( [] ),
1128  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1129  'fileExists' => true
1130  ], $this->db->timestamp( '20010115123500' ), $user );
1131 
1132  # This image will be blacklisted in [[MediaWiki:Bad image list]]
1133  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1134  $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1135  'size' => 12345,
1136  'width' => 320,
1137  'height' => 240,
1138  'bits' => 24,
1139  'media_type' => MEDIATYPE_BITMAP,
1140  'mime' => 'image/jpeg',
1141  'metadata' => serialize( [] ),
1142  'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1143  'fileExists' => true
1144  ], $this->db->timestamp( '20010115123500' ), $user );
1145 
1146  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1147  $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1148  'size' => 12345,
1149  'width' => 320,
1150  'height' => 240,
1151  'bits' => 0,
1152  'media_type' => MEDIATYPE_VIDEO,
1153  'mime' => 'application/ogg',
1154  'metadata' => serialize( [] ),
1155  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1156  'fileExists' => true
1157  ], $this->db->timestamp( '20010115123500' ), $user );
1158 
1159  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1160  $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1161  'size' => 12345,
1162  'width' => 0,
1163  'height' => 0,
1164  'bits' => 0,
1165  'media_type' => MEDIATYPE_AUDIO,
1166  'mime' => 'application/ogg',
1167  'metadata' => serialize( [] ),
1168  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1169  'fileExists' => true
1170  ], $this->db->timestamp( '20010115123500' ), $user );
1171 
1172  # A DjVu file
1173  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1174  $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1175  'size' => 3249,
1176  'width' => 2480,
1177  'height' => 3508,
1178  'bits' => 0,
1179  'media_type' => MEDIATYPE_BITMAP,
1180  'mime' => 'image/vnd.djvu',
1181  'metadata' => '<?xml version="1.0" ?>
1182 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1183 <DjVuXML>
1184 <HEAD></HEAD>
1185 <BODY><OBJECT height="3508" width="2480">
1186 <PARAM name="DPI" value="300" />
1187 <PARAM name="GAMMA" value="2.2" />
1188 </OBJECT>
1189 <OBJECT height="3508" width="2480">
1190 <PARAM name="DPI" value="300" />
1191 <PARAM name="GAMMA" value="2.2" />
1192 </OBJECT>
1193 <OBJECT height="3508" width="2480">
1194 <PARAM name="DPI" value="300" />
1195 <PARAM name="GAMMA" value="2.2" />
1196 </OBJECT>
1197 <OBJECT height="3508" width="2480">
1198 <PARAM name="DPI" value="300" />
1199 <PARAM name="GAMMA" value="2.2" />
1200 </OBJECT>
1201 <OBJECT height="3508" width="2480">
1202 <PARAM name="DPI" value="300" />
1203 <PARAM name="GAMMA" value="2.2" />
1204 </OBJECT>
1205 </BODY>
1206 </DjVuXML>',
1207  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1208  'fileExists' => true
1209  ], $this->db->timestamp( '20010115123600' ), $user );
1210  }
1211 
1212  public function teardownDatabase() {
1213  if ( !$this->databaseSetupDone ) {
1214  $this->teardownGlobals();
1215  return;
1216  }
1217  $this->teardownUploadDir( $this->uploadDir );
1218 
1219  $this->dbClone->destroy();
1220  $this->databaseSetupDone = false;
1221 
1222  if ( $this->useTemporaryTables ) {
1223  if ( $this->db->getType() == 'sqlite' ) {
1224  # Under SQLite the searchindex table is virtual and need
1225  # to be explicitly destroyed. See bug 29912
1226  # See also MediaWikiTestCase::destroyDB()
1227  wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1228  $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1229  }
1230  # Don't need to do anything
1231  $this->teardownGlobals();
1232  return;
1233  }
1234 
1235  $tables = $this->listTables();
1236 
1237  foreach ( $tables as $table ) {
1238  if ( $this->db->getType() == 'oracle' ) {
1239  $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1240  } else {
1241  $this->db->query( "DROP TABLE `parsertest_$table`" );
1242  }
1243  }
1244 
1245  if ( $this->db->getType() == 'oracle' ) {
1246  $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1247  }
1248 
1249  $this->teardownGlobals();
1250  }
1251 
1258  private function setupUploadDir() {
1259  global $IP;
1260 
1262  if ( $this->keepUploads && is_dir( $dir ) ) {
1263  return;
1264  }
1265 
1266  // wfDebug( "Creating upload directory $dir\n" );
1267  if ( file_exists( $dir ) ) {
1268  wfDebug( "Already exists!\n" );
1269  return;
1270  }
1271 
1272  wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1273  copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1274  wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1275  copy( "$IP/tests/phpunit/data/parser/wiki.png", "$dir/e/ea/Thumb.png" );
1276  wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1277  copy( "$IP/tests/phpunit/data/parser/headbg.jpg", "$dir/0/09/Bad.jpg" );
1278  wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1279  file_put_contents( "$dir/f/ff/Foobar.svg",
1280  '<?xml version="1.0" encoding="utf-8"?>' .
1281  '<svg xmlns="http://www.w3.org/2000/svg"' .
1282  ' version="1.1" width="240" height="180"/>' );
1283  wfMkdirParents( $dir . '/5/5f', null, __METHOD__ );
1284  copy( "$IP/tests/phpunit/data/parser/LoremIpsum.djvu", "$dir/5/5f/LoremIpsum.djvu" );
1285  wfMkdirParents( $dir . '/0/00', null, __METHOD__ );
1286  copy( "$IP/tests/phpunit/data/parser/320x240.ogv", "$dir/0/00/Video.ogv" );
1287  wfMkdirParents( $dir . '/4/41', null, __METHOD__ );
1288  copy( "$IP/tests/phpunit/data/media/say-test.ogg", "$dir/4/41/Audio.oga" );
1289 
1290  return;
1291  }
1292 
1297  private function teardownGlobals() {
1301  LinkCache::singleton()->clear();
1303 
1304  foreach ( $this->savedGlobals as $var => $val ) {
1305  $GLOBALS[$var] = $val;
1306  }
1307  }
1308 
1313  private function teardownUploadDir( $dir ) {
1314  if ( $this->keepUploads ) {
1315  return;
1316  }
1317 
1318  // delete the files first, then the dirs.
1319  self::deleteFiles(
1320  [
1321  "$dir/3/3a/Foobar.jpg",
1322  "$dir/thumb/3/3a/Foobar.jpg/*.jpg",
1323  "$dir/e/ea/Thumb.png",
1324  "$dir/0/09/Bad.jpg",
1325  "$dir/5/5f/LoremIpsum.djvu",
1326  "$dir/thumb/5/5f/LoremIpsum.djvu/*-LoremIpsum.djvu.jpg",
1327  "$dir/f/ff/Foobar.svg",
1328  "$dir/thumb/f/ff/Foobar.svg/*-Foobar.svg.png",
1329  "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1330  "$dir/0/00/Video.ogv",
1331  "$dir/thumb/0/00/Video.ogv/120px--Video.ogv.jpg",
1332  "$dir/thumb/0/00/Video.ogv/180px--Video.ogv.jpg",
1333  "$dir/thumb/0/00/Video.ogv/240px--Video.ogv.jpg",
1334  "$dir/thumb/0/00/Video.ogv/320px--Video.ogv.jpg",
1335  "$dir/thumb/0/00/Video.ogv/270px--Video.ogv.jpg",
1336  "$dir/thumb/0/00/Video.ogv/320px-seek=2-Video.ogv.jpg",
1337  "$dir/thumb/0/00/Video.ogv/320px-seek=3.3666666666667-Video.ogv.jpg",
1338  "$dir/4/41/Audio.oga",
1339  ]
1340  );
1341 
1342  self::deleteDirs(
1343  [
1344  "$dir/3/3a",
1345  "$dir/3",
1346  "$dir/thumb/3/3a/Foobar.jpg",
1347  "$dir/thumb/3/3a",
1348  "$dir/thumb/3",
1349  "$dir/e/ea",
1350  "$dir/e",
1351  "$dir/f/ff/",
1352  "$dir/f/",
1353  "$dir/thumb/f/ff/Foobar.svg",
1354  "$dir/thumb/f/ff/",
1355  "$dir/thumb/f/",
1356  "$dir/0/00/",
1357  "$dir/0/09/",
1358  "$dir/0/",
1359  "$dir/5/5f",
1360  "$dir/5",
1361  "$dir/thumb/0/00/Video.ogv",
1362  "$dir/thumb/0/00",
1363  "$dir/thumb/0",
1364  "$dir/thumb/5/5f/LoremIpsum.djvu",
1365  "$dir/thumb/5/5f",
1366  "$dir/thumb/5",
1367  "$dir/thumb",
1368  "$dir/4/41",
1369  "$dir/4",
1370  "$dir/math/f/a/5",
1371  "$dir/math/f/a",
1372  "$dir/math/f",
1373  "$dir/math",
1374  "$dir/lockdir",
1375  "$dir",
1376  ]
1377  );
1378  }
1379 
1384  private static function deleteFiles( $files ) {
1385  foreach ( $files as $pattern ) {
1386  foreach ( glob( $pattern ) as $file ) {
1387  if ( file_exists( $file ) ) {
1388  unlink( $file );
1389  }
1390  }
1391  }
1392  }
1393 
1398  private static function deleteDirs( $dirs ) {
1399  foreach ( $dirs as $dir ) {
1400  if ( is_dir( $dir ) ) {
1401  rmdir( $dir );
1402  }
1403  }
1404  }
1405 
1410  protected function showTesting( $desc ) {
1411  print "Running test $desc... ";
1412  }
1413 
1422  protected function showSuccess( ParserTestResult $testResult ) {
1423  if ( $this->showProgress ) {
1424  print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1425  }
1426 
1427  return true;
1428  }
1429 
1439  protected function showFailure( ParserTestResult $testResult ) {
1440  if ( $this->showFailure ) {
1441  if ( !$this->showProgress ) {
1442  # In quiet mode we didn't show the 'Testing' message before the
1443  # test, in case it succeeded. Show it now:
1444  $this->showTesting( $testResult->description );
1445  }
1446 
1447  print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1448 
1449  if ( $this->showOutput ) {
1450  print "--- Expected ---\n{$testResult->expected}\n";
1451  print "--- Actual ---\n{$testResult->actual}\n";
1452  }
1453 
1454  if ( $this->showDiffs ) {
1455  print $this->quickDiff( $testResult->expected, $testResult->actual );
1456  if ( !$this->wellFormed( $testResult->actual ) ) {
1457  print "XML error: $this->mXmlError\n";
1458  }
1459  }
1460  }
1461 
1462  return false;
1463  }
1464 
1470  protected function showSkipped() {
1471  if ( $this->showProgress ) {
1472  print $this->term->color( '1;33' ) . 'SKIPPED' . $this->term->reset() . "\n";
1473  }
1474 
1475  return true;
1476  }
1477 
1488  protected function quickDiff( $input, $output,
1489  $inFileTail = 'expected', $outFileTail = 'actual'
1490  ) {
1491  if ( $this->markWhitespace ) {
1492  $pairs = [
1493  "\n" => '¶',
1494  ' ' => '·',
1495  "\t" => '→'
1496  ];
1497  $input = strtr( $input, $pairs );
1498  $output = strtr( $output, $pairs );
1499  }
1500 
1501  # Windows, or at least the fc utility, is retarded
1502  $slash = wfIsWindows() ? '\\' : '/';
1503  $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1504 
1505  $infile = "$prefix-$inFileTail";
1506  $this->dumpToFile( $input, $infile );
1507 
1508  $outfile = "$prefix-$outFileTail";
1509  $this->dumpToFile( $output, $outfile );
1510 
1511  $shellInfile = wfEscapeShellArg( $infile );
1512  $shellOutfile = wfEscapeShellArg( $outfile );
1513 
1514  global $wgDiff3;
1515  // we assume that people with diff3 also have usual diff
1516  if ( $this->useDwdiff ) {
1517  $shellCommand = 'dwdiff -Pc';
1518  } else {
1519  $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1520  }
1521 
1522  $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1523 
1524  unlink( $infile );
1525  unlink( $outfile );
1526 
1527  if ( $this->useDwdiff ) {
1528  return $diff;
1529  } else {
1530  return $this->colorDiff( $diff );
1531  }
1532  }
1533 
1540  private function dumpToFile( $data, $filename ) {
1541  $file = fopen( $filename, "wt" );
1542  fwrite( $file, $data . "\n" );
1543  fclose( $file );
1544  }
1545 
1553  protected function colorDiff( $text ) {
1554  return preg_replace(
1555  [ '/^(-.*)$/m', '/^(\+.*)$/m' ],
1556  [ $this->term->color( 34 ) . '$1' . $this->term->reset(),
1557  $this->term->color( 31 ) . '$1' . $this->term->reset() ],
1558  $text );
1559  }
1560 
1566  public function showRunFile( $path ) {
1567  print $this->term->color( 1 ) .
1568  "Reading tests from \"$path\"..." .
1569  $this->term->reset() .
1570  "\n";
1571  }
1572 
1582  public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1584 
1585  $oldCapitalLinks = $wgCapitalLinks;
1586  $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1587 
1588  $text = self::chomp( $text );
1589  $name = self::chomp( $name );
1590 
1592 
1593  if ( is_null( $title ) ) {
1594  throw new MWException( "invalid title '$name' at line $line\n" );
1595  }
1596 
1598  $page->loadPageData( 'fromdbmaster' );
1599 
1600  if ( $page->exists() ) {
1601  if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1602  return;
1603  } else {
1604  throw new MWException( "duplicate article '$name' at line $line\n" );
1605  }
1606  }
1607 
1608  $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1609 
1610  $wgCapitalLinks = $oldCapitalLinks;
1611  }
1612 
1621  public function requireHook( $name ) {
1622  global $wgParser;
1623 
1624  $wgParser->firstCallInit(); // make sure hooks are loaded.
1625 
1626  if ( isset( $wgParser->mTagHooks[$name] ) ) {
1627  $this->hooks[$name] = $wgParser->mTagHooks[$name];
1628  } else {
1629  echo " This test suite requires the '$name' hook extension, skipping.\n";
1630  return false;
1631  }
1632 
1633  return true;
1634  }
1635 
1644  public function requireFunctionHook( $name ) {
1645  global $wgParser;
1646 
1647  $wgParser->firstCallInit(); // make sure hooks are loaded.
1648 
1649  if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1650  $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1651  } else {
1652  echo " This test suite requires the '$name' function hook extension, skipping.\n";
1653  return false;
1654  }
1655 
1656  return true;
1657  }
1658 
1667  public function requireTransparentHook( $name ) {
1668  global $wgParser;
1669 
1670  $wgParser->firstCallInit(); // make sure hooks are loaded.
1671 
1672  if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1673  $this->transparentHooks[$name] = $wgParser->mTransparentTagHooks[$name];
1674  } else {
1675  echo " This test suite requires the '$name' transparent hook extension, skipping.\n";
1676  return false;
1677  }
1678 
1679  return true;
1680  }
1681 
1682  private function wellFormed( $text ) {
1683  $html =
1685  '<html>' .
1686  $text .
1687  '</html>';
1688 
1689  $parser = xml_parser_create( "UTF-8" );
1690 
1691  # case folding violates XML standard, turn it off
1692  xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1693 
1694  if ( !xml_parse( $parser, $html, true ) ) {
1695  $err = xml_error_string( xml_get_error_code( $parser ) );
1696  $position = xml_get_current_byte_index( $parser );
1697  $fragment = $this->extractFragment( $html, $position );
1698  $this->mXmlError = "$err at byte $position:\n$fragment";
1699  xml_parser_free( $parser );
1700 
1701  return false;
1702  }
1703 
1704  xml_parser_free( $parser );
1705 
1706  return true;
1707  }
1708 
1709  private function extractFragment( $text, $position ) {
1710  $start = max( 0, $position - 10 );
1711  $before = $position - $start;
1712  $fragment = '...' .
1713  $this->term->color( 34 ) .
1714  substr( $text, $start, $before ) .
1715  $this->term->color( 0 ) .
1716  $this->term->color( 31 ) .
1717  $this->term->color( 1 ) .
1718  substr( $text, $position, 1 ) .
1719  $this->term->color( 0 ) .
1720  $this->term->color( 34 ) .
1721  substr( $text, $position + 1, 9 ) .
1722  $this->term->color( 0 ) .
1723  '...';
1724  $display = str_replace( "\n", ' ', $fragment );
1725  $caret = ' ' .
1726  str_repeat( ' ', $before ) .
1727  $this->term->color( 31 ) .
1728  '^' .
1729  $this->term->color( 0 );
1730 
1731  return "$display\n$caret";
1732  }
1733 
1734  static function getFakeTimestamp( &$parser, &$ts ) {
1735  $ts = 123; // parsed as '1970-01-01T00:02:03Z'
1736  return true;
1737  }
1738 }
1739 
1741  protected $doc, $xpath, $invalid;
1742 
1743  public static function normalize( $text, $funcs ) {
1744  $norm = new self( $text );
1745  if ( $norm->invalid ) {
1746  return $text;
1747  }
1748  foreach ( $funcs as $func ) {
1749  $norm->$func();
1750  }
1751  return $norm->serialize();
1752  }
1753 
1754  protected function __construct( $text ) {
1755  $this->doc = new DOMDocument( '1.0', 'utf-8' );
1756 
1757  // Note: parsing a supposedly XHTML document with an XML parser is not
1758  // guaranteed to give accurate results. For example, it may introduce
1759  // differences in the number of line breaks in <pre> tags.
1760 
1761  MediaWiki\suppressWarnings();
1762  if ( !$this->doc->loadXML( '<html><body>' . $text . '</body></html>' ) ) {
1763  $this->invalid = true;
1764  }
1765  MediaWiki\restoreWarnings();
1766  $this->xpath = new DOMXPath( $this->doc );
1767  $this->body = $this->xpath->query( '//body' )->item( 0 );
1768  }
1769 
1770  protected function removeTbody() {
1771  foreach ( $this->xpath->query( '//tbody' ) as $tbody ) {
1772  while ( $tbody->firstChild ) {
1773  $child = $tbody->firstChild;
1774  $tbody->removeChild( $child );
1775  $tbody->parentNode->insertBefore( $child, $tbody );
1776  }
1777  $tbody->parentNode->removeChild( $tbody );
1778  }
1779  }
1780 
1792  protected function trimWhitespace() {
1793  foreach ( $this->xpath->query( '//text()' ) as $child ) {
1794  if ( strtolower( $child->parentNode->nodeName ) === 'pre' ) {
1795  // Just trim one line break from the start and end
1796  if ( substr_compare( $child->data, "\n", 0 ) === 0 ) {
1797  $child->data = substr( $child->data, 1 );
1798  }
1799  if ( substr_compare( $child->data, "\n", -1 ) === 0 ) {
1800  $child->data = substr( $child->data, 0, -1 );
1801  }
1802  } else {
1803  // Trim all whitespace
1804  $child->data = trim( $child->data );
1805  }
1806  if ( $child->data === '' ) {
1807  $child->parentNode->removeChild( $child );
1808  }
1809  }
1810  }
1811 
1815  protected function serialize() {
1816  return strtr( $this->doc->saveXML( $this->body ),
1817  [ '<body>' => '', '</body>' => '' ] );
1818  }
1819 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:101
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to copy
Definition: LICENSE.txt:10
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
static getLocalisationCache()
Get the LocalisationCache instance.
Definition: Language.php:402
static getMainWANInstance()
Get the main WAN cache object.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1816
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
static clearPendingUpdates()
Clear all pending updates without performing them.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:776
Database error base class.
static getFakeTimestamp(&$parser, &$ts)
$wgScript
The URL path to index.php.
Group all the pieces relevant to the context of a request into one instance.
$context
Definition: load.php:43
if(count($args)==0) $dir
__construct($options=[])
Sets terminal colorization and diff/quick modes depending on OS and command-line options (–color and ...
Definition: parserTest.inc:99
runTest($desc, $input, $result, $opts, $config)
Run a given wikitext input through a freshly-constructed wiki parser, and compare the output against ...
Definition: parserTest.inc:630
const NS_MAIN
Definition: Defines.php:69
static addArticle($name, $text, $line= 'unknown', $ignoreDuplicate= '')
Insert a temporary test article.
listTables()
List of temporary tables to create, without prefix.
$IP
Definition: WebStart.php:58
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfMkdirParents($dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest to get request data $messageMemc
Definition: globals.txt:25
setupGlobals($opts= '', $config= '')
Set up the global variables for a consistent environment for each test.
Definition: parserTest.inc:861
$wgParser
Definition: Setup.php:816
setTOCEnabled($flag)
teardownUploadDir($dir)
Remove the dummy uploads directory.
$wgThumbnailScriptPath
Give a path here to use thumb.php for thumbnail generation on client request, instead of generating t...
if(!isset($args[0])) $lang
getFuzzInput($filenames)
Get an input dictionary from a set of parser test files.
Definition: parserTest.inc:472
setupUploadDir()
Create a dummy uploads directory which will contain a couple of files in order to pass existence test...
static destroySingleton()
Destroy the singleton instance, so that a new one will be created next time singleton() is called...
Definition: RepoGroup.php:73
$wgLocalFileRepo
File repository structures.
CloneDatabase $dbClone
Database clone helper.
Definition: parserTest.inc:66
$value
getParser($preprocessor=null)
Get a Parser object.
Definition: parserTest.inc:594
static normalize($text, $funcs)
$files
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
$wgNamespaceAliases
Namespace aliases.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2588
$wgHooks['ArticleShow'][]
Definition: hooks.txt:110
const MEDIATYPE_VIDEO
Definition: Defines.php:122
static hackDocType()
Hack up a private DOCTYPE with HTML's standard entity declarations.
Definition: Sanitizer.php:1842
static createNew($name, $params=[])
Add a user to the database, return the user object.
Definition: User.php:4039
wfShellExec($cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
requireFunctionHook($name)
Steal a callback function from the primary parser, save it for application to our scary parser...
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:256
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static chomp($s)
Remove last character if it is a newline utility.
Definition: parserTest.inc:387
static destroySingleton()
Destroy the singleton instance.
$wgArticlePath
Definition: img_auth.php:45
wfIsWindows()
Check if the operating system is Windows.
static posix_isatty($fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
static newFromUser($user)
Get a ParserOptions object from a given user.
wfLocalFile($title)
Get an object referring to a locally registered file.
magic word & $parser
Definition: hooks.txt:2372
which are not or by specifying more than one search term(only pages containing all of the search terms will appear in the result).</td >< td >
wfGetMessageCacheStorage()
Get the cache object used by the message cache.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
Definition: hooks.txt:981
parseOptions($instring)
Definition: parserTest.inc:767
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfGetParserCacheStorage()
Get the cache object used by the parser cache.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition: design.txt:56
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1814
static deleteDirs($dirs)
Delete the specified directories, if they exist.
showSuccess(ParserTestResult $testResult)
Print a happy success message.
static BagOStuff[] $instances
Map of (id => BagOStuff)
Definition: ObjectCache.php:83
static destroySingleton()
Destroy the current singleton instance.
Definition: MWTidy.php:160
$wgExtraInterlanguageLinkPrefixes
List of additional interwiki prefixes that should be treated as interlanguage links (i...
static tearDownInterwikis()
Remove the hardcoded interwiki lookup table.
Definition: parserTest.inc:352
$wgStylePath
The URL path of the skins directory.
static register($name, $callback)
Attach an event handler to a given hook.
Definition: Hooks.php:49
wfGetLB($wiki=false)
Get a load balancer object.
$normalizationFunctions
Definition: parserTest.inc:92
$wgParserCacheType
The cache type for storing article HTML.
wfTempDir()
Tries to get the system directory for temporary files.
static getMain()
Static methods.
static singleton()
Get an instance of this class.
Definition: LinkCache.php:65
static clear($name)
Clears hooks registered via Hooks::register().
Definition: Hooks.php:66
$GLOBALS['IP']
$wgCapitalLinks
Set this to false to avoid forcing the first letter of links to capitals.
quickDiff($input, $output, $inFileTail= 'expected', $outFileTail= 'actual')
Run given strings through a diff and return the (colorized) output.
trimWhitespace()
The point of this function is to produce a normalized DOM in which Tidy's output matches the output o...
setupRecorder($options)
Definition: parserTest.inc:369
DjVuSupport $djVuSupport
Definition: parserTest.inc:71
$wgLocalInterwikis
Array for multiple $wgLocalInterwiki values, in case there are several interwiki prefixes that point ...
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1020
requireHook($name)
Steal a callback function from the primary parser, save it for application to our scary parser...
$wgMessageCacheType
The cache type for storing the contents of the MediaWiki namespace.
controlled by $wgMainCacheType * $parserMemc
Definition: memcached.txt:78
showTesting($desc)
"Running test $desc..."
MediaWiki exception.
Definition: MWException.php:26
static clearCache()
Clear the self::$mObjects variable For use in parser tests.
Definition: MagicWord.php:319
teardownGlobals()
Restore default values and perform any necessary clean-up after each test runs.
static destroySingletons()
Destroy the singleton instances.
serialize()
Serialize the XML DOM for comparison purposes.
$wgResourceBasePath
The default 'remoteBasePath' value for instances of ResourceLoaderFileModule.
static resetMain()
Resets singleton returned by getMain().
CACHE_MEMCACHED $wgMainCacheType
Definition: memcached.txt:63
dumpToFile($data, $filename)
Write the given string to a file, adding a final newline.
Class to implement stub globals, which are globals that delay loading the their associated module cod...
Definition: StubObject.php:44
static setupInterwikis()
Insert hardcoded interwiki in the lookup table.
Definition: parserTest.inc:284
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:312
A BagOStuff object with no objects in it.
Using a hook running we can avoid having all this option specific stuff in our mainline code Using hooks
Definition: hooks.txt:73
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
isSuccess()
Whether the test passed.
extractFragment($text, $position)
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:981
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
const NS_FILE
Definition: Defines.php:75
A colour-less terminal.
Definition: MWTerm.php:64
setupDatabase()
Set up a temporary set of wiki tables to work with for the tests.
const NS_FILE_TALK
Definition: Defines.php:76
showRunFile($path)
Show "Reading tests from ...".
Initialize and detect the DjVu files support.
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2044
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
showFailure(ParserTestResult $testResult)
Print a failure message and provide some explanatory output about what went wrong if so configured...
const NS_MEDIAWIKI
Definition: Defines.php:77
static formatComment($comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition: Linker.php:1181
getMemoryBreakdown()
Get a memory usage breakdown.
Definition: parserTest.inc:495
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:2755
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
in the sidebar</td >< td > font color
wellFormed($text)
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1020
Initialize and detect the tidy support.
$wgDiff3
Path to the GNU diff3 utility.
Simple store for keeping values in an associative array for the current process.
$wgExtraNamespaces
Additional namespaces.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
$wgNamespaceProtection
Set the minimum permissions required to edit pages in each namespace.
Terminal that supports ANSI escape sequences.
Definition: MWTerm.php:31
ITestRecorder $recorder
Definition: parserTest.inc:81
static getOptionValue($key, $opts, $default)
Use a regex to find out the value of an option.
Definition: parserTest.inc:757
showTestResult(ParserTestResult $testResult)
Refactored in 1.22 to use ParserTestResult.
Definition: parserTest.inc:740
const EDIT_NEW
Definition: Defines.php:179
$wgScriptPath
The path we should point to.
colorDiff($text)
Colorize unified diff output if set for ANSI color output.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1020
wfGetMainCache()
Get the main cache object.
$wgExtensionAssetsPath
The URL path of the extensions directory.
$line
Definition: cdb.php:59
$wgDBprefix
Table name prefix.
DatabaseBase $db
Our connection to the database.
Definition: parserTest.inc:60
$wgStyleDirectory
Filesystem stylesheets directory.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition: hooks.txt:776
wfEscapeShellArg()
Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell...
const MEDIATYPE_DRAWING
Definition: Defines.php:117
const DB_MASTER
Definition: Defines.php:47
$wgLockManagers
Array of configuration arrays for each lock manager.
$wgOut
Definition: Setup.php:811
serialize()
Definition: ApiMessage.php:94
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest to get request data $wgMemc
Definition: globals.txt:25
runTestsFromFiles($filenames)
Run a series of tests listed in the given text files.
Definition: parserTest.inc:542
const CACHE_NONE
Definition: Defines.php:102
static decode($value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:187
static getVersion($flags= '', $lang=null)
Return a string of the MediaWiki version with Git revision if available.
Class for a file system (FS) based file backend.
static factory($code)
Get a cached or new language object for a given language code.
Definition: Language.php:179
Represent the result of a parser test.
showSkipped()
Print a skipped message.
requireTransparentHook($name)
Steal a callback function from the primary parser, save it for application to our scary parser...
fuzzTest($filenames)
Run a fuzz test series Draw input from a set of test files.
Definition: parserTest.inc:400
static resetTitleServices()
Reset the Title-related services that need resetting for each test.
Definition: parserTest.inc:360
static getCanonicalNamespaces($rebuild=false)
Returns array of all defined namespaces with their canonical (English) names.
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:663
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:503
TidySupport $tidySupport
Definition: parserTest.inc:76
runTests($tests)
Definition: parserTest.inc:571
static singleton()
Get the signleton instance of this class.
cleanupOption($opt)
Definition: parserTest.inc:839
const CACHE_DB
Definition: Defines.php:103
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2376
static deleteFiles($files)
Delete the specified files, if they exist.
$wgUser
Definition: Setup.php:801
$matches
const MEDIATYPE_AUDIO
Definition: Defines.php:119
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310
const MEDIATYPE_BITMAP
Definition: Defines.php:115