MediaWiki  master
NewParserTest.php
Go to the documentation of this file.
1 <?php
12  static protected $articles = []; // Array of test articles defined by the tests
13  /* The data provider is run on a different instance than the test, so it must be static
14  * When running tests from several files, all tests will see all articles.
15  */
16  static protected $backendToUse;
17 
18  public $keepUploads = false;
19  public $runDisabled = false;
20  public $runParsoid = false;
21  public $regex = '';
22  public $showProgress = true;
23  public $savedWeirdGlobals = [];
24  public $savedGlobals = [];
25  public $hooks = [];
26  public $functionHooks = [];
27  public $transparentHooks = [];
28 
29  // Fuzz test
30  public $maxFuzzTestLength = 300;
31  public $fuzzSeed = 0;
32  public $memoryLimit = 50;
33 
37  private $djVuSupport;
41  private $tidySupport;
42 
43  protected $file = false;
44 
45  public static function setUpBeforeClass() {
46  // Inject ParserTest well-known interwikis
48  }
49 
50  protected function setUp() {
53 
54  parent::setUp();
55 
56  // Setup CLI arguments
57  if ( $this->getCliArg( 'regex' ) ) {
58  $this->regex = $this->getCliArg( 'regex' );
59  } else {
60  # Matches anything
61  $this->regex = '';
62  }
63 
64  $this->keepUploads = $this->getCliArg( 'keep-uploads' );
65 
66  $tmpGlobals = [];
67 
68  $tmpGlobals['wgLanguageCode'] = 'en';
69  $tmpGlobals['wgContLang'] = Language::factory( 'en' );
70  $tmpGlobals['wgSitename'] = 'MediaWiki';
71  $tmpGlobals['wgServer'] = 'http://example.org';
72  $tmpGlobals['wgServerName'] = 'example.org';
73  $tmpGlobals['wgScriptPath'] = '';
74  $tmpGlobals['wgScript'] = '/index.php';
75  $tmpGlobals['wgResourceBasePath'] = '';
76  $tmpGlobals['wgStylePath'] = '/skins';
77  $tmpGlobals['wgExtensionAssetsPath'] = '/extensions';
78  $tmpGlobals['wgArticlePath'] = '/wiki/$1';
79  $tmpGlobals['wgActionPaths'] = [];
80  $tmpGlobals['wgVariantArticlePath'] = false;
81  $tmpGlobals['wgEnableUploads'] = true;
82  $tmpGlobals['wgUploadNavigationUrl'] = false;
83  $tmpGlobals['wgThumbnailScriptPath'] = false;
84  $tmpGlobals['wgLocalFileRepo'] = [
85  'class' => 'LocalRepo',
86  'name' => 'local',
87  'url' => 'http://example.com/images',
88  'hashLevels' => 2,
89  'transformVia404' => false,
90  'backend' => 'local-backend'
91  ];
92  $tmpGlobals['wgForeignFileRepos'] = [];
93  $tmpGlobals['wgDefaultExternalStore'] = [];
94  $tmpGlobals['wgParserCacheType'] = CACHE_NONE;
95  $tmpGlobals['wgCapitalLinks'] = true;
96  $tmpGlobals['wgNoFollowLinks'] = true;
97  $tmpGlobals['wgNoFollowDomainExceptions'] = [ 'no-nofollow.org' ];
98  $tmpGlobals['wgExternalLinkTarget'] = false;
99  $tmpGlobals['wgThumbnailScriptPath'] = false;
100  $tmpGlobals['wgUseImageResize'] = true;
101  $tmpGlobals['wgAllowExternalImages'] = true;
102  $tmpGlobals['wgRawHtml'] = false;
103  $tmpGlobals['wgExperimentalHtmlIds'] = false;
104  $tmpGlobals['wgAdaptiveMessageCache'] = true;
105  $tmpGlobals['wgUseDatabaseMessages'] = true;
106  $tmpGlobals['wgLocaltimezone'] = 'UTC';
107  $tmpGlobals['wgGroupPermissions'] = [
108  '*' => [
109  'createaccount' => true,
110  'read' => true,
111  'edit' => true,
112  'createpage' => true,
113  'createtalk' => true,
114  ] ];
115  $tmpGlobals['wgNamespaceProtection'] = [ NS_MEDIAWIKI => 'editinterface' ];
116 
117  $tmpGlobals['wgParser'] = new StubObject(
118  'wgParser', $GLOBALS['wgParserConf']['class'],
119  [ $GLOBALS['wgParserConf'] ] );
120 
121  $tmpGlobals['wgFileExtensions'][] = 'svg';
122  $tmpGlobals['wgSVGConverter'] = 'rsvg';
123  $tmpGlobals['wgSVGConverters']['rsvg'] =
124  '$path/rsvg-convert -w $width -h $height -o $output $input';
125 
126  if ( $GLOBALS['wgStyleDirectory'] === false ) {
127  $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
128  }
129 
130  # Replace all media handlers with a mock. We do not need to generate
131  # actual thumbnails to do parser testing, we only care about receiving
132  # a ThumbnailImage properly initialized.
134  foreach ( $wgMediaHandlers as $type => $handler ) {
135  $tmpGlobals['wgMediaHandlers'][$type] = 'MockBitmapHandler';
136  }
137  // Vector images have to be handled slightly differently
138  $tmpGlobals['wgMediaHandlers']['image/svg+xml'] = 'MockSvgHandler';
139 
140  // DjVu images have to be handled slightly differently
141  $tmpGlobals['wgMediaHandlers']['image/vnd.djvu'] = 'MockDjVuHandler';
142 
143  // Ogg video/audio increasingly more differently
144  $tmpGlobals['wgMediaHandlers']['application/ogg'] = 'MockOggHandler';
145 
146  $tmpHooks = $wgHooks;
147  $tmpHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
148  $tmpHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
149  $tmpGlobals['wgHooks'] = $tmpHooks;
150  # add a namespace shadowing a interwiki link, to test
151  # proper precedence when resolving links. (bug 51680)
152  $tmpGlobals['wgExtraNamespaces'] = [
153  100 => 'MemoryAlpha',
154  101 => 'MemoryAlpha_talk'
155  ];
156 
157  $tmpGlobals['wgLocalInterwikis'] = [ 'local', 'mi' ];
158  # "extra language links"
159  # see https://gerrit.wikimedia.org/r/111390
160  $tmpGlobals['wgExtraInterlanguageLinkPrefixes'] = [ 'mul' ];
161 
162  // DjVu support
163  $this->djVuSupport = new DjVuSupport();
164  // Tidy support
165  $this->tidySupport = new TidySupport();
166  $tmpGlobals['wgTidyConfig'] = $this->tidySupport->getConfig();
167  $tmpGlobals['wgUseTidy'] = false;
168 
169  $this->setMwGlobals( $tmpGlobals );
170 
171  $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
172  $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
173 
174  $wgNamespaceAliases['Image'] = NS_FILE;
175  $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
176 
177  MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
178  $wgContLang->resetNamespaces(); # reset namespace cache
179  ParserTest::resetTitleServices();
180  }
181 
182  protected function tearDown() {
184 
185  $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
186  $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
187 
189 
190  // Restore backends
193 
194  // Remove temporary pages from the link cache
195  LinkCache::singleton()->clear();
196 
197  // Restore message cache (temporary pages and $wgUseDatabaseMessages)
199 
200  parent::tearDown();
201 
202  MWNamespace::getCanonicalNamespaces( true ); # reset namespace cache
203  $wgContLang->resetNamespaces(); # reset namespace cache
204  }
205 
206  public static function tearDownAfterClass() {
208  parent::tearDownAfterClass();
209  }
210 
211  function addDBDataOnce() {
212  # disabled for performance
213  # $this->tablesUsed[] = 'image';
214 
215  # Update certain things in site_stats
216  $this->db->insert( 'site_stats',
217  [ 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ],
218  __METHOD__,
219  [ 'IGNORE' ]
220  );
221 
222  $user = User::newFromId( 0 );
223  LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision
224 
225  # Upload DB table entries for files.
226  # We will upload the actual files later. Note that if anything causes LocalFile::load()
227  # to be triggered before then, it will break via maybeUpgrade() setting the fileExists
228  # member to false and storing it in cache.
229  # note that the size/width/height/bits/etc of the file
230  # are actually set by inspecting the file itself; the arguments
231  # to recordUpload2 have no effect. That said, we try to make things
232  # match up so it is less confusing to readers of the code & tests.
233  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
234  if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
235  $image->recordUpload2(
236  '', // archive name
237  'Upload of some lame file',
238  'Some lame file',
239  [
240  'size' => 7881,
241  'width' => 1941,
242  'height' => 220,
243  'bits' => 8,
244  'media_type' => MEDIATYPE_BITMAP,
245  'mime' => 'image/jpeg',
246  'metadata' => serialize( [] ),
247  'sha1' => Wikimedia\base_convert( '1', 16, 36, 31 ),
248  'fileExists' => true ],
249  $this->db->timestamp( '20010115123500' ), $user
250  );
251  }
252 
253  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
254  if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
255  $image->recordUpload2(
256  '', // archive name
257  'Upload of some lame thumbnail',
258  'Some lame thumbnail',
259  [
260  'size' => 22589,
261  'width' => 135,
262  'height' => 135,
263  'bits' => 8,
264  'media_type' => MEDIATYPE_BITMAP,
265  'mime' => 'image/png',
266  'metadata' => serialize( [] ),
267  'sha1' => Wikimedia\base_convert( '2', 16, 36, 31 ),
268  'fileExists' => true ],
269  $this->db->timestamp( '20130225203040' ), $user
270  );
271  }
272 
273  # This image will be blacklisted in [[MediaWiki:Bad image list]]
274  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
275  if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
276  $image->recordUpload2(
277  '', // archive name
278  'zomgnotcensored',
279  'Borderline image',
280  [
281  'size' => 12345,
282  'width' => 320,
283  'height' => 240,
284  'bits' => 24,
285  'media_type' => MEDIATYPE_BITMAP,
286  'mime' => 'image/jpeg',
287  'metadata' => serialize( [] ),
288  'sha1' => Wikimedia\base_convert( '3', 16, 36, 31 ),
289  'fileExists' => true ],
290  $this->db->timestamp( '20010115123500' ), $user
291  );
292  }
293  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
294  if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
295  $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', [
296  'size' => 12345,
297  'width' => 240,
298  'height' => 180,
299  'bits' => 0,
300  'media_type' => MEDIATYPE_DRAWING,
301  'mime' => 'image/svg+xml',
302  'metadata' => serialize( [] ),
303  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
304  'fileExists' => true
305  ], $this->db->timestamp( '20010115123500' ), $user );
306  }
307 
308  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Video.ogv' ) );
309  if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
310  $image->recordUpload2( '', 'A pretty movie', 'Will it play', [
311  'size' => 12345,
312  'width' => 320,
313  'height' => 240,
314  'bits' => 0,
315  'media_type' => MEDIATYPE_VIDEO,
316  'mime' => 'application/ogg',
317  'metadata' => serialize( [] ),
318  'sha1' => Wikimedia\base_convert( '', 16, 36, 32 ),
319  'fileExists' => true
320  ], $this->db->timestamp( '20010115123500' ), $user );
321  }
322 
323  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Audio.oga' ) );
324  if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
325  $image->recordUpload2( '', 'An awesome hitsong ', 'Will it play', [
326  'size' => 12345,
327  'width' => 0,
328  'height' => 0,
329  'bits' => 0,
330  'media_type' => MEDIATYPE_AUDIO,
331  'mime' => 'application/ogg',
332  'metadata' => serialize( [] ),
333  'sha1' => Wikimedia\base_convert( '', 16, 36, 32 ),
334  'fileExists' => true
335  ], $this->db->timestamp( '20010115123500' ), $user );
336  }
337 
338  # A DjVu file
339  $image = wfLocalFile( Title::makeTitle( NS_FILE, 'LoremIpsum.djvu' ) );
340  if ( !$this->db->selectField( 'image', '1', [ 'img_name' => $image->getName() ] ) ) {
341  $image->recordUpload2( '', 'Upload a DjVu', 'A DjVu', [
342  'size' => 3249,
343  'width' => 2480,
344  'height' => 3508,
345  'bits' => 0,
346  'media_type' => MEDIATYPE_BITMAP,
347  'mime' => 'image/vnd.djvu',
348  'metadata' => '<?xml version="1.0" ?>
349 <!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
350 <DjVuXML>
351 <HEAD></HEAD>
352 <BODY><OBJECT height="3508" width="2480">
353 <PARAM name="DPI" value="300" />
354 <PARAM name="GAMMA" value="2.2" />
355 </OBJECT>
356 <OBJECT height="3508" width="2480">
357 <PARAM name="DPI" value="300" />
358 <PARAM name="GAMMA" value="2.2" />
359 </OBJECT>
360 <OBJECT height="3508" width="2480">
361 <PARAM name="DPI" value="300" />
362 <PARAM name="GAMMA" value="2.2" />
363 </OBJECT>
364 <OBJECT height="3508" width="2480">
365 <PARAM name="DPI" value="300" />
366 <PARAM name="GAMMA" value="2.2" />
367 </OBJECT>
368 <OBJECT height="3508" width="2480">
369 <PARAM name="DPI" value="300" />
370 <PARAM name="GAMMA" value="2.2" />
371 </OBJECT>
372 </BODY>
373 </DjVuXML>',
374  'sha1' => Wikimedia\base_convert( '', 16, 36, 31 ),
375  'fileExists' => true
376  ], $this->db->timestamp( '20140115123600' ), $user );
377  }
378  }
379 
380  // ParserTest setup/teardown functions
381 
389  protected function setupGlobals( $opts = [], $config = '' ) {
391  # Find out values for some special options.
392  $lang =
393  self::getOptionValue( 'language', $opts, 'en' );
394  $variant =
395  self::getOptionValue( 'variant', $opts, false );
396  $maxtoclevel =
397  self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
398  $linkHolderBatchSize =
399  self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
400 
401  $uploadDir = $this->getUploadDir();
402  if ( $this->getCliArg( 'use-filebackend' ) ) {
403  if ( self::$backendToUse ) {
404  $backend = self::$backendToUse;
405  } else {
406  $name = $this->getCliArg( 'use-filebackend' );
407  $useConfig = [];
408  foreach ( $wgFileBackends as $conf ) {
409  if ( $conf['name'] == $name ) {
410  $useConfig = $conf;
411  }
412  }
413  $useConfig['name'] = 'local-backend'; // swap name
414  unset( $useConfig['lockManager'] );
415  unset( $useConfig['fileJournal'] );
416  $class = $useConfig['class'];
417  self::$backendToUse = new $class( $useConfig );
418  $backend = self::$backendToUse;
419  }
420  } else {
421  # Replace with a mock. We do not care about generating real
422  # files on the filesystem, just need to expose the file
423  # informations.
424  $backend = new MockFileBackend( [
425  'name' => 'local-backend',
426  'wikiId' => wfWikiID()
427  ] );
428  }
429 
430  $settings = [
431  'wgLocalFileRepo' => [
432  'class' => 'LocalRepo',
433  'name' => 'local',
434  'url' => 'http://example.com/images',
435  'hashLevels' => 2,
436  'transformVia404' => false,
437  'backend' => $backend
438  ],
439  'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
440  'wgLanguageCode' => $lang,
441  'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
442  'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
443  'wgNamespacesWithSubpages' => [ NS_MAIN => isset( $opts['subpage'] ) ],
444  'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
445  'wgThumbLimits' => [ self::getOptionValue( 'thumbsize', $opts, 180 ) ],
446  'wgMaxTocLevel' => $maxtoclevel,
447  'wgUseTeX' => isset( $opts['math'] ) || isset( $opts['texvc'] ),
448  'wgMathDirectory' => $uploadDir . '/math',
449  'wgDefaultLanguageVariant' => $variant,
450  'wgLinkHolderBatchSize' => $linkHolderBatchSize,
451  'wgUseTidy' => false,
452  'wgTidyConfig' => isset( $opts['tidy'] ) ? $this->tidySupport->getConfig() : null
453  ];
454 
455  if ( $config ) {
456  $configLines = explode( "\n", $config );
457 
458  foreach ( $configLines as $line ) {
459  list( $var, $value ) = explode( '=', $line, 2 );
460 
461  $settings[$var] = eval( "return $value;" ); // ???
462  }
463  }
464 
465  $this->savedGlobals = [];
466 
468  Hooks::run( 'ParserTestGlobals', [ &$settings ] );
469 
470  $langObj = Language::factory( $lang );
471  $settings['wgContLang'] = $langObj;
472  $settings['wgLang'] = $langObj;
473 
474  $context = new RequestContext();
475  $settings['wgOut'] = $context->getOutput();
476  $settings['wgUser'] = $context->getUser();
477  $settings['wgRequest'] = $context->getRequest();
478 
479  // We (re)set $wgThumbLimits to a single-element array above.
480  $context->getUser()->setOption( 'thumbsize', 0 );
481 
482  foreach ( $settings as $var => $val ) {
483  if ( array_key_exists( $var, $GLOBALS ) ) {
484  $this->savedGlobals[$var] = $GLOBALS[$var];
485  }
486 
487  $GLOBALS[$var] = $val;
488  }
489 
492 
493  # The entries saved into RepoGroup cache with previous globals will be wrong.
496 
497  # Create dummy files in storage
498  $this->setupUploads();
499 
500  # Publish the articles after we have the final language set
501  $this->publishTestArticles();
502 
504 
505  return $context;
506  }
507 
513  protected function getUploadDir() {
514  if ( $this->keepUploads ) {
515  // Don't use getNewTempDirectory() as this is meant to persist
516  $dir = wfTempDir() . '/mwParser-images';
517 
518  if ( is_dir( $dir ) ) {
519  return $dir;
520  }
521  } else {
522  $dir = $this->getNewTempDirectory();
523  }
524 
525  if ( file_exists( $dir ) ) {
526  wfDebug( "Already exists!\n" );
527 
528  return $dir;
529  }
530 
531  return $dir;
532  }
533 
540  protected function setupUploads() {
541  global $IP;
542 
543  $base = $this->getBaseDir();
544  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
545  $backend->prepare( [ 'dir' => "$base/local-public/3/3a" ] );
546  $backend->store( [
547  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
548  'dst' => "$base/local-public/3/3a/Foobar.jpg"
549  ] );
550  $backend->prepare( [ 'dir' => "$base/local-public/e/ea" ] );
551  $backend->store( [
552  'src' => "$IP/tests/phpunit/data/parser/wiki.png",
553  'dst' => "$base/local-public/e/ea/Thumb.png"
554  ] );
555  $backend->prepare( [ 'dir' => "$base/local-public/0/09" ] );
556  $backend->store( [
557  'src' => "$IP/tests/phpunit/data/parser/headbg.jpg",
558  'dst' => "$base/local-public/0/09/Bad.jpg"
559  ] );
560  $backend->prepare( [ 'dir' => "$base/local-public/5/5f" ] );
561  $backend->store( [
562  'src' => "$IP/tests/phpunit/data/parser/LoremIpsum.djvu",
563  'dst' => "$base/local-public/5/5f/LoremIpsum.djvu"
564  ] );
565 
566  // No helpful SVG file to copy, so make one ourselves
567  $data = '<?xml version="1.0" encoding="utf-8"?>' .
568  '<svg xmlns="http://www.w3.org/2000/svg"' .
569  ' version="1.1" width="240" height="180"/>';
570 
571  $backend->prepare( [ 'dir' => "$base/local-public/f/ff" ] );
572  $backend->quickCreate( [
573  'content' => $data, 'dst' => "$base/local-public/f/ff/Foobar.svg"
574  ] );
575  }
576 
581  protected function teardownGlobals() {
582  $this->teardownUploads();
583 
584  foreach ( $this->savedGlobals as $var => $val ) {
585  $GLOBALS[$var] = $val;
586  }
587  }
588 
592  private function teardownUploads() {
593  if ( $this->keepUploads ) {
594  return;
595  }
596 
597  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
598  if ( $backend instanceof MockFileBackend ) {
599  # In memory backend, so dont bother cleaning them up.
600  return;
601  }
602 
603  $base = $this->getBaseDir();
604  // delete the files first, then the dirs.
605  self::deleteFiles(
606  [
607  "$base/local-public/3/3a/Foobar.jpg",
608  "$base/local-thumb/3/3a/Foobar.jpg/1000px-Foobar.jpg",
609  "$base/local-thumb/3/3a/Foobar.jpg/100px-Foobar.jpg",
610  "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
611  "$base/local-thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
612  "$base/local-thumb/3/3a/Foobar.jpg/137px-Foobar.jpg",
613  "$base/local-thumb/3/3a/Foobar.jpg/1500px-Foobar.jpg",
614  "$base/local-thumb/3/3a/Foobar.jpg/177px-Foobar.jpg",
615  "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
616  "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
617  "$base/local-thumb/3/3a/Foobar.jpg/206px-Foobar.jpg",
618  "$base/local-thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
619  "$base/local-thumb/3/3a/Foobar.jpg/220px-Foobar.jpg",
620  "$base/local-thumb/3/3a/Foobar.jpg/265px-Foobar.jpg",
621  "$base/local-thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
622  "$base/local-thumb/3/3a/Foobar.jpg/274px-Foobar.jpg",
623  "$base/local-thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
624  "$base/local-thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
625  "$base/local-thumb/3/3a/Foobar.jpg/330px-Foobar.jpg",
626  "$base/local-thumb/3/3a/Foobar.jpg/353px-Foobar.jpg",
627  "$base/local-thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
628  "$base/local-thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
629  "$base/local-thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
630  "$base/local-thumb/3/3a/Foobar.jpg/440px-Foobar.jpg",
631  "$base/local-thumb/3/3a/Foobar.jpg/442px-Foobar.jpg",
632  "$base/local-thumb/3/3a/Foobar.jpg/450px-Foobar.jpg",
633  "$base/local-thumb/3/3a/Foobar.jpg/50px-Foobar.jpg",
634  "$base/local-thumb/3/3a/Foobar.jpg/600px-Foobar.jpg",
635  "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
636  "$base/local-thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
637  "$base/local-thumb/3/3a/Foobar.jpg/75px-Foobar.jpg",
638  "$base/local-thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
639 
640  "$base/local-public/e/ea/Thumb.png",
641 
642  "$base/local-public/0/09/Bad.jpg",
643 
644  "$base/local-public/5/5f/LoremIpsum.djvu",
645  "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-2480px-LoremIpsum.djvu.jpg",
646  "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-3720px-LoremIpsum.djvu.jpg",
647  "$base/local-thumb/5/5f/LoremIpsum.djvu/page2-4960px-LoremIpsum.djvu.jpg",
648 
649  "$base/local-public/f/ff/Foobar.svg",
650  "$base/local-thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
651  "$base/local-thumb/f/ff/Foobar.svg/2000px-Foobar.svg.png",
652  "$base/local-thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
653  "$base/local-thumb/f/ff/Foobar.svg/3000px-Foobar.svg.png",
654  "$base/local-thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
655  "$base/local-thumb/f/ff/Foobar.svg/4000px-Foobar.svg.png",
656  "$base/local-thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
657  "$base/local-thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
658  "$base/local-thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
659 
660  "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
661  ]
662  );
663  }
664 
669  private static function deleteFiles( $files ) {
670  $backend = RepoGroup::singleton()->getLocalRepo()->getBackend();
671  foreach ( $files as $file ) {
672  $backend->delete( [ 'src' => $file ], [ 'force' => 1 ] );
673  }
674  foreach ( $files as $file ) {
675  $tmp = FileBackend::parentStoragePath( $file );
676  while ( $tmp ) {
677  if ( !$backend->clean( [ 'dir' => $tmp ] )->isOK() ) {
678  break;
679  }
680  $tmp = FileBackend::parentStoragePath( $tmp );
681  }
682  }
683  }
684 
685  protected function getBaseDir() {
686  return 'mwstore://local-backend';
687  }
688 
689  public function parserTestProvider() {
690  if ( $this->file === false ) {
692  $this->file = $wgParserTestFiles[0];
693  }
694 
695  return new TestFileDataProvider( $this->file, $this );
696  }
697 
702  public function setParserTestFile( $filename ) {
703  $this->file = $filename;
704  }
705 
716  public function testParserTest( $desc, $input, $result, $opts, $config ) {
717  if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) {
718  $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions"
719  // $this->markTestSkipped( 'Filtered out by the user' );
720  return;
721  }
722 
723  if ( !$this->isWikitextNS( NS_MAIN ) ) {
724  // parser tests frequently assume that the main namespace contains wikitext.
725  // @todo When setting up pages, force the content model. Only skip if
726  // $wgtContentModelUseDB is false.
727  $this->markTestSkipped( "Main namespace does not support wikitext,"
728  . "skipping parser test: $desc" );
729  }
730 
731  wfDebug( "Running parser test: $desc\n" );
732 
733  $opts = $this->parseOptions( $opts );
734  $context = $this->setupGlobals( $opts, $config );
735 
736  $user = $context->getUser();
738 
739  if ( isset( $opts['title'] ) ) {
740  $titleText = $opts['title'];
741  } else {
742  $titleText = 'Parser test';
743  }
744 
745  $local = isset( $opts['local'] );
746  $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
747  $parser = $this->getParser( $preprocessor );
748 
749  $title = Title::newFromText( $titleText );
750 
751  # Parser test requiring math. Make sure texvc is executable
752  # or just skip such tests.
753  if ( isset( $opts['math'] ) || isset( $opts['texvc'] ) ) {
754  global $wgTexvc;
755 
756  if ( !isset( $wgTexvc ) ) {
757  $this->markTestSkipped( "SKIPPED: \$wgTexvc is not set" );
758  } elseif ( !is_executable( $wgTexvc ) ) {
759  $this->markTestSkipped( "SKIPPED: texvc binary does not exist"
760  . " or is not executable.\n"
761  . "Current configuration is:\n\$wgTexvc = '$wgTexvc'" );
762  }
763  }
764 
765  if ( isset( $opts['djvu'] ) ) {
766  if ( !$this->djVuSupport->isEnabled() ) {
767  $this->markTestSkipped( "SKIPPED: djvu binaries do not exist or are not executable.\n" );
768  }
769  }
770 
771  if ( isset( $opts['tidy'] ) ) {
772  if ( !$this->tidySupport->isEnabled() ) {
773  $this->markTestSkipped( "SKIPPED: tidy extension is not installed.\n" );
774  } else {
775  $options->setTidy( true );
776  }
777  }
778 
779  if ( isset( $opts['pst'] ) ) {
780  $out = $parser->preSaveTransform( $input, $title, $user, $options );
781  } elseif ( isset( $opts['msg'] ) ) {
782  $out = $parser->transformMsg( $input, $options, $title );
783  } elseif ( isset( $opts['section'] ) ) {
784  $section = $opts['section'];
785  $out = $parser->getSection( $input, $section );
786  } elseif ( isset( $opts['replace'] ) ) {
787  $section = $opts['replace'][0];
788  $replace = $opts['replace'][1];
789  $out = $parser->replaceSection( $input, $section, $replace );
790  } elseif ( isset( $opts['comment'] ) ) {
791  $out = Linker::formatComment( $input, $title, $local );
792  } elseif ( isset( $opts['preload'] ) ) {
793  $out = $parser->getPreloadText( $input, $title, $options );
794  } else {
795  $output = $parser->parse( $input, $title, $options, true, true, 1337 );
796  $output->setTOCEnabled( !isset( $opts['notoc'] ) );
797  $out = $output->getText();
798  if ( isset( $opts['tidy'] ) ) {
799  $out = preg_replace( '/\s+$/', '', $out );
800  }
801 
802  if ( isset( $opts['showtitle'] ) ) {
803  if ( $output->getTitleText() ) {
805  }
806 
807  $out = "$title\n$out";
808  }
809 
810  if ( isset( $opts['showindicators'] ) ) {
811  $indicators = '';
812  foreach ( $output->getIndicators() as $id => $content ) {
813  $indicators .= "$id=$content\n";
814  }
815  $out = $indicators . $out;
816  }
817 
818  if ( isset( $opts['ill'] ) ) {
819  $out = implode( ' ', $output->getLanguageLinks() );
820  } elseif ( isset( $opts['cat'] ) ) {
821  $outputPage = $context->getOutput();
822  $outputPage->addCategoryLinks( $output->getCategories() );
823  $cats = $outputPage->getCategoryLinks();
824 
825  if ( isset( $cats['normal'] ) ) {
826  $out = implode( ' ', $cats['normal'] );
827  } else {
828  $out = '';
829  }
830  }
831  $parser->mPreprocessor = null;
832  }
833 
834  $this->teardownGlobals();
835 
836  $this->assertEquals( $result, $out, $desc );
837  }
838 
847  public function testFuzzTests() {
849 
851 
852  if ( $this->getCliArg( 'file' ) ) {
853  $files = [ $this->getCliArg( 'file' ) ];
854  }
855 
856  $dict = $this->getFuzzInput( $files );
857  $dictSize = strlen( $dict );
858  $logMaxLength = log( $this->maxFuzzTestLength );
859 
860  ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
861 
862  $user = new User;
864  $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
865 
866  $id = 1;
867 
868  while ( true ) {
869 
870  // Generate test input
871  mt_srand( ++$this->fuzzSeed );
872  $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
873  $input = '';
874 
875  while ( strlen( $input ) < $totalLength ) {
876  $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
877  $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
878  $offset = mt_rand( 0, $dictSize - $hairLength );
879  $input .= substr( $dict, $offset, $hairLength );
880  }
881 
882  $this->setupGlobals();
883  $parser = $this->getParser();
884 
885  // Run the test
886  try {
887  $parser->parse( $input, $title, $opts );
888  $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
889  } catch ( Exception $exception ) {
890  $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input );
891 
892  $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\n" .
893  "Input: $input_dump\n\nError: {$exception->getMessage()}\n\n" .
894  "Backtrace: {$exception->getTraceAsString()}" );
895  }
896 
897  $this->teardownGlobals();
898  $parser->__destruct();
899 
900  if ( $id % 100 == 0 ) {
901  $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
902  // echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
903  if ( $usage > 90 ) {
904  $ret = "Out of memory:\n";
905  $memStats = $this->getMemoryBreakdown();
906 
907  foreach ( $memStats as $name => $usage ) {
908  $ret .= "$name: $usage\n";
909  }
910 
911  throw new MWException( $ret );
912  }
913  }
914 
915  $id++;
916  }
917  }
918 
919  // Various getter functions
920 
926  function getFuzzInput( $filenames ) {
927  $dict = '';
928 
929  foreach ( $filenames as $filename ) {
930  $contents = file_get_contents( $filename );
931  preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
932 
933  foreach ( $matches[1] as $match ) {
934  $dict .= $match . "\n";
935  }
936  }
937 
938  return $dict;
939  }
940 
945  function getMemoryBreakdown() {
946  $memStats = [];
947 
948  foreach ( $GLOBALS as $name => $value ) {
949  $memStats['$' . $name] = strlen( serialize( $value ) );
950  }
951 
952  $classes = get_declared_classes();
953 
954  foreach ( $classes as $class ) {
955  $rc = new ReflectionClass( $class );
956  $props = $rc->getStaticProperties();
957  $memStats[$class] = strlen( serialize( $props ) );
958  $methods = $rc->getMethods();
959 
960  foreach ( $methods as $method ) {
961  $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
962  }
963  }
964 
965  $functions = get_defined_functions();
966 
967  foreach ( $functions['user'] as $function ) {
968  $rf = new ReflectionFunction( $function );
969  $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
970  }
971 
972  asort( $memStats );
973 
974  return $memStats;
975  }
976 
982  function getParser( $preprocessor = null ) {
983  global $wgParserConf;
984 
985  $class = $wgParserConf['class'];
986  $parser = new $class( [ 'preprocessorClass' => $preprocessor ] + $wgParserConf );
987 
988  Hooks::run( 'ParserTestParser', [ &$parser ] );
989 
990  return $parser;
991  }
992 
993  // Various action functions
994 
995  public function addArticle( $name, $text, $line ) {
996  self::$articles[$name] = [ $text, $line ];
997  }
998 
999  public function publishTestArticles() {
1000  if ( empty( self::$articles ) ) {
1001  return;
1002  }
1003 
1004  foreach ( self::$articles as $name => $info ) {
1005  list( $text, $line ) = $info;
1006  ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' );
1007  }
1008  }
1009 
1018  public function requireHook( $name ) {
1019  global $wgParser;
1020  $wgParser->firstCallInit(); // make sure hooks are loaded.
1021  return isset( $wgParser->mTagHooks[$name] );
1022  }
1023 
1024  public function requireFunctionHook( $name ) {
1025  global $wgParser;
1026  $wgParser->firstCallInit(); // make sure hooks are loaded.
1027  return isset( $wgParser->mFunctionHooks[$name] );
1028  }
1029 
1030  public function requireTransparentHook( $name ) {
1031  global $wgParser;
1032  $wgParser->firstCallInit(); // make sure hooks are loaded.
1033  return isset( $wgParser->mTransparentTagHooks[$name] );
1034  }
1035 
1036  // Various "cleanup" functions
1037 
1043  public function removeEndingNewline( $s ) {
1044  if ( substr( $s, -1 ) === "\n" ) {
1045  return substr( $s, 0, -1 );
1046  } else {
1047  return $s;
1048  }
1049  }
1050 
1051  // Test options parser functions
1052 
1053  protected function parseOptions( $instring ) {
1054  $opts = [];
1055  // foo
1056  // foo=bar
1057  // foo="bar baz"
1058  // foo=[[bar baz]]
1059  // foo=bar,"baz quux"
1060  $regex = '/\b
1061  ([\w-]+) # Key
1062  \b
1063  (?:\s*
1064  = # First sub-value
1065  \s*
1066  (
1067  "
1068  [^"]* # Quoted val
1069  "
1070  |
1071  \[\[
1072  [^]]* # Link target
1073  \]\]
1074  |
1075  [\w-]+ # Plain word
1076  )
1077  (?:\s*
1078  , # Sub-vals 1..N
1079  \s*
1080  (
1081  "[^"]*" # Quoted val
1082  |
1083  \[\[[^]]*\]\] # Link target
1084  |
1085  [\w-]+ # Plain word
1086  )
1087  )*
1088  )?
1089  /x';
1090 
1091  if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
1092  foreach ( $matches as $bits ) {
1093  array_shift( $bits );
1094  $key = strtolower( array_shift( $bits ) );
1095  if ( count( $bits ) == 0 ) {
1096  $opts[$key] = true;
1097  } elseif ( count( $bits ) == 1 ) {
1098  $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
1099  } else {
1100  // Array!
1101  $opts[$key] = array_map( [ $this, 'cleanupOption' ], $bits );
1102  }
1103  }
1104  }
1105 
1106  return $opts;
1107  }
1108 
1109  protected function cleanupOption( $opt ) {
1110  if ( substr( $opt, 0, 1 ) == '"' ) {
1111  return substr( $opt, 1, -1 );
1112  }
1113 
1114  if ( substr( $opt, 0, 2 ) == '[[' ) {
1115  return substr( $opt, 2, -2 );
1116  }
1117 
1118  return $opt;
1119  }
1120 
1128  protected static function getOptionValue( $key, $opts, $default ) {
1129  $key = strtolower( $key );
1130 
1131  if ( isset( $opts[$key] ) ) {
1132  return $opts[$key];
1133  } else {
1134  return $default;
1135  }
1136  }
1137 }
static $backendToUse
#define the
table suitable for use with IDatabase::select()
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
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:776
$wgParserTestFiles
Parser test suite files to be run by parserTests.php when no specific filename is passed to it...
Group all the pieces relevant to the context of a request into one instance.
$context
Definition: load.php:43
if(count($args)==0) $dir
teardownUploads()
Remove the dummy uploads directory.
const NS_MAIN
Definition: Defines.php:69
Class simulating a backend store.
static addArticle($name, $text, $line= 'unknown', $ignoreDuplicate= '')
Insert a temporary test article.
$IP
Definition: WebStart.php:58
TidySupport $tidySupport
setupUploads()
Create a dummy uploads directory which will contain a couple of files in order to pass existence test...
$wgParser
Definition: Setup.php:816
setTOCEnabled($flag)
getFuzzInput($filenames)
Get an input dictionary from a set of parser test files.
if(!isset($args[0])) $lang
static destroyInstance()
Destroy the singleton instance.
$wgFileBackends
File backend structure configuration.
static destroySingleton()
Destroy the singleton instance, so that a new one will be created next time singleton() is called...
Definition: RepoGroup.php:73
getUploadDir()
Get an FS upload directory (only applies to FSFileBackend)
$value
static newFromId($id)
Static factory method for creation from a given user ID.
Definition: User.php:545
$files
$wgNamespaceAliases
Namespace aliases.
$wgHooks['ArticleShow'][]
Definition: hooks.txt:110
const MEDIATYPE_VIDEO
Definition: Defines.php:122
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:256
$wgMediaHandlers
Plugins for media file type handling.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static destroySingleton()
Destroy the singleton instance.
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:2372
static tearDownAfterClass()
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1814
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
static getOptionValue($key, $opts, $default)
Use a regex to find out the value of an option.
static destroySingleton()
Destroy the current singleton instance.
Definition: MWTidy.php:160
static tearDownInterwikis()
Remove the hardcoded interwiki lookup table.
Definition: parserTest.inc:352
when a variable name is used in a function
Definition: design.txt:93
static deleteFiles($files)
Delete the specified files, if they exist.
requireTransparentHook($name)
wfTempDir()
Tries to get the system directory for temporary files.
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
static singleton()
Get an instance of this class.
Definition: LinkCache.php:65
getMemoryBreakdown()
Get a memory usage breakdown.
parseOptions($instring)
$GLOBALS['IP']
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:1020
getParser($preprocessor=null)
Get a Parser object.
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
Although marked as a stub, can work independently.
testFuzzTests()
Run a fuzz test series Draw input from a set of test files.
MediaWiki exception.
Definition: MWException.php:26
static clearCache()
Clear the self::$mObjects variable For use in parser tests.
Definition: MagicWord.php:319
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:284
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:312
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
const NS_FILE
Definition: Defines.php:75
const NS_FILE_TALK
Definition: Defines.php:76
Initialize and detect the DjVu files support.
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:1816
addArticle($name, $text, $line)
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
An iterator for use as a phpunit data provider.
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:1181
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:2755
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
testParserTest($desc, $input, $result, $opts, $config)
medium ParserTests parserTestProvider
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:1020
Initialize and detect the tidy support.
DjVuSupport $djVuSupport
setupGlobals($opts=[], $config= '')
Set up the global variables for a consistent environment for each test.
static setUpBeforeClass()
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
setParserTestFile($filename)
Set the file from whose tests will be run by this instance.
teardownGlobals()
Restore default values and perform any necessary clean-up after each test runs.
unless you explicitly specified the no dev flag during the install In this case just run composer update Otherwise follow the installation instructions in the PHPUnit Manual at
Definition: README:1
removeEndingNewline($s)
Remove last character if it is a newline.
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:1020
$line
Definition: cdb.php:59
isWikitextNS($ns)
Returns true if the given namespace defaults to Wikitext according to $wgNamespaceContentModels.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
this hook is for auditing only 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:776
requireHook($name)
Steal a callback function from the primary parser, save it for application to our scary parser...
getNewTempDirectory()
obtains a new temporary directory
const MEDIATYPE_DRAWING
Definition: Defines.php:117
serialize()
Definition: ApiMessage.php:94
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 set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:776
const CACHE_NONE
Definition: Defines.php:102
static factory($code)
Get a cached or new language object for a given language code.
Definition: Language.php:179
setMwGlobals($pairs, $value=null)
requireFunctionHook($name)
static getCanonicalNamespaces($rebuild=false)
Returns array of all defined namespaces with their canonical (English) names.
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 one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2376
static makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:503
$matches
static parentStoragePath($storagePath)
Get the parent storage directory of a storage path.
const MEDIATYPE_AUDIO
Definition: Defines.php:119
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310
const MEDIATYPE_BITMAP
Definition: Defines.php:115