MediaWiki  1.23.13
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['wgWellFormedXml'] = true;
94  $tmpGlobals['wgAllowMicrodataAttributes'] = true;
95  $tmpGlobals['wgExperimentalHtmlIds'] = false;
96  $tmpGlobals['wgAdaptiveMessageCache'] = true;
97  $tmpGlobals['wgUseDatabaseMessages'] = true;
98  $tmpGlobals['wgLocaltimezone'] = 'UTC';
99  $tmpGlobals['wgDeferredUpdateList'] = array();
100  $tmpGlobals['wgGroupPermissions'] = array(
101  '*' => array(
102  'createaccount' => true,
103  'read' => true,
104  'edit' => true,
105  'createpage' => true,
106  'createtalk' => true,
107  ) );
108  $tmpGlobals['wgNamespaceProtection'] = array( NS_MEDIAWIKI => 'editinterface' );
109 
110  $tmpGlobals['wgParser'] = new StubObject(
111  'wgParser', $GLOBALS['wgParserConf']['class'],
112  array( $GLOBALS['wgParserConf'] ) );
113 
114  $tmpGlobals['wgFileExtensions'][] = 'svg';
115  $tmpGlobals['wgSVGConverter'] = 'rsvg';
116  $tmpGlobals['wgSVGConverters']['rsvg'] =
117  '$path/rsvg-convert -w $width -h $height $input -o $output';
118 
119  if ( $GLOBALS['wgStyleDirectory'] === false ) {
120  $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
121  }
122 
123  # Replace all media handlers with a mock. We do not need to generate
124  # actual thumbnails to do parser testing, we only care about receiving
125  # a ThumbnailImage properly initialized.
126  global $wgMediaHandlers;
127  foreach ( $wgMediaHandlers as $type => $handler ) {
128  $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
129  }
130  // Vector images have to be handled slightly differently
131  $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
132 
133  $tmpHooks = $wgHooks;
134  $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
135  $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
136  $tmpGlobals['wgHooks'] = $tmpHooks;
137  # add a namespace shadowing a interwiki link, to test
138  # proper precedence when resolving links. (bug 51680)
139  $tmpGlobals['wgExtraNamespaces'] = array( 100 => 'MemoryAlpha' );
140 
141  $this->setMwGlobals( $tmpGlobals );
142 
143  $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
144  $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
145 
146  $wgNamespaceAliases['Image'] = NS_FILE;
147  $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
148 
149  MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
150  $wgContLang->resetNamespaces(); # reset namespace cache
151  }
152 
153  protected function tearDown() {
155 
156  $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
157  $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
158 
159  // Restore backends
162 
163  // Remove temporary pages from the link cache
164  LinkCache::singleton()->clear();
165 
166  // Restore message cache (temporary pages and $wgUseDatabaseMessages)
168 
169  parent::tearDown();
170 
171  MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
172  $wgContLang->resetNamespaces(); # reset namespace cache
173  }
174 
175  public static function tearDownAfterClass() {
176  ParserTest::tearDownInterwikis();
177  parent::tearDownAfterClass();
178  }
179 
180  function addDBData() {
181  $this->tablesUsed[] = 'site_stats';
182  # disabled for performance
183  #$this->tablesUsed[] = 'image';
184 
185  # Update certain things in site_stats
186  $this->db->insert( 'site_stats',
187  array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ),
188  __METHOD__
189  );
190 
191  $user = User::newFromId( 0 );
192  LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
193 
194  # Upload DB table entries for files.
195  # We will upload the actual files later. Note that if anything causes LocalFile::load()
196  # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
197  # member to false and storing it in cache.
198  # note that the size/width/height/bits/etc of the file
199  # are actually set by inspecting the file itself; the arguments
200  # to recordUpload2 have no effect. That said, we try to make things
201  # match up so it is less confusing to readers of the code & tests.
202  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
203  if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
204  $image->recordUpload2(
205  '', // archive name
206  'Upload of some lame file',
207  'Some lame file',
208  array(
209  'size' => 7881,
210  'width' => 1941,
211  'height' => 220,
212  'bits' => 8,
213  'media_type' => MEDIATYPE_BITMAP,
214  'mime' => 'image/jpeg',
215  'metadata' => serialize( array() ),
216  'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
217  'fileExists' => true ),
218  $this->db->timestamp( '20010115123500' ), $user
219  );
220  }
221 
222  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
223  if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
224  $image->recordUpload2(
225  '', // archive name
226  'Upload of some lame thumbnail',
227  'Some lame thumbnail',
228  array(
229  'size' => 22589,
230  'width' => 135,
231  'height' => 135,
232  'bits' => 8,
233  'media_type' => MEDIATYPE_BITMAP,
234  'mime' => 'image/png',
235  'metadata' => serialize( array() ),
236  'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
237  'fileExists' => true ),
238  $this->db->timestamp( '20130225203040' ), $user
239  );
240  }
241 
242  # This image will be blacklisted in [[MediaWiki:Bad image list]]
243  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
244  if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
245  $image->recordUpload2(
246  '', // archive name
247  'zomgnotcensored',
248  'Borderline image',
249  array(
250  'size' => 12345,
251  'width' => 320,
252  'height' => 240,
253  'bits' => 24,
254  'media_type' => MEDIATYPE_BITMAP,
255  'mime' => 'image/jpeg',
256  'metadata' => serialize( array() ),
257  'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
258  'fileExists' => true ),
259  $this->db->timestamp( '20010115123500' ), $user
260  );
261  }
262  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
263  if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) {
264  $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
265  'size' => 12345,
266  'width' => 240,
267  'height' => 180,
268  'bits' => 24,
269  'media_type' => MEDIATYPE_DRAWING,
270  'mime' => 'image/svg+xml',
271  'metadata' => serialize( array() ),
272  'sha1' => wfBaseConvert( '', 16, 36, 31 ),
273  'fileExists' => true
274  ), $this->db->timestamp( '20010115123500' ), $user );
275  }
276  }
277 
278  //ParserTest setup/teardown functions
279 
284  protected function setupGlobals( $opts = array(), $config = '' ) {
285  global $wgFileBackends;
286  # Find out values for some special options.
287  $lang =
288  self::getOptionValue( 'language', $opts, 'en' );
289  $variant =
290  self::getOptionValue( 'variant', $opts, false );
291  $maxtoclevel =
292  self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
293  $linkHolderBatchSize =
294  self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
295 
296  $uploadDir = $this->getUploadDir();
297  if ( $this->getCliArg( 'use-filebackend=' ) ) {
298  if ( self::$backendToUse ) {
299  $backend = self::$backendToUse;
300  } else {
301  $name = $this->getCliArg( 'use-filebackend=' );
302  $useConfig = array();
303  foreach ( $wgFileBackends as $conf ) {
304  if ( $conf['name'] == $name ) {
305  $useConfig = $conf;
306  }
307  }
308  $useConfig['name'] = 'local-backend'; // swap name
309  unset( $useConfig['lockManager'] );
310  unset( $useConfig['fileJournal'] );
311  $class = $useConfig['class'];
312  self::$backendToUse = new $class( $useConfig );
313  $backend = self::$backendToUse;
314  }
315  } else {
316  # Replace with a mock. We do not care about generating real
317  # files on the filesystem, just need to expose the file
318  # informations.
319  $backend = new MockFileBackend( array(
320  'name' => 'local-backend',
321  'wikiId' => wfWikiId()
322  ) );
323  }
324 
325  $settings = array(
326  'wgLocalFileRepo' => array(
327  'class' => 'LocalRepo',
328  'name' => 'local',
329  'url' => 'http://example.com/images',
330  'hashLevels' => 2,
331  'transformVia404' => false,
332  'backend' => $backend
333  ),
334  'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
335  'wgLanguageCode' => $lang,
336  'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
337  'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
338  'wgNamespacesWithSubpages' => array( NS_MAIN => isset( $opts['subpage'] ) ),
339  'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
340  'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
341  'wgMaxTocLevel' => $maxtoclevel,
342  'wgUseTeX' => isset( $opts['math'] ) || isset( $opts['texvc'] ),
343  'wgMathDirectory' => $uploadDir . '/math',
344  'wgDefaultLanguageVariant' => $variant,
345  'wgLinkHolderBatchSize' => $linkHolderBatchSize,
346  );
347 
348  if ( $config ) {
349  $configLines = explode( "\n", $config );
350 
351  foreach ( $configLines as $line ) {
352  list( $var, $value ) = explode( '=', $line, 2 );
353 
354  $settings[$var] = eval( "return $value;" ); //???
355  }
356  }
357 
358  $this->savedGlobals = array();
359 
361  wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
362 
363  $langObj = Language::factory( $lang );
364  $settings['wgContLang'] = $langObj;
365  $settings['wgLang'] = $langObj;
366 
367  $context = new RequestContext();
368  $settings['wgOut'] = $context->getOutput();
369  $settings['wgUser'] = $context->getUser();
370  $settings['wgRequest'] = $context->getRequest();
371 
372  // We (re)set $wgThumbLimits to a single-element array above.
373  $context->getUser()->setOption( 'thumbsize', 0 );
374 
375  foreach ( $settings as $var => $val ) {
376  if ( array_key_exists( $var, $GLOBALS ) ) {
377  $this->savedGlobals[$var] = $GLOBALS[$var];
378  }
379 
380  $GLOBALS[$var] = $val;
381  }
382 
384 
385  # The entries saved into RepoGroup cache with previous globals will be wrong.
388 
389  # Create dummy files in storage
390  $this->setupUploads();
391 
392  # Publish the articles after we have the final language set
393  $this->publishTestArticles();
394 
396 
397  return $context;
398  }
399 
405  protected function getUploadDir() {
406  if ( $this->keepUploads ) {
407  $dir = wfTempDir() . '/mwParser-images';
408 
409  if ( is_dir( $dir ) ) {
410  return $dir;
411  }
412  } else {
413  $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
414  }
415 
416  // wfDebug( "Creating upload directory $dir\n" );
417  if ( file_exists( $dir ) ) {
418  wfDebug( "Already exists!\n" );
419 
420  return $dir;
421  }
422 
423  return $dir;
424  }
425 
432  protected function setupUploads() {
433  global $IP;
434 
435  $base = $this->getBaseDir();
436  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
437  $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) );
438  $backend->store( array(
439  'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg"
440  ) );
441  $backend->prepare( array( 'dir' => "$base/local-public/e/ea" ) );
442  $backend->store( array(
443  'src' => "$IP/skins/monobook/wiki.png", 'dst' => "$base/local-public/e/ea/Thumb.png"
444  ) );
445  $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) );
446  $backend->store( array(
447  'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg"
448  ) );
449 
450  // No helpful SVG file to copy, so make one ourselves
451  $data = '<?xml version="1.0" encoding="utf-8"?>' .
452  '<svg xmlns="http://www.w3.org/2000/svg"' .
453  ' version="1.1" width="240" height="180"/>';
454 
455  $backend->prepare( array( 'dir' => "$base/local-public/f/ff" ) );
456  $backend->quickCreate( array(
457  'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
458  ) );
459  }
460 
465  protected function teardownGlobals() {
466  $this->teardownUploads();
467 
468  foreach ( $this->savedGlobals as $var => $val ) {
469  $GLOBALS[$var] = $val;
470  }
471  }
472 
476  private function teardownUploads() {
477  if ( $this->keepUploads ) {
478  return;
479  }
480 
481  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
482  if ( $backend instanceof MockFileBackend ) {
483  # In memory backend, so dont bother cleaning them up.
484  return;
485  }
486 
487  $base = $this->getBaseDir();
488  // delete the files first, then the dirs.
489  self::deleteFiles(
490  array(
491  "$base/local-public/3/3a/Foobar.jpg",
492  "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
493  "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
494  "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
495  "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
496  "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
497  "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
498  "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
499  "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
500  "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
501  "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
502  "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
503  "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
504  "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
505  "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
506  "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
507  "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
508  "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
509  "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
510  "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
511  "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
512  "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
513  "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
514  "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
515  "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
516  "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
517  "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
518  "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
519  "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
520  "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
521  "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
522  "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
523 
524  "$base/local-public/e/ea/Thumb.png",
525 
526  "$base/local-public/0/09/Bad.jpg",
527 
528  "$base/local-public/f/ff/Foobar.svg",
529  "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
530  "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
531  "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
532  "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
533  "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
534  "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
535  "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
536  "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
537  "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
538 
539  "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
540  )
541  );
542  }
543 
548  private static function deleteFiles( $files ) {
549  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
550  foreach ( $files as $file ) {
551  $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) );
552  }
553  foreach ( $files as $file ) {
554  $tmp = $file;
555  while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) {
556  if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) {
557  break;
558  }
559  }
560  }
561  }
562 
563  protected function getBaseDir() {
564  return 'mwstore://local-backend';
565  }
566 
567  public function parserTestProvider() {
568  if ( $this->file === false ) {
569  global $wgParserTestFiles;
570  $this->file = $wgParserTestFiles[0];
571  }
572 
573  return new TestFileIterator( $this->file, $this );
574  }
575 
579  public function setParserTestFile( $filename ) {
580  $this->file = $filename;
581  }
582 
588  public function testParserTest( $desc, $input, $result, $opts, $config ) {
589  if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
590  $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
591  //$this->markTestSkipped( 'Filtered out by the user' );
592  return;
593  }
594 
595  if ( !$this->isWikitextNS( NS_MAIN ) ) {
596  // parser tests frequently assume that the main namespace contains wikitext.
597  // @todo When setting up pages, force the content model. Only skip if
598  // $wgtContentModelUseDB is false.
599  $this->markTestSkipped( "Main namespace does not support wikitext,"
600  . "skipping parser test: $desc" );
601  }
602 
603  wfDebug( "Running parser test: $desc\n" );
604 
605  $opts = $this->parseOptions( $opts );
606  $context = $this->setupGlobals( $opts, $config );
607 
608  $user = $context->getUser();
610 
611  if ( isset( $opts['title'] ) ) {
612  $titleText = $opts['title'];
613  } else {
614  $titleText = 'Parser test';
615  }
616 
617  $local = isset( $opts['local'] );
618  $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
619  $parser = $this->getParser( $preprocessor );
620 
621  $title = Title::newFromText( $titleText );
622 
623  # Parser test requiring math. Make sure texvc is executable
624  # or just skip such tests.
625  if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
626  global $wgTexvc;
627 
628  if ( !isset( $wgTexvc ) ) {
629  $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
630  } elseif ( !is_executable( $wgTexvc ) ) {
631  $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
632  . " or is not executable.\n"
633  . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
634  }
635  }
636 
637  if ( isset( $opts['pst'] ) ) {
638  $out = $parser->preSaveTransform( $input, $title, $user, $options );
639  } elseif ( isset( $opts['msg'] ) ) {
640  $out = $parser->transformMsg( $input, $options, $title );
641  } elseif ( isset( $opts['section'] ) ) {
642  $section = $opts['section'];
643  $out = $parser->getSection( $input, $section );
644  } elseif ( isset( $opts['replace'] ) ) {
645  $section = $opts['replace'][0];
646  $replace = $opts['replace'][1];
647  $out = $parser->replaceSection( $input, $section, $replace );
648  } elseif ( isset( $opts['comment'] ) ) {
649  $out = Linker::formatComment( $input, $title, $local );
650  } elseif ( isset( $opts['preload'] ) ) {
651  $out = $parser->getPreloadText( $input, $title, $options );
652  } else {
653  $output = $parser->parse( $input, $title, $options, true, true, 1337 );
654  $output->setTOCEnabled( !isset( $opts['notoc'] ) );
655  $out = $output->getText();
656 
657  if ( isset( $opts['showtitle'] ) ) {
658  if ( $output->getTitleText() ) {
659  $title = $output->getTitleText();
660  }
661 
662  $out = "$title\n$out";
663  }
664 
665  if ( isset( $opts['ill'] ) ) {
666  $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
667  } elseif ( isset( $opts['cat'] ) ) {
668  $outputPage = $context->getOutput();
669  $outputPage->addCategoryLinks( $output->getCategories() );
670  $cats = $outputPage->getCategoryLinks();
671 
672  if ( isset( $cats['normal'] ) ) {
673  $out = $this->tidy( implode( ' ', $cats['normal'] ) );
674  } else {
675  $out = '';
676  }
677  }
678  $parser->mPreprocessor = null;
679 
680  $result = $this->tidy( $result );
681  }
682 
683  $this->teardownGlobals();
684 
685  $this->assertEquals( $result, $out, $desc );
686  }
687 
696  public function testFuzzTests() {
697  global $wgParserTestFiles;
698 
699  $files = $wgParserTestFiles;
700 
701  if ( $this->getCliArg( 'file=' ) ) {
702  $files = array( $this->getCliArg( 'file=' ) );
703  }
704 
705  $dict = $this->getFuzzInput( $files );
706  $dictSize = strlen( $dict );
707  $logMaxLength = log( $this->maxFuzzTestLength );
708 
709  ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
710 
711  $user = new User;
713  $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
714 
715  $id = 1;
716 
717  while ( true ) {
718 
719  // Generate test input
720  mt_srand( ++$this->fuzzSeed );
721  $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
722  $input = '';
723 
724  while ( strlen( $input ) < $totalLength ) {
725  $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
726  $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
727  $offset = mt_rand( 0, $dictSize - $hairLength );
728  $input .= substr( $dict, $offset, $hairLength );
729  }
730 
731  $this->setupGlobals();
732  $parser = $this->getParser();
733 
734  // Run the test
735  try {
736  $parser->parse( $input, $title, $opts );
737  $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
738  } catch ( Exception $exception ) {
739  $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
740 
741  $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
742  "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
743  "Backtrace: {$exception->getTraceAsString()}" );
744  }
745 
746  $this->teardownGlobals();
747  $parser->__destruct();
748 
749  if ( $id % 100 == 0 ) {
750  $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
751  //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
752  if ( $usage > 90 ) {
753  $ret = "Out of memory:\n";
754  $memStats = $this->getMemoryBreakdown();
755 
756  foreach ( $memStats as $name => $usage ) {
757  $ret .= "$name: $usage\n";
758  }
759 
760  throw new MWException( $ret );
761  }
762  }
763 
764  $id++;
765  }
766  }
767 
768  //Various getter functions
769 
773  function getFuzzInput( $filenames ) {
774  $dict = '';
775 
776  foreach ( $filenames as $filename ) {
777  $contents = file_get_contents( $filename );
778  preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
779 
780  foreach ( $matches[1] as $match ) {
781  $dict .= $match . "\n";
782  }
783  }
784 
785  return $dict;
786  }
787 
791  function getMemoryBreakdown() {
792  $memStats = array();
793 
794  foreach ( $GLOBALS as $name => $value ) {
795  $memStats['$' . $name] = strlen( serialize( $value ) );
796  }
797 
798  $classes = get_declared_classes();
799 
800  foreach ( $classes as $class ) {
801  $rc = new ReflectionClass( $class );
802  $props = $rc->getStaticProperties();
803  $memStats[$class] = strlen( serialize( $props ) );
804  $methods = $rc->getMethods();
805 
806  foreach ( $methods as $method ) {
807  $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
808  }
809  }
810 
811  $functions = get_defined_functions();
812 
813  foreach ( $functions['user'] as $function ) {
814  $rf = new ReflectionFunction( $function );
815  $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
816  }
817 
818  asort( $memStats );
819 
820  return $memStats;
821  }
822 
826  function getParser( $preprocessor = null ) {
827  global $wgParserConf;
828 
829  $class = $wgParserConf['class'];
830  $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
831 
832  wfRunHooks( 'ParserTestParser', array( &$parser ) );
833 
834  return $parser;
835  }
836 
837  //Various action functions
838 
839  public function addArticle( $name, $text, $line ) {
840  self::$articles[$name] = array( $text, $line );
841  }
842 
843  public function publishTestArticles() {
844  if ( empty( self::$articles ) ) {
845  return;
846  }
847 
848  foreach ( self::$articles as $name => $info ) {
849  list( $text, $line ) = $info;
850  ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
851  }
852  }
853 
862  public function requireHook( $name ) {
864  $wgParser->firstCallInit(); // make sure hooks are loaded.
865  return isset( $wgParser->mTagHooks[$name] );
866  }
867 
868  public function requireFunctionHook( $name ) {
870  $wgParser->firstCallInit(); // make sure hooks are loaded.
871  return isset( $wgParser->mFunctionHooks[$name] );
872  }
873 
874  //Various "cleanup" functions
875 
883  protected function tidy( $text ) {
884  global $wgUseTidy;
885 
886  if ( $wgUseTidy ) {
887  $text = MWTidy::tidy( $text );
888  }
889 
890  return $text;
891  }
892 
896  public function removeEndingNewline( $s ) {
897  if ( substr( $s, -1 ) === "\n" ) {
898  return substr( $s, 0, -1 );
899  } else {
900  return $s;
901  }
902  }
903 
904  //Test options parser functions
905 
906  protected function parseOptions( $instring ) {
907  $opts = array();
908  // foo
909  // foo=bar
910  // foo="bar baz"
911  // foo=[[bar baz]]
912  // foo=bar,"baz quux"
913  $regex = '/\b
914  ([\w-]+) # Key
915  \b
916  (?:\s*
917  = # First sub-value
918  \s*
919  (
920  "
921  [^"]* # Quoted val
922  "
923  |
924  \[\[
925  [^]]* # Link target
926  \]\]
927  |
928  [\w-]+ # Plain word
929  )
930  (?:\s*
931  , # Sub-vals 1..N
932  \s*
933  (
934  "[^"]*" # Quoted val
935  |
936  \[\[[^]]*\]\] # Link target
937  |
938  [\w-]+ # Plain word
939  )
940  )*
941  )?
942  /x';
943 
944  if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
945  foreach ( $matches as $bits ) {
946  array_shift( $bits );
947  $key = strtolower( array_shift( $bits ) );
948  if ( count( $bits ) == 0 ) {
949  $opts[$key] = true;
950  } elseif ( count( $bits ) == 1 ) {
951  $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
952  } else {
953  // Array!
954  $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
955  }
956  }
957  }
958 
959  return $opts;
960  }
961 
962  protected function cleanupOption( $opt ) {
963  if ( substr( $opt, 0, 1 ) == '"' ) {
964  return substr( $opt, 1, -1 );
965  }
966 
967  if ( substr( $opt, 0, 2 ) == '[[' ) {
968  return substr( $opt, 2, -2 );
969  }
970 
971  return $opt;
972  }
973 
980  protected static function getOptionValue( $key, $opts, $default ) {
981  $key = strtolower( $key );
982 
983  if ( isset( $opts[$key] ) ) {
984  return $opts[$key];
985  } else {
986  return $default;
987  }
988  }
989 }
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:1254
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:4058
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:3424
$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:88
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:3760
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