MediaWiki  master
ParserTestRunner.php
Go to the documentation of this file.
1 <?php
34 
39 
46  private static $coreTestFiles = [
47  'parserTests.txt',
48  'extraParserTests.txt',
49  ];
50 
54  private $useTemporaryTables = true;
55 
59  private $setupDone = [
60  'staticSetup' => false,
61  'perTestSetup' => false,
62  'setupDatabase' => false,
63  'setDatabase' => false,
64  'setupUploads' => false,
65  ];
66 
71  private $db;
72 
77  private $dbClone;
78 
82  private $tidyDriver = null;
83 
87  private $recorder;
88 
94  private $uploadDir = null;
95 
101 
106  private $regex;
107 
114 
119  private $runDisabled;
120 
126 
131  private $keepUploads;
132 
134  private $defaultTitle;
135 
140  public function __construct( TestRecorder $recorder, $options = [] ) {
141  $this->recorder = $recorder;
142 
143  if ( isset( $options['norm'] ) ) {
144  foreach ( $options['norm'] as $func ) {
145  if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
146  $this->normalizationFunctions[] = $func;
147  } else {
148  $this->recorder->warning(
149  "Warning: unknown normalization option \"$func\"\n" );
150  }
151  }
152  }
153 
154  if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
155  $this->regex = $options['regex'];
156  } else {
157  # Matches anything
158  $this->regex = '//';
159  }
160 
161  $this->keepUploads = !empty( $options['keep-uploads'] );
162 
163  $this->fileBackendName = $options['file-backend'] ?? false;
164 
165  $this->runDisabled = !empty( $options['run-disabled'] );
166 
167  $this->disableSaveParse = !empty( $options['disable-save-parse'] );
168 
169  if ( isset( $options['upload-dir'] ) ) {
170  $this->uploadDir = $options['upload-dir'];
171  }
172 
173  $this->defaultTitle = Title::newFromText( 'Parser test' );
174  }
175 
181  public static function getParserTestFiles() {
182  global $wgParserTestFiles;
183 
184  // Add core test files
185  $files = array_map( function ( $item ) {
186  return __DIR__ . "/$item";
187  }, self::$coreTestFiles );
188 
189  // Plus legacy global files
190  $files = array_merge( $files, $wgParserTestFiles );
191 
192  // Auto-discover extension parser tests
193  $registry = ExtensionRegistry::getInstance();
194  foreach ( $registry->getAllThings() as $info ) {
195  $dir = dirname( $info['path'] ) . '/tests/parser';
196  if ( !file_exists( $dir ) ) {
197  continue;
198  }
199  $counter = 1;
200  $dirIterator = new RecursiveIteratorIterator(
201  new RecursiveDirectoryIterator( $dir )
202  );
203  foreach ( $dirIterator as $fileInfo ) {
205  if ( substr( $fileInfo->getFilename(), -4 ) === '.txt' ) {
206  $name = $info['name'] . $counter;
207  while ( isset( $files[$name] ) ) {
208  $name = $info['name'] . '_' . $counter++;
209  }
210  $files[$name] = $fileInfo->getPathname();
211  }
212  }
213  }
214 
215  return array_unique( $files );
216  }
217 
218  public function getRecorder() {
219  return $this->recorder;
220  }
221 
241  public function staticSetup( $nextTeardown = null ) {
242  // A note on coding style:
243 
244  // The general idea here is to keep setup code together with
245  // corresponding teardown code, in a fine-grained manner. We have two
246  // arrays: $setup and $teardown. The code snippets in the $setup array
247  // are executed at the end of the method, before it returns, and the
248  // code snippets in the $teardown array are executed in reverse order
249  // when the Wikimedia\ScopedCallback object is consumed.
250 
251  // Because it is a common operation to save, set and restore global
252  // variables, we have an additional convention: when the array key of
253  // $setup is a string, the string is taken to be the name of the global
254  // variable, and the element value is taken to be the desired new value.
255 
256  // It's acceptable to just do the setup immediately, instead of adding
257  // a closure to $setup, except when the setup action depends on global
258  // variable initialisation being done first. In this case, you have to
259  // append a closure to $setup after the global variable is appended.
260 
261  // When you add to setup functions in this class, please keep associated
262  // setup and teardown actions together in the source code, and please
263  // add comments explaining why the setup action is necessary.
264 
265  $setup = [];
266  $teardown = [];
267 
268  $teardown[] = $this->markSetupDone( 'staticSetup' );
269 
270  // Some settings which influence HTML output
271  $setup['wgSitename'] = 'MediaWiki';
272  $setup['wgServer'] = 'http://example.org';
273  $setup['wgServerName'] = 'example.org';
274  $setup['wgScriptPath'] = '';
275  $setup['wgScript'] = '/index.php';
276  $setup['wgResourceBasePath'] = '';
277  $setup['wgStylePath'] = '/skins';
278  $setup['wgExtensionAssetsPath'] = '/extensions';
279  $setup['wgArticlePath'] = '/wiki/$1';
280  $setup['wgActionPaths'] = [];
281  $setup['wgVariantArticlePath'] = false;
282  $setup['wgUploadNavigationUrl'] = false;
283  $setup['wgCapitalLinks'] = true;
284  $setup['wgNoFollowLinks'] = true;
285  $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
286  $setup['wgExternalLinkTarget'] = false;
287  $setup['wgLocaltimezone'] = 'UTC';
288  $setup['wgDisableLangConversion'] = false;
289  $setup['wgDisableTitleConversion'] = false;
290 
291  // "extra language links"
292  // see https://gerrit.wikimedia.org/r/111390
293  $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
294 
295  // All FileRepo changes should be done here by injecting services,
296  // there should be no need to change global variables.
297  MediaWikiServices::getInstance()->disableService( 'RepoGroup' );
298  MediaWikiServices::getInstance()->redefineService( 'RepoGroup',
299  function () {
300  return $this->createRepoGroup();
301  }
302  );
303  $teardown[] = function () {
304  MediaWikiServices::getInstance()->resetServiceForTesting( 'RepoGroup' );
305  };
306 
307  // Set up null lock managers
308  $setup['wgLockManagers'] = [ [
309  'name' => 'fsLockManager',
310  'class' => NullLockManager::class,
311  ], [
312  'name' => 'nullLockManager',
313  'class' => NullLockManager::class,
314  ] ];
315  $reset = function () {
317  };
318  $setup[] = $reset;
319  $teardown[] = $reset;
320 
321  // This allows article insertion into the prefixed DB
322  $setup['wgDefaultExternalStore'] = false;
323 
324  // This might slightly reduce memory usage
325  $setup['wgAdaptiveMessageCache'] = true;
326 
327  // This is essential and overrides disabling of database messages in TestSetup
328  $setup['wgUseDatabaseMessages'] = true;
329  $reset = function () {
331  };
332  $setup[] = $reset;
333  $teardown[] = $reset;
334 
335  // It's not necessary to actually convert any files
336  $setup['wgSVGConverter'] = 'null';
337  $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
338 
339  // Fake constant timestamp
340  Hooks::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
341  $ts = $this->getFakeTimestamp();
342  return true;
343  } );
344  $teardown[] = function () {
345  Hooks::clear( 'ParserGetVariableValueTs' );
346  };
347 
348  $this->appendNamespaceSetup( $setup, $teardown );
349 
350  // Set up interwikis and append teardown function
351  $teardown[] = $this->setupInterwikis();
352 
353  // This affects title normalization in links. It invalidates
354  // MediaWikiTitleCodec objects.
355  $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
356  $reset = function () {
357  $this->resetTitleServices();
358  };
359  $setup[] = $reset;
360  $teardown[] = $reset;
361 
362  // Set up a mock MediaHandlerFactory
363  MediaWikiServices::getInstance()->disableService( 'MediaHandlerFactory' );
364  MediaWikiServices::getInstance()->redefineService(
365  'MediaHandlerFactory',
366  function ( MediaWikiServices $services ) {
367  $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
368  return new MediaHandlerFactory( $handlers );
369  }
370  );
371  $teardown[] = function () {
372  MediaWikiServices::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
373  };
374 
375  // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
376  // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
377  // This works around it for now...
378  global $wgObjectCaches;
379  $setup['wgObjectCaches'] = [ CACHE_DB => $wgObjectCaches['hash'] ] + $wgObjectCaches;
380  if ( isset( ObjectCache::$instances[CACHE_DB] ) ) {
381  $savedCache = ObjectCache::$instances[CACHE_DB];
383  $teardown[] = function () use ( $savedCache ) {
384  ObjectCache::$instances[CACHE_DB] = $savedCache;
385  };
386  }
387 
388  $teardown[] = $this->executeSetupSnippets( $setup );
389 
390  // Schedule teardown snippets in reverse order
391  return $this->createTeardownObject( $teardown, $nextTeardown );
392  }
393 
394  private function appendNamespaceSetup( &$setup, &$teardown ) {
395  // Add a namespace shadowing a interwiki link, to test
396  // proper precedence when resolving links. (T53680)
397  $setup['wgExtraNamespaces'] = [
398  100 => 'MemoryAlpha',
399  101 => 'MemoryAlpha_talk'
400  ];
401  // Changing wgExtraNamespaces invalidates caches in NamespaceInfo and any live Language
402  // object, both on setup and teardown
403  $reset = function () {
404  MediaWikiServices::getInstance()->resetServiceForTesting( 'NamespaceInfo' );
405  MediaWikiServices::getInstance()->getContentLanguage()->resetNamespaces();
406  };
407  $setup[] = $reset;
408  $teardown[] = $reset;
409  }
410 
415  protected function createRepoGroup() {
416  if ( $this->uploadDir ) {
417  if ( $this->fileBackendName ) {
418  throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
419  }
420  $backend = new FSFileBackend( [
421  'name' => 'local-backend',
422  'wikiId' => wfWikiID(),
423  'basePath' => $this->uploadDir,
424  'tmpDirectory' => wfTempDir()
425  ] );
426  } elseif ( $this->fileBackendName ) {
427  global $wgFileBackends;
429  $useConfig = false;
430  foreach ( $wgFileBackends as $conf ) {
431  if ( $conf['name'] === $name ) {
432  $useConfig = $conf;
433  }
434  }
435  if ( $useConfig === false ) {
436  throw new MWException( "Unable to find file backend \"$name\"" );
437  }
438  $useConfig['name'] = 'local-backend'; // swap name
439  unset( $useConfig['lockManager'] );
440  unset( $useConfig['fileJournal'] );
441  $class = $useConfig['class'];
442  $backend = new $class( $useConfig );
443  } else {
444  # Replace with a mock. We do not care about generating real
445  # files on the filesystem, just need to expose the file
446  # informations.
447  $backend = new MockFileBackend( [
448  'name' => 'local-backend',
449  'wikiId' => wfWikiID()
450  ] );
451  }
452 
453  return new RepoGroup(
454  [
455  'class' => MockLocalRepo::class,
456  'name' => 'local',
457  'url' => 'http://example.com/images',
458  'hashLevels' => 2,
459  'transformVia404' => false,
460  'backend' => $backend
461  ],
462  [],
463  MediaWikiServices::getInstance()->getMainWANObjectCache()
464  );
465  }
466 
480  protected function executeSetupSnippets( $setup ) {
481  $saved = [];
482  foreach ( $setup as $name => $value ) {
483  if ( is_int( $name ) ) {
484  $value();
485  } else {
486  $saved[$name] = $GLOBALS[$name] ?? null;
487  $GLOBALS[$name] = $value;
488  }
489  }
490  return function () use ( $saved ) {
491  $this->executeSetupSnippets( $saved );
492  };
493  }
494 
507  protected function createTeardownObject( $teardown, $nextTeardown = null ) {
508  return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
509  // Schedule teardown snippets in reverse order
510  $teardown = array_reverse( $teardown );
511 
512  $this->executeSetupSnippets( $teardown );
513  if ( $nextTeardown ) {
514  ScopedCallback::consume( $nextTeardown );
515  }
516  } );
517  }
518 
526  protected function markSetupDone( $funcName ) {
527  if ( $this->setupDone[$funcName] ) {
528  throw new MWException( "$funcName is already done" );
529  }
530  $this->setupDone[$funcName] = true;
531  return function () use ( $funcName ) {
532  $this->setupDone[$funcName] = false;
533  };
534  }
535 
542  protected function checkSetupDone( $funcName, $funcName2 = null ) {
543  if ( !$this->setupDone[$funcName]
544  && ( $funcName === null || !$this->setupDone[$funcName2] )
545  ) {
546  throw new MWException( "$funcName must be called before calling " .
547  wfGetCaller() );
548  }
549  }
550 
557  public function isSetupDone( $funcName ) {
558  return $this->setupDone[$funcName] ?? false;
559  }
560 
572  private function setupInterwikis() {
573  # Hack: insert a few Wikipedia in-project interwiki prefixes,
574  # for testing inter-language links
575  Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
576  static $testInterwikis = [
577  'local' => [
578  'iw_url' => 'http://doesnt.matter.org/$1',
579  'iw_api' => '',
580  'iw_wikiid' => '',
581  'iw_local' => 0 ],
582  'wikipedia' => [
583  'iw_url' => 'http://en.wikipedia.org/wiki/$1',
584  'iw_api' => '',
585  'iw_wikiid' => '',
586  'iw_local' => 0 ],
587  'meatball' => [
588  'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
589  'iw_api' => '',
590  'iw_wikiid' => '',
591  'iw_local' => 0 ],
592  'memoryalpha' => [
593  'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
594  'iw_api' => '',
595  'iw_wikiid' => '',
596  'iw_local' => 0 ],
597  'zh' => [
598  'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
599  'iw_api' => '',
600  'iw_wikiid' => '',
601  'iw_local' => 1 ],
602  'es' => [
603  'iw_url' => 'http://es.wikipedia.org/wiki/$1',
604  'iw_api' => '',
605  'iw_wikiid' => '',
606  'iw_local' => 1 ],
607  'fr' => [
608  'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
609  'iw_api' => '',
610  'iw_wikiid' => '',
611  'iw_local' => 1 ],
612  'ru' => [
613  'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
614  'iw_api' => '',
615  'iw_wikiid' => '',
616  'iw_local' => 1 ],
617  'mi' => [
618  'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
619  'iw_api' => '',
620  'iw_wikiid' => '',
621  'iw_local' => 1 ],
622  'mul' => [
623  'iw_url' => 'http://wikisource.org/wiki/$1',
624  'iw_api' => '',
625  'iw_wikiid' => '',
626  'iw_local' => 1 ],
627  ];
628  if ( array_key_exists( $prefix, $testInterwikis ) ) {
629  $iwData = $testInterwikis[$prefix];
630  }
631 
632  // We only want to rely on the above fixtures
633  return false;
634  } );// hooks::register
635 
636  // Reset the service in case any other tests already cached some prefixes.
637  MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
638 
639  return function () {
640  // Tear down
641  Hooks::clear( 'InterwikiLoadPrefix' );
642  MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
643  };
644  }
645 
652  private function resetTitleServices() {
653  $services = MediaWikiServices::getInstance();
654  $services->resetServiceForTesting( 'TitleFormatter' );
655  $services->resetServiceForTesting( 'TitleParser' );
656  $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
657  $services->resetServiceForTesting( 'LinkRenderer' );
658  $services->resetServiceForTesting( 'LinkRendererFactory' );
659  $services->resetServiceForTesting( 'NamespaceInfo' );
660  }
661 
667  public static function chomp( $s ) {
668  if ( substr( $s, -1 ) === "\n" ) {
669  return substr( $s, 0, -1 );
670  } else {
671  return $s;
672  }
673  }
674 
688  public function runTestsFromFiles( $filenames ) {
689  $ok = false;
690 
691  $teardownGuard = $this->staticSetup();
692  $teardownGuard = $this->setupDatabase( $teardownGuard );
693  $teardownGuard = $this->setupUploads( $teardownGuard );
694 
695  $this->recorder->start();
696  try {
697  $ok = true;
698 
699  foreach ( $filenames as $filename ) {
700  $testFileInfo = TestFileReader::read( $filename, [
701  'runDisabled' => $this->runDisabled,
702  'regex' => $this->regex ] );
703 
704  // Don't start the suite if there are no enabled tests in the file
705  if ( !$testFileInfo['tests'] ) {
706  continue;
707  }
708 
709  $this->recorder->startSuite( $filename );
710  $ok = $this->runTests( $testFileInfo ) && $ok;
711  $this->recorder->endSuite( $filename );
712  }
713 
714  $this->recorder->report();
715  } catch ( DBError $e ) {
716  $this->recorder->warning( $e->getMessage() );
717  }
718  $this->recorder->end();
719 
720  ScopedCallback::consume( $teardownGuard );
721 
722  return $ok;
723  }
724 
731  public function meetsRequirements( $requirements ) {
732  foreach ( $requirements as $requirement ) {
733  switch ( $requirement['type'] ) {
734  case 'hook':
735  $ok = $this->requireHook( $requirement['name'] );
736  break;
737  case 'functionHook':
738  $ok = $this->requireFunctionHook( $requirement['name'] );
739  break;
740  case 'transparentHook':
741  $ok = $this->requireTransparentHook( $requirement['name'] );
742  break;
743  }
744  if ( !$ok ) {
745  return false;
746  }
747  }
748  return true;
749  }
750 
758  public function runTests( $testFileInfo ) {
759  $ok = true;
760 
761  $this->checkSetupDone( 'staticSetup' );
762 
763  // Don't add articles from the file if there are no enabled tests from the file
764  if ( !$testFileInfo['tests'] ) {
765  return true;
766  }
767 
768  // If any requirements are not met, mark all tests from the file as skipped
769  if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
770  foreach ( $testFileInfo['tests'] as $test ) {
771  $this->recorder->startTest( $test );
772  $this->recorder->skipped( $test, 'required extension not enabled' );
773  }
774  return true;
775  }
776 
777  // Add articles
778  $this->addArticles( $testFileInfo['articles'] );
779 
780  // Run tests
781  foreach ( $testFileInfo['tests'] as $test ) {
782  $this->recorder->startTest( $test );
783  $result =
784  $this->runTest( $test );
785  if ( $result !== false ) {
786  $ok = $ok && $result->isSuccess();
787  $this->recorder->record( $test, $result );
788  }
789  }
790 
791  return $ok;
792  }
793 
800  function getParser( $preprocessor = null ) {
801  global $wgParserConf;
802 
803  $class = $wgParserConf['class'];
804  $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
805  if ( $preprocessor ) {
806  # Suppress deprecation warning for Preprocessor_DOM while testing
807  Wikimedia\suppressWarnings();
808  wfDeprecated( 'Preprocessor_DOM::__construct' );
809  Wikimedia\restoreWarnings();
810  $parser->getPreprocessor();
811  }
813 
814  return $parser;
815  }
816 
834  public function runTest( $test ) {
835  wfDebug( __METHOD__ . ": running {$test['desc']}" );
836  $opts = $this->parseOptions( $test['options'] );
837  $teardownGuard = $this->perTestSetup( $test );
838 
840  $user = $context->getUser();
842  $options->setTimestamp( $this->getFakeTimestamp() );
843 
844  if ( isset( $opts['tidy'] ) ) {
845  $options->setTidy( true );
846  }
847 
848  $revId = 1337; // see Parser::getRevisionId()
849  $title = isset( $opts['title'] )
850  ? Title::newFromText( $opts['title'] )
852 
853  if ( isset( $opts['lastsavedrevision'] ) ) {
854  $content = new WikitextContent( $test['input'] );
855  $title = Title::newFromRow( (object)[
856  'page_id' => 187,
857  'page_len' => $content->getSize(),
858  'page_latest' => 1337,
859  'page_namespace' => $title->getNamespace(),
860  'page_title' => $title->getDBkey(),
861  'page_is_redirect' => 0
862  ] );
863  $rev = new Revision(
864  [
865  'id' => $title->getLatestRevID(),
866  'page' => $title->getArticleID(),
867  'user' => $user,
868  'content' => $content,
869  'timestamp' => $this->getFakeTimestamp(),
870  'title' => $title
871  ],
872  Revision::READ_LATEST,
873  $title
874  );
875  $oldCallback = $options->getCurrentRevisionCallback();
876  $options->setCurrentRevisionCallback(
877  function ( Title $t, $parser ) use ( $title, $rev, $oldCallback ) {
878  if ( $t->equals( $title ) ) {
879  return $rev;
880  } else {
881  return call_user_func( $oldCallback, $t, $parser );
882  }
883  }
884  );
885  }
886 
887  if ( isset( $opts['maxincludesize'] ) ) {
888  $options->setMaxIncludeSize( $opts['maxincludesize'] );
889  }
890  if ( isset( $opts['maxtemplatedepth'] ) ) {
891  $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
892  }
893 
894  $local = isset( $opts['local'] );
895  $preprocessor = $opts['preprocessor'] ?? null;
896  $parser = $this->getParser( $preprocessor );
897 
898  if ( isset( $opts['styletag'] ) ) {
899  // For testing the behavior of <style> (including those deduplicated
900  // into <link> tags), add tag hooks to allow them to be generated.
901  $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
902  $marker = Parser::MARKER_PREFIX . '-style-' . md5( $content ) . Parser::MARKER_SUFFIX;
903  $parser->mStripState->addNoWiki( $marker, $content );
904  return Html::inlineStyle( $marker, 'all', $attributes );
905  } );
906  $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
907  return Html::element( 'link', $attributes );
908  } );
909  }
910 
911  if ( isset( $opts['pst'] ) ) {
912  $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
913  $output = $parser->getOutput();
914  } elseif ( isset( $opts['msg'] ) ) {
915  $out = $parser->transformMsg( $test['input'], $options, $title );
916  } elseif ( isset( $opts['section'] ) ) {
917  $section = $opts['section'];
918  $out = $parser->getSection( $test['input'], $section );
919  } elseif ( isset( $opts['replace'] ) ) {
920  $section = $opts['replace'][0];
921  $replace = $opts['replace'][1];
922  $out = $parser->replaceSection( $test['input'], $section, $replace );
923  } elseif ( isset( $opts['comment'] ) ) {
924  $out = Linker::formatComment( $test['input'], $title, $local );
925  } elseif ( isset( $opts['preload'] ) ) {
926  $out = $parser->getPreloadText( $test['input'], $title, $options );
927  } else {
928  $output = $parser->parse( $test['input'], $title, $options, true, true, $revId );
929  $out = $output->getText( [
930  'allowTOC' => !isset( $opts['notoc'] ),
931  'unwrap' => !isset( $opts['wrap'] ),
932  ] );
933  if ( isset( $opts['tidy'] ) ) {
934  $out = preg_replace( '/\s+$/', '', $out );
935  }
936 
937  if ( isset( $opts['showtitle'] ) ) {
938  if ( $output->getTitleText() ) {
939  $title = $output->getTitleText();
940  }
941 
942  $out = "$title\n$out";
943  }
944 
945  if ( isset( $opts['showindicators'] ) ) {
946  $indicators = '';
947  foreach ( $output->getIndicators() as $id => $content ) {
948  $indicators .= "$id=$content\n";
949  }
950  $out = $indicators . $out;
951  }
952 
953  if ( isset( $opts['ill'] ) ) {
954  $out = implode( ' ', $output->getLanguageLinks() );
955  } elseif ( isset( $opts['cat'] ) ) {
956  $out = '';
957  foreach ( $output->getCategories() as $name => $sortkey ) {
958  if ( $out !== '' ) {
959  $out .= "\n";
960  }
961  $out .= "cat=$name sort=$sortkey";
962  }
963  }
964  }
965 
966  if ( isset( $output ) && isset( $opts['showflags'] ) ) {
967  $actualFlags = array_keys( TestingAccessWrapper::newFromObject( $output )->mFlags );
968  sort( $actualFlags );
969  $out .= "\nflags=" . implode( ', ', $actualFlags );
970  }
971 
972  ScopedCallback::consume( $teardownGuard );
973 
974  $expected = $test['result'];
975  if ( count( $this->normalizationFunctions ) ) {
977  $test['expected'], $this->normalizationFunctions );
978  $out = ParserTestResultNormalizer::normalize( $out, $this->normalizationFunctions );
979  }
980 
981  $testResult = new ParserTestResult( $test, $expected, $out );
982  return $testResult;
983  }
984 
992  private static function getOptionValue( $key, $opts, $default ) {
993  $key = strtolower( $key );
994  return $opts[$key] ?? $default;
995  }
996 
1004  private function parseOptions( $instring ) {
1005  $opts = [];
1006  // foo
1007  // foo=bar
1008  // foo="bar baz"
1009  // foo=[[bar baz]]
1010  // foo=bar,"baz quux"
1011  // foo={...json...}
1012  $defs = '(?(DEFINE)
1013  (?<qstr> # Quoted string
1014  "
1015  (?:[^\\\\"] | \\\\.)*
1016  "
1017  )
1018  (?<json>
1019  \{ # Open bracket
1020  (?:
1021  [^"{}] | # Not a quoted string or object, or
1022  (?&qstr) | # A quoted string, or
1023  (?&json) # A json object (recursively)
1024  )*
1025  \} # Close bracket
1026  )
1027  (?<value>
1028  (?:
1029  (?&qstr) # Quoted val
1030  |
1031  \[\[
1032  [^]]* # Link target
1033  \]\]
1034  |
1035  [\w-]+ # Plain word
1036  |
1037  (?&json) # JSON object
1038  )
1039  )
1040  )';
1041  $regex = '/' . $defs . '\b
1042  (?<k>[\w-]+) # Key
1043  \b
1044  (?:\s*
1045  = # First sub-value
1046  \s*
1047  (?<v>
1048  (?&value)
1049  (?:\s*
1050  , # Sub-vals 1..N
1051  \s*
1052  (?&value)
1053  )*
1054  )
1055  )?
1056  /x';
1057  $valueregex = '/' . $defs . '(?&value)/x';
1058 
1059  if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
1060  foreach ( $matches as $bits ) {
1061  $key = strtolower( $bits['k'] );
1062  if ( !isset( $bits['v'] ) ) {
1063  $opts[$key] = true;
1064  } else {
1065  preg_match_all( $valueregex, $bits['v'], $vmatches );
1066  $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1067  if ( count( $opts[$key] ) == 1 ) {
1068  $opts[$key] = $opts[$key][0];
1069  }
1070  }
1071  }
1072  }
1073  return $opts;
1074  }
1075 
1076  private function cleanupOption( $opt ) {
1077  if ( substr( $opt, 0, 1 ) == '"' ) {
1078  return stripcslashes( substr( $opt, 1, -1 ) );
1079  }
1080 
1081  if ( substr( $opt, 0, 2 ) == '[[' ) {
1082  return substr( $opt, 2, -2 );
1083  }
1084 
1085  if ( substr( $opt, 0, 1 ) == '{' ) {
1086  return FormatJson::decode( $opt, true );
1087  }
1088  return $opt;
1089  }
1090 
1100  public function perTestSetup( $test, $nextTeardown = null ) {
1101  $teardown = [];
1102 
1103  $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1104  $teardown[] = $this->markSetupDone( 'perTestSetup' );
1105 
1106  $opts = $this->parseOptions( $test['options'] );
1107  $config = $test['config'];
1108 
1109  // Find out values for some special options.
1110  $langCode =
1111  self::getOptionValue( 'language', $opts, 'en' );
1112  $variant =
1113  self::getOptionValue( 'variant', $opts, false );
1114  $maxtoclevel =
1115  self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1116  $linkHolderBatchSize =
1117  self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1118 
1119  // Default to fallback skin, but allow it to be overridden
1120  $skin = self::getOptionValue( 'skin', $opts, 'fallback' );
1121 
1122  $setup = [
1123  'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
1124  'wgLanguageCode' => $langCode,
1125  'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
1126  'wgNamespacesWithSubpages' => array_fill_keys(
1127  MediaWikiServices::getInstance()->getNamespaceInfo()->getValidNamespaces(),
1128  isset( $opts['subpage'] )
1129  ),
1130  'wgMaxTocLevel' => $maxtoclevel,
1131  'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1132  'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
1133  'wgDefaultLanguageVariant' => $variant,
1134  'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1135  // Set as a JSON object like:
1136  // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1137  'wgEnableMagicLinks' => self::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1138  + [ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1139  // Test with legacy encoding by default until HTML5 is very stable and default
1140  'wgFragmentMode' => [ 'legacy' ],
1141  ];
1142 
1143  $nonIncludable = self::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1144  if ( $nonIncludable !== false ) {
1145  $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1146  }
1147 
1148  if ( $config ) {
1149  $configLines = explode( "\n", $config );
1150 
1151  foreach ( $configLines as $line ) {
1152  list( $var, $value ) = explode( '=', $line, 2 );
1153  $setup[$var] = eval( "return $value;" );
1154  }
1155  }
1156 
1158  Hooks::run( 'ParserTestGlobals', [ &$setup ] );
1159 
1160  // Create tidy driver
1161  if ( isset( $opts['tidy'] ) ) {
1162  // Cache a driver instance
1163  if ( $this->tidyDriver === null ) {
1164  $this->tidyDriver = MWTidy::factory();
1165  }
1166  $tidy = $this->tidyDriver;
1167  } else {
1168  $tidy = false;
1169  }
1170 
1171  # Suppress warnings about running tests without tidy
1172  Wikimedia\suppressWarnings();
1173  wfDeprecated( 'disabling tidy' );
1174  wfDeprecated( 'MWTidy::setInstance' );
1175  Wikimedia\restoreWarnings();
1176 
1177  MWTidy::setInstance( $tidy );
1178  $teardown[] = function () {
1180  };
1181 
1182  // Set content language. This invalidates the magic word cache and title services
1183  $lang = Language::factory( $langCode );
1184  $lang->resetNamespaces();
1185  $setup['wgContLang'] = $lang;
1186  $setup[] = function () use ( $lang ) {
1187  MediaWikiServices::getInstance()->disableService( 'ContentLanguage' );
1188  MediaWikiServices::getInstance()->redefineService(
1189  'ContentLanguage',
1190  function () use ( $lang ) {
1191  return $lang;
1192  }
1193  );
1194  };
1195  $teardown[] = function () {
1196  MediaWikiServices::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1197  };
1198  $reset = function () {
1199  MediaWikiServices::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1200  $this->resetTitleServices();
1201  };
1202  $setup[] = $reset;
1203  $teardown[] = $reset;
1204 
1205  // Make a user object with the same language
1206  $user = new User;
1207  $user->setOption( 'language', $langCode );
1208  $setup['wgLang'] = $lang;
1209 
1210  // We (re)set $wgThumbLimits to a single-element array above.
1211  $user->setOption( 'thumbsize', 0 );
1212 
1213  $setup['wgUser'] = $user;
1214 
1215  // And put both user and language into the context
1217  $context->setUser( $user );
1218  $context->setLanguage( $lang );
1219  // And the skin!
1220  $oldSkin = $context->getSkin();
1221  $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
1222  $context->setSkin( $skinFactory->makeSkin( $skin ) );
1223  $context->setOutput( new OutputPage( $context ) );
1224  $setup['wgOut'] = $context->getOutput();
1225  $teardown[] = function () use ( $context, $oldSkin ) {
1226  // Clear language conversion tables
1227  $wrapper = TestingAccessWrapper::newFromObject(
1228  $context->getLanguage()->getConverter()
1229  );
1230  $wrapper->reloadTables();
1231  // Reset context to the restored globals
1232  $context->setUser( $GLOBALS['wgUser'] );
1233  $context->setLanguage( $GLOBALS['wgContLang'] );
1234  $context->setSkin( $oldSkin );
1235  $context->setOutput( $GLOBALS['wgOut'] );
1236  };
1237 
1238  $teardown[] = $this->executeSetupSnippets( $setup );
1239 
1240  return $this->createTeardownObject( $teardown, $nextTeardown );
1241  }
1242 
1248  private function listTables() {
1250 
1251  $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1252  'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1253  'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1254  'site_stats', 'ipblocks', 'image', 'oldimage',
1255  'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1256  'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1257  'archive', 'user_groups', 'page_props', 'category',
1258  'slots', 'content', 'slot_roles', 'content_models',
1259  'comment', 'revision_comment_temp',
1260  ];
1261 
1262  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
1263  // The new tables for actors are in use
1264  $tables[] = 'actor';
1265  $tables[] = 'revision_actor_temp';
1266  }
1267 
1268  if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite' ] ) ) {
1269  array_push( $tables, 'searchindex' );
1270  }
1271 
1272  // Allow extensions to add to the list of tables to duplicate;
1273  // may be necessary if they hook into page save or other code
1274  // which will require them while running tests.
1275  Hooks::run( 'ParserTestTables', [ &$tables ] );
1276 
1277  return $tables;
1278  }
1279 
1280  public function setDatabase( IDatabase $db ) {
1281  $this->db = $db;
1282  $this->setupDone['setDatabase'] = true;
1283  }
1284 
1302  public function setupDatabase( $nextTeardown = null ) {
1303  global $wgDBprefix;
1304 
1305  $this->db = MediaWikiServices::getInstance()->getDBLoadBalancer()->getConnection( DB_MASTER );
1306  $dbType = $this->db->getType();
1307 
1308  $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1309  if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1310  throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1311  }
1312 
1313  $teardown = [];
1314 
1315  $teardown[] = $this->markSetupDone( 'setupDatabase' );
1316 
1317  # CREATE TEMPORARY TABLE breaks if there is more than one server
1318  if ( MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1319  $this->useTemporaryTables = false;
1320  }
1321 
1322  $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1323  $prefix = 'parsertest_';
1324 
1325  $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1326  $this->dbClone->useTemporaryTables( $temporary );
1327  $this->dbClone->cloneTableStructure();
1328  CloneDatabase::changePrefix( $prefix );
1329 
1330  $teardown[] = function () {
1331  $this->teardownDatabase();
1332  };
1333 
1334  // Wipe some DB query result caches on setup and teardown
1335  $reset = function () {
1336  MediaWikiServices::getInstance()->getLinkCache()->clear();
1337 
1338  // Clear the message cache
1339  MessageCache::singleton()->clear();
1340  };
1341  $reset();
1342  $teardown[] = $reset;
1343  return $this->createTeardownObject( $teardown, $nextTeardown );
1344  }
1345 
1354  public function setupUploads( $nextTeardown = null ) {
1355  $teardown = [];
1356 
1357  $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1358  $teardown[] = $this->markSetupDone( 'setupUploads' );
1359 
1360  // Create the files in the upload directory (or pretend to create them
1361  // in a MockFileBackend). Append teardown callback.
1362  $teardown[] = $this->setupUploadBackend();
1363 
1364  // Create a user
1365  $user = User::createNew( 'WikiSysop' );
1366 
1367  // Register the uploads in the database
1368 
1369  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1370  # note that the size/width/height/bits/etc of the file
1371  # are actually set by inspecting the file itself; the arguments
1372  # to recordUpload2 have no effect. That said, we try to make things
1373  # match up so it is less confusing to readers of the code & tests.
1374  $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1375  'size' => 7881,
1376  'width' => 1941,
1377  'height' => 220,
1378  'bits' => 8,
1379  'media_type' => MEDIATYPE_BITMAP,
1380  'mime' => 'image/jpeg',
1381  'metadata' => serialize( [] ),
1382  'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1383  'fileExists' => true
1384  ], $this->db->timestamp( '20010115123500' ), $user );
1385 
1386  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1387  # again, note that size/width/height below are ignored; see above.
1388  $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1389  'size' => 22589,
1390  'width' => 135,
1391  'height' => 135,
1392  'bits' => 8,
1393  'media_type' => MEDIATYPE_BITMAP,
1394  'mime' => 'image/png',
1395  'metadata' => serialize( [] ),
1396  'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1397  'fileExists' => true
1398  ], $this->db->timestamp( '20130225203040' ), $user );
1399 
1400  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1401  $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1402  'size' => 12345,
1403  'width' => 240,
1404  'height' => 180,
1405  'bits' => 0,
1406  'media_type' => MEDIATYPE_DRAWING,
1407  'mime' => 'image/svg+xml',
1408  'metadata' => serialize( [
1409  'version' => SvgHandler::SVG_METADATA_VERSION,
1410  'width' => 240,
1411  'height' => 180,
1412  'originalWidth' => '100%',
1413  'originalHeight' => '100%',
1414  'translations' => [
1417  ],
1418  ] ),
1419  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1420  'fileExists' => true
1421  ], $this->db->timestamp( '20010115123500' ), $user );
1422 
1423  # This image will be blacklisted in [[MediaWiki:Bad image list]]
1424  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1425  $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1426  'size' => 12345,
1427  'width' => 320,
1428  'height' => 240,
1429  'bits' => 24,
1430  'media_type' => MEDIATYPE_BITMAP,
1431  'mime' => 'image/jpeg',
1432  'metadata' => serialize( [] ),
1433  'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1434  'fileExists' => true
1435  ], $this->db->timestamp( '20010115123500' ), $user );
1436 
1437  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1438  $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1439  'size' => 12345,
1440  'width' => 320,
1441  'height' => 240,
1442  'bits' => 0,
1443  'media_type' => MEDIATYPE_VIDEO,
1444  'mime' => 'application/ogg',
1445  'metadata' => serialize( [] ),
1446  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1447  'fileExists' => true
1448  ], $this->db->timestamp( '20010115123500' ), $user );
1449 
1450  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1451  $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1452  'size' => 12345,
1453  'width' => 0,
1454  'height' => 0,
1455  'bits' => 0,
1456  'media_type' => MEDIATYPE_AUDIO,
1457  'mime' => 'application/ogg',
1458  'metadata' => serialize( [] ),
1459  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1460  'fileExists' => true
1461  ], $this->db->timestamp( '20010115123500' ), $user );
1462 
1463  # A DjVu file
1464  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1465  $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1466  'size' => 3249,
1467  'width' => 2480,
1468  'height' => 3508,
1469  'bits' => 0,
1470  'media_type' => MEDIATYPE_BITMAP,
1471  'mime' => 'image/vnd.djvu',
1472  'metadata' => '<?xml version="1.0" ?>
1473 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1474 <DjVuXML>
1475 <HEAD></HEAD>
1476 <BODY><OBJECT height="3508" width="2480">
1477 <PARAM name="DPI" value="300" />
1478 <PARAM name="GAMMA" value="2.2" />
1479 </OBJECT>
1480 <OBJECT height="3508" width="2480">
1481 <PARAM name="DPI" value="300" />
1482 <PARAM name="GAMMA" value="2.2" />
1483 </OBJECT>
1484 <OBJECT height="3508" width="2480">
1485 <PARAM name="DPI" value="300" />
1486 <PARAM name="GAMMA" value="2.2" />
1487 </OBJECT>
1488 <OBJECT height="3508" width="2480">
1489 <PARAM name="DPI" value="300" />
1490 <PARAM name="GAMMA" value="2.2" />
1491 </OBJECT>
1492 <OBJECT height="3508" width="2480">
1493 <PARAM name="DPI" value="300" />
1494 <PARAM name="GAMMA" value="2.2" />
1495 </OBJECT>
1496 </BODY>
1497 </DjVuXML>',
1498  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1499  'fileExists' => true
1500  ], $this->db->timestamp( '20010115123600' ), $user );
1501 
1502  return $this->createTeardownObject( $teardown, $nextTeardown );
1503  }
1504 
1511  private function teardownDatabase() {
1512  $this->checkSetupDone( 'setupDatabase' );
1513 
1514  $this->dbClone->destroy();
1515 
1516  if ( $this->useTemporaryTables ) {
1517  if ( $this->db->getType() == 'sqlite' ) {
1518  # Under SQLite the searchindex table is virtual and need
1519  # to be explicitly destroyed. See T31912
1520  # See also MediaWikiTestCase::destroyDB()
1521  wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1522  $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1523  }
1524  # Don't need to do anything
1525  return;
1526  }
1527 
1528  $tables = $this->listTables();
1529 
1530  foreach ( $tables as $table ) {
1531  $this->db->query( "DROP TABLE `parsertest_$table`" );
1532  }
1533  }
1534 
1540  private function setupUploadBackend() {
1541  global $IP;
1542 
1543  $repo = RepoGroup::singleton()->getLocalRepo();
1544  $base = $repo->getZonePath( 'public' );
1545  $backend = $repo->getBackend();
1546  $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1547  $backend->store( [
1548  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1549  'dst' => "$base/3/3a/Foobar.jpg"
1550  ] );
1551  $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1552  $backend->store( [
1553  'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1554  'dst' => "$base/e/ea/Thumb.png"
1555  ] );
1556  $backend->prepare( [ 'dir' => "$base/0/09" ] );
1557  $backend->store( [
1558  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1559  'dst' => "$base/0/09/Bad.jpg"
1560  ] );
1561  $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1562  $backend->store( [
1563  'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1564  'dst' => "$base/5/5f/LoremIpsum.djvu"
1565  ] );
1566 
1567  // No helpful SVG file to copy, so make one ourselves
1568  $data = '<?xml version="1.0" encoding="utf-8"?>' .
1569  '<svg xmlns="http://www.w3.org/2000/svg"' .
1570  ' version="1.1" width="240" height="180"/>';
1571 
1572  $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1573  $backend->quickCreate( [
1574  'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1575  ] );
1576 
1577  return function () use ( $backend ) {
1578  if ( $backend instanceof MockFileBackend ) {
1579  // In memory backend, so dont bother cleaning them up.
1580  return;
1581  }
1582  $this->teardownUploadBackend();
1583  };
1584  }
1585 
1589  private function teardownUploadBackend() {
1590  if ( $this->keepUploads ) {
1591  return;
1592  }
1593 
1594  $repo = RepoGroup::singleton()->getLocalRepo();
1595  $public = $repo->getZonePath( 'public' );
1596 
1597  $this->deleteFiles(
1598  [
1599  "$public/3/3a/Foobar.jpg",
1600  "$public/e/ea/Thumb.png",
1601  "$public/0/09/Bad.jpg",
1602  "$public/5/5f/LoremIpsum.djvu",
1603  "$public/f/ff/Foobar.svg",
1604  "$public/0/00/Video.ogv",
1605  "$public/4/41/Audio.oga",
1606  ]
1607  );
1608  }
1609 
1614  private function deleteFiles( $files ) {
1615  // Delete the files
1616  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
1617  foreach ( $files as $file ) {
1618  $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1619  }
1620 
1621  // Delete the parent directories
1622  foreach ( $files as $file ) {
1623  $tmp = FileBackend::parentStoragePath( $file );
1624  while ( $tmp ) {
1625  if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1626  break;
1627  }
1628  $tmp = FileBackend::parentStoragePath( $tmp );
1629  }
1630  }
1631  }
1632 
1638  public function addArticles( $articles ) {
1639  $setup = [];
1640  $teardown = [];
1641 
1642  // Be sure ParserTestRunner::addArticle has correct language set,
1643  // so that system messages get into the right language cache
1644  if ( MediaWikiServices::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1645  $setup['wgLanguageCode'] = 'en';
1646  $lang = Language::factory( 'en' );
1647  $setup['wgContLang'] = $lang;
1648  $setup[] = function () use ( $lang ) {
1649  $services = MediaWikiServices::getInstance();
1650  $services->disableService( 'ContentLanguage' );
1651  $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1652  return $lang;
1653  } );
1654  };
1655  $teardown[] = function () {
1656  MediaWikiServices::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1657  };
1658  }
1659 
1660  // Add special namespaces, in case that hasn't been done by staticSetup() yet
1661  $this->appendNamespaceSetup( $setup, $teardown );
1662 
1663  // wgCapitalLinks obviously needs initialisation
1664  $setup['wgCapitalLinks'] = true;
1665 
1666  $teardown[] = $this->executeSetupSnippets( $setup );
1667 
1668  foreach ( $articles as $info ) {
1669  $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1670  }
1671 
1672  // Wipe WANObjectCache process cache, which is invalidated by article insertion
1673  // due to T144706
1674  MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
1675 
1676  $this->executeSetupSnippets( $teardown );
1677  }
1678 
1688  private function addArticle( $name, $text, $file, $line ) {
1689  $text = self::chomp( $text );
1690  $name = self::chomp( $name );
1691 
1693  wfDebug( __METHOD__ . ": adding $name" );
1694 
1695  if ( is_null( $title ) ) {
1696  throw new MWException( "invalid title '$name' at $file:$line\n" );
1697  }
1698 
1699  $newContent = ContentHandler::makeContent( $text, $title );
1700 
1701  $page = WikiPage::factory( $title );
1702  $page->loadPageData( 'fromdbmaster' );
1703 
1704  if ( $page->exists() ) {
1705  $content = $page->getContent( Revision::RAW );
1706  // Only reject the title, if the content/content model is different.
1707  // This makes it easier to create Template:(( or Template:)) in different extensions
1708  if ( $newContent->equals( $content ) ) {
1709  return;
1710  }
1711  throw new MWException(
1712  "duplicate article '$name' with different content at $file:$line\n"
1713  );
1714  }
1715 
1716  // Optionally use mock parser, to make debugging of actual parser tests simpler.
1717  // But initialise the MessageCache clone first, don't let MessageCache
1718  // get a reference to the mock object.
1719  if ( $this->disableSaveParse ) {
1720  MessageCache::singleton()->getParser();
1721  $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser ] );
1722  } else {
1723  $restore = false;
1724  }
1725  try {
1726  $status = $page->doEditContent(
1727  $newContent,
1728  '',
1730  );
1731  } finally {
1732  if ( $restore ) {
1733  $restore();
1734  }
1735  }
1736 
1737  if ( !$status->isOK() ) {
1738  throw new MWException( $status->getWikiText( false, false, 'en' ) );
1739  }
1740 
1741  // The RepoGroup cache is invalidated by the creation of file redirects
1742  if ( $title->inNamespace( NS_FILE ) ) {
1743  RepoGroup::singleton()->clearCache( $title );
1744  }
1745  }
1746 
1753  public function requireHook( $name ) {
1754  $parser = MediaWikiServices::getInstance()->getParser();
1755 
1756  $parser->firstCallInit(); // make sure hooks are loaded.
1757  if ( isset( $parser->mTagHooks[$name] ) ) {
1758  return true;
1759  } else {
1760  $this->recorder->warning( " This test suite requires the '$name' hook " .
1761  "extension, skipping." );
1762  return false;
1763  }
1764  }
1765 
1772  public function requireFunctionHook( $name ) {
1773  $parser = MediaWikiServices::getInstance()->getParser();
1774 
1775  $parser->firstCallInit(); // make sure hooks are loaded.
1776 
1777  if ( isset( $parser->mFunctionHooks[$name] ) ) {
1778  return true;
1779  } else {
1780  $this->recorder->warning( " This test suite requires the '$name' function " .
1781  "hook extension, skipping." );
1782  return false;
1783  }
1784  }
1785 
1792  public function requireTransparentHook( $name ) {
1793  $parser = MediaWikiServices::getInstance()->getParser();
1794 
1795  $parser->firstCallInit(); // make sure hooks are loaded.
1796 
1797  if ( isset( $parser->mTransparentTagHooks[$name] ) ) {
1798  return true;
1799  } else {
1800  $this->recorder->warning( " This test suite requires the '$name' transparent " .
1801  "hook extension, skipping.\n" );
1802  return false;
1803  }
1804  }
1805 
1813  private function getFakeTimestamp() {
1814  // parsed as '1970-01-01T00:02:03Z'
1815  return 123;
1816  }
1817 }
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 MARKER_PREFIX
Definition: Parser.php:138
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource 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:231
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
equals(LinkTarget $title)
Compare with another title.
Definition: Title.php:4008
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:2147
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.
const EDIT_INTERNAL
Definition: Defines.php:139
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...
static newFromRow( $row)
Make a Title object from a DB row.
Definition: Title.php:522
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:1781
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:960
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:2205
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\*-\*)") will be honored when streaming the file. '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:1970
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:767
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:1972
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:1244
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:2205
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:266
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:1972
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:767
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
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:1972
$wgParserConf
Parser configuration.
$GLOBALS['IP']
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1748
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:3039
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:592
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:132
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:767
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:2621
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:619
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:4082
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:1454
bool $keepUploads
Reuse upload directory.
const CACHE_DB
Definition: Defines.php:83
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:322