MediaWiki  1.30.0
ApiMainTest.php
Go to the documentation of this file.
1 <?php
2 
3 use Wikimedia\TestingAccessWrapper;
4 
12 class ApiMainTest extends ApiTestCase {
13 
17  public function testApi() {
18  $api = new ApiMain(
19  new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
20  );
21  $api->execute();
22  $data = $api->getResult()->getResultData();
23  $this->assertInternalType( 'array', $data );
24  $this->assertArrayHasKey( 'query', $data );
25  }
26 
27  public static function provideAssert() {
28  return [
29  [ false, [], 'user', 'assertuserfailed' ],
30  [ true, [], 'user', false ],
31  [ true, [], 'bot', 'assertbotfailed' ],
32  [ true, [ 'bot' ], 'user', false ],
33  [ true, [ 'bot' ], 'bot', false ],
34  ];
35  }
36 
47  public function testAssert( $registered, $rights, $assert, $error ) {
48  if ( $registered ) {
49  $user = $this->getMutableTestUser()->getUser();
50  $user->load(); // load before setting mRights
51  } else {
52  $user = new User();
53  }
54  $user->mRights = $rights;
55  try {
56  $this->doApiRequest( [
57  'action' => 'query',
58  'assert' => $assert,
59  ], null, null, $user );
60  $this->assertFalse( $error ); // That no error was expected
61  } catch ( ApiUsageException $e ) {
62  $this->assertTrue( self::apiExceptionHasCode( $e, $error ),
63  "Error '{$e->getMessage()}' matched expected '$error'" );
64  }
65  }
66 
72  public function testAssertUser() {
73  $user = $this->getTestUser()->getUser();
74  $this->doApiRequest( [
75  'action' => 'query',
76  'assertuser' => $user->getName(),
77  ], null, null, $user );
78 
79  try {
80  $this->doApiRequest( [
81  'action' => 'query',
82  'assertuser' => $user->getName() . 'X',
83  ], null, null, $user );
84  $this->fail( 'Expected exception not thrown' );
85  } catch ( ApiUsageException $e ) {
86  $this->assertTrue( self::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
87  }
88  }
89 
93  public function testClassNamesInModuleManager() {
94  $api = new ApiMain(
95  new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
96  );
97  $modules = $api->getModuleManager()->getNamesWithClasses();
98 
99  foreach ( $modules as $name => $class ) {
100  $this->assertTrue(
101  class_exists( $class ),
102  'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
103  );
104  }
105  }
106 
118  $headers, $conditions, $status, $post = false
119  ) {
120  $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
121  $request->setHeaders( $headers );
122  $request->response()->statusHeader( 200 ); // Why doesn't it default?
123 
124  $context = $this->apiContext->newTestContext( $request, null );
125  $api = new ApiMain( $context );
126  $priv = TestingAccessWrapper::newFromObject( $api );
127  $priv->mInternalMode = false;
128 
129  $module = $this->getMockBuilder( 'ApiBase' )
130  ->setConstructorArgs( [ $api, 'mock' ] )
131  ->setMethods( [ 'getConditionalRequestData' ] )
132  ->getMockForAbstractClass();
133  $module->expects( $this->any() )
134  ->method( 'getConditionalRequestData' )
135  ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
136  return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
137  } ) );
138 
139  $ret = $priv->checkConditionalRequestHeaders( $module );
140 
141  $this->assertSame( $status, $request->response()->getStatusCode() );
142  $this->assertSame( $status === 200, $ret );
143  }
144 
145  public static function provideCheckConditionalRequestHeaders() {
146  $now = time();
147 
148  return [
149  // Non-existing from module is ignored
150  [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
151  [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
152 
153  // No headers
154  [
155  [],
156  [
157  'etag' => '""',
158  'last-modified' => '20150815000000',
159  ],
160  200
161  ],
162 
163  // Basic If-None-Match
164  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
165  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
166  [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
167  [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
168  [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
169 
170  // Pointless, but supported
171  [ [ 'If-None-Match' => '*' ], [], 304 ],
172 
173  // Basic If-Modified-Since
174  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
175  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
176  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
177  [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
178  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
179  [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
180 
181  // If-Modified-Since ignored when If-None-Match is given too
182  [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
183  [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
184  [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
185  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
186 
187  // Ignored for POST
188  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200, true ],
189  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
190  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200, true ],
191 
192  // Other date formats allowed by the RFC
193  [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
194  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
195  [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
196  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
197 
198  // Old browser extension to HTTP/1.0
199  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
200  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
201 
202  // Invalid date formats should be ignored
203  [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
204  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
205  ];
206  }
207 
217  $conditions, $headers, $isError = false, $post = false
218  ) {
219  $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
220  $response = $request->response();
221 
222  $api = new ApiMain( $request );
223  $priv = TestingAccessWrapper::newFromObject( $api );
224  $priv->mInternalMode = false;
225 
226  $module = $this->getMockBuilder( 'ApiBase' )
227  ->setConstructorArgs( [ $api, 'mock' ] )
228  ->setMethods( [ 'getConditionalRequestData' ] )
229  ->getMockForAbstractClass();
230  $module->expects( $this->any() )
231  ->method( 'getConditionalRequestData' )
232  ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
233  return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
234  } ) );
235  $priv->mModule = $module;
236 
237  $priv->sendCacheHeaders( $isError );
238 
239  foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
240  $this->assertEquals(
241  isset( $headers[$header] ) ? $headers[$header] : null,
242  $response->getHeader( $header ),
243  $header
244  );
245  }
246  }
247 
248  public static function provideConditionalRequestHeadersOutput() {
249  return [
250  [
251  [],
252  []
253  ],
254  [
255  [ 'etag' => '"foo"' ],
256  [ 'ETag' => '"foo"' ]
257  ],
258  [
259  [ 'last-modified' => '20150818000102' ],
260  [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
261  ],
262  [
263  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
264  [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
265  ],
266  [
267  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
268  [],
269  true,
270  ],
271  [
272  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
273  [],
274  false,
275  true,
276  ],
277  ];
278  }
279 
283  public function testLacksSameOriginSecurity() {
284  // Basic test
285  $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
286  $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
287 
288  // JSONp
289  $main = new ApiMain(
290  new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
291  );
292  $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
293 
294  // Header
295  $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
296  $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
297  $main = new ApiMain( $request );
298  $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
299 
300  // Hook
301  $this->mergeMwGlobalArrayValue( 'wgHooks', [
302  'RequestHasSameOriginSecurity' => [ function () {
303  return false;
304  } ]
305  ] );
306  $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
307  $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
308  }
309 
322  public function testApiErrorFormatterCreation( array $request, array $expect ) {
323  $context = new RequestContext();
324  $context->setRequest( new FauxRequest( $request ) );
325  $context->setLanguage( 'ru' );
326 
327  $main = new ApiMain( $context );
328  $formatter = $main->getErrorFormatter();
329  $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
330 
331  $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
332  $this->assertInstanceOf( $expect['class'], $formatter );
333  $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
334  $this->assertSame( $expect['format'], $wrappedFormatter->format );
335  $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
336  }
337 
338  public static function provideApiErrorFormatterCreation() {
339  return [
340  'Default (BC)' => [ [], [
341  'uselang' => 'ru',
343  'lang' => 'en',
344  'format' => 'none',
345  'usedb' => false,
346  ] ],
347  'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
348  'uselang' => 'ru',
350  'lang' => 'en',
351  'format' => 'none',
352  'usedb' => false,
353  ] ],
354  'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
355  'uselang' => 'ru',
357  'lang' => 'en',
358  'format' => 'none',
359  'usedb' => false,
360  ] ],
361  'Basic' => [ [ 'errorformat' => 'wikitext' ], [
362  'uselang' => 'ru',
363  'class' => ApiErrorFormatter::class,
364  'lang' => 'ru',
365  'format' => 'wikitext',
366  'usedb' => false,
367  ] ],
368  'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
369  'uselang' => 'fr',
370  'class' => ApiErrorFormatter::class,
371  'lang' => 'fr',
372  'format' => 'plaintext',
373  'usedb' => false,
374  ] ],
375  'Explicitly follows uselang' => [
376  [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
377  [
378  'uselang' => 'fr',
379  'class' => ApiErrorFormatter::class,
380  'lang' => 'fr',
381  'format' => 'plaintext',
382  'usedb' => false,
383  ]
384  ],
385  'uselang=content' => [
386  [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
387  [
388  'uselang' => 'en',
389  'class' => ApiErrorFormatter::class,
390  'lang' => 'en',
391  'format' => 'plaintext',
392  'usedb' => false,
393  ]
394  ],
395  'errorlang=content' => [
396  [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
397  [
398  'uselang' => 'ru',
399  'class' => ApiErrorFormatter::class,
400  'lang' => 'en',
401  'format' => 'plaintext',
402  'usedb' => false,
403  ]
404  ],
405  'Explicit parameters' => [
406  [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
407  [
408  'uselang' => 'ru',
409  'class' => ApiErrorFormatter::class,
410  'lang' => 'de',
411  'format' => 'html',
412  'usedb' => true,
413  ]
414  ],
415  'Explicit parameters override uselang' => [
416  [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
417  [
418  'uselang' => 'fr',
419  'class' => ApiErrorFormatter::class,
420  'lang' => 'de',
421  'format' => 'raw',
422  'usedb' => false,
423  ]
424  ],
425  'Bogus language doesn\'t explode' => [
426  [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
427  [
428  'uselang' => 'en',
429  'class' => ApiErrorFormatter::class,
430  'lang' => 'en',
431  'format' => 'none',
432  'usedb' => false,
433  ]
434  ],
435  'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
436  'uselang' => 'ru',
438  'lang' => 'en',
439  'format' => 'none',
440  'usedb' => false,
441  ] ],
442  ];
443  }
444 
453  public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
454  $context = new RequestContext();
455  $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
456  $context->setLanguage( 'en' );
457  $context->setConfig( new MultiConfig( [
458  new HashConfig( [
459  'ShowHostnames' => true, 'ShowSQLErrors' => false,
460  'ShowExceptionDetails' => true, 'ShowDBErrorBacktrace' => true,
461  ] ),
462  $context->getConfig()
463  ] ) );
464 
465  $main = new ApiMain( $context );
466  $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
467  $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
468 
469  $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
470  $this->assertSame( $expectReturn, $ret );
471 
472  // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
473  // so let's try ->assertEquals().
474  $this->assertEquals(
475  $expectResult,
476  $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
477  );
478  }
479 
480  // Not static so $this can be used
481  public function provideExceptionErrors() {
482  $reqId = WebRequest::getRequestId();
483  $doclink = wfExpandUrl( wfScript( 'api' ) );
484 
485  $ex = new InvalidArgumentException( 'Random exception' );
486  $trace = wfMessage( 'api-exception-trace',
487  get_class( $ex ),
488  $ex->getFile(),
489  $ex->getLine(),
491  )->inLanguage( 'en' )->useDatabase( false )->text();
492 
493  $dbex = new DBQueryError(
494  $this->createMock( 'IDatabase' ),
495  'error', 1234, 'SELECT 1', __METHOD__ );
496  $dbtrace = wfMessage( 'api-exception-trace',
497  get_class( $dbex ),
498  $dbex->getFile(),
499  $dbex->getLine(),
501  )->inLanguage( 'en' )->useDatabase( false )->text();
502 
503  MediaWiki\suppressWarnings();
504  $usageEx = new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] );
505  MediaWiki\restoreWarnings();
506 
507  $apiEx1 = new ApiUsageException( null,
508  StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
509  TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
510  $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
511  $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
512  $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
513 
514  return [
515  [
516  $ex,
517  [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
518  [
519  'warnings' => [
520  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
521  ],
522  'errors' => [
523  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
524  [
525  'code' => 'internal_api_error_InvalidArgumentException',
526  'text' => "[$reqId] Exception caught: Random exception",
527  ]
528  ],
529  'trace' => $trace,
530  'servedby' => wfHostname(),
531  ]
532  ],
533  [
534  $dbex,
535  [ 'existing-error', 'internal_api_error_DBQueryError' ],
536  [
537  'warnings' => [
538  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
539  ],
540  'errors' => [
541  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
542  [
543  'code' => 'internal_api_error_DBQueryError',
544  'text' => "[$reqId] Database query error.",
545  ]
546  ],
547  'trace' => $dbtrace,
548  'servedby' => wfHostname(),
549  ]
550  ],
551  [
552  $usageEx,
553  [ 'existing-error', 'ue' ],
554  [
555  'warnings' => [
556  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
557  ],
558  'errors' => [
559  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
560  [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
561  ],
562  'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
563  "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
564  "for notice of API deprecations and breaking changes.",
565  'servedby' => wfHostname(),
566  ]
567  ],
568  [
569  $apiEx1,
570  [ 'existing-error', 'sv-error1', 'sv-error2' ],
571  [
572  'warnings' => [
573  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
574  [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
575  [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
576  ],
577  'errors' => [
578  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
579  [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
580  [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
581  ],
582  'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
583  "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
584  "for notice of API deprecations and breaking changes.",
585  'servedby' => wfHostname(),
586  ]
587  ],
588  ];
589  }
590 }
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:45
$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:244
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:104
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
$context
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2581
MediaWikiTestCase\mergeMwGlobalArrayValue
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
Definition: MediaWikiTestCase.php:807
MediaWikiTestCase\getTestUser
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
Definition: MediaWikiTestCase.php:148
MultiConfig
Provides a fallback sequence for Config objects.
Definition: MultiConfig.php:28
HashConfig
A Config instance which stores all settings as a member variable.
Definition: HashConfig.php:28
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2040
$status
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1245
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
ApiMainTest\testApi
testApi()
Test that the API will accept a FauxRequest and execute.
Definition: ApiMainTest.php:17
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
ApiMainTest\testConditionalRequestHeadersOutput
testConditionalRequestHeadersOutput( $conditions, $headers, $isError=false, $post=false)
Test conditional headers output provideConditionalRequestHeadersOutput.
Definition: ApiMainTest.php:216
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1482
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
User
User
Definition: All_system_messages.txt:425
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ApiRawMessage
Extension of RawMessage implementing IApiMessage.
Definition: ApiMessage.php:268
ApiMainTest\provideCheckConditionalRequestHeaders
static provideCheckConditionalRequestHeaders()
Definition: ApiMainTest.php:145
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2934
UsageException
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiUsageException.php:28
ApiMainTest\testAssertUser
testAssertUser()
Tests the assertuser= functionality.
Definition: ApiMainTest.php:72
$modules
$modules
Definition: HTMLFormElement.php:12
ApiMainTest\testLacksSameOriginSecurity
testLacksSameOriginSecurity()
ApiMain::lacksSameOriginSecurity.
Definition: ApiMainTest.php:283
RequestContext
Group all the pieces relevant to the context of a request into one instance.
Definition: RequestContext.php:33
ApiMainTest
API Database medium.
Definition: ApiMainTest.php:12
$request
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2581
ApiMainTest\testCheckConditionalRequestHeaders
testCheckConditionalRequestHeaders( $headers, $conditions, $status, $post=false)
Test HTTP precondition headers.
Definition: ApiMainTest.php:117
any
they could even be mouse clicks or menu items whatever suits your program You should also get your if any
Definition: COPYING.txt:326
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2141
ApiTestCase
Definition: ApiTestCase.php:3
$header
$header
Definition: updateCredits.php:35
MediaWikiTestCase\getMutableTestUser
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
Definition: MediaWikiTestCase.php:160
$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:1965
$response
this hook is for auditing only $response
Definition: hooks.txt:781
ApiTestCase\doApiRequest
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:73
ApiMainTest\testExceptionErrors
testExceptionErrors( $error, $expectReturn, $expectResult)
ApiMain::errorMessagesFromException ApiMain::substituteResultWithError provideExceptionErrors.
Definition: ApiMainTest.php:453
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:272
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
true
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1965
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
ApiMainTest\provideAssert
static provideAssert()
Definition: ApiMainTest.php:27
ApiMainTest\provideApiErrorFormatterCreation
static provideApiErrorFormatterCreation()
Definition: ApiMainTest.php:338
RawMessage
Variant of the Message class.
Definition: RawMessage.php:34
ApiMainTest\testAssert
testAssert( $registered, $rights, $assert, $error)
Tests the assert={user|bot} functionality.
Definition: ApiMainTest.php:47
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
Definition: MWExceptionHandler.php:311
ApiMainTest\provideExceptionErrors
provideExceptionErrors()
Definition: ApiMainTest.php:481
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:586
array
the array() calling protocol came about after MediaWiki 1.4rc1.
ApiMainTest\provideConditionalRequestHeadersOutput
static provideConditionalRequestHeadersOutput()
Definition: ApiMainTest.php:248
ApiMainTest\testApiErrorFormatterCreation
testApiErrorFormatterCreation(array $request, array $expect)
Test proper creation of the ApiErrorFormatter ApiMain::__construct provideApiErrorFormatterCreation.
Definition: ApiMainTest.php:322
ApiMainTest\testClassNamesInModuleManager
testClassNamesInModuleManager()
Test if all classes in the main module manager exists.
Definition: ApiMainTest.php:93