MediaWiki  master
ParserTestRunner.php
Go to the documentation of this file.
1 <?php
33 
38 
45  private static $coreTestFiles = [
46  'parserTests.txt',
47  'extraParserTests.txt',
48  ];
49 
53  private $useTemporaryTables = true;
54 
58  private $setupDone = [
59  'staticSetup' => false,
60  'perTestSetup' => false,
61  'setupDatabase' => false,
62  'setDatabase' => false,
63  'setupUploads' => false,
64  ];
65 
70  private $db;
71 
76  private $dbClone;
77 
81  private $tidyDriver = null;
82 
86  private $recorder;
87 
93  private $uploadDir = null;
94 
100 
105  private $regex;
106 
113 
118  private $runDisabled;
119 
125 
130  private $keepUploads;
131 
136  public function __construct( TestRecorder $recorder, $options = [] ) {
137  $this->recorder = $recorder;
138 
139  if ( isset( $options['norm'] ) ) {
140  foreach ( $options['norm'] as $func ) {
141  if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
142  $this->normalizationFunctions[] = $func;
143  } else {
144  $this->recorder->warning(
145  "Warning: unknown normalization option \"$func\"\n" );
146  }
147  }
148  }
149 
150  if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
151  $this->regex = $options['regex'];
152  } else {
153  # Matches anything
154  $this->regex = '//';
155  }
156 
157  $this->keepUploads = !empty( $options['keep-uploads'] );
158 
159  $this->fileBackendName = $options['file-backend'] ?? false;
160 
161  $this->runDisabled = !empty( $options['run-disabled'] );
162 
163  $this->disableSaveParse = !empty( $options['disable-save-parse'] );
164 
165  if ( isset( $options['upload-dir'] ) ) {
166  $this->uploadDir = $options['upload-dir'];
167  }
168  }
169 
175  public static function getParserTestFiles() {
176  global $wgParserTestFiles;
177 
178  // Add core test files
179  $files = array_map( function ( $item ) {
180  return __DIR__ . "/$item";
181  }, self::$coreTestFiles );
182 
183  // Plus legacy global files
184  $files = array_merge( $files, $wgParserTestFiles );
185 
186  // Auto-discover extension parser tests
187  $registry = ExtensionRegistry::getInstance();
188  foreach ( $registry->getAllThings() as $info ) {
189  $dir = dirname( $info['path'] ) . '/tests/parser';
190  if ( !file_exists( $dir ) ) {
191  continue;
192  }
193  $counter = 1;
194  $dirIterator = new RecursiveIteratorIterator(
195  new RecursiveDirectoryIterator( $dir )
196  );
197  foreach ( $dirIterator as $fileInfo ) {
199  if ( substr( $fileInfo->getFilename(), -4 ) === '.txt' ) {
200  $name = $info['name'] . $counter;
201  while ( isset( $files[$name] ) ) {
202  $name = $info['name'] . '_' . $counter++;
203  }
204  $files[$name] = $fileInfo->getPathname();
205  }
206  }
207  }
208 
209  return array_unique( $files );
210  }
211 
212  public function getRecorder() {
213  return $this->recorder;
214  }
215 
235  public function staticSetup( $nextTeardown = null ) {
236  // A note on coding style:
237 
238  // The general idea here is to keep setup code together with
239  // corresponding teardown code, in a fine-grained manner. We have two
240  // arrays: $setup and $teardown. The code snippets in the $setup array
241  // are executed at the end of the method, before it returns, and the
242  // code snippets in the $teardown array are executed in reverse order
243  // when the Wikimedia\ScopedCallback object is consumed.
244 
245  // Because it is a common operation to save, set and restore global
246  // variables, we have an additional convention: when the array key of
247  // $setup is a string, the string is taken to be the name of the global
248  // variable, and the element value is taken to be the desired new value.
249 
250  // It's acceptable to just do the setup immediately, instead of adding
251  // a closure to $setup, except when the setup action depends on global
252  // variable initialisation being done first. In this case, you have to
253  // append a closure to $setup after the global variable is appended.
254 
255  // When you add to setup functions in this class, please keep associated
256  // setup and teardown actions together in the source code, and please
257  // add comments explaining why the setup action is necessary.
258 
259  $setup = [];
260  $teardown = [];
261 
262  $teardown[] = $this->markSetupDone( 'staticSetup' );
263 
264  // Some settings which influence HTML output
265  $setup['wgSitename'] = 'MediaWiki';
266  $setup['wgServer'] = 'http://example.org';
267  $setup['wgServerName'] = 'example.org';
268  $setup['wgScriptPath'] = '';
269  $setup['wgScript'] = '/index.php';
270  $setup['wgResourceBasePath'] = '';
271  $setup['wgStylePath'] = '/skins';
272  $setup['wgExtensionAssetsPath'] = '/extensions';
273  $setup['wgArticlePath'] = '/wiki/$1';
274  $setup['wgActionPaths'] = [];
275  $setup['wgVariantArticlePath'] = false;
276  $setup['wgUploadNavigationUrl'] = false;
277  $setup['wgCapitalLinks'] = true;
278  $setup['wgNoFollowLinks'] = true;
279  $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
280  $setup['wgExternalLinkTarget'] = false;
281  $setup['wgLocaltimezone'] = 'UTC';
282  $setup['wgHtml5'] = true;
283  $setup['wgDisableLangConversion'] = false;
284  $setup['wgDisableTitleConversion'] = false;
285 
286  // "extra language links"
287  // see https://gerrit.wikimedia.org/r/111390
288  $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
289 
290  // All FileRepo changes should be done here by injecting services,
291  // there should be no need to change global variables.
292  MediaWikiServices::getInstance()->disableService( 'RepoGroup' );
293  MediaWikiServices::getInstance()->redefineService( 'RepoGroup',
294  function () {
295  return $this->createRepoGroup();
296  }
297  );
298  $teardown[] = function () {
299  MediaWikiServices::getInstance()->resetServiceForTesting( 'RepoGroup' );
300  };
301 
302  // Set up null lock managers
303  $setup['wgLockManagers'] = [ [
304  'name' => 'fsLockManager',
305  'class' => NullLockManager::class,
306  ], [
307  'name' => 'nullLockManager',
308  'class' => NullLockManager::class,
309  ] ];
310  $reset = function () {
312  };
313  $setup[] = $reset;
314  $teardown[] = $reset;
315 
316  // This allows article insertion into the prefixed DB
317  $setup['wgDefaultExternalStore'] = false;
318 
319  // This might slightly reduce memory usage
320  $setup['wgAdaptiveMessageCache'] = true;
321 
322  // This is essential and overrides disabling of database messages in TestSetup
323  $setup['wgUseDatabaseMessages'] = true;
324  $reset = function () {
326  };
327  $setup[] = $reset;
328  $teardown[] = $reset;
329 
330  // It's not necessary to actually convert any files
331  $setup['wgSVGConverter'] = 'null';
332  $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
333 
334  // Fake constant timestamp
335  Hooks::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
336  $ts = $this->getFakeTimestamp();
337  return true;
338  } );
339  $teardown[] = function () {
340  Hooks::clear( 'ParserGetVariableValueTs' );
341  };
342 
343  $this->appendNamespaceSetup( $setup, $teardown );
344 
345  // Set up interwikis and append teardown function
346  $teardown[] = $this->setupInterwikis();
347 
348  // This affects title normalization in links. It invalidates
349  // MediaWikiTitleCodec objects.
350  $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
351  $reset = function () {
352  $this->resetTitleServices();
353  };
354  $setup[] = $reset;
355  $teardown[] = $reset;
356 
357  // Set up a mock MediaHandlerFactory
358  MediaWikiServices::getInstance()->disableService( 'MediaHandlerFactory' );
359  MediaWikiServices::getInstance()->redefineService(
360  'MediaHandlerFactory',
361  function ( MediaWikiServices $services ) {
362  $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
363  return new MediaHandlerFactory( $handlers );
364  }
365  );
366  $teardown[] = function () {
367  MediaWikiServices::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
368  };
369 
370  // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
371  // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
372  // This works around it for now...
373  global $wgObjectCaches;
374  $setup['wgObjectCaches'] = [ CACHE_DB => $wgObjectCaches['hash'] ] + $wgObjectCaches;
375  if ( isset( ObjectCache::$instances[CACHE_DB] ) ) {
376  $savedCache = ObjectCache::$instances[CACHE_DB];
378  $teardown[] = function () use ( $savedCache ) {
379  ObjectCache::$instances[CACHE_DB] = $savedCache;
380  };
381  }
382 
383  $teardown[] = $this->executeSetupSnippets( $setup );
384 
385  // Schedule teardown snippets in reverse order
386  return $this->createTeardownObject( $teardown, $nextTeardown );
387  }
388 
389  private function appendNamespaceSetup( &$setup, &$teardown ) {
390  // Add a namespace shadowing a interwiki link, to test
391  // proper precedence when resolving links. (T53680)
392  $setup['wgExtraNamespaces'] = [
393  100 => 'MemoryAlpha',
394  101 => 'MemoryAlpha_talk'
395  ];
396  // Changing wgExtraNamespaces invalidates caches in NamespaceInfo and any live Language
397  // object, both on setup and teardown
398  $reset = function () {
399  MediaWikiServices::getInstance()->resetServiceForTesting( 'NamespaceInfo' );
400  MediaWikiServices::getInstance()->getContentLanguage()->resetNamespaces();
401  };
402  $setup[] = $reset;
403  $teardown[] = $reset;
404  }
405 
410  protected function createRepoGroup() {
411  if ( $this->uploadDir ) {
412  if ( $this->fileBackendName ) {
413  throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
414  }
415  $backend = new FSFileBackend( [
416  'name' => 'local-backend',
417  'wikiId' => wfWikiID(),
418  'basePath' => $this->uploadDir,
419  'tmpDirectory' => wfTempDir()
420  ] );
421  } elseif ( $this->fileBackendName ) {
422  global $wgFileBackends;
424  $useConfig = false;
425  foreach ( $wgFileBackends as $conf ) {
426  if ( $conf['name'] === $name ) {
427  $useConfig = $conf;
428  }
429  }
430  if ( $useConfig === false ) {
431  throw new MWException( "Unable to find file backend \"$name\"" );
432  }
433  $useConfig['name'] = 'local-backend'; // swap name
434  unset( $useConfig['lockManager'] );
435  unset( $useConfig['fileJournal'] );
436  $class = $useConfig['class'];
437  $backend = new $class( $useConfig );
438  } else {
439  # Replace with a mock. We do not care about generating real
440  # files on the filesystem, just need to expose the file
441  # informations.
442  $backend = new MockFileBackend( [
443  'name' => 'local-backend',
444  'wikiId' => wfWikiID()
445  ] );
446  }
447 
448  return new RepoGroup(
449  [
450  'class' => MockLocalRepo::class,
451  'name' => 'local',
452  'url' => 'http://example.com/images',
453  'hashLevels' => 2,
454  'transformVia404' => false,
455  'backend' => $backend
456  ],
457  [],
458  MediaWikiServices::getInstance()->getMainWANObjectCache()
459  );
460  }
461 
475  protected function executeSetupSnippets( $setup ) {
476  $saved = [];
477  foreach ( $setup as $name => $value ) {
478  if ( is_int( $name ) ) {
479  $value();
480  } else {
481  $saved[$name] = $GLOBALS[$name] ?? null;
482  $GLOBALS[$name] = $value;
483  }
484  }
485  return function () use ( $saved ) {
486  $this->executeSetupSnippets( $saved );
487  };
488  }
489 
502  protected function createTeardownObject( $teardown, $nextTeardown = null ) {
503  return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
504  // Schedule teardown snippets in reverse order
505  $teardown = array_reverse( $teardown );
506 
507  $this->executeSetupSnippets( $teardown );
508  if ( $nextTeardown ) {
509  ScopedCallback::consume( $nextTeardown );
510  }
511  } );
512  }
513 
521  protected function markSetupDone( $funcName ) {
522  if ( $this->setupDone[$funcName] ) {
523  throw new MWException( "$funcName is already done" );
524  }
525  $this->setupDone[$funcName] = true;
526  return function () use ( $funcName ) {
527  $this->setupDone[$funcName] = false;
528  };
529  }
530 
537  protected function checkSetupDone( $funcName, $funcName2 = null ) {
538  if ( !$this->setupDone[$funcName]
539  && ( $funcName === null || !$this->setupDone[$funcName2] )
540  ) {
541  throw new MWException( "$funcName must be called before calling " .
542  wfGetCaller() );
543  }
544  }
545 
552  public function isSetupDone( $funcName ) {
553  return $this->setupDone[$funcName] ?? false;
554  }
555 
567  private function setupInterwikis() {
568  # Hack: insert a few Wikipedia in-project interwiki prefixes,
569  # for testing inter-language links
570  Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
571  static $testInterwikis = [
572  'local' => [
573  'iw_url' => 'http://doesnt.matter.org/$1',
574  'iw_api' => '',
575  'iw_wikiid' => '',
576  'iw_local' => 0 ],
577  'wikipedia' => [
578  'iw_url' => 'http://en.wikipedia.org/wiki/$1',
579  'iw_api' => '',
580  'iw_wikiid' => '',
581  'iw_local' => 0 ],
582  'meatball' => [
583  'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
584  'iw_api' => '',
585  'iw_wikiid' => '',
586  'iw_local' => 0 ],
587  'memoryalpha' => [
588  'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
589  'iw_api' => '',
590  'iw_wikiid' => '',
591  'iw_local' => 0 ],
592  'zh' => [
593  'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
594  'iw_api' => '',
595  'iw_wikiid' => '',
596  'iw_local' => 1 ],
597  'es' => [
598  'iw_url' => 'http://es.wikipedia.org/wiki/$1',
599  'iw_api' => '',
600  'iw_wikiid' => '',
601  'iw_local' => 1 ],
602  'fr' => [
603  'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
604  'iw_api' => '',
605  'iw_wikiid' => '',
606  'iw_local' => 1 ],
607  'ru' => [
608  'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
609  'iw_api' => '',
610  'iw_wikiid' => '',
611  'iw_local' => 1 ],
612  'mi' => [
613  'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
614  'iw_api' => '',
615  'iw_wikiid' => '',
616  'iw_local' => 1 ],
617  'mul' => [
618  'iw_url' => 'http://wikisource.org/wiki/$1',
619  'iw_api' => '',
620  'iw_wikiid' => '',
621  'iw_local' => 1 ],
622  ];
623  if ( array_key_exists( $prefix, $testInterwikis ) ) {
624  $iwData = $testInterwikis[$prefix];
625  }
626 
627  // We only want to rely on the above fixtures
628  return false;
629  } );// hooks::register
630 
631  // Reset the service in case any other tests already cached some prefixes.
632  MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
633 
634  return function () {
635  // Tear down
636  Hooks::clear( 'InterwikiLoadPrefix' );
637  MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
638  };
639  }
640 
647  private function resetTitleServices() {
648  $services = MediaWikiServices::getInstance();
649  $services->resetServiceForTesting( 'TitleFormatter' );
650  $services->resetServiceForTesting( 'TitleParser' );
651  $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
652  $services->resetServiceForTesting( 'LinkRenderer' );
653  $services->resetServiceForTesting( 'LinkRendererFactory' );
654  $services->resetServiceForTesting( 'NamespaceInfo' );
655  }
656 
662  public static function chomp( $s ) {
663  if ( substr( $s, -1 ) === "\n" ) {
664  return substr( $s, 0, -1 );
665  } else {
666  return $s;
667  }
668  }
669 
683  public function runTestsFromFiles( $filenames ) {
684  $ok = false;
685 
686  $teardownGuard = $this->staticSetup();
687  $teardownGuard = $this->setupDatabase( $teardownGuard );
688  $teardownGuard = $this->setupUploads( $teardownGuard );
689 
690  $this->recorder->start();
691  try {
692  $ok = true;
693 
694  foreach ( $filenames as $filename ) {
695  $testFileInfo = TestFileReader::read( $filename, [
696  'runDisabled' => $this->runDisabled,
697  'regex' => $this->regex ] );
698 
699  // Don't start the suite if there are no enabled tests in the file
700  if ( !$testFileInfo['tests'] ) {
701  continue;
702  }
703 
704  $this->recorder->startSuite( $filename );
705  $ok = $this->runTests( $testFileInfo ) && $ok;
706  $this->recorder->endSuite( $filename );
707  }
708 
709  $this->recorder->report();
710  } catch ( DBError $e ) {
711  $this->recorder->warning( $e->getMessage() );
712  }
713  $this->recorder->end();
714 
715  ScopedCallback::consume( $teardownGuard );
716 
717  return $ok;
718  }
719 
726  public function meetsRequirements( $requirements ) {
727  foreach ( $requirements as $requirement ) {
728  switch ( $requirement['type'] ) {
729  case 'hook':
730  $ok = $this->requireHook( $requirement['name'] );
731  break;
732  case 'functionHook':
733  $ok = $this->requireFunctionHook( $requirement['name'] );
734  break;
735  case 'transparentHook':
736  $ok = $this->requireTransparentHook( $requirement['name'] );
737  break;
738  }
739  if ( !$ok ) {
740  return false;
741  }
742  }
743  return true;
744  }
745 
753  public function runTests( $testFileInfo ) {
754  $ok = true;
755 
756  $this->checkSetupDone( 'staticSetup' );
757 
758  // Don't add articles from the file if there are no enabled tests from the file
759  if ( !$testFileInfo['tests'] ) {
760  return true;
761  }
762 
763  // If any requirements are not met, mark all tests from the file as skipped
764  if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
765  foreach ( $testFileInfo['tests'] as $test ) {
766  $this->recorder->startTest( $test );
767  $this->recorder->skipped( $test, 'required extension not enabled' );
768  }
769  return true;
770  }
771 
772  // Add articles
773  $this->addArticles( $testFileInfo['articles'] );
774 
775  // Run tests
776  foreach ( $testFileInfo['tests'] as $test ) {
777  $this->recorder->startTest( $test );
778  $result =
779  $this->runTest( $test );
780  if ( $result !== false ) {
781  $ok = $ok && $result->isSuccess();
782  $this->recorder->record( $test, $result );
783  }
784  }
785 
786  return $ok;
787  }
788 
795  function getParser( $preprocessor = null ) {
796  global $wgParserConf;
797 
798  $class = $wgParserConf['class'];
799  $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
800  if ( $preprocessor ) {
801  # Suppress deprecation warning for Preprocessor_DOM while testing
802  Wikimedia\suppressWarnings();
803  wfDeprecated( 'Preprocessor_DOM::__construct' );
804  Wikimedia\restoreWarnings();
805  $parser->getPreprocessor();
806  }
808 
809  return $parser;
810  }
811 
829  public function runTest( $test ) {
830  wfDebug( __METHOD__ . ": running {$test['desc']}" );
831  $opts = $this->parseOptions( $test['options'] );
832  $teardownGuard = $this->perTestSetup( $test );
833 
835  $user = $context->getUser();
837  $options->setTimestamp( $this->getFakeTimestamp() );
838 
839  if ( isset( $opts['tidy'] ) ) {
840  $options->setTidy( true );
841  }
842 
843  if ( isset( $opts['title'] ) ) {
844  $titleText = $opts['title'];
845  } else {
846  $titleText = 'Parser test';
847  }
848 
849  if ( isset( $opts['maxincludesize'] ) ) {
850  $options->setMaxIncludeSize( $opts['maxincludesize'] );
851  }
852  if ( isset( $opts['maxtemplatedepth'] ) ) {
853  $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
854  }
855 
856  $local = isset( $opts['local'] );
857  $preprocessor = $opts['preprocessor'] ?? null;
858  $parser = $this->getParser( $preprocessor );
859  $title = Title::newFromText( $titleText );
860 
861  if ( isset( $opts['styletag'] ) ) {
862  // For testing the behavior of <style> (including those deduplicated
863  // into <link> tags), add tag hooks to allow them to be generated.
864  $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
865  $marker = Parser::MARKER_PREFIX . '-style-' . md5( $content ) . Parser::MARKER_SUFFIX;
866  $parser->mStripState->addNoWiki( $marker, $content );
867  return Html::inlineStyle( $marker, 'all', $attributes );
868  } );
869  $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
870  return Html::element( 'link', $attributes );
871  } );
872  }
873 
874  if ( isset( $opts['pst'] ) ) {
875  $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
876  $output = $parser->getOutput();
877  } elseif ( isset( $opts['msg'] ) ) {
878  $out = $parser->transformMsg( $test['input'], $options, $title );
879  } elseif ( isset( $opts['section'] ) ) {
880  $section = $opts['section'];
881  $out = $parser->getSection( $test['input'], $section );
882  } elseif ( isset( $opts['replace'] ) ) {
883  $section = $opts['replace'][0];
884  $replace = $opts['replace'][1];
885  $out = $parser->replaceSection( $test['input'], $section, $replace );
886  } elseif ( isset( $opts['comment'] ) ) {
887  $out = Linker::formatComment( $test['input'], $title, $local );
888  } elseif ( isset( $opts['preload'] ) ) {
889  $out = $parser->getPreloadText( $test['input'], $title, $options );
890  } else {
891  $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
892  $out = $output->getText( [
893  'allowTOC' => !isset( $opts['notoc'] ),
894  'unwrap' => !isset( $opts['wrap'] ),
895  ] );
896  if ( isset( $opts['tidy'] ) ) {
897  $out = preg_replace( '/\s+$/', '', $out );
898  }
899 
900  if ( isset( $opts['showtitle'] ) ) {
901  if ( $output->getTitleText() ) {
902  $title = $output->getTitleText();
903  }
904 
905  $out = "$title\n$out";
906  }
907 
908  if ( isset( $opts['showindicators'] ) ) {
909  $indicators = '';
910  foreach ( $output->getIndicators() as $id => $content ) {
911  $indicators .= "$id=$content\n";
912  }
913  $out = $indicators . $out;
914  }
915 
916  if ( isset( $opts['ill'] ) ) {
917  $out = implode( ' ', $output->getLanguageLinks() );
918  } elseif ( isset( $opts['cat'] ) ) {
919  $out = '';
920  foreach ( $output->getCategories() as $name => $sortkey ) {
921  if ( $out !== '' ) {
922  $out .= "\n";
923  }
924  $out .= "cat=$name sort=$sortkey";
925  }
926  }
927  }
928 
929  if ( isset( $output ) && isset( $opts['showflags'] ) ) {
930  $actualFlags = array_keys( TestingAccessWrapper::newFromObject( $output )->mFlags );
931  sort( $actualFlags );
932  $out .= "\nflags=" . implode( ', ', $actualFlags );
933  }
934 
935  ScopedCallback::consume( $teardownGuard );
936 
937  $expected = $test['result'];
938  if ( count( $this->normalizationFunctions ) ) {
940  $test['expected'], $this->normalizationFunctions );
941  $out = ParserTestResultNormalizer::normalize( $out, $this->normalizationFunctions );
942  }
943 
944  $testResult = new ParserTestResult( $test, $expected, $out );
945  return $testResult;
946  }
947 
955  private static function getOptionValue( $key, $opts, $default ) {
956  $key = strtolower( $key );
957  return $opts[$key] ?? $default;
958  }
959 
967  private function parseOptions( $instring ) {
968  $opts = [];
969  // foo
970  // foo=bar
971  // foo="bar baz"
972  // foo=[[bar baz]]
973  // foo=bar,"baz quux"
974  // foo={...json...}
975  $defs = '(?(DEFINE)
976  (?<qstr> # Quoted string
977  "
978  (?:[^\\\\"] | \\\\.)*
979  "
980  )
981  (?<json>
982  \{ # Open bracket
983  (?:
984  [^"{}] | # Not a quoted string or object, or
985  (?&qstr) | # A quoted string, or
986  (?&json) # A json object (recursively)
987  )*
988  \} # Close bracket
989  )
990  (?<value>
991  (?:
992  (?&qstr) # Quoted val
993  |
994  \[\[
995  [^]]* # Link target
996  \]\]
997  |
998  [\w-]+ # Plain word
999  |
1000  (?&json) # JSON object
1001  )
1002  )
1003  )';
1004  $regex = '/' . $defs . '\b
1005  (?<k>[\w-]+) # Key
1006  \b
1007  (?:\s*
1008  = # First sub-value
1009  \s*
1010  (?<v>
1011  (?&value)
1012  (?:\s*
1013  , # Sub-vals 1..N
1014  \s*
1015  (?&value)
1016  )*
1017  )
1018  )?
1019  /x';
1020  $valueregex = '/' . $defs . '(?&value)/x';
1021 
1022  if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
1023  foreach ( $matches as $bits ) {
1024  $key = strtolower( $bits['k'] );
1025  if ( !isset( $bits['v'] ) ) {
1026  $opts[$key] = true;
1027  } else {
1028  preg_match_all( $valueregex, $bits['v'], $vmatches );
1029  $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1030  if ( count( $opts[$key] ) == 1 ) {
1031  $opts[$key] = $opts[$key][0];
1032  }
1033  }
1034  }
1035  }
1036  return $opts;
1037  }
1038 
1039  private function cleanupOption( $opt ) {
1040  if ( substr( $opt, 0, 1 ) == '"' ) {
1041  return stripcslashes( substr( $opt, 1, -1 ) );
1042  }
1043 
1044  if ( substr( $opt, 0, 2 ) == '[[' ) {
1045  return substr( $opt, 2, -2 );
1046  }
1047 
1048  if ( substr( $opt, 0, 1 ) == '{' ) {
1049  return FormatJson::decode( $opt, true );
1050  }
1051  return $opt;
1052  }
1053 
1063  public function perTestSetup( $test, $nextTeardown = null ) {
1064  $teardown = [];
1065 
1066  $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1067  $teardown[] = $this->markSetupDone( 'perTestSetup' );
1068 
1069  $opts = $this->parseOptions( $test['options'] );
1070  $config = $test['config'];
1071 
1072  // Find out values for some special options.
1073  $langCode =
1074  self::getOptionValue( 'language', $opts, 'en' );
1075  $variant =
1076  self::getOptionValue( 'variant', $opts, false );
1077  $maxtoclevel =
1078  self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1079  $linkHolderBatchSize =
1080  self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1081 
1082  // Default to fallback skin, but allow it to be overridden
1083  $skin = self::getOptionValue( 'skin', $opts, 'fallback' );
1084 
1085  $setup = [
1086  'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
1087  'wgLanguageCode' => $langCode,
1088  'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
1089  'wgNamespacesWithSubpages' => array_fill_keys(
1090  MediaWikiServices::getInstance()->getNamespaceInfo()->getValidNamespaces(),
1091  isset( $opts['subpage'] )
1092  ),
1093  'wgMaxTocLevel' => $maxtoclevel,
1094  'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1095  'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
1096  'wgDefaultLanguageVariant' => $variant,
1097  'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1098  // Set as a JSON object like:
1099  // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1100  'wgEnableMagicLinks' => self::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1101  + [ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1102  // Test with legacy encoding by default until HTML5 is very stable and default
1103  'wgFragmentMode' => [ 'legacy' ],
1104  ];
1105 
1106  $nonIncludable = self::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1107  if ( $nonIncludable !== false ) {
1108  $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1109  }
1110 
1111  if ( $config ) {
1112  $configLines = explode( "\n", $config );
1113 
1114  foreach ( $configLines as $line ) {
1115  list( $var, $value ) = explode( '=', $line, 2 );
1116  $setup[$var] = eval( "return $value;" );
1117  }
1118  }
1119 
1121  Hooks::run( 'ParserTestGlobals', [ &$setup ] );
1122 
1123  // Create tidy driver
1124  if ( isset( $opts['tidy'] ) ) {
1125  // Cache a driver instance
1126  if ( $this->tidyDriver === null ) {
1127  $this->tidyDriver = MWTidy::factory();
1128  }
1129  $tidy = $this->tidyDriver;
1130  } else {
1131  $tidy = false;
1132  }
1133 
1134  # Suppress warnings about running tests without tidy
1135  Wikimedia\suppressWarnings();
1136  wfDeprecated( 'disabling tidy' );
1137  wfDeprecated( 'MWTidy::setInstance' );
1138  Wikimedia\restoreWarnings();
1139 
1140  MWTidy::setInstance( $tidy );
1141  $teardown[] = function () {
1143  };
1144 
1145  // Set content language. This invalidates the magic word cache and title services
1146  $lang = Language::factory( $langCode );
1147  $lang->resetNamespaces();
1148  $setup['wgContLang'] = $lang;
1149  $setup[] = function () use ( $lang ) {
1150  MediaWikiServices::getInstance()->disableService( 'ContentLanguage' );
1151  MediaWikiServices::getInstance()->redefineService(
1152  'ContentLanguage',
1153  function () use ( $lang ) {
1154  return $lang;
1155  }
1156  );
1157  };
1158  $teardown[] = function () {
1159  MediaWikiServices::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1160  };
1161  $reset = function () {
1162  MediaWikiServices::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1163  $this->resetTitleServices();
1164  };
1165  $setup[] = $reset;
1166  $teardown[] = $reset;
1167 
1168  // Make a user object with the same language
1169  $user = new User;
1170  $user->setOption( 'language', $langCode );
1171  $setup['wgLang'] = $lang;
1172 
1173  // We (re)set $wgThumbLimits to a single-element array above.
1174  $user->setOption( 'thumbsize', 0 );
1175 
1176  $setup['wgUser'] = $user;
1177 
1178  // And put both user and language into the context
1180  $context->setUser( $user );
1181  $context->setLanguage( $lang );
1182  // And the skin!
1183  $oldSkin = $context->getSkin();
1184  $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
1185  $context->setSkin( $skinFactory->makeSkin( $skin ) );
1186  $context->setOutput( new OutputPage( $context ) );
1187  $setup['wgOut'] = $context->getOutput();
1188  $teardown[] = function () use ( $context, $oldSkin ) {
1189  // Clear language conversion tables
1190  $wrapper = TestingAccessWrapper::newFromObject(
1191  $context->getLanguage()->getConverter()
1192  );
1193  $wrapper->reloadTables();
1194  // Reset context to the restored globals
1195  $context->setUser( $GLOBALS['wgUser'] );
1196  $context->setLanguage( $GLOBALS['wgContLang'] );
1197  $context->setSkin( $oldSkin );
1198  $context->setOutput( $GLOBALS['wgOut'] );
1199  };
1200 
1201  $teardown[] = $this->executeSetupSnippets( $setup );
1202 
1203  return $this->createTeardownObject( $teardown, $nextTeardown );
1204  }
1205 
1211  private function listTables() {
1213 
1214  $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1215  'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1216  'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1217  'site_stats', 'ipblocks', 'image', 'oldimage',
1218  'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1219  'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1220  'archive', 'user_groups', 'page_props', 'category',
1221  'slots', 'content', 'slot_roles', 'content_models',
1222  'comment', 'revision_comment_temp',
1223  ];
1224 
1225  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
1226  // The new tables for actors are in use
1227  $tables[] = 'actor';
1228  $tables[] = 'revision_actor_temp';
1229  }
1230 
1231  if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1232  array_push( $tables, 'searchindex' );
1233  }
1234 
1235  // Allow extensions to add to the list of tables to duplicate;
1236  // may be necessary if they hook into page save or other code
1237  // which will require them while running tests.
1238  Hooks::run( 'ParserTestTables', [ &$tables ] );
1239 
1240  return $tables;
1241  }
1242 
1243  public function setDatabase( IDatabase $db ) {
1244  $this->db = $db;
1245  $this->setupDone['setDatabase'] = true;
1246  }
1247 
1265  public function setupDatabase( $nextTeardown = null ) {
1266  global $wgDBprefix;
1267 
1268  $this->db = wfGetDB( DB_MASTER );
1269  $dbType = $this->db->getType();
1270 
1271  if ( $dbType == 'oracle' ) {
1272  $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase::ORA_DB_PREFIX ];
1273  } else {
1274  $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1275  }
1276  if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1277  throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1278  }
1279 
1280  $teardown = [];
1281 
1282  $teardown[] = $this->markSetupDone( 'setupDatabase' );
1283 
1284  # CREATE TEMPORARY TABLE breaks if there is more than one server
1285  if ( MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1286  $this->useTemporaryTables = false;
1287  }
1288 
1289  $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1290  $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1291 
1292  $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1293  $this->dbClone->useTemporaryTables( $temporary );
1294  $this->dbClone->cloneTableStructure();
1295  CloneDatabase::changePrefix( $prefix );
1296 
1297  if ( $dbType == 'oracle' ) {
1298  $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1299  # Insert 0 user to prevent FK violations
1300 
1301  # Anonymous user
1302  $this->db->insert( 'user', [
1303  'user_id' => 0,
1304  'user_name' => 'Anonymous' ] );
1305  }
1306 
1307  $teardown[] = function () {
1308  $this->teardownDatabase();
1309  };
1310 
1311  // Wipe some DB query result caches on setup and teardown
1312  $reset = function () {
1313  MediaWikiServices::getInstance()->getLinkCache()->clear();
1314 
1315  // Clear the message cache
1316  MessageCache::singleton()->clear();
1317  };
1318  $reset();
1319  $teardown[] = $reset;
1320  return $this->createTeardownObject( $teardown, $nextTeardown );
1321  }
1322 
1331  public function setupUploads( $nextTeardown = null ) {
1332  $teardown = [];
1333 
1334  $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1335  $teardown[] = $this->markSetupDone( 'setupUploads' );
1336 
1337  // Create the files in the upload directory (or pretend to create them
1338  // in a MockFileBackend). Append teardown callback.
1339  $teardown[] = $this->setupUploadBackend();
1340 
1341  // Create a user
1342  $user = User::createNew( 'WikiSysop' );
1343 
1344  // Register the uploads in the database
1345 
1346  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1347  # note that the size/width/height/bits/etc of the file
1348  # are actually set by inspecting the file itself; the arguments
1349  # to recordUpload2 have no effect. That said, we try to make things
1350  # match up so it is less confusing to readers of the code & tests.
1351  $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1352  'size' => 7881,
1353  'width' => 1941,
1354  'height' => 220,
1355  'bits' => 8,
1356  'media_type' => MEDIATYPE_BITMAP,
1357  'mime' => 'image/jpeg',
1358  'metadata' => serialize( [] ),
1359  'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1360  'fileExists' => true
1361  ], $this->db->timestamp( '20010115123500' ), $user );
1362 
1363  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1364  # again, note that size/width/height below are ignored; see above.
1365  $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1366  'size' => 22589,
1367  'width' => 135,
1368  'height' => 135,
1369  'bits' => 8,
1370  'media_type' => MEDIATYPE_BITMAP,
1371  'mime' => 'image/png',
1372  'metadata' => serialize( [] ),
1373  'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1374  'fileExists' => true
1375  ], $this->db->timestamp( '20130225203040' ), $user );
1376 
1377  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1378  $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1379  'size' => 12345,
1380  'width' => 240,
1381  'height' => 180,
1382  'bits' => 0,
1383  'media_type' => MEDIATYPE_DRAWING,
1384  'mime' => 'image/svg+xml',
1385  'metadata' => serialize( [
1386  'version' => SvgHandler::SVG_METADATA_VERSION,
1387  'width' => 240,
1388  'height' => 180,
1389  'originalWidth' => '100%',
1390  'originalHeight' => '100%',
1391  'translations' => [
1394  ],
1395  ] ),
1396  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1397  'fileExists' => true
1398  ], $this->db->timestamp( '20010115123500' ), $user );
1399 
1400  # This image will be blacklisted in [[MediaWiki:Bad image list]]
1401  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1402  $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1403  'size' => 12345,
1404  'width' => 320,
1405  'height' => 240,
1406  'bits' => 24,
1407  'media_type' => MEDIATYPE_BITMAP,
1408  'mime' => 'image/jpeg',
1409  'metadata' => serialize( [] ),
1410  'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1411  'fileExists' => true
1412  ], $this->db->timestamp( '20010115123500' ), $user );
1413 
1414  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1415  $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1416  'size' => 12345,
1417  'width' => 320,
1418  'height' => 240,
1419  'bits' => 0,
1420  'media_type' => MEDIATYPE_VIDEO,
1421  'mime' => 'application/ogg',
1422  'metadata' => serialize( [] ),
1423  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1424  'fileExists' => true
1425  ], $this->db->timestamp( '20010115123500' ), $user );
1426 
1427  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1428  $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1429  'size' => 12345,
1430  'width' => 0,
1431  'height' => 0,
1432  'bits' => 0,
1433  'media_type' => MEDIATYPE_AUDIO,
1434  'mime' => 'application/ogg',
1435  'metadata' => serialize( [] ),
1436  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1437  'fileExists' => true
1438  ], $this->db->timestamp( '20010115123500' ), $user );
1439 
1440  # A DjVu file
1441  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1442  $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1443  'size' => 3249,
1444  'width' => 2480,
1445  'height' => 3508,
1446  'bits' => 0,
1447  'media_type' => MEDIATYPE_BITMAP,
1448  'mime' => 'image/vnd.djvu',
1449  'metadata' => '<?xml version="1.0" ?>
1450 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1451 <DjVuXML>
1452 <HEAD></HEAD>
1453 <BODY><OBJECT height="3508" width="2480">
1454 <PARAM name="DPI" value="300" />
1455 <PARAM name="GAMMA" value="2.2" />
1456 </OBJECT>
1457 <OBJECT height="3508" width="2480">
1458 <PARAM name="DPI" value="300" />
1459 <PARAM name="GAMMA" value="2.2" />
1460 </OBJECT>
1461 <OBJECT height="3508" width="2480">
1462 <PARAM name="DPI" value="300" />
1463 <PARAM name="GAMMA" value="2.2" />
1464 </OBJECT>
1465 <OBJECT height="3508" width="2480">
1466 <PARAM name="DPI" value="300" />
1467 <PARAM name="GAMMA" value="2.2" />
1468 </OBJECT>
1469 <OBJECT height="3508" width="2480">
1470 <PARAM name="DPI" value="300" />
1471 <PARAM name="GAMMA" value="2.2" />
1472 </OBJECT>
1473 </BODY>
1474 </DjVuXML>',
1475  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1476  'fileExists' => true
1477  ], $this->db->timestamp( '20010115123600' ), $user );
1478 
1479  return $this->createTeardownObject( $teardown, $nextTeardown );
1480  }
1481 
1488  private function teardownDatabase() {
1489  $this->checkSetupDone( 'setupDatabase' );
1490 
1491  $this->dbClone->destroy();
1492 
1493  if ( $this->useTemporaryTables ) {
1494  if ( $this->db->getType() == 'sqlite' ) {
1495  # Under SQLite the searchindex table is virtual and need
1496  # to be explicitly destroyed. See T31912
1497  # See also MediaWikiTestCase::destroyDB()
1498  wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1499  $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1500  }
1501  # Don't need to do anything
1502  return;
1503  }
1504 
1505  $tables = $this->listTables();
1506 
1507  foreach ( $tables as $table ) {
1508  if ( $this->db->getType() == 'oracle' ) {
1509  $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1510  } else {
1511  $this->db->query( "DROP TABLE `parsertest_$table`" );
1512  }
1513  }
1514 
1515  if ( $this->db->getType() == 'oracle' ) {
1516  $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1517  }
1518  }
1519 
1525  private function setupUploadBackend() {
1526  global $IP;
1527 
1528  $repo = RepoGroup::singleton()->getLocalRepo();
1529  $base = $repo->getZonePath( 'public' );
1530  $backend = $repo->getBackend();
1531  $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1532  $backend->store( [
1533  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1534  'dst' => "$base/3/3a/Foobar.jpg"
1535  ] );
1536  $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1537  $backend->store( [
1538  'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1539  'dst' => "$base/e/ea/Thumb.png"
1540  ] );
1541  $backend->prepare( [ 'dir' => "$base/0/09" ] );
1542  $backend->store( [
1543  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1544  'dst' => "$base/0/09/Bad.jpg"
1545  ] );
1546  $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1547  $backend->store( [
1548  'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1549  'dst' => "$base/5/5f/LoremIpsum.djvu"
1550  ] );
1551 
1552  // No helpful SVG file to copy, so make one ourselves
1553  $data = '<?xml version="1.0" encoding="utf-8"?>' .
1554  '<svg xmlns="http://www.w3.org/2000/svg"' .
1555  ' version="1.1" width="240" height="180"/>';
1556 
1557  $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1558  $backend->quickCreate( [
1559  'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1560  ] );
1561 
1562  return function () use ( $backend ) {
1563  if ( $backend instanceof MockFileBackend ) {
1564  // In memory backend, so dont bother cleaning them up.
1565  return;
1566  }
1567  $this->teardownUploadBackend();
1568  };
1569  }
1570 
1574  private function teardownUploadBackend() {
1575  if ( $this->keepUploads ) {
1576  return;
1577  }
1578 
1579  $repo = RepoGroup::singleton()->getLocalRepo();
1580  $public = $repo->getZonePath( 'public' );
1581 
1582  $this->deleteFiles(
1583  [
1584  "$public/3/3a/Foobar.jpg",
1585  "$public/e/ea/Thumb.png",
1586  "$public/0/09/Bad.jpg",
1587  "$public/5/5f/LoremIpsum.djvu",
1588  "$public/f/ff/Foobar.svg",
1589  "$public/0/00/Video.ogv",
1590  "$public/4/41/Audio.oga",
1591  ]
1592  );
1593  }
1594 
1599  private function deleteFiles( $files ) {
1600  // Delete the files
1601  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
1602  foreach ( $files as $file ) {
1603  $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1604  }
1605 
1606  // Delete the parent directories
1607  foreach ( $files as $file ) {
1608  $tmp = FileBackend::parentStoragePath( $file );
1609  while ( $tmp ) {
1610  if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1611  break;
1612  }
1613  $tmp = FileBackend::parentStoragePath( $tmp );
1614  }
1615  }
1616  }
1617 
1623  public function addArticles( $articles ) {
1624  $setup = [];
1625  $teardown = [];
1626 
1627  // Be sure ParserTestRunner::addArticle has correct language set,
1628  // so that system messages get into the right language cache
1629  if ( MediaWikiServices::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1630  $setup['wgLanguageCode'] = 'en';
1631  $lang = Language::factory( 'en' );
1632  $setup['wgContLang'] = $lang;
1633  $setup[] = function () use ( $lang ) {
1634  $services = MediaWikiServices::getInstance();
1635  $services->disableService( 'ContentLanguage' );
1636  $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1637  return $lang;
1638  } );
1639  };
1640  $teardown[] = function () {
1641  MediaWikiServices::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1642  };
1643  }
1644 
1645  // Add special namespaces, in case that hasn't been done by staticSetup() yet
1646  $this->appendNamespaceSetup( $setup, $teardown );
1647 
1648  // wgCapitalLinks obviously needs initialisation
1649  $setup['wgCapitalLinks'] = true;
1650 
1651  $teardown[] = $this->executeSetupSnippets( $setup );
1652 
1653  foreach ( $articles as $info ) {
1654  $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1655  }
1656 
1657  // Wipe WANObjectCache process cache, which is invalidated by article insertion
1658  // due to T144706
1659  ObjectCache::getMainWANInstance()->clearProcessCache();
1660 
1661  $this->executeSetupSnippets( $teardown );
1662  }
1663 
1673  private function addArticle( $name, $text, $file, $line ) {
1674  $text = self::chomp( $text );
1675  $name = self::chomp( $name );
1676 
1678  wfDebug( __METHOD__ . ": adding $name" );
1679 
1680  if ( is_null( $title ) ) {
1681  throw new MWException( "invalid title '$name' at $file:$line\n" );
1682  }
1683 
1684  $newContent = ContentHandler::makeContent( $text, $title );
1685 
1686  $page = WikiPage::factory( $title );
1687  $page->loadPageData( 'fromdbmaster' );
1688 
1689  if ( $page->exists() ) {
1690  $content = $page->getContent( Revision::RAW );
1691  // Only reject the title, if the content/content model is different.
1692  // This makes it easier to create Template:(( or Template:)) in different extensions
1693  if ( $newContent->equals( $content ) ) {
1694  return;
1695  }
1696  throw new MWException(
1697  "duplicate article '$name' with different content at $file:$line\n"
1698  );
1699  }
1700 
1701  // Optionally use mock parser, to make debugging of actual parser tests simpler.
1702  // But initialise the MessageCache clone first, don't let MessageCache
1703  // get a reference to the mock object.
1704  if ( $this->disableSaveParse ) {
1705  MessageCache::singleton()->getParser();
1706  $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser ] );
1707  } else {
1708  $restore = false;
1709  }
1710  try {
1711  $status = $page->doEditContent(
1712  $newContent,
1713  '',
1715  );
1716  } finally {
1717  if ( $restore ) {
1718  $restore();
1719  }
1720  }
1721 
1722  if ( !$status->isOK() ) {
1723  throw new MWException( $status->getWikiText( false, false, 'en' ) );
1724  }
1725 
1726  // The RepoGroup cache is invalidated by the creation of file redirects
1727  if ( $title->inNamespace( NS_FILE ) ) {
1728  RepoGroup::singleton()->clearCache( $title );
1729  }
1730  }
1731 
1738  public function requireHook( $name ) {
1739  $parser = MediaWikiServices::getInstance()->getParser();
1740 
1741  $parser->firstCallInit(); // make sure hooks are loaded.
1742  if ( isset( $parser->mTagHooks[$name] ) ) {
1743  return true;
1744  } else {
1745  $this->recorder->warning( " This test suite requires the '$name' hook " .
1746  "extension, skipping." );
1747  return false;
1748  }
1749  }
1750 
1757  public function requireFunctionHook( $name ) {
1758  $parser = MediaWikiServices::getInstance()->getParser();
1759 
1760  $parser->firstCallInit(); // make sure hooks are loaded.
1761 
1762  if ( isset( $parser->mFunctionHooks[$name] ) ) {
1763  return true;
1764  } else {
1765  $this->recorder->warning( " This test suite requires the '$name' function " .
1766  "hook extension, skipping." );
1767  return false;
1768  }
1769  }
1770 
1777  public function requireTransparentHook( $name ) {
1778  $parser = MediaWikiServices::getInstance()->getParser();
1779 
1780  $parser->firstCallInit(); // make sure hooks are loaded.
1781 
1782  if ( isset( $parser->mTransparentTagHooks[$name] ) ) {
1783  return true;
1784  } else {
1785  $this->recorder->warning( " This test suite requires the '$name' transparent " .
1786  "hook extension, skipping.\n" );
1787  return false;
1788  }
1789  }
1790 
1798  private function getFakeTimestamp() {
1799  // parsed as '1970-01-01T00:02:03Z'
1800  return 123;
1801  }
1802 }
requireFunctionHook( $name)
Check if a function hook is installed.
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:138
const DB_PREFIX
Table name prefixes.
const MARKER_PREFIX
Definition: Parser.php:136
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
static getMainWANInstance()
Get the main WAN cache object.
checkSetupDone( $funcName, $funcName2=null)
Ensure a given setup stage has been done, throw an exception if it has not.
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
$wgParserTestFiles
Parser test suite files to be run by parserTests.php when no specific filename is passed to it...
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:232
static setInstance( $instance)
Set the driver to be used.
Definition: MWTidy.php:85
Class simulating a backend store.
meetsRequirements( $requirements)
Determine whether the current parser has the hooks registered in it that are required by a file read ...
serialize()
$IP
Definition: WebStart.php:41
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static parentStoragePath( $storagePath)
Get the parent storage directory of a storage path.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2159
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
if(!isset( $args[0])) $lang
static destroyInstance()
Destroy the singleton instance.
static array $coreTestFiles
MediaWiki core parser test files, paths will be prefixed with DIR .
$wgFileBackends
File backend structure configuration.
isSetupDone( $funcName)
Determine whether a particular setup function has been run.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
const EDIT_INTERNAL
Definition: Defines.php:155
setupUploadBackend()
Upload test files to the backend created by createRepoGroup().
teardownUploadBackend()
Remove the dummy uploads directory.
static read( $file, array $options=[])
resetTitleServices()
Reset the Title-related services that need resetting for each test.
$value
teardownDatabase()
Helper for database teardown, called from the teardown closure.
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
string null $fileBackendName
The name of the file backend to use, or null to use MockFileBackend.
createRepoGroup()
Create a RepoGroup object appropriate for the current configuration.
const MEDIATYPE_DRAWING
Definition: defines.php:30
getFakeTimestamp()
Fake constant timestamp to make sure time-related parser functions give a persistent value...
setDatabase(IDatabase $db)
setupDatabase( $nextTeardown=null)
Set up temporary DB tables.
static factory(array $config=null)
Create a new Tidy driver object from configuration.
Definition: MWTidy.php:76
wfLocalFile( $title)
Get an object referring to a locally registered file.
const MEDIATYPE_BITMAP
Definition: defines.php:28
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1799
const DB_MASTER
Definition: defines.php:26
bool $runDisabled
Run disabled parser tests.
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:979
static clear( $name)
Clears hooks registered via Hooks::register().
Definition: Hooks.php:63
markSetupDone( $funcName)
Set a setupDone flag to indicate that setup has been done, and return the teardown closure...
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2217
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 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name '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. '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 '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:Array with elements of the form "language:title" in the order that they will be output. & $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 since 1.28! 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:1980
Database $db
Our connection to the database.
static BagOStuff [] $instances
Map of (id => BagOStuff)
Definition: ObjectCache.php:82
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
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 true
Definition: hooks.txt:1982
static destroySingleton()
Destroy the current singleton instance.
Definition: MWTidy.php:93
const MEDIATYPE_VIDEO
Definition: defines.php:35
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1263
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
runTests( $testFileInfo)
Run the tests from a single file.
wfTempDir()
Tries to get the system directory for temporary files.
static getMain()
Get the RequestContext object associated with the main request.
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:1160
getMainConfig()
Returns the Config object that provides configuration for MediaWiki core.
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response 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:2217
TidyDriverBase $tidyDriver
static register( $name, $callback)
Attach an event handler to a given hook.
Definition: Hooks.php:49
const SCHEMA_COMPAT_WRITE_NEW
Definition: Defines.php:282
static singleton()
Definition: RepoGroup.php:60
createTeardownObject( $teardown, $nextTeardown=null)
Take a setup array in the same format as the one given to executeSetupSnippets(), and return a Scoped...
warning( $message)
Show a warning to the user.
const LANG_FULL_MATCH
Definition: SVGReader.php:36
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
addArticle( $name, $text, $file, $line)
Insert a temporary test article.
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:174
parseOptions( $instring)
Given the options string, return an associative array of options.
static destroySingletons()
Destroy the singleton instances.
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 & $options
Definition: hooks.txt:1982
deleteFiles( $files)
Delete the specified files and their parent directories.
requireTransparentHook( $name)
Check if a transparent tag hook is installed.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:216
getParser( $preprocessor=null)
Get a Parser object.
__construct(TestRecorder $recorder, $options=[])
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
const NS_FILE
Definition: Defines.php:66
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
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 $skin
Definition: hooks.txt:1982
$wgParserConf
Parser configuration.
$GLOBALS['IP']
const RAW
Definition: Revision.php:56
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
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:3050
addArticles( $articles)
Add articles to the test DB.
const SVG_METADATA_VERSION
Definition: SvgHandler.php:33
string $regex
A complete regex for filtering tests.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:589
Interface to record parser test results.
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
array $normalizationFunctions
A list of normalization functions to apply to the expected and actual output.
setupInterwikis()
Insert hardcoded interwiki in the lookup table.
runTest( $test)
Run a given wikitext input through a freshly-constructed wiki parser, and compare the output against ...
static getOptionValue( $key, $opts, $default)
Use a regex to find out the value of an option.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
const MEDIATYPE_AUDIO
Definition: defines.php:32
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
const EDIT_NEW
Definition: Defines.php:148
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
setupUploads( $nextTeardown=null)
Add data about uploads to the new test DB, and set up the upload directory.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$line
Definition: cdb.php:59
$wgDBprefix
Table name prefix.
staticSetup( $nextTeardown=null)
Do any setup which can be done once for all tests, independent of test options, except for database s...
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2633
A parser used during article insertion which does nothing, to avoid unnecessary log noise and other i...
runTestsFromFiles( $filenames)
Run a series of tests listed in the given text files.
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any). ...
Definition: Html.php:620
bool $disableSaveParse
Disable parse on article insertion.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
$wgObjectCaches
Advanced object cache configuration.
appendNamespaceSetup(&$setup, &$teardown)
static getParserTestFiles()
Get list of filenames to extension and core parser tests.
static chomp( $s)
Remove last character if it is a newline.
static createNew( $name, $params=[])
Add a user to the database, return the user object.
Definition: User.php:4174
TestRecorder $recorder
Class for a file system (FS) based file backend.
listTables()
List of temporary tables to create, without prefix.
executeSetupSnippets( $setup)
Execute an array in which elements with integer keys are taken to be callable objects, and other elements are taken to be global variable set operations, with the key giving the variable name and the value giving the new global variable value.
Represent the result of a parser test.
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
$content
Definition: pageupdater.txt:72
MediaWikiServices is the service locator for the application scope of MediaWiki.
CloneDatabase $dbClone
Database clone helper.
static changePrefix( $prefix)
Change the table prefix on all open DB connections.
perTestSetup( $test, $nextTeardown=null)
Do any required setup which is dependent on test options.
string null $uploadDir
The upload directory, or null to not set up an upload directory.
static singleton()
Get the signleton instance of this class.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
bool $keepUploads
Reuse upload directory.
const CACHE_DB
Definition: Defines.php:99
requireHook( $name)
Check if a hook is installed.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
$matches
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:319