MediaWiki  1.23.15
NewParserTest.php
Go to the documentation of this file.
1 <?php
2 
12 class NewParserTest extends MediaWikiTestCase {
13  static protected $articles = array(); // Array of test articles defined by the tests
14  /* The data provider is run on a different instance than the test, so it must be static
15  * When running tests from several files, all tests will see all articles.
16  */
17  static protected $backendToUse;
18 
19  public $keepUploads = false;
20  public $runDisabled = false;
21  public $runParsoid = false;
22  public $regex = '';
23  public $showProgress = true;
24  public $savedWeirdGlobals = array();
25  public $savedGlobals = array();
26  public $hooks = array();
27  public $functionHooks = array();
28 
29  //Fuzz test
30  public $maxFuzzTestLength = 300;
31  public $fuzzSeed = 0;
32  public $memoryLimit = 50;
33 
34  protected $file = false;
35 
36  public static function setUpBeforeClass() {
37  // Inject ParserTest well-known interwikis
38  ParserTest::setupInterwikis();
39  }
40 
41  protected function setUp() {
44 
45  parent::setUp();
46 
47  //Setup CLI arguments
48  if ( $this->getCliArg( 'regex=' ) ) {
49  $this->regex = $this->getCliArg( 'regex=' );
50  } else {
51  # Matches anything
52  $this->regex = '';
53  }
54 
55  $this->keepUploads = $this->getCliArg( 'keep-uploads' );
56 
57  $tmpGlobals = array();
58 
59  $tmpGlobals['wgLanguageCode'] = 'en';
60  $tmpGlobals['wgContLang'] = Language::factory( 'en' );
61  $tmpGlobals['wgSitename'] = 'MediaWiki';
62  $tmpGlobals['wgServer'] = 'http://example.org';
63  $tmpGlobals['wgScript'] = '/index.php';
64  $tmpGlobals['wgScriptPath'] = '/';
65  $tmpGlobals['wgArticlePath'] = '/wiki/$1';
66  $tmpGlobals['wgActionPaths'] = array();
67  $tmpGlobals['wgVariantArticlePath'] = false;
68  $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
69  $tmpGlobals['wgStylePath'] = '/skins';
70  $tmpGlobals['wgEnableUploads'] = true;
71  $tmpGlobals['wgThumbnailScriptPath'] = false;
72  $tmpGlobals['wgLocalFileRepo'] = array(
73  'class' => 'LocalRepo',
74  'name' => 'local',
75  'url' => 'http://example.com/images',
76  'hashLevels' => 2,
77  'transformVia404' => false,
78  'backend' => 'local-backend'
79  );
80  $tmpGlobals['wgForeignFileRepos'] = array();
81  $tmpGlobals['wgDefaultExternalStore'] = array();
82  $tmpGlobals['wgEnableParserCache'] = false;
83  $tmpGlobals['wgCapitalLinks'] = true;
84  $tmpGlobals['wgNoFollowLinks'] = true;
85  $tmpGlobals['wgNoFollowDomainExceptions'] = array();
86  $tmpGlobals['wgExternalLinkTarget'] = false;
87  $tmpGlobals['wgThumbnailScriptPath'] = false;
88  $tmpGlobals['wgUseImageResize'] = true;
89  $tmpGlobals['wgAllowExternalImages'] = true;
90  $tmpGlobals['wgRawHtml'] = false;
91  $tmpGlobals['wgUseTidy'] = false;
92  $tmpGlobals['wgAlwaysUseTidy'] = false;
93  $tmpGlobals['wgAllowMicrodataAttributes'] = true;
94  $tmpGlobals['wgExperimentalHtmlIds'] = false;
95  $tmpGlobals['wgAdaptiveMessageCache'] = true;
96  $tmpGlobals['wgUseDatabaseMessages'] = true;
97  $tmpGlobals['wgLocaltimezone'] = 'UTC';
98  $tmpGlobals['wgDeferredUpdateList'] = array();
99  $tmpGlobals['wgGroupPermissions'] = array(
100  '*' => array(
101  'createaccount' => true,
102  'read' => true,
103  'edit' => true,
104  'createpage' => true,
105  'createtalk' => true,
106  ) );
107  $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI => 'editinterface' );
108 
109  $tmpGlobals['wgParser'] = new StubObject(
110  'wgParser', $GLOBALS['wgParserConf']['class'],
111  array( $GLOBALS['wgParserConf'] ) );
112 
113  $tmpGlobals['wgFileExtensions'][] = 'svg';
114  $tmpGlobals['wgSVGConverter'] = 'rsvg';
115  $tmpGlobals['wgSVGConverters']['rsvg'] =
116  '$path/rsvg-convert -w $width -h $height $input -o $output';
117 
118  if ( $GLOBALS['wgStyleDirectory'] === false ) {
119  $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
120  }
121 
122  # Replace all media handlers with a mock. We do not need to generate
123  # actual thumbnails to do parser testing, we only care about receiving
124  # a ThumbnailImage properly initialized.
125  global $wgMediaHandlers;
126  foreach ( $wgMediaHandlers as $type => $handler ) {
127  $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
128  }
129  // Vector images have to be handled slightly differently
130  $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
131 
132  $tmpHooks = $wgHooks;
133  $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
134  $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
135  $tmpGlobals['wgHooks'] = $tmpHooks;
136  # add a namespace shadowing a interwiki link, to test
137  # proper precedence when resolving links. (bug 51680)
138  $tmpGlobals['wgExtraNamespaces'] = array( 100 => 'MemoryAlpha' );
139 
140  $this->setMwGlobals( $tmpGlobals );
141 
142  $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
143  $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
144 
145  $wgNamespaceAliases['Image'] = NS_FILE;
146  $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
147 
148  MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
149  $wgContLang->resetNamespaces(); # reset namespace cache
150  }
151 
152  protected function tearDown() {
154 
155  $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
156  $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
157 
158  // Restore backends
161 
162  // Remove temporary pages from the link cache
163  LinkCache::singleton()->clear();
164 
165  // Restore message cache (temporary pages and $wgUseDatabaseMessages)
167 
168  parent::tearDown();
169 
170  MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
171  $wgContLang->resetNamespaces(); # reset namespace cache
172  }
173 
174  public static function tearDownAfterClass() {
175  ParserTest::tearDownInterwikis();
176  parent::tearDownAfterClass();
177  }
178 
179  function addDBData() {
180  $this->tablesUsed[] = 'site_stats';
181  # disabled for performance
182  #$this->tablesUsed[] = 'image';
183 
184  # Update certain things in site_stats
185  $this->db->insert( 'site_stats',
186  array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
187  __METHOD__
188  );
189 
190  $user = User::newFromId( 0 );
191  LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
192 
193  # Upload DB table entries for files.
194  # We will upload the actual files later. Note that if anything causes LocalFile::load()
195  # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
196  # member to false and storing it in cache.
197  # note that the size/width/height/bits/etc of the file
198  # are actually set by inspecting the file itself; the arguments
199  # to recordUpload2 have no effect. That said, we try to make things
200  # match up so it is less confusing to readers of the code & tests.
201  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
202  if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
203  $image->recordUpload2(
204  '', // archive name
205  'Upload of some lame file',
206  'Some lame file',
207  array(
208  'size' => 7881,
209  'width' => 1941,
210  'height' => 220,
211  'bits' => 8,
212  'media_type' => MEDIATYPE_BITMAP,
213  'mime' => 'image/jpeg',
214  'metadata' => serialize( array() ),
215  'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
216  'fileExists' => true ),
217  $this->db->timestamp( '20010115123500' ), $user
218  );
219  }
220 
221  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
222  if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
223  $image->recordUpload2(
224  '', // archive name
225  'Upload of some lame thumbnail',
226  'Some lame thumbnail',
227  array(
228  'size' => 22589,
229  'width' => 135,
230  'height' => 135,
231  'bits' => 8,
232  'media_type' => MEDIATYPE_BITMAP,
233  'mime' => 'image/png',
234  'metadata' => serialize( array() ),
235  'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
236  'fileExists' => true ),
237  $this->db->timestamp( '20130225203040' ), $user
238  );
239  }
240 
241  # This image will be blacklisted in [[MediaWiki:Bad image list]]
242  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
243  if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
244  $image->recordUpload2(
245  '', // archive name
246  'zomgnotcensored',
247  'Borderline image',
248  array(
249  'size' => 12345,
250  'width' => 320,
251  'height' => 240,
252  'bits' => 24,
253  'media_type' => MEDIATYPE_BITMAP,
254  'mime' => 'image/jpeg',
255  'metadata' => serialize( array() ),
256  'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
257  'fileExists' => true ),
258  $this->db->timestamp( '20010115123500' ), $user
259  );
260  }
261  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
262  if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
263  $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
264  'size' => 12345,
265  'width' => 240,
266  'height' => 180,
267  'bits' => 24,
268  'media_type' => MEDIATYPE_DRAWING,
269  'mime' => 'image/svg+xml',
270  'metadata' => serialize( array() ),
271  'sha1' => wfBaseConvert( '', 16, 36, 31 ),
272  'fileExists' => true
273  ), $this->db->timestamp( '20010115123500' ), $user );
274  }
275  }
276 
277  //ParserTest setup/teardown functions
278 
283  protected function setupGlobals( $opts = array(), $config = '' ) {
284  global $wgFileBackends;
285  # Find out values for some special options.
286  $lang =
287  self::getOptionValue( 'language', $opts, 'en' );
288  $variant =
289  self::getOptionValue( 'variant', $opts, false );
290  $maxtoclevel =
291  self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
292  $linkHolderBatchSize =
293  self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
294 
295  $uploadDir = $this->getUploadDir();
296  if ( $this->getCliArg( 'use-filebackend=' ) ) {
297  if ( self::$backendToUse ) {
298  $backend = self::$backendToUse;
299  } else {
300  $name = $this->getCliArg( 'use-filebackend=' );
301  $useConfig = array();
302  foreach ( $wgFileBackends as $conf ) {
303  if ( $conf['name'] == $name ) {
304  $useConfig = $conf;
305  }
306  }
307  $useConfig['name'] = 'local-backend'; // swap name
308  unset( $useConfig['lockManager'] );
309  unset( $useConfig['fileJournal'] );
310  $class = $useConfig['class'];
311  self::$backendToUse = new $class( $useConfig );
312  $backend = self::$backendToUse;
313  }
314  } else {
315  # Replace with a mock. We do not care about generating real
316  # files on the filesystem, just need to expose the file
317  # informations.
318  $backend = new MockFileBackend( array(
319  'name' => 'local-backend',
320  'wikiId' => wfWikiId()
321  ) );
322  }
323 
324  $settings = array(
325  'wgLocalFileRepo' => array(
326  'class' => 'LocalRepo',
327  'name' => 'local',
328  'url' => 'http://example.com/images',
329  'hashLevels' => 2,
330  'transformVia404' => false,
331  'backend' => $backend
332  ),
333  'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
334  'wgLanguageCode' => $lang,
335  'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
336  'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
337  'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
338  'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
339  'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
340  'wgMaxTocLevel' => $maxtoclevel,
341  'wgUseTeX' => isset( $opts['math'] ) || isset( $opts['texvc'] ),
342  'wgMathDirectory' => $uploadDir . '/math',
343  'wgDefaultLanguageVariant' => $variant,
344  'wgLinkHolderBatchSize' => $linkHolderBatchSize,
345  );
346 
347  if ( $config ) {
348  $configLines = explode( "\n", $config );
349 
350  foreach ( $configLines as $line ) {
351  list( $var, $value ) = explode( '=', $line, 2 );
352 
353  $settings[$var] = eval( "return $value;" ); //???
354  }
355  }
356 
357  $this->savedGlobals = array();
358 
360  wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
361 
362  $langObj = Language::factory( $lang );
363  $settings['wgContLang'] = $langObj;
364  $settings['wgLang'] = $langObj;
365 
366  $context = new RequestContext();
367  $settings['wgOut'] = $context->getOutput();
368  $settings['wgUser'] = $context->getUser();
369  $settings['wgRequest'] = $context->getRequest();
370 
371  // We (re)set $wgThumbLimits to a single-element array above.
372  $context->getUser()->setOption( 'thumbsize', 0 );
373 
374  foreach ( $settings as $var => $val ) {
375  if ( array_key_exists( $var, $GLOBALS ) ) {
376  $this->savedGlobals[$var] = $GLOBALS[$var];
377  }
378 
379  $GLOBALS[$var] = $val;
380  }
381 
383 
384  # The entries saved into RepoGroup cache with previous globals will be wrong.
387 
388  # Create dummy files in storage
389  $this->setupUploads();
390 
391  # Publish the articles after we have the final language set
392  $this->publishTestArticles();
393 
395 
396  return $context;
397  }
398 
404  protected function getUploadDir() {
405  if ( $this->keepUploads ) {
406  $dir = wfTempDir() . '/mwParser-images';
407 
408  if ( is_dir( $dir ) ) {
409  return $dir;
410  }
411  } else {
412  $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
413  }
414 
415  // wfDebug( "Creating upload directory $dir\n" );
416  if ( file_exists( $dir ) ) {
417  wfDebug( "Already exists!\n" );
418 
419  return $dir;
420  }
421 
422  return $dir;
423  }
424 
431  protected function setupUploads() {
432  global $IP;
433 
434  $base = $this->getBaseDir();
435  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
436  $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
437  $backend->store( array(
438  'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
439  ) );
440  $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
441  $backend->store( array(
442  'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
443  ) );
444  $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
445  $backend->store( array(
446  'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
447  ) );
448 
449  // No helpful SVG file to copy, so make one ourselves
450  $data = '<?xml version="1.0" encoding="utf-8"?>' .
451  '<svg xmlns="http://www.w3.org/2000/svg"' .
452  ' version="1.1" width="240" height="180"/>';
453 
454  $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
455  $backend->quickCreate( array(
456  'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
457  ) );
458  }
459 
464  protected function teardownGlobals() {
465  $this->teardownUploads();
466 
467  foreach ( $this->savedGlobals as $var => $val ) {
468  $GLOBALS[$var] = $val;
469  }
470  }
471 
475  private function teardownUploads() {
476  if ( $this->keepUploads ) {
477  return;
478  }
479 
480  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
481  if ( $backend instanceof MockFileBackend ) {
482  # In memory backend, so dont bother cleaning them up.
483  return;
484  }
485 
486  $base = $this->getBaseDir();
487  // delete the files first, then the dirs.
488  self::deleteFiles(
489  array(
490  "$base/local-public/3/3a/Foobar.jpg",
491  "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
492  "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
493  "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
494  "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
495  "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
496  "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
497  "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
498  "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
499  "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
500  "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
501  "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
502  "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
503  "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
504  "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
505  "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
506  "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
507  "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
508  "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
509  "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
510  "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
511  "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
512  "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
513  "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
514  "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
515  "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
516  "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
517  "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
518  "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
519  "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
520  "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
521  "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
522 
523  "$base/local-public/e/ea/Thumb.png",
524 
525  "$base/local-public/0/09/Bad.jpg",
526 
527  "$base/local-public/f/ff/Foobar.svg",
528  "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
529  "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
530  "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
531  "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
532  "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
533  "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
534  "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
535  "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
536  "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
537 
538  "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
539  )
540  );
541  }
542 
547  private static function deleteFiles( $files ) {
548  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
549  foreach ( $files as $file ) {
550  $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
551  }
552  foreach ( $files as $file ) {
553  $tmp = $file;
554  while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
555  if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
556  break;
557  }
558  }
559  }
560  }
561 
562  protected function getBaseDir() {
563  return 'mwstore://local-backend';
564  }
565 
566  public function parserTestProvider() {
567  if ( $this->file === false ) {
568  global $wgParserTestFiles;
569  $this->file = $wgParserTestFiles[0];
570  }
571 
572  return new TestFileIterator( $this->file, $this );
573  }
574 
578  public function setParserTestFile( $filename ) {
579  $this->file = $filename;
580  }
581 
587  public function testParserTest( $desc, $input, $result, $opts, $config ) {
588  if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
589  $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
590  //$this->markTestSkipped( 'Filtered out by the user' );
591  return;
592  }
593 
594  if ( !$this->isWikitextNS( NS_MAIN ) ) {
595  // parser tests frequently assume that the main namespace contains wikitext.
596  // @todo When setting up pages, force the content model. Only skip if
597  // $wgtContentModelUseDB is false.
598  $this->markTestSkipped( "Main namespace does not support wikitext,"
599  . "skipping parser test: $desc" );
600  }
601 
602  wfDebug( "Running parser test: $desc\n" );
603 
604  $opts = $this->parseOptions( $opts );
605  $context = $this->setupGlobals( $opts, $config );
606 
607  $user = $context->getUser();
609 
610  if ( isset( $opts['title'] ) ) {
611  $titleText = $opts['title'];
612  } else {
613  $titleText = 'Parser test';
614  }
615 
616  $local = isset( $opts['local'] );
617  $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
618  $parser = $this->getParser( $preprocessor );
619 
620  $title = Title::newFromText( $titleText );
621 
622  # Parser test requiring math. Make sure texvc is executable
623  # or just skip such tests.
624  if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
625  global $wgTexvc;
626 
627  if ( !isset( $wgTexvc ) ) {
628  $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
629  } elseif ( !is_executable( $wgTexvc ) ) {
630  $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
631  . " or is not executable.\n"
632  . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
633  }
634  }
635 
636  if ( isset( $opts['pst'] ) ) {
637  $out = $parser->preSaveTransform( $input, $title, $user, $options );
638  } elseif ( isset( $opts['msg'] ) ) {
639  $out = $parser->transformMsg( $input, $options, $title );
640  } elseif ( isset( $opts['section'] ) ) {
641  $section = $opts['section'];
642  $out = $parser->getSection( $input, $section );
643  } elseif ( isset( $opts['replace'] ) ) {
644  $section = $opts['replace'][0];
645  $replace = $opts['replace'][1];
646  $out = $parser->replaceSection( $input, $section, $replace );
647  } elseif ( isset( $opts['comment'] ) ) {
648  $out = Linker::formatComment( $input, $title, $local );
649  } elseif ( isset( $opts['preload'] ) ) {
650  $out = $parser->getPreloadText( $input, $title, $options );
651  } else {
652  $output = $parser->parse( $input, $title, $options, true, true, 1337 );
653  $output->setTOCEnabled( !isset( $opts['notoc'] ) );
654  $out = $output->getText();
655 
656  if ( isset( $opts['showtitle'] ) ) {
657  if ( $output->getTitleText() ) {
658  $title = $output->getTitleText();
659  }
660 
661  $out = "$title\n$out";
662  }
663 
664  if ( isset( $opts['ill'] ) ) {
665  $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
666  } elseif ( isset( $opts['cat'] ) ) {
667  $outputPage = $context->getOutput();
668  $outputPage->addCategoryLinks( $output->getCategories() );
669  $cats = $outputPage->getCategoryLinks();
670 
671  if ( isset( $cats['normal'] ) ) {
672  $out = $this->tidy( implode( ' ', $cats['normal'] ) );
673  } else {
674  $out = '';
675  }
676  }
677  $parser->mPreprocessor = null;
678 
679  $result = $this->tidy( $result );
680  }
681 
682  $this->teardownGlobals();
683 
684  $this->assertEquals( $result, $out, $desc );
685  }
686 
695  public function testFuzzTests() {
696  global $wgParserTestFiles;
697 
698  $files = $wgParserTestFiles;
699 
700  if ( $this->getCliArg( 'file=' ) ) {
701  $files = array( $this->getCliArg( 'file=' ) );
702  }
703 
704  $dict = $this->getFuzzInput( $files );
705  $dictSize = strlen( $dict );
706  $logMaxLength = log( $this->maxFuzzTestLength );
707 
708  ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
709 
710  $user = new User;
712  $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
713 
714  $id = 1;
715 
716  while ( true ) {
717 
718  // Generate test input
719  mt_srand( ++$this->fuzzSeed );
720  $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
721  $input = '';
722 
723  while ( strlen( $input ) < $totalLength ) {
724  $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
725  $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
726  $offset = mt_rand( 0, $dictSize - $hairLength );
727  $input .= substr( $dict, $offset, $hairLength );
728  }
729 
730  $this->setupGlobals();
731  $parser = $this->getParser();
732 
733  // Run the test
734  try {
735  $parser->parse( $input, $title, $opts );
736  $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
737  } catch ( Exception $exception ) {
738  $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
739 
740  $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
741  "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
742  "Backtrace: {$exception->getTraceAsString()}" );
743  }
744 
745  $this->teardownGlobals();
746  $parser->__destruct();
747 
748  if ( $id % 100 == 0 ) {
749  $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
750  //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
751  if ( $usage > 90 ) {
752  $ret = "Out of memory:\n";
753  $memStats = $this->getMemoryBreakdown();
754 
755  foreach ( $memStats as $name => $usage ) {
756  $ret .= "$name: $usage\n";
757  }
758 
759  throw new MWException( $ret );
760  }
761  }
762 
763  $id++;
764  }
765  }
766 
767  //Various getter functions
768 
772  function getFuzzInput( $filenames ) {
773  $dict = '';
774 
775  foreach ( $filenames as $filename ) {
776  $contents = file_get_contents( $filename );
777  preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
778 
779  foreach ( $matches[1] as $match ) {
780  $dict .= $match . "\n";
781  }
782  }
783 
784  return $dict;
785  }
786 
790  function getMemoryBreakdown() {
791  $memStats = array();
792 
793  foreach ( $GLOBALS as $name => $value ) {
794  $memStats['$' . $name] = strlen( serialize( $value ) );
795  }
796 
797  $classes = get_declared_classes();
798 
799  foreach ( $classes as $class ) {
800  $rc = new ReflectionClass( $class );
801  $props = $rc->getStaticProperties();
802  $memStats[$class] = strlen( serialize( $props ) );
803  $methods = $rc->getMethods();
804 
805  foreach ( $methods as $method ) {
806  $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
807  }
808  }
809 
810  $functions = get_defined_functions();
811 
812  foreach ( $functions['user'] as $function ) {
813  $rf = new ReflectionFunction( $function );
814  $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
815  }
816 
817  asort( $memStats );
818 
819  return $memStats;
820  }
821 
825  function getParser( $preprocessor = null ) {
826  global $wgParserConf;
827 
828  $class = $wgParserConf['class'];
829  $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
830 
831  wfRunHooks( 'ParserTestParser', array( &$parser ) );
832 
833  return $parser;
834  }
835 
836  //Various action functions
837 
838  public function addArticle( $name, $text, $line ) {
839  self::$articles[$name] = array( $text, $line );
840  }
841 
842  public function publishTestArticles() {
843  if ( empty( self::$articles ) ) {
844  return;
845  }
846 
847  foreach ( self::$articles as $name => $info ) {
848  list( $text, $line ) = $info;
849  ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
850  }
851  }
852 
861  public function requireHook( $name ) {
863  $wgParser->firstCallInit(); // make sure hooks are loaded.
864  return isset( $wgParser->mTagHooks[$name] );
865  }
866 
867  public function requireFunctionHook( $name ) {
869  $wgParser->firstCallInit(); // make sure hooks are loaded.
870  return isset( $wgParser->mFunctionHooks[$name] );
871  }
872 
873  //Various "cleanup" functions
874 
882  protected function tidy( $text ) {
883  global $wgUseTidy;
884 
885  if ( $wgUseTidy ) {
886  $text = MWTidy::tidy( $text );
887  }
888 
889  return $text;
890  }
891 
895  public function removeEndingNewline( $s ) {
896  if ( substr( $s, -1 ) === "\n" ) {
897  return substr( $s, 0, -1 );
898  } else {
899  return $s;
900  }
901  }
902 
903  //Test options parser functions
904 
905  protected function parseOptions( $instring ) {
906  $opts = array();
907  // foo
908  // foo=bar
909  // foo="bar baz"
910  // foo=[[bar baz]]
911  // foo=bar,"baz quux"
912  $regex = '/\b
913  ([\w-]+) # Key
914  \b
915  (?:\s*
916  = # First sub-value
917  \s*
918  (
919  "
920  [^"]* # Quoted val
921  "
922  |
923  \[\[
924  [^]]* # Link target
925  \]\]
926  |
927  [\w-]+ # Plain word
928  )
929  (?:\s*
930  , # Sub-vals 1..N
931  \s*
932  (
933  "[^"]*" # Quoted val
934  |
935  \[\[[^]]*\]\] # Link target
936  |
937  [\w-]+ # Plain word
938  )
939  )*
940  )?
941  /x';
942 
943  if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
944  foreach ( $matches as $bits ) {
945  array_shift( $bits );
946  $key = strtolower( array_shift( $bits ) );
947  if ( count( $bits ) == 0 ) {
948  $opts[$key] = true;
949  } elseif ( count( $bits ) == 1 ) {
950  $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
951  } else {
952  // Array!
953  $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
954  }
955  }
956  }
957 
958  return $opts;
959  }
960 
961  protected function cleanupOption( $opt ) {
962  if ( substr( $opt, 0, 1 ) == '"' ) {
963  return substr( $opt, 1, -1 );
964  }
965 
966  if ( substr( $opt, 0, 2 ) == '[[' ) {
967  return substr( $opt, 2, -2 );
968  }
969 
970  return $opt;
971  }
972 
979  protected static function getOptionValue( $key, $opts, $default ) {
980  $key = strtolower( $key );
981 
982  if ( isset( $opts[$key] ) ) {
983  return $opts[$key];
984  } else {
985  return $default;
986  }
987  }
988 }
Title\makeTitle
static & makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:398
$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. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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 User::isValidEmailAddr(), 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 '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) '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. '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:1528
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:412
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:189
RepoGroup\singleton
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:53
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
$files
$files
Definition: importImages.php:67
StubObject
Class to implement stub globals, which are globals that delay loading the their associated module cod...
Definition: StubObject.php:44
$ret
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 & $ret
Definition: hooks.txt:1530
NS_FILE
const NS_FILE
Definition: Defines.php:85
MediaWikiTestCase\getCliArg
getCliArg( $offset)
Definition: MediaWikiTestCase.php:658
MockFileBackend
Class simulating a backend store.
Definition: MockFileBackend.php:31
$s
$s
Definition: mergeMessageFileList.php:156
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:56
$wgHooks
$wgHooks['ArticleShow'][]
Definition: hooks.txt:110
Linker\formatComment
static formatComment( $comment, $title=null, $local=false)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition: Linker.php:1263
cache
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
FileBackendGroup\destroySingleton
static destroySingleton()
Destroy the singleton instance.
Definition: FileBackendGroup.php:55
NS_MAIN
const NS_MAIN
Definition: Defines.php:79
file
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
Definition: hooks.txt:93
MWException
MediaWiki exception.
Definition: MWException.php:26
$out
$out
Definition: UtfNormalGenerate.php:167
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Definition: MediaWikiTestCase.php:302
$parser
do that in ParserLimitReportFormat instead $parser
Definition: hooks.txt:1961
MediaWikiTestCase
Definition: MediaWikiTestCase.php:6
wfRunHooks
wfRunHooks( $event, array $args=array(), $deprecatedVersion=null)
Call hook functions defined in $wgHooks.
Definition: GlobalFunctions.php:4066
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
RequestContext
Group all the pieces relevant to the context of a request into one instance.
Definition: RequestContext.php:30
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
$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:1530
MagicWord\clearCache
static clearCache()
Clear the self::$mObjects variable For use in parser tests.
Definition: MagicWord.php:300
$section
$section
Definition: Utf8Test.php:88
$line
$line
Definition: cdb.php:57
wfDebug
wfDebug( $text, $dest='all')
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:980
RepoGroup\destroySingleton
static destroySingleton()
Destroy the singleton instance, so that a new one will be created next time singleton() is called.
Definition: RepoGroup.php:67
$title
presenting them properly to the user as errors is done by the caller $title
Definition: hooks.txt:1324
function
when a variable name is used in a function
Definition: design.txt:93
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:336
$matches
if(!defined( 'MEDIAWIKI')) if(!isset( $wgVersion)) $matches
Definition: NoLocalSettings.php:33
$value
$value
Definition: styleTest.css.php:45
TestFileIterator
Definition: testHelpers.inc:352
ParserOptions\newFromContext
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Definition: ParserOptions.php:396
$wgNamespaceAliases
$wgNamespaceAliases['Image']
The canonical names of namespaces 6 and 7 are, as of v1.14, "File" and "File_talk".
Definition: Setup.php:142
$user
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 account $user
Definition: hooks.txt:237
MediaWikiTestCase\setUp
setUp()
Definition: MediaWikiTestCase.php:187
$file
if(PHP_SAPI !='cli') $file
Definition: UtfNormalTest2.php:30
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:2611
$wgParser
$wgParser
Definition: Setup.php:587
$dir
if(count( $args)==0) $dir
Definition: importImages.php:49
wfBaseConvert
wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true, $engine='auto')
Convert an arbitrarily-long digit string from one numeric base to another, optionally zero-padding to...
Definition: GlobalFunctions.php:3432
$output
& $output
Definition: hooks.txt:375
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
MWNamespace\getCanonicalNamespaces
static getCanonicalNamespaces( $rebuild=false)
Returns array of all defined namespaces with their canonical (English) names.
Definition: Namespace.php:218
User
User
Definition: All_system_messages.txt:425
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:184
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:87
NS_FILE_TALK
const NS_FILE_TALK
Definition: Defines.php:86
$IP
$IP
Definition: WebStart.php:92
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:3768
LinkCache\singleton
static & singleton()
Get an instance of this class.
Definition: LinkCache.php:49
MEDIATYPE_DRAWING
const MEDIATYPE_DRAWING
Definition: Defines.php:127
$GLOBALS
$GLOBALS['IP']
Definition: ComposerHookHandler.php:6
ParserOptions\newFromUser
static newFromUser( $user)
Get a ParserOptions object from a given user.
Definition: ParserOptions.php:375
FileBackend\parentStoragePath
static parentStoragePath( $storagePath)
Get the parent storage directory of a storage path.
Definition: FileBackend.php:1387
$type
$type
Definition: testCompression.php:46
MWTidy\tidy
static tidy( $text)
Interface with html tidy, used if $wgUseTidy = true.
Definition: Tidy.php:126
MEDIATYPE_BITMAP
const MEDIATYPE_BITMAP
Definition: Defines.php:125
MessageCache\destroyInstance
static destroyInstance()
Destroy the singleton instance.
Definition: MessageCache.php:119