MediaWiki  1.33.0
ParserTestRunner.php
Go to the documentation of this file.
1 <?php
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\TestingAccessWrapper;
33 
37 class ParserTestRunner {
38 
45  private static $coreTestFiles = [
46  'parserTests.txt',
47  'extraParserTests.txt',
48  ];
49 
53  private $useTemporaryTables = true;
54 
58  private $setupDone = [
59  'staticSetup' => false,
60  'perTestSetup' => false,
61  'setupDatabase' => false,
62  'setDatabase' => false,
63  'setupUploads' => false,
64  ];
65 
70  private $db;
71 
76  private $dbClone;
77 
81  private $tidyDriver = null;
82 
86  private $recorder;
87 
93  private $uploadDir = null;
94 
99  private $fileBackendName;
100 
105  private $regex;
106 
112  private $normalizationFunctions = [];
113 
118  private $runDisabled;
119 
124  private $disableSaveParse;
125 
130  private $keepUploads;
131 
136  public function __construct( TestRecorder $recorder, $options = [] ) {
137  $this->recorder = $recorder;
138 
139  if ( isset( $options['norm'] ) ) {
140  foreach ( $options['norm'] as $func ) {
141  if ( in_array( $func, [ 'removeTbody', 'trimWhitespace' ] ) ) {
142  $this->normalizationFunctions[] = $func;
143  } else {
144  $this->recorder->warning(
145  "Warning: unknown normalization option \"$func\"\n" );
146  }
147  }
148  }
149 
150  if ( isset( $options['regex'] ) && $options['regex'] !== false ) {
151  $this->regex = $options['regex'];
152  } else {
153  # Matches anything
154  $this->regex = '//';
155  }
156 
157  $this->keepUploads = !empty( $options['keep-uploads'] );
158 
159  $this->fileBackendName = $options['file-backend'] ?? false;
160 
161  $this->runDisabled = !empty( $options['run-disabled'] );
162 
163  $this->disableSaveParse = !empty( $options['disable-save-parse'] );
164 
165  if ( isset( $options['upload-dir'] ) ) {
166  $this->uploadDir = $options['upload-dir'];
167  }
168  }
169 
175  public static function getParserTestFiles() {
176  global $wgParserTestFiles;
177 
178  // Add core test files
179  $files = array_map( function ( $item ) {
180  return __DIR__ . "/$item";
181  }, self::$coreTestFiles );
182 
183  // Plus legacy global files
184  $files = array_merge( $files, $wgParserTestFiles );
185 
186  // Auto-discover extension parser tests
187  $registry = ExtensionRegistry::getInstance();
188  foreach ( $registry->getAllThings() as $info ) {
189  $dir = dirname( $info['path'] ) . '/tests/parser';
190  if ( !file_exists( $dir ) ) {
191  continue;
192  }
193  $counter = 1;
194  $dirIterator = new RecursiveIteratorIterator(
195  new RecursiveDirectoryIterator( $dir )
196  );
197  foreach ( $dirIterator as $fileInfo ) {
199  if ( substr( $fileInfo->getFilename(), -4 ) === '.txt' ) {
200  $name = $info['name'] . $counter;
201  while ( isset( $files[$name] ) ) {
202  $name = $info['name'] . '_' . $counter++;
203  }
204  $files[$name] = $fileInfo->getPathname();
205  }
206  }
207  }
208 
209  return array_unique( $files );
210  }
211 
212  public function getRecorder() {
213  return $this->recorder;
214  }
215 
235  public function staticSetup( $nextTeardown = null ) {
236  // A note on coding style:
237 
238  // The general idea here is to keep setup code together with
239  // corresponding teardown code, in a fine-grained manner. We have two
240  // arrays: $setup and $teardown. The code snippets in the $setup array
241  // are executed at the end of the method, before it returns, and the
242  // code snippets in the $teardown array are executed in reverse order
243  // when the Wikimedia\ScopedCallback object is consumed.
244 
245  // Because it is a common operation to save, set and restore global
246  // variables, we have an additional convention: when the array key of
247  // $setup is a string, the string is taken to be the name of the global
248  // variable, and the element value is taken to be the desired new value.
249 
250  // It's acceptable to just do the setup immediately, instead of adding
251  // a closure to $setup, except when the setup action depends on global
252  // variable initialisation being done first. In this case, you have to
253  // append a closure to $setup after the global variable is appended.
254 
255  // When you add to setup functions in this class, please keep associated
256  // setup and teardown actions together in the source code, and please
257  // add comments explaining why the setup action is necessary.
258 
259  $setup = [];
260  $teardown = [];
261 
262  $teardown[] = $this->markSetupDone( 'staticSetup' );
263 
264  // Some settings which influence HTML output
265  $setup['wgSitename'] = 'MediaWiki';
266  $setup['wgServer'] = 'http://example.org';
267  $setup['wgServerName'] = 'example.org';
268  $setup['wgScriptPath'] = '';
269  $setup['wgScript'] = '/index.php';
270  $setup['wgResourceBasePath'] = '';
271  $setup['wgStylePath'] = '/skins';
272  $setup['wgExtensionAssetsPath'] = '/extensions';
273  $setup['wgArticlePath'] = '/wiki/$1';
274  $setup['wgActionPaths'] = [];
275  $setup['wgVariantArticlePath'] = false;
276  $setup['wgUploadNavigationUrl'] = false;
277  $setup['wgCapitalLinks'] = true;
278  $setup['wgNoFollowLinks'] = true;
279  $setup['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
280  $setup['wgExternalLinkTarget'] = false;
281  $setup['wgLocaltimezone'] = 'UTC';
282  $setup['wgHtml5'] = true;
283  $setup['wgDisableLangConversion'] = false;
284  $setup['wgDisableTitleConversion'] = false;
285 
286  // "extra language links"
287  // see https://gerrit.wikimedia.org/r/111390
288  $setup['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
289 
290  // All FileRepo changes should be done here by injecting services,
291  // there should be no need to change global variables.
292  RepoGroup::setSingleton( $this->createRepoGroup() );
293  $teardown[] = function () {
295  };
296 
297  // Set up null lock managers
298  $setup['wgLockManagers'] = [ [
299  'name' => 'fsLockManager',
300  'class' => NullLockManager::class,
301  ], [
302  'name' => 'nullLockManager',
303  'class' => NullLockManager::class,
304  ] ];
305  $reset = function () {
307  };
308  $setup[] = $reset;
309  $teardown[] = $reset;
310 
311  // This allows article insertion into the prefixed DB
312  $setup['wgDefaultExternalStore'] = false;
313 
314  // This might slightly reduce memory usage
315  $setup['wgAdaptiveMessageCache'] = true;
316 
317  // This is essential and overrides disabling of database messages in TestSetup
318  $setup['wgUseDatabaseMessages'] = true;
319  $reset = function () {
321  };
322  $setup[] = $reset;
323  $teardown[] = $reset;
324 
325  // It's not necessary to actually convert any files
326  $setup['wgSVGConverter'] = 'null';
327  $setup['wgSVGConverters'] = [ 'null' => 'echo "1">$output' ];
328 
329  // Fake constant timestamp
330  Hooks::register( 'ParserGetVariableValueTs', function ( &$parser, &$ts ) {
331  $ts = $this->getFakeTimestamp();
332  return true;
333  } );
334  $teardown[] = function () {
335  Hooks::clear( 'ParserGetVariableValueTs' );
336  };
337 
338  $this->appendNamespaceSetup( $setup, $teardown );
339 
340  // Set up interwikis and append teardown function
341  $teardown[] = $this->setupInterwikis();
342 
343  // This affects title normalization in links. It invalidates
344  // MediaWikiTitleCodec objects.
345  $setup['wgLocalInterwikis'] = [ 'local', 'mi' ];
346  $reset = function () {
347  $this->resetTitleServices();
348  };
349  $setup[] = $reset;
350  $teardown[] = $reset;
351 
352  // Set up a mock MediaHandlerFactory
353  MediaWikiServices::getInstance()->disableService( 'MediaHandlerFactory' );
354  MediaWikiServices::getInstance()->redefineService(
355  'MediaHandlerFactory',
356  function ( MediaWikiServices $services ) {
357  $handlers = $services->getMainConfig()->get( 'ParserTestMediaHandlers' );
358  return new MediaHandlerFactory( $handlers );
359  }
360  );
361  $teardown[] = function () {
362  MediaWikiServices::getInstance()->resetServiceForTesting( 'MediaHandlerFactory' );
363  };
364 
365  // SqlBagOStuff broke when using temporary tables on r40209 (T17892).
366  // It seems to have been fixed since (r55079?), but regressed at some point before r85701.
367  // This works around it for now...
368  global $wgObjectCaches;
369  $setup['wgObjectCaches'] = [ CACHE_DB => $wgObjectCaches['hash'] ] + $wgObjectCaches;
370  if ( isset( ObjectCache::$instances[CACHE_DB] ) ) {
371  $savedCache = ObjectCache::$instances[CACHE_DB];
373  $teardown[] = function () use ( $savedCache ) {
374  ObjectCache::$instances[CACHE_DB] = $savedCache;
375  };
376  }
377 
378  $teardown[] = $this->executeSetupSnippets( $setup );
379 
380  // Schedule teardown snippets in reverse order
381  return $this->createTeardownObject( $teardown, $nextTeardown );
382  }
383 
384  private function appendNamespaceSetup( &$setup, &$teardown ) {
385  // Add a namespace shadowing a interwiki link, to test
386  // proper precedence when resolving links. (T53680)
387  $setup['wgExtraNamespaces'] = [
388  100 => 'MemoryAlpha',
389  101 => 'MemoryAlpha_talk'
390  ];
391  // Changing wgExtraNamespaces invalidates caches in MWNamespace and
392  // any live Language object, both on setup and teardown
393  $reset = function () {
395  MediaWikiServices::getInstance()->getContentLanguage()->resetNamespaces();
396  };
397  $setup[] = $reset;
398  $teardown[] = $reset;
399  }
400 
405  protected function createRepoGroup() {
406  if ( $this->uploadDir ) {
407  if ( $this->fileBackendName ) {
408  throw new MWException( 'You cannot specify both use-filebackend and upload-dir' );
409  }
410  $backend = new FSFileBackend( [
411  'name' => 'local-backend',
412  'wikiId' => wfWikiID(),
413  'basePath' => $this->uploadDir,
414  'tmpDirectory' => wfTempDir()
415  ] );
416  } elseif ( $this->fileBackendName ) {
417  global $wgFileBackends;
418  $name = $this->fileBackendName;
419  $useConfig = false;
420  foreach ( $wgFileBackends as $conf ) {
421  if ( $conf['name'] === $name ) {
422  $useConfig = $conf;
423  }
424  }
425  if ( $useConfig === false ) {
426  throw new MWException( "Unable to find file backend \"$name\"" );
427  }
428  $useConfig['name'] = 'local-backend'; // swap name
429  unset( $useConfig['lockManager'] );
430  unset( $useConfig['fileJournal'] );
431  $class = $useConfig['class'];
432  $backend = new $class( $useConfig );
433  } else {
434  # Replace with a mock. We do not care about generating real
435  # files on the filesystem, just need to expose the file
436  # informations.
437  $backend = new MockFileBackend( [
438  'name' => 'local-backend',
439  'wikiId' => wfWikiID()
440  ] );
441  }
442 
443  return new RepoGroup(
444  [
445  'class' => MockLocalRepo::class,
446  'name' => 'local',
447  'url' => 'http://example.com/images',
448  'hashLevels' => 2,
449  'transformVia404' => false,
450  'backend' => $backend
451  ],
452  []
453  );
454  }
455 
469  protected function executeSetupSnippets( $setup ) {
470  $saved = [];
471  foreach ( $setup as $name => $value ) {
472  if ( is_int( $name ) ) {
473  $value();
474  } else {
475  $saved[$name] = $GLOBALS[$name] ?? null;
476  $GLOBALS[$name] = $value;
477  }
478  }
479  return function () use ( $saved ) {
480  $this->executeSetupSnippets( $saved );
481  };
482  }
483 
496  protected function createTeardownObject( $teardown, $nextTeardown = null ) {
497  return new ScopedCallback( function () use ( $teardown, $nextTeardown ) {
498  // Schedule teardown snippets in reverse order
499  $teardown = array_reverse( $teardown );
500 
501  $this->executeSetupSnippets( $teardown );
502  if ( $nextTeardown ) {
503  ScopedCallback::consume( $nextTeardown );
504  }
505  } );
506  }
507 
515  protected function markSetupDone( $funcName ) {
516  if ( $this->setupDone[$funcName] ) {
517  throw new MWException( "$funcName is already done" );
518  }
519  $this->setupDone[$funcName] = true;
520  return function () use ( $funcName ) {
521  $this->setupDone[$funcName] = false;
522  };
523  }
524 
531  protected function checkSetupDone( $funcName, $funcName2 = null ) {
532  if ( !$this->setupDone[$funcName]
533  && ( $funcName === null || !$this->setupDone[$funcName2] )
534  ) {
535  throw new MWException( "$funcName must be called before calling " .
536  wfGetCaller() );
537  }
538  }
539 
546  public function isSetupDone( $funcName ) {
547  return $this->setupDone[$funcName] ?? false;
548  }
549 
561  private function setupInterwikis() {
562  # Hack: insert a few Wikipedia in-project interwiki prefixes,
563  # for testing inter-language links
564  Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
565  static $testInterwikis = [
566  'local' => [
567  'iw_url' => 'http://doesnt.matter.org/$1',
568  'iw_api' => '',
569  'iw_wikiid' => '',
570  'iw_local' => 0 ],
571  'wikipedia' => [
572  'iw_url' => 'http://en.wikipedia.org/wiki/$1',
573  'iw_api' => '',
574  'iw_wikiid' => '',
575  'iw_local' => 0 ],
576  'meatball' => [
577  'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
578  'iw_api' => '',
579  'iw_wikiid' => '',
580  'iw_local' => 0 ],
581  'memoryalpha' => [
582  'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
583  'iw_api' => '',
584  'iw_wikiid' => '',
585  'iw_local' => 0 ],
586  'zh' => [
587  'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
588  'iw_api' => '',
589  'iw_wikiid' => '',
590  'iw_local' => 1 ],
591  'es' => [
592  'iw_url' => 'http://es.wikipedia.org/wiki/$1',
593  'iw_api' => '',
594  'iw_wikiid' => '',
595  'iw_local' => 1 ],
596  'fr' => [
597  'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
598  'iw_api' => '',
599  'iw_wikiid' => '',
600  'iw_local' => 1 ],
601  'ru' => [
602  'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
603  'iw_api' => '',
604  'iw_wikiid' => '',
605  'iw_local' => 1 ],
606  'mi' => [
607  'iw_url' => 'http://mi.wikipedia.org/wiki/$1',
608  'iw_api' => '',
609  'iw_wikiid' => '',
610  'iw_local' => 1 ],
611  'mul' => [
612  'iw_url' => 'http://wikisource.org/wiki/$1',
613  'iw_api' => '',
614  'iw_wikiid' => '',
615  'iw_local' => 1 ],
616  ];
617  if ( array_key_exists( $prefix, $testInterwikis ) ) {
618  $iwData = $testInterwikis[$prefix];
619  }
620 
621  // We only want to rely on the above fixtures
622  return false;
623  } );// hooks::register
624 
625  // Reset the service in case any other tests already cached some prefixes.
626  MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
627 
628  return function () {
629  // Tear down
630  Hooks::clear( 'InterwikiLoadPrefix' );
631  MediaWikiServices::getInstance()->resetServiceForTesting( 'InterwikiLookup' );
632  };
633  }
634 
639  private function resetTitleServices() {
640  $services = MediaWikiServices::getInstance();
641  $services->resetServiceForTesting( 'TitleFormatter' );
642  $services->resetServiceForTesting( 'TitleParser' );
643  $services->resetServiceForTesting( '_MediaWikiTitleCodec' );
644  $services->resetServiceForTesting( 'LinkRenderer' );
645  $services->resetServiceForTesting( 'LinkRendererFactory' );
646  }
647 
653  public static function chomp( $s ) {
654  if ( substr( $s, -1 ) === "\n" ) {
655  return substr( $s, 0, -1 );
656  } else {
657  return $s;
658  }
659  }
660 
674  public function runTestsFromFiles( $filenames ) {
675  $ok = false;
676 
677  $teardownGuard = $this->staticSetup();
678  $teardownGuard = $this->setupDatabase( $teardownGuard );
679  $teardownGuard = $this->setupUploads( $teardownGuard );
680 
681  $this->recorder->start();
682  try {
683  $ok = true;
684 
685  foreach ( $filenames as $filename ) {
686  $testFileInfo = TestFileReader::read( $filename, [
687  'runDisabled' => $this->runDisabled,
688  'regex' => $this->regex ] );
689 
690  // Don't start the suite if there are no enabled tests in the file
691  if ( !$testFileInfo['tests'] ) {
692  continue;
693  }
694 
695  $this->recorder->startSuite( $filename );
696  $ok = $this->runTests( $testFileInfo ) && $ok;
697  $this->recorder->endSuite( $filename );
698  }
699 
700  $this->recorder->report();
701  } catch ( DBError $e ) {
702  $this->recorder->warning( $e->getMessage() );
703  }
704  $this->recorder->end();
705 
706  ScopedCallback::consume( $teardownGuard );
707 
708  return $ok;
709  }
710 
717  public function meetsRequirements( $requirements ) {
718  foreach ( $requirements as $requirement ) {
719  switch ( $requirement['type'] ) {
720  case 'hook':
721  $ok = $this->requireHook( $requirement['name'] );
722  break;
723  case 'functionHook':
724  $ok = $this->requireFunctionHook( $requirement['name'] );
725  break;
726  case 'transparentHook':
727  $ok = $this->requireTransparentHook( $requirement['name'] );
728  break;
729  }
730  if ( !$ok ) {
731  return false;
732  }
733  }
734  return true;
735  }
736 
744  public function runTests( $testFileInfo ) {
745  $ok = true;
746 
747  $this->checkSetupDone( 'staticSetup' );
748 
749  // Don't add articles from the file if there are no enabled tests from the file
750  if ( !$testFileInfo['tests'] ) {
751  return true;
752  }
753 
754  // If any requirements are not met, mark all tests from the file as skipped
755  if ( !$this->meetsRequirements( $testFileInfo['requirements'] ) ) {
756  foreach ( $testFileInfo['tests'] as $test ) {
757  $this->recorder->startTest( $test );
758  $this->recorder->skipped( $test, 'required extension not enabled' );
759  }
760  return true;
761  }
762 
763  // Add articles
764  $this->addArticles( $testFileInfo['articles'] );
765 
766  // Run tests
767  foreach ( $testFileInfo['tests'] as $test ) {
768  $this->recorder->startTest( $test );
769  $result =
770  $this->runTest( $test );
771  if ( $result !== false ) {
772  $ok = $ok && $result->isSuccess();
773  $this->recorder->record( $test, $result );
774  }
775  }
776 
777  return $ok;
778  }
779 
786  function getParser( $preprocessor = null ) {
787  global $wgParserConf;
788 
789  $class = $wgParserConf['class'];
790  $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
792 
793  return $parser;
794  }
795 
813  public function runTest( $test ) {
814  wfDebug( __METHOD__ . ": running {$test['desc']}" );
815  $opts = $this->parseOptions( $test['options'] );
816  $teardownGuard = $this->perTestSetup( $test );
817 
819  $user = $context->getUser();
821  $options->setTimestamp( $this->getFakeTimestamp() );
822 
823  if ( isset( $opts['tidy'] ) ) {
824  $options->setTidy( true );
825  }
826 
827  if ( isset( $opts['title'] ) ) {
828  $titleText = $opts['title'];
829  } else {
830  $titleText = 'Parser test';
831  }
832 
833  if ( isset( $opts['maxincludesize'] ) ) {
834  $options->setMaxIncludeSize( $opts['maxincludesize'] );
835  }
836  if ( isset( $opts['maxtemplatedepth'] ) ) {
837  $options->setMaxTemplateDepth( $opts['maxtemplatedepth'] );
838  }
839 
840  $local = isset( $opts['local'] );
841  $preprocessor = $opts['preprocessor'] ?? null;
842  $parser = $this->getParser( $preprocessor );
843  $title = Title::newFromText( $titleText );
844 
845  if ( isset( $opts['styletag'] ) ) {
846  // For testing the behavior of <style> (including those deduplicated
847  // into <link> tags), add tag hooks to allow them to be generated.
848  $parser->setHook( 'style', function ( $content, $attributes, $parser ) {
849  $marker = Parser::MARKER_PREFIX . '-style-' . md5( $content ) . Parser::MARKER_SUFFIX;
850  $parser->mStripState->addNoWiki( $marker, $content );
851  return Html::inlineStyle( $marker, 'all', $attributes );
852  } );
853  $parser->setHook( 'link', function ( $content, $attributes, $parser ) {
854  return Html::element( 'link', $attributes );
855  } );
856  }
857 
858  if ( isset( $opts['pst'] ) ) {
859  $out = $parser->preSaveTransform( $test['input'], $title, $user, $options );
860  $output = $parser->getOutput();
861  } elseif ( isset( $opts['msg'] ) ) {
862  $out = $parser->transformMsg( $test['input'], $options, $title );
863  } elseif ( isset( $opts['section'] ) ) {
864  $section = $opts['section'];
865  $out = $parser->getSection( $test['input'], $section );
866  } elseif ( isset( $opts['replace'] ) ) {
867  $section = $opts['replace'][0];
868  $replace = $opts['replace'][1];
869  $out = $parser->replaceSection( $test['input'], $section, $replace );
870  } elseif ( isset( $opts['comment'] ) ) {
871  $out = Linker::formatComment( $test['input'], $title, $local );
872  } elseif ( isset( $opts['preload'] ) ) {
873  $out = $parser->getPreloadText( $test['input'], $title, $options );
874  } else {
875  $output = $parser->parse( $test['input'], $title, $options, true, true, 1337 );
876  $out = $output->getText( [
877  'allowTOC' => !isset( $opts['notoc'] ),
878  'unwrap' => !isset( $opts['wrap'] ),
879  ] );
880  if ( isset( $opts['tidy'] ) ) {
881  $out = preg_replace( '/\s+$/', '', $out );
882  }
883 
884  if ( isset( $opts['showtitle'] ) ) {
885  if ( $output->getTitleText() ) {
886  $title = $output->getTitleText();
887  }
888 
889  $out = "$title\n$out";
890  }
891 
892  if ( isset( $opts['showindicators'] ) ) {
893  $indicators = '';
894  foreach ( $output->getIndicators() as $id => $content ) {
895  $indicators .= "$id=$content\n";
896  }
897  $out = $indicators . $out;
898  }
899 
900  if ( isset( $opts['ill'] ) ) {
901  $out = implode( ' ', $output->getLanguageLinks() );
902  } elseif ( isset( $opts['cat'] ) ) {
903  $out = '';
904  foreach ( $output->getCategories() as $name => $sortkey ) {
905  if ( $out !== '' ) {
906  $out .= "\n";
907  }
908  $out .= "cat=$name sort=$sortkey";
909  }
910  }
911  }
912 
913  if ( isset( $output ) && isset( $opts['showflags'] ) ) {
914  $actualFlags = array_keys( TestingAccessWrapper::newFromObject( $output )->mFlags );
915  sort( $actualFlags );
916  $out .= "\nflags=" . implode( ', ', $actualFlags );
917  }
918 
919  ScopedCallback::consume( $teardownGuard );
920 
921  $expected = $test['result'];
922  if ( count( $this->normalizationFunctions ) ) {
924  $test['expected'], $this->normalizationFunctions );
925  $out = ParserTestResultNormalizer::normalize( $out, $this->normalizationFunctions );
926  }
927 
928  $testResult = new ParserTestResult( $test, $expected, $out );
929  return $testResult;
930  }
931 
939  private static function getOptionValue( $key, $opts, $default ) {
940  $key = strtolower( $key );
941  return $opts[$key] ?? $default;
942  }
943 
951  private function parseOptions( $instring ) {
952  $opts = [];
953  // foo
954  // foo=bar
955  // foo="bar baz"
956  // foo=[[bar baz]]
957  // foo=bar,"baz quux"
958  // foo={...json...}
959  $defs = '(?(DEFINE)
960  (?<qstr> # Quoted string
961  "
962  (?:[^\\\\"] | \\\\.)*
963  "
964  )
965  (?<json>
966  \{ # Open bracket
967  (?:
968  [^"{}] | # Not a quoted string or object, or
969  (?&qstr) | # A quoted string, or
970  (?&json) # A json object (recursively)
971  )*
972  \} # Close bracket
973  )
974  (?<value>
975  (?:
976  (?&qstr) # Quoted val
977  |
978  \[\[
979  [^]]* # Link target
980  \]\]
981  |
982  [\w-]+ # Plain word
983  |
984  (?&json) # JSON object
985  )
986  )
987  )';
988  $regex = '/' . $defs . '\b
989  (?<k>[\w-]+) # Key
990  \b
991  (?:\s*
992  = # First sub-value
993  \s*
994  (?<v>
995  (?&value)
996  (?:\s*
997  , # Sub-vals 1..N
998  \s*
999  (?&value)
1000  )*
1001  )
1002  )?
1003  /x';
1004  $valueregex = '/' . $defs . '(?&value)/x';
1005 
1006  if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
1007  foreach ( $matches as $bits ) {
1008  $key = strtolower( $bits['k'] );
1009  if ( !isset( $bits['v'] ) ) {
1010  $opts[$key] = true;
1011  } else {
1012  preg_match_all( $valueregex, $bits['v'], $vmatches );
1013  $opts[$key] = array_map( [ $this, 'cleanupOption' ], $vmatches[0] );
1014  if ( count( $opts[$key] ) == 1 ) {
1015  $opts[$key] = $opts[$key][0];
1016  }
1017  }
1018  }
1019  }
1020  return $opts;
1021  }
1022 
1023  private function cleanupOption( $opt ) {
1024  if ( substr( $opt, 0, 1 ) == '"' ) {
1025  return stripcslashes( substr( $opt, 1, -1 ) );
1026  }
1027 
1028  if ( substr( $opt, 0, 2 ) == '[[' ) {
1029  return substr( $opt, 2, -2 );
1030  }
1031 
1032  if ( substr( $opt, 0, 1 ) == '{' ) {
1033  return FormatJson::decode( $opt, true );
1034  }
1035  return $opt;
1036  }
1037 
1047  public function perTestSetup( $test, $nextTeardown = null ) {
1048  $teardown = [];
1049 
1050  $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1051  $teardown[] = $this->markSetupDone( 'perTestSetup' );
1052 
1053  $opts = $this->parseOptions( $test['options'] );
1054  $config = $test['config'];
1055 
1056  // Find out values for some special options.
1057  $langCode =
1058  self::getOptionValue( 'language', $opts, 'en' );
1059  $variant =
1060  self::getOptionValue( 'variant', $opts, false );
1061  $maxtoclevel =
1062  self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
1063  $linkHolderBatchSize =
1064  self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
1065 
1066  // Default to fallback skin, but allow it to be overridden
1067  $skin = self::getOptionValue( 'skin', $opts, 'fallback' );
1068 
1069  $setup = [
1070  'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
1071  'wgLanguageCode' => $langCode,
1072  'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
1073  'wgNamespacesWithSubpages' => array_fill_keys(
1074  MWNamespace::getValidNamespaces(), isset( $opts['subpage'] )
1075  ),
1076  'wgMaxTocLevel' => $maxtoclevel,
1077  'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
1078  'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
1079  'wgDefaultLanguageVariant' => $variant,
1080  'wgLinkHolderBatchSize' => $linkHolderBatchSize,
1081  // Set as a JSON object like:
1082  // wgEnableMagicLinks={"ISBN":false, "PMID":false, "RFC":false}
1083  'wgEnableMagicLinks' => self::getOptionValue( 'wgEnableMagicLinks', $opts, [] )
1084  + [ 'ISBN' => true, 'PMID' => true, 'RFC' => true ],
1085  // Test with legacy encoding by default until HTML5 is very stable and default
1086  'wgFragmentMode' => [ 'legacy' ],
1087  ];
1088 
1089  $nonIncludable = self::getOptionValue( 'wgNonincludableNamespaces', $opts, false );
1090  if ( $nonIncludable !== false ) {
1091  $setup['wgNonincludableNamespaces'] = [ $nonIncludable ];
1092  }
1093 
1094  if ( $config ) {
1095  $configLines = explode( "\n", $config );
1096 
1097  foreach ( $configLines as $line ) {
1098  list( $var, $value ) = explode( '=', $line, 2 );
1099  $setup[$var] = eval( "return $value;" );
1100  }
1101  }
1102 
1104  Hooks::run( 'ParserTestGlobals', [ &$setup ] );
1105 
1106  // Create tidy driver
1107  if ( isset( $opts['tidy'] ) ) {
1108  // Cache a driver instance
1109  if ( $this->tidyDriver === null ) {
1110  $this->tidyDriver = MWTidy::factory();
1111  }
1112  $tidy = $this->tidyDriver;
1113  } else {
1114  $tidy = false;
1115  }
1116 
1117  # Suppress warnings about running tests without tidy
1118  Wikimedia\suppressWarnings();
1119  wfDeprecated( 'disabling tidy' );
1120  wfDeprecated( 'MWTidy::setInstance' );
1121  Wikimedia\restoreWarnings();
1122 
1123  MWTidy::setInstance( $tidy );
1124  $teardown[] = function () {
1126  };
1127 
1128  // Set content language. This invalidates the magic word cache and title services
1129  $lang = Language::factory( $langCode );
1130  $lang->resetNamespaces();
1131  $setup['wgContLang'] = $lang;
1132  $setup[] = function () use ( $lang ) {
1133  MediaWikiServices::getInstance()->disableService( 'ContentLanguage' );
1134  MediaWikiServices::getInstance()->redefineService(
1135  'ContentLanguage',
1136  function () use ( $lang ) {
1137  return $lang;
1138  }
1139  );
1140  };
1141  $teardown[] = function () {
1142  MediaWikiServices::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1143  };
1144  $reset = function () {
1145  MediaWikiServices::getInstance()->resetServiceForTesting( 'MagicWordFactory' );
1146  $this->resetTitleServices();
1147  };
1148  $setup[] = $reset;
1149  $teardown[] = $reset;
1150 
1151  // Make a user object with the same language
1152  $user = new User;
1153  $user->setOption( 'language', $langCode );
1154  $setup['wgLang'] = $lang;
1155 
1156  // We (re)set $wgThumbLimits to a single-element array above.
1157  $user->setOption( 'thumbsize', 0 );
1158 
1159  $setup['wgUser'] = $user;
1160 
1161  // And put both user and language into the context
1163  $context->setUser( $user );
1164  $context->setLanguage( $lang );
1165  // And the skin!
1166  $oldSkin = $context->getSkin();
1167  $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
1168  $context->setSkin( $skinFactory->makeSkin( $skin ) );
1169  $context->setOutput( new OutputPage( $context ) );
1170  $setup['wgOut'] = $context->getOutput();
1171  $teardown[] = function () use ( $context, $oldSkin ) {
1172  // Clear language conversion tables
1173  $wrapper = TestingAccessWrapper::newFromObject(
1174  $context->getLanguage()->getConverter()
1175  );
1176  $wrapper->reloadTables();
1177  // Reset context to the restored globals
1178  $context->setUser( $GLOBALS['wgUser'] );
1179  $context->setLanguage( $GLOBALS['wgContLang'] );
1180  $context->setSkin( $oldSkin );
1181  $context->setOutput( $GLOBALS['wgOut'] );
1182  };
1183 
1184  $teardown[] = $this->executeSetupSnippets( $setup );
1185 
1186  return $this->createTeardownObject( $teardown, $nextTeardown );
1187  }
1188 
1194  private function listTables() {
1196 
1197  $tables = [ 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
1198  'protected_titles', 'revision', 'ip_changes', 'text', 'pagelinks', 'imagelinks',
1199  'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
1200  'site_stats', 'ipblocks', 'image', 'oldimage',
1201  'recentchanges', 'watchlist', 'interwiki', 'logging', 'log_search',
1202  'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
1203  'archive', 'user_groups', 'page_props', 'category',
1204  'slots', 'content', 'slot_roles', 'content_models',
1205  'comment', 'revision_comment_temp',
1206  ];
1207 
1209  // The new tables for actors are in use
1210  $tables[] = 'actor';
1211  $tables[] = 'revision_actor_temp';
1212  }
1213 
1214  if ( in_array( $this->db->getType(), [ 'mysql', 'sqlite', 'oracle' ] ) ) {
1215  array_push( $tables, 'searchindex' );
1216  }
1217 
1218  // Allow extensions to add to the list of tables to duplicate;
1219  // may be necessary if they hook into page save or other code
1220  // which will require them while running tests.
1221  Hooks::run( 'ParserTestTables', [ &$tables ] );
1222 
1223  return $tables;
1224  }
1225 
1226  public function setDatabase( IDatabase $db ) {
1227  $this->db = $db;
1228  $this->setupDone['setDatabase'] = true;
1229  }
1230 
1248  public function setupDatabase( $nextTeardown = null ) {
1249  global $wgDBprefix;
1250 
1251  $this->db = wfGetDB( DB_MASTER );
1252  $dbType = $this->db->getType();
1253 
1254  if ( $dbType == 'oracle' ) {
1255  $suspiciousPrefixes = [ 'pt_', MediaWikiTestCase::ORA_DB_PREFIX ];
1256  } else {
1257  $suspiciousPrefixes = [ 'parsertest_', MediaWikiTestCase::DB_PREFIX ];
1258  }
1259  if ( in_array( $wgDBprefix, $suspiciousPrefixes ) ) {
1260  throw new MWException( "\$wgDBprefix=$wgDBprefix suggests DB setup is already done" );
1261  }
1262 
1263  $teardown = [];
1264 
1265  $teardown[] = $this->markSetupDone( 'setupDatabase' );
1266 
1267  # CREATE TEMPORARY TABLE breaks if there is more than one server
1268  if ( MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() != 1 ) {
1269  $this->useTemporaryTables = false;
1270  }
1271 
1272  $temporary = $this->useTemporaryTables || $dbType == 'postgres';
1273  $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
1274 
1275  $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
1276  $this->dbClone->useTemporaryTables( $temporary );
1277  $this->dbClone->cloneTableStructure();
1278  CloneDatabase::changePrefix( $prefix );
1279 
1280  if ( $dbType == 'oracle' ) {
1281  $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1282  # Insert 0 user to prevent FK violations
1283 
1284  # Anonymous user
1285  $this->db->insert( 'user', [
1286  'user_id' => 0,
1287  'user_name' => 'Anonymous' ] );
1288  }
1289 
1290  $teardown[] = function () {
1291  $this->teardownDatabase();
1292  };
1293 
1294  // Wipe some DB query result caches on setup and teardown
1295  $reset = function () {
1296  MediaWikiServices::getInstance()->getLinkCache()->clear();
1297 
1298  // Clear the message cache
1299  MessageCache::singleton()->clear();
1300  };
1301  $reset();
1302  $teardown[] = $reset;
1303  return $this->createTeardownObject( $teardown, $nextTeardown );
1304  }
1305 
1314  public function setupUploads( $nextTeardown = null ) {
1315  $teardown = [];
1316 
1317  $this->checkSetupDone( 'setupDatabase', 'setDatabase' );
1318  $teardown[] = $this->markSetupDone( 'setupUploads' );
1319 
1320  // Create the files in the upload directory (or pretend to create them
1321  // in a MockFileBackend). Append teardown callback.
1322  $teardown[] = $this->setupUploadBackend();
1323 
1324  // Create a user
1325  $user = User::createNew( 'WikiSysop' );
1326 
1327  // Register the uploads in the database
1328 
1329  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
1330  # note that the size/width/height/bits/etc of the file
1331  # are actually set by inspecting the file itself; the arguments
1332  # to recordUpload2 have no effect. That said, we try to make things
1333  # match up so it is less confusing to readers of the code & tests.
1334  $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', [
1335  'size' => 7881,
1336  'width' => 1941,
1337  'height' => 220,
1338  'bits' => 8,
1339  'media_type' => MEDIATYPE_BITMAP,
1340  'mime' => 'image/jpeg',
1341  'metadata' => serialize( [] ),
1342  'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
1343  'fileExists' => true
1344  ], $this->db->timestamp( '20010115123500' ), $user );
1345 
1346  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
1347  # again, note that size/width/height below are ignored; see above.
1348  $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', [
1349  'size' => 22589,
1350  'width' => 135,
1351  'height' => 135,
1352  'bits' => 8,
1353  'media_type' => MEDIATYPE_BITMAP,
1354  'mime' => 'image/png',
1355  'metadata' => serialize( [] ),
1356  'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
1357  'fileExists' => true
1358  ], $this->db->timestamp( '20130225203040' ), $user );
1359 
1360  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
1361  $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
1362  'size' => 12345,
1363  'width' => 240,
1364  'height' => 180,
1365  'bits' => 0,
1366  'media_type' => MEDIATYPE_DRAWING,
1367  'mime' => 'image/svg+xml',
1368  'metadata' => serialize( [
1369  'version' => SvgHandler::SVG_METADATA_VERSION,
1370  'width' => 240,
1371  'height' => 180,
1372  'originalWidth' => '100%',
1373  'originalHeight' => '100%',
1374  'translations' => [
1377  ],
1378  ] ),
1379  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1380  'fileExists' => true
1381  ], $this->db->timestamp( '20010115123500' ), $user );
1382 
1383  # This image will be blacklisted in [[MediaWiki:Bad image list]]
1384  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
1385  $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', [
1386  'size' => 12345,
1387  'width' => 320,
1388  'height' => 240,
1389  'bits' => 24,
1390  'media_type' => MEDIATYPE_BITMAP,
1391  'mime' => 'image/jpeg',
1392  'metadata' => serialize( [] ),
1393  'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
1394  'fileExists' => true
1395  ], $this->db->timestamp( '20010115123500' ), $user );
1396 
1397  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
1398  $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
1399  'size' => 12345,
1400  'width' => 320,
1401  'height' => 240,
1402  'bits' => 0,
1403  'media_type' => MEDIATYPE_VIDEO,
1404  'mime' => 'application/ogg',
1405  'metadata' => serialize( [] ),
1406  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1407  'fileExists' => true
1408  ], $this->db->timestamp( '20010115123500' ), $user );
1409 
1410  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
1411  $image->recordUpload2( '', 'An awesome hitsong', 'Will it play', [
1412  'size' => 12345,
1413  'width' => 0,
1414  'height' => 0,
1415  'bits' => 0,
1416  'media_type' => MEDIATYPE_AUDIO,
1417  'mime' => 'application/ogg',
1418  'metadata' => serialize( [] ),
1419  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1420  'fileExists' => true
1421  ], $this->db->timestamp( '20010115123500' ), $user );
1422 
1423  # A DjVu file
1424  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
1425  $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
1426  'size' => 3249,
1427  'width' => 2480,
1428  'height' => 3508,
1429  'bits' => 0,
1430  'media_type' => MEDIATYPE_BITMAP,
1431  'mime' => 'image/vnd.djvu',
1432  'metadata' => '<?xml version="1.0" ?>
1433 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
1434 <DjVuXML>
1435 <HEAD></HEAD>
1436 <BODY><OBJECT height="3508" width="2480">
1437 <PARAM name="DPI" value="300" />
1438 <PARAM name="GAMMA" value="2.2" />
1439 </OBJECT>
1440 <OBJECT height="3508" width="2480">
1441 <PARAM name="DPI" value="300" />
1442 <PARAM name="GAMMA" value="2.2" />
1443 </OBJECT>
1444 <OBJECT height="3508" width="2480">
1445 <PARAM name="DPI" value="300" />
1446 <PARAM name="GAMMA" value="2.2" />
1447 </OBJECT>
1448 <OBJECT height="3508" width="2480">
1449 <PARAM name="DPI" value="300" />
1450 <PARAM name="GAMMA" value="2.2" />
1451 </OBJECT>
1452 <OBJECT height="3508" width="2480">
1453 <PARAM name="DPI" value="300" />
1454 <PARAM name="GAMMA" value="2.2" />
1455 </OBJECT>
1456 </BODY>
1457 </DjVuXML>',
1458  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
1459  'fileExists' => true
1460  ], $this->db->timestamp( '20010115123600' ), $user );
1461 
1462  return $this->createTeardownObject( $teardown, $nextTeardown );
1463  }
1464 
1471  private function teardownDatabase() {
1472  $this->checkSetupDone( 'setupDatabase' );
1473 
1474  $this->dbClone->destroy();
1475 
1476  if ( $this->useTemporaryTables ) {
1477  if ( $this->db->getType() == 'sqlite' ) {
1478  # Under SQLite the searchindex table is virtual and need
1479  # to be explicitly destroyed. See T31912
1480  # See also MediaWikiTestCase::destroyDB()
1481  wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1482  $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1483  }
1484  # Don't need to do anything
1485  return;
1486  }
1487 
1488  $tables = $this->listTables();
1489 
1490  foreach ( $tables as $table ) {
1491  if ( $this->db->getType() == 'oracle' ) {
1492  $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1493  } else {
1494  $this->db->query( "DROP TABLE `parsertest_$table`" );
1495  }
1496  }
1497 
1498  if ( $this->db->getType() == 'oracle' ) {
1499  $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1500  }
1501  }
1502 
1508  private function setupUploadBackend() {
1509  global $IP;
1510 
1511  $repo = RepoGroup::singleton()->getLocalRepo();
1512  $base = $repo->getZonePath( 'public' );
1513  $backend = $repo->getBackend();
1514  $backend->prepare( [ 'dir' => "$base/3/3a" ] );
1515  $backend->store( [
1516  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1517  'dst' => "$base/3/3a/Foobar.jpg"
1518  ] );
1519  $backend->prepare( [ 'dir' => "$base/e/ea" ] );
1520  $backend->store( [
1521  'src' => "$IP/tests/phpunit/data/parser/wiki.png",
1522  'dst' => "$base/e/ea/Thumb.png"
1523  ] );
1524  $backend->prepare( [ 'dir' => "$base/0/09" ] );
1525  $backend->store( [
1526  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
1527  'dst' => "$base/0/09/Bad.jpg"
1528  ] );
1529  $backend->prepare( [ 'dir' => "$base/5/5f" ] );
1530  $backend->store( [
1531  'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
1532  'dst' => "$base/5/5f/LoremIpsum.djvu"
1533  ] );
1534 
1535  // No helpful SVG file to copy, so make one ourselves
1536  $data = '<?xml version="1.0" encoding="utf-8"?>' .
1537  '<svg xmlns="http://www.w3.org/2000/svg"' .
1538  ' version="1.1" width="240" height="180"/>';
1539 
1540  $backend->prepare( [ 'dir' => "$base/f/ff" ] );
1541  $backend->quickCreate( [
1542  'content' => $data, 'dst' => "$base/f/ff/Foobar.svg"
1543  ] );
1544 
1545  return function () use ( $backend ) {
1546  if ( $backend instanceof MockFileBackend ) {
1547  // In memory backend, so dont bother cleaning them up.
1548  return;
1549  }
1550  $this->teardownUploadBackend();
1551  };
1552  }
1553 
1557  private function teardownUploadBackend() {
1558  if ( $this->keepUploads ) {
1559  return;
1560  }
1561 
1562  $repo = RepoGroup::singleton()->getLocalRepo();
1563  $public = $repo->getZonePath( 'public' );
1564 
1565  $this->deleteFiles(
1566  [
1567  "$public/3/3a/Foobar.jpg",
1568  "$public/e/ea/Thumb.png",
1569  "$public/0/09/Bad.jpg",
1570  "$public/5/5f/LoremIpsum.djvu",
1571  "$public/f/ff/Foobar.svg",
1572  "$public/0/00/Video.ogv",
1573  "$public/4/41/Audio.oga",
1574  ]
1575  );
1576  }
1577 
1582  private function deleteFiles( $files ) {
1583  // Delete the files
1584  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
1585  foreach ( $files as $file ) {
1586  $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
1587  }
1588 
1589  // Delete the parent directories
1590  foreach ( $files as $file ) {
1592  while ( $tmp ) {
1593  if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
1594  break;
1595  }
1596  $tmp = FileBackend::parentStoragePath( $tmp );
1597  }
1598  }
1599  }
1600 
1606  public function addArticles( $articles ) {
1607  $setup = [];
1608  $teardown = [];
1609 
1610  // Be sure ParserTestRunner::addArticle has correct language set,
1611  // so that system messages get into the right language cache
1612  if ( MediaWikiServices::getInstance()->getContentLanguage()->getCode() !== 'en' ) {
1613  $setup['wgLanguageCode'] = 'en';
1614  $lang = Language::factory( 'en' );
1615  $setup['wgContLang'] = $lang;
1616  $setup[] = function () use ( $lang ) {
1617  $services = MediaWikiServices::getInstance();
1618  $services->disableService( 'ContentLanguage' );
1619  $services->redefineService( 'ContentLanguage', function () use ( $lang ) {
1620  return $lang;
1621  } );
1622  };
1623  $teardown[] = function () {
1624  MediaWikiServices::getInstance()->resetServiceForTesting( 'ContentLanguage' );
1625  };
1626  }
1627 
1628  // Add special namespaces, in case that hasn't been done by staticSetup() yet
1629  $this->appendNamespaceSetup( $setup, $teardown );
1630 
1631  // wgCapitalLinks obviously needs initialisation
1632  $setup['wgCapitalLinks'] = true;
1633 
1634  $teardown[] = $this->executeSetupSnippets( $setup );
1635 
1636  foreach ( $articles as $info ) {
1637  $this->addArticle( $info['name'], $info['text'], $info['file'], $info['line'] );
1638  }
1639 
1640  // Wipe WANObjectCache process cache, which is invalidated by article insertion
1641  // due to T144706
1642  ObjectCache::getMainWANInstance()->clearProcessCache();
1643 
1644  $this->executeSetupSnippets( $teardown );
1645  }
1646 
1656  private function addArticle( $name, $text, $file, $line ) {
1657  $text = self::chomp( $text );
1658  $name = self::chomp( $name );
1659 
1661  wfDebug( __METHOD__ . ": adding $name" );
1662 
1663  if ( is_null( $title ) ) {
1664  throw new MWException( "invalid title '$name' at $file:$line\n" );
1665  }
1666 
1667  $newContent = ContentHandler::makeContent( $text, $title );
1668 
1669  $page = WikiPage::factory( $title );
1670  $page->loadPageData( 'fromdbmaster' );
1671 
1672  if ( $page->exists() ) {
1673  $content = $page->getContent( Revision::RAW );
1674  // Only reject the title, if the content/content model is different.
1675  // This makes it easier to create Template:(( or Template:)) in different extensions
1676  if ( $newContent->equals( $content ) ) {
1677  return;
1678  }
1679  throw new MWException(
1680  "duplicate article '$name' with different content at $file:$line\n"
1681  );
1682  }
1683 
1684  // Optionally use mock parser, to make debugging of actual parser tests simpler.
1685  // But initialise the MessageCache clone first, don't let MessageCache
1686  // get a reference to the mock object.
1687  if ( $this->disableSaveParse ) {
1688  MessageCache::singleton()->getParser();
1689  $restore = $this->executeSetupSnippets( [ 'wgParser' => new ParserTestMockParser ] );
1690  } else {
1691  $restore = false;
1692  }
1693  try {
1694  $status = $page->doEditContent(
1695  $newContent,
1696  '',
1698  );
1699  } finally {
1700  if ( $restore ) {
1701  $restore();
1702  }
1703  }
1704 
1705  if ( !$status->isOK() ) {
1706  throw new MWException( $status->getWikiText( false, false, 'en' ) );
1707  }
1708 
1709  // The RepoGroup cache is invalidated by the creation of file redirects
1710  if ( $title->inNamespace( NS_FILE ) ) {
1711  RepoGroup::singleton()->clearCache( $title );
1712  }
1713  }
1714 
1721  public function requireHook( $name ) {
1722  global $wgParser;
1723 
1724  $wgParser->firstCallInit(); // make sure hooks are loaded.
1725  if ( isset( $wgParser->mTagHooks[$name] ) ) {
1726  return true;
1727  } else {
1728  $this->recorder->warning( " This test suite requires the '$name' hook " .
1729  "extension, skipping." );
1730  return false;
1731  }
1732  }
1733 
1740  public function requireFunctionHook( $name ) {
1741  global $wgParser;
1742 
1743  $wgParser->firstCallInit(); // make sure hooks are loaded.
1744 
1745  if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1746  return true;
1747  } else {
1748  $this->recorder->warning( " This test suite requires the '$name' function " .
1749  "hook extension, skipping." );
1750  return false;
1751  }
1752  }
1753 
1760  public function requireTransparentHook( $name ) {
1761  global $wgParser;
1762 
1763  $wgParser->firstCallInit(); // make sure hooks are loaded.
1764 
1765  if ( isset( $wgParser->mTransparentTagHooks[$name] ) ) {
1766  return true;
1767  } else {
1768  $this->recorder->warning( " This test suite requires the '$name' transparent " .
1769  "hook extension, skipping.\n" );
1770  return false;
1771  }
1772  }
1773 
1781  private function getFakeTimestamp() {
1782  // parsed as '1970-01-01T00:02:03Z'
1783  return 123;
1784  }
1785 }
$status
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 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object '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:1266
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:306
RepoGroup\singleton
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:61
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition: router.php:42
MEDIATYPE_AUDIO
const MEDIATYPE_AUDIO
Definition: defines.php:32
MWNamespace\getValidNamespaces
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
Definition: MWNamespace.php:287
LockManagerGroup\destroySingletons
static destroySingletons()
Destroy the singleton instances.
Definition: LockManagerGroup.php:68
$context
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:2636
$wgParser
$wgParser
Definition: Setup.php:886
HashBagOStuff
Simple store for keeping values in an associative array for the current process.
Definition: HashBagOStuff.php:31
ParserTestResult
Represent the result of a parser test.
Definition: ParserTestResult.php:14
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:103
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
$opt
$opt
Definition: postprocess-phan.php:115
EDIT_INTERNAL
const EDIT_INTERNAL
Definition: Defines.php:159
$wgParserConf
$wgParserConf
Parser configuration.
Definition: DefaultSettings.php:4120
captcha-old.count
count
Definition: captcha-old.py:249
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1983
$out
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:780
ParserTestResultNormalizer\normalize
static normalize( $text, $funcs)
Definition: ParserTestResultNormalizer.php:10
ObjectCache\$instances
static BagOStuff[] $instances
Map of (id => BagOStuff)
Definition: ObjectCache.php:82
MEDIATYPE_DRAWING
const MEDIATYPE_DRAWING
Definition: defines.php:30
$tables
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:979
TestRecorder\warning
warning( $message)
Show a warning to the user.
Definition: TestRecorder.php:72
NS_FILE
const NS_FILE
Definition: Defines.php:70
MockFileBackend
Class simulating a backend store.
Definition: MockFileBackend.php:31
$s
$s
Definition: mergeMessageFileList.php:186
Hooks\clear
static clear( $name)
Clears hooks registered via Hooks::register().
Definition: Hooks.php:63
User
User
Definition: All_system_messages.txt:425
serialize
serialize()
Definition: ApiMessageTrait.php:134
$base
$base
Definition: generateLocalAutoload.php:11
$wgDBprefix
$wgDBprefix
Table name prefix.
Definition: DefaultSettings.php:1941
php
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
MediaHandlerFactory
Class to construct MediaHandler objects.
Definition: MediaHandlerFactory.php:29
User\createNew
static createNew( $name, $params=[])
Add a user to the database, return the user object.
Definition: User.php:4303
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
MWNamespace\clearCaches
static clearCaches()
Clear internal caches.
Definition: MWNamespace.php:77
ExtensionRegistry\getInstance
static getInstance()
Definition: ExtensionRegistry.php:98
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:174
MWException
MediaWiki exception.
Definition: MWException.php:26
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:138
MWTidy\factory
static factory(array $config=null)
Create a new Tidy driver object from configuration.
Definition: MWTidy.php:76
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1078
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2636
$matches
$matches
Definition: NoLocalSettings.php:24
TestRecorder
Interface to record parser test results.
Definition: TestRecorder.php:35
$IP
$IP
Definition: update.php:3
$wgObjectCaches
$wgObjectCaches
Advanced object cache configuration.
Definition: DefaultSettings.php:2384
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
SVGReader\LANG_FULL_MATCH
const LANG_FULL_MATCH
Definition: SVGMetadataExtractor.php:47
$parser
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1802
MEDIATYPE_BITMAP
const MEDIATYPE_BITMAP
Definition: defines.php:28
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:576
$wgParserTestFiles
$wgParserTestFiles
Parser test suite files to be run by parserTests.php when no specific filename is passed to it.
Definition: DefaultSettings.php:6476
$output
$output
Definition: SyntaxHighlight.php:334
$wgFileBackends
$wgFileBackends
File backend structure configuration.
Definition: DefaultSettings.php:765
$image
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition: hooks.txt:780
DB_MASTER
const DB_MASTER
Definition: defines.php:26
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:949
list
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
MessageCache\singleton
static singleton()
Get the signleton instance of this class.
Definition: MessageCache.php:114
ContentHandler\makeContent
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:133
MediaWiki\Tidy\TidyDriverBase
Base class for HTML cleanup utilities.
Definition: TidyDriverBase.php:8
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
MWTidy\setInstance
static setInstance( $instance)
Set the driver to be used.
Definition: MWTidy.php:85
$line
$line
Definition: cdb.php:59
RepoGroup\destroySingleton
static destroySingleton()
Destroy the singleton instance, so that a new one will be created next time singleton() is called.
Definition: RepoGroup.php:76
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2602
ParserTestParserHook\setup
static setup(&$parser)
Definition: ParserTestParserHook.php:30
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
Hooks\register
static register( $name, $callback)
Attach an event handler to a given hook.
Definition: Hooks.php:49
$value
$value
Definition: styleTest.css.php:49
ParserOptions\newFromContext
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Definition: ParserOptions.php:1043
ParserTestMockParser
A parser used during article insertion which does nothing, to avoid unnecessary log noise and other i...
Definition: ParserTestMockParser.php:7
SCHEMA_COMPAT_WRITE_NEW
const SCHEMA_COMPAT_WRITE_NEW
Definition: Defines.php:286
Revision\RAW
const RAW
Definition: Revision.php:56
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:430
Linker\formatComment
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:1122
EDIT_NEW
const EDIT_NEW
Definition: Defines.php:152
TestFileReader\read
static read( $file, array $options=[])
Definition: TestFileReader.php:37
MediaWikiTestCase\DB_PREFIX
const DB_PREFIX
Table name prefixes.
Definition: MediaWikiTestCase.php:134
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1989
CloneDatabase
Definition: CloneDatabase.php:26
FSFileBackend
Class for a file system (FS) based file backend.
Definition: FSFileBackend.php:41
MEDIATYPE_VIDEO
const MEDIATYPE_VIDEO
Definition: defines.php:35
$options
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:1985
MediaWikiTestCase\ORA_DB_PREFIX
const ORA_DB_PREFIX
Definition: MediaWikiTestCase.php:135
ObjectCache\getMainWANInstance
static getMainWANInstance()
Get the main WAN cache object.
Definition: ObjectCache.php:369
CloneDatabase\changePrefix
static changePrefix( $prefix)
Change the table prefix on all open DB connections.
Definition: CloneDatabase.php:136
$section
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:3053
as
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
$skin
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:1985
Wikimedia
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
RepoGroup
Prioritized list of file repositories.
Definition: RepoGroup.php:31
true
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:1985
$content
$content
Definition: pageupdater.txt:72
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:215
class
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
$services
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:2220
SvgHandler\SVG_METADATA_VERSION
const SVG_METADATA_VERSION
Definition: SvgHandler.php:33
MediaWikiServices
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
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:2688
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
MWTidy\destroySingleton
static destroySingleton()
Destroy the current singleton instance.
Definition: MWTidy.php:93
wfGetCaller
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
Definition: GlobalFunctions.php:1480
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
RepoGroup\setSingleton
static setSingleton( $instance)
Set the singleton instance to a given object Used by extensions which hook into the Repo chain.
Definition: RepoGroup.php:88
CACHE_DB
const CACHE_DB
Definition: Defines.php:103
FileBackend\parentStoragePath
static parentStoragePath( $storagePath)
Get the parent storage directory of a storage path.
Definition: FileBackend.php:1476
MessageCache\destroyInstance
static destroyInstance()
Destroy the singleton instance.
Definition: MessageCache.php:138
$wgActorTableSchemaMigrationStage
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
Definition: DefaultSettings.php:8979