MediaWiki  1.28.0
ParserTestRunner.php
Go to the documentation of this file.
1 <?php
30 
38  private $useTemporaryTables = true;
39 
43  private $setupDone = [
44  'staticSetup' => false,
45  'perTestSetup' => false,
46  'setupDatabase' => false,
47  'setDatabase' => false,
48  'setupUploads' => false,
49  ];
50 
55  private $db;
56 
61  private $dbClone;
62 
66  private $tidySupport;
67 
71  private $tidyDriver = null;
72 
76  private $recorder;
77 
83  private $uploadDir = null;
84 
90 
95  private $regex;
96 
103 
108  public function __construct( TestRecorder $recorder, $options = [] ) {
109  $this->recorder = $recorder;
110 
111  if ( isset( $options['norm'] ) ) {
112  foreach ( $options['norm'] as $func ) {
113  if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
114  $this->normalizationFunctions[] = $func;
115  } else {
116  $this->recorder->warning(
117  "Warning: unknown normalization option \"$func\"\n" );
118  }
119  }
120  }
121 
122  if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
123  $this->regex = $options['regex'];
124  } else {
125  # Matches anything
126  $this->regex = '//';
127  }
128 
129  $this->keepUploads = !empty( $options['keep-uploads'] );
130 
131  $this->fileBackendName = isset( $options['file-backend'] ) ?
132  $options['file-backend'] : false;
133 
134  $this->runDisabled = !empty( $options['run-disabled'] );
135  $this->runParsoid = !empty( $options['run-parsoid'] );
136 
137  $this->tidySupport = new TidySupport( !empty( $options['use-tidy-config'] ) );
138  if ( !$this->tidySupport->isEnabled() ) {
139  $this->recorder->warning(
140  "Warning: tidy is not installed, skipping some tests\n" );
141  }
142 
143  if ( isset( $options['upload-dir'] ) ) {
144  $this->uploadDir = $options['upload-dir'];
145  }
146  }
147 
148  public function getRecorder() {
149  return $this->recorder;
150  }
151 
171  public function staticSetup( $nextTeardown = null ) {
172  // A note on coding style:
173 
174  // The general idea here is to keep setup code together with
175  // corresponding teardown code, in a fine-grained manner. We have two
176  // arrays: $setup and $teardown. The code snippets in the $setup array
177  // are executed at the end of the method, before it returns, and the
178  // code snippets in the $teardown array are executed in reverse order
179  // when the Wikimedia\ScopedCallback object is consumed.
180 
181  // Because it is a common operation to save, set and restore global
182  // variables, we have an additional convention: when the array key of
183  // $setup is a string, the string is taken to be the name of the global
184  // variable, and the element value is taken to be the desired new value.
185 
186  // It's acceptable to just do the setup immediately, instead of adding
187  // a closure to $setup, except when the setup action depends on global
188  // variable initialisation being done first. In this case, you have to
189  // append a closure to $setup after the global variable is appended.
190 
191  // When you add to setup functions in this class, please keep associated
192  // setup and teardown actions together in the source code, and please
193  // add comments explaining why the setup action is necessary.
194 
195  $setup = [];
196  $teardown = [];
197 
198  $teardown[] = $this->markSetupDone( 'staticSetup' );
199 
200  // Some settings which influence HTML output
201  $setup['wgSitename'] = 'MediaWiki';
202  $setup['wgServer'] = 'http://example.org';
203  $setup['wgServerName'] = 'example.org';
204  $setup['wgScriptPath'] = '';
205  $setup['wgScript'] = '/index.php';
206  $setup['wgResourceBasePath'] = '';
207  $setup['wgStylePath'] = '/skins';
208  $setup['wgExtensionAssetsPath'] = '/extensions';
209  $setup['wgArticlePath'] = '/wiki/$1';
210  $setup['wgActionPaths'] = [];
211  $setup['wgVariantArticlePath'] = false;
212  $setup['wgUploadNavigationUrl'] = false;
213  $setup['wgCapitalLinks'] = true;
214  $setup['wgNoFollowLinks'] = true;
215  $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
216  $setup['wgExternalLinkTarget'] = false;
217  $setup['wgExperimentalHtmlIds'] = false;
218  $setup['wgLocaltimezone'] = 'UTC';
219  $setup['wgHtml5'] = true;
220  $setup['wgDisableLangConversion'] = false;
221  $setup['wgDisableTitleConversion'] = false;
222 
223  // "extra language links"
224  // see https://gerrit.wikimedia.org/r/111390
225  $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
226 
227  // All FileRepo changes should be done here by injecting services,
228  // there should be no need to change global variables.
230  $teardown[] = function () {
232  };
233 
234  // Set up null lock managers
235  $setup['wgLockManagers'] = [ [
236  'name' => 'fsLockManager',
237  'class' => 'NullLockManager',
238  ], [
239  'name' => 'nullLockManager',
240  'class' => 'NullLockManager',
241  ] ];
242  $reset = function() {
244  };
245  $setup[] = $reset;
246  $teardown[] = $reset;
247 
248  // This allows article insertion into the prefixed DB
249  $setup['wgDefaultExternalStore'] = false;
250 
251  // This might slightly reduce memory usage
252  $setup['wgAdaptiveMessageCache'] = true;
253 
254  // This is essential and overrides disabling of database messages in TestSetup
255  $setup['wgUseDatabaseMessages'] = true;
256  $reset = function () {
258  };
259  $setup[] = $reset;
260  $teardown[] = $reset;
261 
262  // It's not necessary to actually convert any files
263  $setup['wgSVGConverter'] = 'null';
264  $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
265 
266  // Fake constant timestamp
267  Hooks::register( 'ParserGetVariableValueTs', 'ParserTestRunner::getFakeTimestamp' );
268  $teardown[] = function () {
269  Hooks::clear( 'ParserGetVariableValueTs' );
270  };
271 
272  $this->appendNamespaceSetup( $setup, $teardown );
273 
274  // Set up interwikis and append teardown function
275  $teardown[] = $this->setupInterwikis();
276 
277  // This affects title normalization in links. It invalidates
278  // MediaWikiTitleCodec objects.
279  $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
280  $reset = function () {
281  $this->resetTitleServices();
282  };
283  $setup[] = $reset;
284  $teardown[] = $reset;
285 
286  // Set up a mock MediaHandlerFactory
287  MediaWikiServices::getInstance()->disableService( 'MediaHandlerFactory' );
288  MediaWikiServices::getInstance()->redefineService(
289  'MediaHandlerFactory',
290  function() {
291  return new MockMediaHandlerFactory();
292  }
293  );
294  $teardown[] = function () {
295  MediaWikiServices::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
296  };
297 
298  // SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
299  // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
300  // This works around it for now...
302  $setup['wgObjectCaches'] = [ CACHE_DB => $wgObjectCaches['hash'] ] + $wgObjectCaches;
303  if ( isset( ObjectCache::$instances[CACHE_DB] ) ) {
304  $savedCache = ObjectCache::$instances[CACHE_DB];
306  $teardown[] = function () use ( $savedCache ) {
307  ObjectCache::$instances[CACHE_DB] = $savedCache;
308  };
309  }
310 
311  $teardown[] = $this->executeSetupSnippets( $setup );
312 
313  // Schedule teardown snippets in reverse order
314  return $this->createTeardownObject( $teardown, $nextTeardown );
315  }
316 
317  private function appendNamespaceSetup( &$setup, &$teardown ) {
318  // Add a namespace shadowing a interwiki link, to test
319  // proper precedence when resolving links. (bug 51680)
320  $setup['wgExtraNamespaces'] = [
321  100 => 'MemoryAlpha',
322  101 => 'MemoryAlpha_talk'
323  ];
324  // Changing wgExtraNamespaces invalidates caches in MWNamespace and
325  // any live Language object, both on setup and teardown
326  $reset = function () {
328  $GLOBALS['wgContLang']->resetNamespaces();
329  };
330  $setup[] = $reset;
331  $teardown[] = $reset;
332  }
333 
338  protected function createRepoGroup() {
339  if ( $this->uploadDir ) {
340  if ( $this->fileBackendName ) {
341  throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
342  }
343  $backend = new FSFileBackend( [
344  'name' => 'local-backend',
345  'wikiId' => wfWikiID(),
346  'basePath' => $this->uploadDir,
347  'tmpDirectory' => wfTempDir()
348  ] );
349  } elseif ( $this->fileBackendName ) {
352  $useConfig = false;
353  foreach ( $wgFileBackends as $conf ) {
354  if ( $conf['name'] === $name ) {
355  $useConfig = $conf;
356  }
357  }
358  if ( $useConfig === false ) {
359  throw new MWException( "Unable to find file backend \"$name\"" );
360  }
361  $useConfig['name'] = 'local-backend'; // swap name
362  unset( $useConfig['lockManager'] );
363  unset( $useConfig['fileJournal'] );
364  $class = $useConfig['class'];
365  $backend = new $class( $useConfig );
366  } else {
367  # Replace with a mock. We do not care about generating real
368  # files on the filesystem, just need to expose the file
369  # informations.
370  $backend = new MockFileBackend( [
371  'name' => 'local-backend',
372  'wikiId' => wfWikiID()
373  ] );
374  }
375 
376  return new RepoGroup(
377  [
378  'class' => 'MockLocalRepo',
379  'name' => 'local',
380  'url' => 'http://example.com/images',
381  'hashLevels' => 2,
382  'transformVia404' => false,
383  'backend' => $backend
384  ],
385  []
386  );
387  }
388 
402  protected function executeSetupSnippets( $setup ) {
403  $saved = [];
404  foreach ( $setup as $name => $value ) {
405  if ( is_int( $name ) ) {
406  $value();
407  } else {
408  $saved[$name] = isset( $GLOBALS[$name] ) ? $GLOBALS[$name] : null;
409  $GLOBALS[$name] = $value;
410  }
411  }
412  return function () use ( $saved ) {
413  $this->executeSetupSnippets( $saved );
414  };
415  }
416 
429  protected function createTeardownObject( $teardown, $nextTeardown ) {
430  return new ScopedCallback( function() use ( $teardown, $nextTeardown ) {
431  // Schedule teardown snippets in reverse order
432  $teardown = array_reverse( $teardown );
433 
434  $this->executeSetupSnippets( $teardown );
435  if ( $nextTeardown ) {
436  ScopedCallback::consume( $nextTeardown );
437  }
438  } );
439  }
440 
448  protected function markSetupDone( $funcName ) {
449  if ( $this->setupDone[$funcName] ) {
450  throw new MWException( "$funcName is already done" );
451  }
452  $this->setupDone[$funcName] = true;
453  return function () use ( $funcName ) {
454  $this->setupDone[$funcName] = false;
455  };
456  }
457 
462  protected function checkSetupDone( $funcName, $funcName2 = null ) {
463  if ( !$this->setupDone[$funcName]
464  && ( $funcName === null || !$this->setupDone[$funcName2] )
465  ) {
466  throw new MWException( "$funcName must be called before calling " .
467  wfGetCaller() );
468  }
469  }
470 
477  public function isSetupDone( $funcName ) {
478  return isset( $this->setupDone[$funcName] ) ? $this->setupDone[$funcName] : false;
479  }
480 
492  private function setupInterwikis() {
493  # Hack: insert a few Wikipedia in-project interwiki prefixes,
494  # for testing inter-language links
495  Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
496  static $testInterwikis = [
497  'local' => [
498  'iw_url' => 'http://doesnt.matter.org/$1',
499  'iw_api' => '',
500  'iw_wikiid' => '',
501  'iw_local' => 0 ],
502  'wikipedia' => [
503  'iw_url' => 'http://en.wikipedia.org/wiki/$1',
504  'iw_api' => '',
505  'iw_wikiid' => '',
506  'iw_local' => 0 ],
507  'meatball' => [
508  'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
509  'iw_api' => '',
510  'iw_wikiid' => '',
511  'iw_local' => 0 ],
512  'memoryalpha' => [
513  'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
514  'iw_api' => '',
515  'iw_wikiid' => '',
516  'iw_local' => 0 ],
517  'zh' => [
518  'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
519  'iw_api' => '',
520  'iw_wikiid' => '',
521  'iw_local' => 1 ],
522  'es' => [
523  'iw_url' => 'http://es.wikipedia.org/wiki/$1',
524  'iw_api' => '',
525  'iw_wikiid' => '',
526  'iw_local' => 1 ],
527  'fr' => [
528  'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
529  'iw_api' => '',
530  'iw_wikiid' => '',
531  'iw_local' => 1 ],
532  'ru' => [
533  'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
534  'iw_api' => '',
535  'iw_wikiid' => '',
536  'iw_local' => 1 ],
537  'mi' => [
538  'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
539  'iw_api' => '',
540  'iw_wikiid' => '',
541  'iw_local' => 1 ],
542  'mul' => [
543  'iw_url' => 'http://wikisource.org/wiki/$1',
544  'iw_api' => '',
545  'iw_wikiid' => '',
546  'iw_local' => 1 ],
547  ];
548  if ( array_key_exists( $prefix, $testInterwikis ) ) {
549  $iwData = $testInterwikis[$prefix];
550  }
551 
552  // We only want to rely on the above fixtures
553  return false;
554  } );// hooks::register
555 
556  return function () {
557  // Tear down
558  Hooks::clear( 'InterwikiLoadPrefix' );
559  };
560  }
561 
566  private function resetTitleServices() {
567  $services = MediaWikiServices::getInstance();
568  $services->resetServiceForTesting( 'TitleFormatter' );
569  $services->resetServiceForTesting( 'TitleParser' );
570  $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
571  $services->resetServiceForTesting( 'LinkRenderer' );
572  $services->resetServiceForTesting( 'LinkRendererFactory' );
573  }
574 
581  public static function chomp( $s ) {
582  if ( substr( $s, -1 ) === "\n" ) {
583  return substr( $s, 0, -1 );
584  } else {
585  return $s;
586  }
587  }
588 
602  public function runTestsFromFiles( $filenames ) {
603  $ok = false;
604 
605  $teardownGuard = $this->staticSetup();
606  $teardownGuard = $this->setupDatabase( $teardownGuard );
607  $teardownGuard = $this->setupUploads( $teardownGuard );
608 
609  $this->recorder->start();
610  try {
611  $ok = true;
612 
613  foreach ( $filenames as $filename ) {
614  $testFileInfo = TestFileReader::read( $filename, [
615  'runDisabled' => $this->runDisabled,
616  'runParsoid' => $this->runParsoid,
617  'regex' => $this->regex ] );
618 
619  // Don't start the suite if there are no enabled tests in the file
620  if ( !$testFileInfo['tests'] ) {
621  continue;
622  }
623 
624  $this->recorder->startSuite( $filename );
625  $ok = $this->runTests( $testFileInfo ) && $ok;
626  $this->recorder->endSuite( $filename );
627  }
628 
629  $this->recorder->report();
630  } catch ( DBError $e ) {
631  $this->recorder->warning( $e->getMessage() );
632  }
633  $this->recorder->end();
634 
635  ScopedCallback::consume( $teardownGuard );
636 
637  return $ok;
638  }
639 
644  public function meetsRequirements( $requirements ) {
645  foreach ( $requirements as $requirement ) {
646  switch ( $requirement['type'] ) {
647  case 'hook':
648  $ok = $this->requireHook( $requirement['name'] );
649  break;
650  case 'functionHook':
651  $ok = $this->requireFunctionHook( $requirement['name'] );
652  break;
653  case 'transparentHook':
654  $ok = $this->requireTransparentHook( $requirement['name'] );
655  break;
656  }
657  if ( !$ok ) {
658  return false;
659  }
660  }
661  return true;
662  }
663 
671  public function runTests( $testFileInfo ) {
672  $ok = true;
673 
674  $this->checkSetupDone( 'staticSetup' );
675 
676  // Don't add articles from the file if there are no enabled tests from the file
677  if ( !$testFileInfo['tests'] ) {
678  return true;
679  }
680 
681  // If any requirements are not met, mark all tests from the file as skipped
682  if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
683  foreach ( $testFileInfo['tests'] as $test ) {
684  $this->recorder->startTest( $test );
685  $this->recorder->skipped( $test, 'required extension not enabled' );
686  }
687  return true;
688  }
689 
690  // Add articles
691  $this->addArticles( $testFileInfo['articles'] );
692 
693  // Run tests
694  foreach ( $testFileInfo['tests'] as $test ) {
695  $this->recorder->startTest( $test );
696  $result =
697  $this->runTest( $test );
698  if ( $result !== false ) {
699  $ok = $ok && $result->isSuccess();
700  $this->recorder->record( $test, $result );
701  }
702  }
703 
704  return $ok;
705  }
706 
713  function getParser( $preprocessor = null ) {
714  global $wgParserConf;
715 
716  $class = $wgParserConf['class'];
717  $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
719 
720  return $parser;
721  }
722 
740  public function runTest( $test ) {
741  wfDebug( __METHOD__.": running {$test['desc']}" );
742  $opts = $this->parseOptions( $test['options'] );
743  $teardownGuard = $this->perTestSetup( $test );
744 
746  $user = $context->getUser();
748 
749  if ( isset( $opts['tidy'] ) ) {
750  if ( !$this->tidySupport->isEnabled() ) {
751  $this->recorder->skipped( $test, 'tidy extension is not installed' );
752  return false;
753  } else {
754  $options->setTidy( true );
755  }
756  }
757 
758  if ( isset( $opts['title'] ) ) {
759  $titleText = $opts['title'];
760  } else {
761  $titleText = 'Parser test';
762  }
763 
764  $local = isset( $opts['local'] );
765  $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
766  $parser = $this->getParser( $preprocessor );
767  $title = Title::newFromText( $titleText );
768 
769  if ( isset( $opts['pst'] ) ) {
770  $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
771  } elseif ( isset( $opts['msg'] ) ) {
772  $out = $parser->transformMsg( $test['input'], $options, $title );
773  } elseif ( isset( $opts['section'] ) ) {
774  $section = $opts['section'];
775  $out = $parser->getSection( $test['input'], $section );
776  } elseif ( isset( $opts['replace'] ) ) {
777  $section = $opts['replace'][0];
778  $replace = $opts['replace'][1];
779  $out = $parser->replaceSection( $test['input'], $section, $replace );
780  } elseif ( isset( $opts['comment'] ) ) {
781  $out = Linker::formatComment( $test['input'], $title, $local );
782  } elseif ( isset( $opts['preload'] ) ) {
783  $out = $parser->getPreloadText( $test['input'], $title, $options );
784  } else {
785  $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
786  $output->setTOCEnabled( !isset( $opts['notoc'] ) );
787  $out = $output->getText();
788  if ( isset( $opts['tidy'] ) ) {
789  $out = preg_replace( '/\s+$/', '', $out );
790  }
791 
792  if ( isset( $opts['showtitle'] ) ) {
793  if ( $output->getTitleText() ) {
795  }
796 
797  $out = "$title\n$out";
798  }
799 
800  if ( isset( $opts['showindicators'] ) ) {
801  $indicators = '';
802  foreach ( $output->getIndicators() as $id => $content ) {
803  $indicators .= "$id=$content\n";
804  }
805  $out = $indicators . $out;
806  }
807 
808  if ( isset( $opts['ill'] ) ) {
809  $out = implode( ' ', $output->getLanguageLinks() );
810  } elseif ( isset( $opts['cat'] ) ) {
811  $out = '';
812  foreach ( $output->getCategories() as $name => $sortkey ) {
813  if ( $out !== '' ) {
814  $out .= "\n";
815  }
816  $out .= "cat=$name sort=$sortkey";
817  }
818  }
819  }
820 
821  ScopedCallback::consume( $teardownGuard );
822 
823  $expected = $test['result'];
824  if ( count( $this->normalizationFunctions ) ) {
826  $test['expected'], $this->normalizationFunctions );
827  $out = ParserTestResultNormalizer::normalize( $out, $this->normalizationFunctions );
828  }
829 
830  $testResult = new ParserTestResult( $test, $expected, $out );
831  return $testResult;
832  }
833 
841  private static function getOptionValue( $key, $opts, $default ) {
842  $key = strtolower( $key );
843 
844  if ( isset( $opts[$key] ) ) {
845  return $opts[$key];
846  } else {
847  return $default;
848  }
849  }
850 
858  private function parseOptions( $instring ) {
859  $opts = [];
860  // foo
861  // foo=bar
862  // foo="bar baz"
863  // foo=[[bar baz]]
864  // foo=bar,"baz quux"
865  // foo={...json...}
866  $defs = '(?(DEFINE)
867  (?<qstr> # Quoted string
868  "
869  (?:[^\\\\"] | \\\\.)*
870  "
871  )
872  (?<json>
873  \{ # Open bracket
874  (?:
875  [^"{}] | # Not a quoted string or object, or
876  (?&qstr) | # A quoted string, or
877  (?&json) # A json object (recursively)
878  )*
879  \} # Close bracket
880  )
881  (?<value>
882  (?:
883  (?&qstr) # Quoted val
884  |
885  \[\[
886  [^]]* # Link target
887  \]\]
888  |
889  [\w-]+ # Plain word
890  |
891  (?&json) # JSON object
892  )
893  )
894  )';
895  $regex = '/' . $defs . '\b
896  (?<k>[\w-]+) # Key
897  \b
898  (?:\s*
899  = # First sub-value
900  \s*
901  (?<v>
902  (?&value)
903  (?:\s*
904  , # Sub-vals 1..N
905  \s*
906  (?&value)
907  )*
908  )
909  )?
910  /x';
911  $valueregex = '/' . $defs . '(?&value)/x';
912 
913  if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
914  foreach ( $matches as $bits ) {
915  $key = strtolower( $bits['k'] );
916  if ( !isset( $bits['v'] ) ) {
917  $opts[$key] = true;
918  } else {
919  preg_match_all( $valueregex, $bits['v'], $vmatches );
920  $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
921  if ( count( $opts[$key] ) == 1 ) {
922  $opts[$key] = $opts[$key][0];
923  }
924  }
925  }
926  }
927  return $opts;
928  }
929 
930  private function cleanupOption( $opt ) {
931  if ( substr( $opt, 0, 1 ) == '"' ) {
932  return stripcslashes( substr( $opt, 1, -1 ) );
933  }
934 
935  if ( substr( $opt, 0, 2 ) == '[[' ) {
936  return substr( $opt, 2, -2 );
937  }
938 
939  if ( substr( $opt, 0, 1 ) == '{' ) {
940  return FormatJson::decode( $opt, true );
941  }
942  return $opt;
943  }
944 
954  public function perTestSetup( $test, $nextTeardown = null ) {
955  $teardown = [];
956 
957  $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
958  $teardown[] = $this->markSetupDone( 'perTestSetup' );
959 
960  $opts = $this->parseOptions( $test['options'] );
961  $config = $test['config'];
962 
963  // Find out values for some special options.
964  $langCode =
965  self::getOptionValue( 'language', $opts, 'en' );
966  $variant =
967  self::getOptionValue( 'variant', $opts, false );
968  $maxtoclevel =
969  self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
970  $linkHolderBatchSize =
971  self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
972 
973  $setup = [
974  'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
975  'wgLanguageCode' => $langCode,
976  'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
977  'wgNamespacesWithSubpages' => [ 0 => isset( $opts['subpage'] ) ],
978  'wgMaxTocLevel' => $maxtoclevel,
979  'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
980  'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
981  'wgDefaultLanguageVariant' => $variant,
982  'wgLinkHolderBatchSize' => $linkHolderBatchSize,
983  // Set as a JSON object like:
984  // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
985  'wgEnableMagicLinks' => self::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
986  + [ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
987  ];
988 
989  if ( $config ) {
990  $configLines = explode( "\n", $config );
991 
992  foreach ( $configLines as $line ) {
993  list( $var, $value ) = explode( '=', $line, 2 );
994  $setup[$var] = eval( "return $value;" );
995  }
996  }
997 
999  Hooks::run( 'ParserTestGlobals', [ &$setup ] );
1000 
1001  // Create tidy driver
1002  if ( isset( $opts['tidy'] ) ) {
1003  // Cache a driver instance
1004  if ( $this->tidyDriver === null ) {
1005  $this->tidyDriver = MWTidy::factory( $this->tidySupport->getConfig() );
1006  }
1007  $tidy = $this->tidyDriver;
1008  } else {
1009  $tidy = false;
1010  }
1011  MWTidy::setInstance( $tidy );
1012  $teardown[] = function () {
1014  };
1015 
1016  // Set content language. This invalidates the magic word cache and title services
1017  $lang = Language::factory( $langCode );
1018  $setup['wgContLang'] = $lang;
1019  $reset = function () {
1021  $this->resetTitleServices();
1022  };
1023  $setup[] = $reset;
1024  $teardown[] = $reset;
1025 
1026  // Make a user object with the same language
1027  $user = new User;
1028  $user->setOption( 'language', $langCode );
1029  $setup['wgLang'] = $lang;
1030 
1031  // We (re)set $wgThumbLimits to a single-element array above.
1032  $user->setOption( 'thumbsize', 0 );
1033 
1034  $setup['wgUser'] = $user;
1035 
1036  // And put both user and language into the context
1038  $context->setUser( $user );
1039  $context->setLanguage( $lang );
1040  $teardown[] = function () use ( $context ) {
1041  // Reset context to the restored globals
1042  $context->setUser( $GLOBALS['wgUser'] );
1043  $context->setLanguage( $GLOBALS['wgContLang'] );
1044  };
1045 
1046  $teardown[] = $this->executeSetupSnippets( $setup );
1047 
1048  return $this->createTeardownObject( $teardown, $nextTeardown );
1049  }
1050 
1056  private function listTables() {
1057  $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1058  'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
1059  'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1060  'site_stats', 'ipblocks', 'image', 'oldimage',
1061  'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1062  'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1063  'archive', 'user_groups', 'page_props', 'category'
1064  ];
1065 
1066  if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1067  array_push( $tables, 'searchindex' );
1068  }
1069 
1070  // Allow extensions to add to the list of tables to duplicate;
1071  // may be necessary if they hook into page save or other code
1072  // which will require them while running tests.
1073  Hooks::run( 'ParserTestTables', [ &$tables ] );
1074 
1075  return $tables;
1076  }
1077 
1078  public function setDatabase( IDatabase $db ) {
1079  $this->db = $db;
1080  $this->setupDone['setDatabase'] = true;
1081  }
1082 
1100  public function setupDatabase( $nextTeardown = null ) {
1102 
1103  $this->db = wfGetDB( DB_MASTER );
1104  $dbType = $this->db->getType();
1105 
1106  if ( $dbType == 'oracle' ) {
1107  $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase::ORA_DB_PREFIX ];
1108  } else {
1109  $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1110  }
1111  if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1112  throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1113  }
1114 
1115  $teardown = [];
1116 
1117  $teardown[] = $this->markSetupDone( 'setupDatabase' );
1118 
1119  # CREATE TEMPORARY TABLE breaks if there is more than one server
1120  if ( wfGetLB()->getServerCount() != 1 ) {
1121  $this->useTemporaryTables = false;
1122  }
1123 
1124  $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1125  $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1126 
1127  $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1128  $this->dbClone->useTemporaryTables( $temporary );
1129  $this->dbClone->cloneTableStructure();
1130 
1131  if ( $dbType == 'oracle' ) {
1132  $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1133  # Insert 0 user to prevent FK violations
1134 
1135  # Anonymous user
1136  $this->db->insert( 'user', [
1137  'user_id' => 0,
1138  'user_name' => 'Anonymous' ] );
1139  }
1140 
1141  $teardown[] = function () {
1142  $this->teardownDatabase();
1143  };
1144 
1145  // Wipe some DB query result caches on setup and teardown
1146  $reset = function () {
1147  LinkCache::singleton()->clear();
1148 
1149  // Clear the message cache
1150  MessageCache::singleton()->clear();
1151  };
1152  $reset();
1153  $teardown[] = $reset;
1154  return $this->createTeardownObject( $teardown, $nextTeardown );
1155  }
1156 
1165  public function setupUploads( $nextTeardown = null ) {
1166  $teardown = [];
1167 
1168  $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1169  $teardown[] = $this->markSetupDone( 'setupUploads' );
1170 
1171  // Create the files in the upload directory (or pretend to create them
1172  // in a MockFileBackend). Append teardown callback.
1173  $teardown[] = $this->setupUploadBackend();
1174 
1175  // Create a user
1176  $user = User::createNew( 'WikiSysop' );
1177 
1178  // Register the uploads in the database
1179 
1180  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1181  # note that the size/width/height/bits/etc of the file
1182  # are actually set by inspecting the file itself; the arguments
1183  # to recordUpload2 have no effect. That said, we try to make things
1184  # match up so it is less confusing to readers of the code & tests.
1185  $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1186  'size' => 7881,
1187  'width' => 1941,
1188  'height' => 220,
1189  'bits' => 8,
1190  'media_type' => MEDIATYPE_BITMAP,
1191  'mime' => 'image/jpeg',
1192  'metadata' => serialize( [] ),
1193  'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1194  'fileExists' => true
1195  ], $this->db->timestamp( '20010115123500' ), $user );
1196 
1197  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1198  # again, note that size/width/height below are ignored; see above.
1199  $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1200  'size' => 22589,
1201  'width' => 135,
1202  'height' => 135,
1203  'bits' => 8,
1204  'media_type' => MEDIATYPE_BITMAP,
1205  'mime' => 'image/png',
1206  'metadata' => serialize( [] ),
1207  'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1208  'fileExists' => true
1209  ], $this->db->timestamp( '20130225203040' ), $user );
1210 
1211  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1212  $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1213  'size' => 12345,
1214  'width' => 240,
1215  'height' => 180,
1216  'bits' => 0,
1217  'media_type' => MEDIATYPE_DRAWING,
1218  'mime' => 'image/svg+xml',
1219  'metadata' => serialize( [] ),
1220  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1221  'fileExists' => true
1222  ], $this->db->timestamp( '20010115123500' ), $user );
1223 
1224  # This image will be blacklisted in [[MediaWiki:Bad image list]]
1225  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1226  $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1227  'size' => 12345,
1228  'width' => 320,
1229  'height' => 240,
1230  'bits' => 24,
1231  'media_type' => MEDIATYPE_BITMAP,
1232  'mime' => 'image/jpeg',
1233  'metadata' => serialize( [] ),
1234  'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1235  'fileExists' => true
1236  ], $this->db->timestamp( '20010115123500' ), $user );
1237 
1238  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1239  $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1240  'size' => 12345,
1241  'width' => 320,
1242  'height' => 240,
1243  'bits' => 0,
1244  'media_type' => MEDIATYPE_VIDEO,
1245  'mime' => 'application/ogg',
1246  'metadata' => serialize( [] ),
1247  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1248  'fileExists' => true
1249  ], $this->db->timestamp( '20010115123500' ), $user );
1250 
1251  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1252  $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1253  'size' => 12345,
1254  'width' => 0,
1255  'height' => 0,
1256  'bits' => 0,
1257  'media_type' => MEDIATYPE_AUDIO,
1258  'mime' => 'application/ogg',
1259  'metadata' => serialize( [] ),
1260  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1261  'fileExists' => true
1262  ], $this->db->timestamp( '20010115123500' ), $user );
1263 
1264  # A DjVu file
1265  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1266  $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1267  'size' => 3249,
1268  'width' => 2480,
1269  'height' => 3508,
1270  'bits' => 0,
1271  'media_type' => MEDIATYPE_BITMAP,
1272  'mime' => 'image/vnd.djvu',
1273  'metadata' => '<?xml version="1.0" ?>
1274 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1275 <DjVuXML>
1276 <HEAD></HEAD>
1277 <BODY><OBJECT height="3508" width="2480">
1278 <PARAM name="DPI" value="300" />
1279 <PARAM name="GAMMA" value="2.2" />
1280 </OBJECT>
1281 <OBJECT height="3508" width="2480">
1282 <PARAM name="DPI" value="300" />
1283 <PARAM name="GAMMA" value="2.2" />
1284 </OBJECT>
1285 <OBJECT height="3508" width="2480">
1286 <PARAM name="DPI" value="300" />
1287 <PARAM name="GAMMA" value="2.2" />
1288 </OBJECT>
1289 <OBJECT height="3508" width="2480">
1290 <PARAM name="DPI" value="300" />
1291 <PARAM name="GAMMA" value="2.2" />
1292 </OBJECT>
1293 <OBJECT height="3508" width="2480">
1294 <PARAM name="DPI" value="300" />
1295 <PARAM name="GAMMA" value="2.2" />
1296 </OBJECT>
1297 </BODY>
1298 </DjVuXML>',
1299  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1300  'fileExists' => true
1301  ], $this->db->timestamp( '20010115123600' ), $user );
1302 
1303  return $this->createTeardownObject( $teardown, $nextTeardown );
1304  }
1305 
1312  private function teardownDatabase() {
1313  $this->checkSetupDone( 'setupDatabase' );
1314 
1315  $this->dbClone->destroy();
1316  $this->databaseSetupDone = false;
1317 
1318  if ( $this->useTemporaryTables ) {
1319  if ( $this->db->getType() == 'sqlite' ) {
1320  # Under SQLite the searchindex table is virtual and need
1321  # to be explicitly destroyed. See bug 29912
1322  # See also MediaWikiTestCase::destroyDB()
1323  wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1324  $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1325  }
1326  # Don't need to do anything
1327  return;
1328  }
1329 
1330  $tables = $this->listTables();
1331 
1332  foreach ( $tables as $table ) {
1333  if ( $this->db->getType() == 'oracle' ) {
1334  $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1335  } else {
1336  $this->db->query( "DROP TABLE `parsertest_$table`" );
1337  }
1338  }
1339 
1340  if ( $this->db->getType() == 'oracle' ) {
1341  $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1342  }
1343  }
1344 
1350  private function setupUploadBackend() {
1351  global $IP;
1352 
1353  $repo = RepoGroup::singleton()->getLocalRepo();
1354  $base = $repo->getZonePath( 'public' );
1355  $backend = $repo->getBackend();
1356  $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1357  $backend->store( [
1358  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1359  'dst' => "$base/3/3a/Foobar.jpg"
1360  ] );
1361  $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1362  $backend->store( [
1363  'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1364  'dst' => "$base/e/ea/Thumb.png"
1365  ] );
1366  $backend->prepare( [ 'dir' => "$base/0/09" ] );
1367  $backend->store( [
1368  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1369  'dst' => "$base/0/09/Bad.jpg"
1370  ] );
1371  $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1372  $backend->store( [
1373  'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1374  'dst' => "$base/5/5f/LoremIpsum.djvu"
1375  ] );
1376 
1377  // No helpful SVG file to copy, so make one ourselves
1378  $data = '<?xml version="1.0" encoding="utf-8"?>' .
1379  '<svg xmlns="http://www.w3.org/2000/svg"' .
1380  ' version="1.1" width="240" height="180"/>';
1381 
1382  $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1383  $backend->quickCreate( [
1384  'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1385  ] );
1386 
1387  return function () use ( $backend ) {
1388  if ( $backend instanceof MockFileBackend ) {
1389  // In memory backend, so dont bother cleaning them up.
1390  return;
1391  }
1392  $this->teardownUploadBackend();
1393  };
1394  }
1395 
1399  private function teardownUploadBackend() {
1400  if ( $this->keepUploads ) {
1401  return;
1402  }
1403 
1404  $repo = RepoGroup::singleton()->getLocalRepo();
1405  $public = $repo->getZonePath( 'public' );
1406 
1407  $this->deleteFiles(
1408  [
1409  "$public/3/3a/Foobar.jpg",
1410  "$public/e/ea/Thumb.png",
1411  "$public/0/09/Bad.jpg",
1412  "$public/5/5f/LoremIpsum.djvu",
1413  "$public/f/ff/Foobar.svg",
1414  "$public/0/00/Video.ogv",
1415  "$public/4/41/Audio.oga",
1416  ]
1417  );
1418  }
1419 
1424  private function deleteFiles( $files ) {
1425  // Delete the files
1426  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
1427  foreach ( $files as $file ) {
1428  $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1429  }
1430 
1431  // Delete the parent directories
1432  foreach ( $files as $file ) {
1433  $tmp = FileBackend::parentStoragePath( $file );
1434  while ( $tmp ) {
1435  if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1436  break;
1437  }
1438  $tmp = FileBackend::parentStoragePath( $tmp );
1439  }
1440  }
1441  }
1442 
1448  public function addArticles( $articles ) {
1450  $setup = [];
1451  $teardown = [];
1452 
1453  // Be sure ParserTestRunner::addArticle has correct language set,
1454  // so that system messages get into the right language cache
1455  if ( $wgContLang->getCode() !== 'en' ) {
1456  $setup['wgLanguageCode'] = 'en';
1457  $setup['wgContLang'] = Language::factory( 'en' );
1458  }
1459 
1460  // Add special namespaces, in case that hasn't been done by staticSetup() yet
1461  $this->appendNamespaceSetup( $setup, $teardown );
1462 
1463  // wgCapitalLinks obviously needs initialisation
1464  $setup['wgCapitalLinks'] = true;
1465 
1466  $teardown[] = $this->executeSetupSnippets( $setup );
1467 
1468  foreach ( $articles as $info ) {
1469  $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1470  }
1471 
1472  // Wipe WANObjectCache process cache, which is invalidated by article insertion
1473  // due to T144706
1474  ObjectCache::getMainWANInstance()->clearProcessCache();
1475 
1476  $this->executeSetupSnippets( $teardown );
1477  }
1478 
1488  private function addArticle( $name, $text, $file, $line ) {
1489  $text = self::chomp( $text );
1490  $name = self::chomp( $name );
1491 
1493  wfDebug( __METHOD__ . ": adding $name" );
1494 
1495  if ( is_null( $title ) ) {
1496  throw new MWException( "invalid title '$name' at $file:$line\n" );
1497  }
1498 
1500  $page->loadPageData( 'fromdbmaster' );
1501 
1502  if ( $page->exists() ) {
1503  throw new MWException( "duplicate article '$name' at $file:$line\n" );
1504  }
1505 
1506  $status = $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1507  if ( !$status->isOK() ) {
1508  throw new MWException( $status->getWikiText( false, false, 'en' ) );
1509  }
1510 
1511  // The RepoGroup cache is invalidated by the creation of file redirects
1512  if ( $title->inNamespace( NS_FILE ) ) {
1513  RepoGroup::singleton()->clearCache( $title );
1514  }
1515  }
1516 
1523  public function requireHook( $name ) {
1524  global $wgParser;
1525 
1526  $wgParser->firstCallInit(); // make sure hooks are loaded.
1527  if ( isset( $wgParser->mTagHooks[$name] ) ) {
1528  return true;
1529  } else {
1530  $this->recorder->warning( " This test suite requires the '$name' hook " .
1531  "extension, skipping." );
1532  return false;
1533  }
1534  }
1535 
1542  public function requireFunctionHook( $name ) {
1543  global $wgParser;
1544 
1545  $wgParser->firstCallInit(); // make sure hooks are loaded.
1546 
1547  if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1548  return true;
1549  } else {
1550  $this->recorder->warning( " This test suite requires the '$name' function " .
1551  "hook extension, skipping." );
1552  return false;
1553  }
1554  }
1555 
1562  public function requireTransparentHook( $name ) {
1563  global $wgParser;
1564 
1565  $wgParser->firstCallInit(); // make sure hooks are loaded.
1566 
1567  if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1568  return true;
1569  } else {
1570  $this->recorder->warning( " This test suite requires the '$name' transparent " .
1571  "hook extension, skipping.\n" );
1572  return false;
1573  }
1574  }
1575 
1580  static function getFakeTimestamp( &$parser, &$ts ) {
1581  $ts = 123; // parsed as '1970-01-01T00:02:03Z'
1582  return true;
1583  }
1584 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:115
const DB_PREFIX
Table name prefixes.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
static getMainWANInstance()
Get the main WAN cache object.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:802
Database error base class.
Definition: DBError.php:26
runTest($test)
Run a given wikitext input through a freshly-constructed wiki parser, and compare the output against ...
addArticle($name, $text, $file, $line)
Insert a temporary test article.
warning($message)
Show a warning to the user.
$context
Definition: load.php:50
Class simulating a backend store.
$IP
Definition: WebStart.php:58
static factory(array $config)
Create a new Tidy driver object from configuration.
Definition: MWTidy.php:124
static getFakeTimestamp(&$parser, &$ts)
The ParserGetVariableValueTs hook, used to make sure time-related parser functions give a persistent ...
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:2102
$wgParser
Definition: Setup.php:821
setTOCEnabled($flag)
requireTransparentHook($name)
Check if a transparent tag hook is installed.
if(!isset($args[0])) $lang
static destroyInstance()
Destroy the singleton instance.
$wgFileBackends
File backend structure configuration.
requireHook($name)
Check if a hook is installed.
static destroySingleton()
Destroy the singleton instance, so that a new one will be created next time singleton() is called...
Definition: RepoGroup.php:73
setupUploadBackend()
Upload test files to the backend created by createRepoGroup().
teardownUploadBackend()
Remove the dummy uploads directory.
resetTitleServices()
Reset the Title-related services that need resetting for each test.
static chomp($s)
Remove last character if it is a newline utility.
$value
teardownDatabase()
Helper for database teardown, called from the teardown closure.
parseOptions($instring)
Given the options string, return an associative array of options.
$files
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
string null $fileBackendName
The name of the file backend to use, or null to use MockFileBackend.
static createNew($name, $params=[])
Add a user to the database, return the user object.
Definition: User.php:3944
createRepoGroup()
Create a RepoGroup object appropriate for the current configuration.
const MEDIATYPE_DRAWING
Definition: defines.php:30
staticSetup($nextTeardown=null)
Do any setup which can be done once for all tests, independent of test options, except for database s...
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
setDatabase(IDatabase $db)
wfLocalFile($title)
Get an object referring to a locally registered file.
const MEDIATYPE_BITMAP
Definition: defines.php:28
magic word & $parser
Definition: hooks.txt:2487
const DB_MASTER
Definition: defines.php:23
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist & $tables
Definition: hooks.txt:1007
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1934
Database $db
Our connection to the database.
static BagOStuff[] $instances
Map of (id => BagOStuff)
Definition: ObjectCache.php:82
static destroySingleton()
Destroy the current singleton instance.
Definition: MWTidy.php:160
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:1936
const MEDIATYPE_VIDEO
Definition: defines.php:35
perTestSetup($test, $nextTeardown=null)
Do any required setup which is dependent on test options.
createTeardownObject($teardown, $nextTeardown)
Take a setup array in the same format as the one given to executeSetupSnippets(), and return a Scoped...
static register($name, $callback)
Attach an event handler to a given hook.
Definition: Hooks.php:49
TidySupport $tidySupport
wfGetLB($wiki=false)
Get a load balancer object.
wfTempDir()
Tries to get the system directory for temporary files.
static getMain()
Static methods.
static singleton()
Get an instance of this class.
Definition: LinkCache.php:64
static clear($name)
Clears hooks registered via Hooks::register().
Definition: Hooks.php:66
$GLOBALS['IP']
TidyDriverBase $tidyDriver
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1046
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
meetsRequirements($requirements)
Determine whether the current parser has the hooks registered in it that are required by a file read ...
static clearCache()
Clear the self::$mObjects variable For use in parser tests.
Definition: MagicWord.php:319
static destroySingletons()
Destroy the singleton instances.
setupDatabase($nextTeardown=null)
Set up temporary DB tables.
runTestsFromFiles($filenames)
Run a series of tests listed in the given text files.
isSetupDone($funcName)
Determine whether a particular setup function has been run.
getParser($preprocessor=null)
Get a Parser object.
runTests($testFileInfo)
Run the tests from a single file.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
__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:62
static makeContent($text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Replace all media handlers with a mock.
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2159
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
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:1180
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:2889
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
string $regex
A complete regex for filtering tests.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1046
Initialize and detect the tidy support.
Definition: TidySupport.php:26
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.
const MEDIATYPE_AUDIO
Definition: defines.php:32
markSetupDone($funcName)
Set a setupDone flag to indicate that setup has been done, and return the teardown closure...
const EDIT_NEW
Definition: Defines.php:146
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1046
$line
Definition: cdb.php:59
$wgDBprefix
Table name prefix.
checkSetupDone($funcName, $funcName2=null)
Ensure a given setup stage has been done, throw an exception if it has not.
Prioritized list of file repositories.
Definition: RepoGroup.php:29
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1046
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition: hooks.txt:802
setupUploads($nextTeardown=null)
Add data about uploads to the new test DB, and set up the upload directory.
$wgObjectCaches
Advanced object cache configuration.
requireFunctionHook($name)
Check if a function hook is installed.
appendNamespaceSetup(&$setup, &$teardown)
static setSingleton($instance)
Set the singleton instance to a given object Used by extensions which hook into the Repo chain...
Definition: RepoGroup.php:85
serialize()
Definition: ApiMessage.php:94
static getOptionValue($key, $opts, $default)
Use a regex to find out the value of an option.
TestRecorder $recorder
static decode($value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:187
addArticles($articles)
Add articles to the test DB.
Class for a file system (FS) based file backend.
listTables()
List of temporary tables to create, without prefix.
static factory($code)
Get a cached or new language object for a given language code.
Definition: Language.php:181
deleteFiles($files)
Delete the specified files and their parent directories.
Represent the result of a parser test.
static read($file, array $options=[])
static getCanonicalNamespaces($rebuild=false)
Returns array of all defined namespaces with their canonical (English) names.
CloneDatabase $dbClone
Database clone helper.
string null $uploadDir
The upload directory, or null to not set up an upload directory.
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:511
wfGetCaller($level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
static setInstance($instance)
Set the driver to be used.
Definition: MWTidy.php:153
static singleton()
Get the signleton instance of this class.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:34
const CACHE_DB
Definition: Defines.php:95
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2491
$matches
static parentStoragePath($storagePath)
Get the parent storage directory of a storage path.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300