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