MediaWiki  1.33.0
ApiMainTest.php
Go to the documentation of this file.
1 <?php
2 
4 use Wikimedia\TestingAccessWrapper;
5 
13 class ApiMainTest extends ApiTestCase {
14 
18  public function testApi() {
19  $api = new ApiMain(
20  new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
21  );
22  $api->execute();
23  $data = $api->getResult()->getResultData();
24  $this->assertInternalType( 'array', $data );
25  $this->assertArrayHasKey( 'query', $data );
26  }
27 
28  public function testApiNoParam() {
29  $api = new ApiMain();
30  $api->execute();
31  $data = $api->getResult()->getResultData();
32  $this->assertInternalType( 'array', $data );
33  }
34 
48  private function getNonInternalApiMain( array $requestData, array $headers = [] ) {
49  $req = $this->getMockBuilder( WebRequest::class )
50  ->setMethods( [ 'response', 'getRawIP' ] )
51  ->getMock();
52  $response = new FauxResponse();
53  $req->method( 'response' )->willReturn( $response );
54  $req->method( 'getRawIP' )->willReturn( '127.0.0.1' );
55 
56  $wrapper = TestingAccessWrapper::newFromObject( $req );
57  $wrapper->data = $requestData;
58  if ( $headers ) {
59  $wrapper->headers = $headers;
60  }
61 
62  return new ApiMain( $req );
63  }
64 
65  public function testUselang() {
66  global $wgLang;
67 
68  $api = $this->getNonInternalApiMain( [
69  'action' => 'query',
70  'meta' => 'siteinfo',
71  'uselang' => 'fr',
72  ] );
73 
74  ob_start();
75  $api->execute();
76  ob_end_clean();
77 
78  $this->assertSame( 'fr', $wgLang->getCode() );
79  }
80 
82  $logFile = $this->getNewTempFile();
83 
84  $this->mergeMwGlobalArrayValue( '_COOKIE', [ 'forceHTTPS' => '1' ] );
85  $logger = new TestLogger( true );
86  $this->setLogger( 'cors', $logger );
87 
88  $api = $this->getNonInternalApiMain( [
89  'action' => 'query',
90  'meta' => 'siteinfo',
91  // For some reason multiple origins (which are not allowed in the
92  // WHATWG Fetch spec that supersedes the RFC) are always considered to
93  // be problematic.
94  ], [ 'ORIGIN' => 'https://www.example.com https://www.com.example' ] );
95 
96  $this->assertSame(
97  [ [ Psr\Log\LogLevel::WARNING, 'Non-whitelisted CORS request with session cookies' ] ],
98  $logger->getBuffer()
99  );
100  }
101 
102  public function testSuppressedLogin() {
103  global $wgUser;
104  $origUser = $wgUser;
105 
106  $api = $this->getNonInternalApiMain( [
107  'action' => 'query',
108  'meta' => 'siteinfo',
109  'origin' => '*',
110  ] );
111 
112  ob_start();
113  $api->execute();
114  ob_end_clean();
115 
116  $this->assertNotSame( $origUser, $wgUser );
117  $this->assertSame( 'true', $api->getContext()->getRequest()->response()
118  ->getHeader( 'MediaWiki-Login-Suppressed' ) );
119  }
120 
121  public function testSetContinuationManager() {
122  $api = new ApiMain();
123  $manager = $this->createMock( ApiContinuationManager::class );
124  $api->setContinuationManager( $manager );
125  $this->assertTrue( true, 'No exception' );
126  return [ $api, $manager ];
127  }
128 
133  $this->setExpectedException( UnexpectedValueException::class,
134  'ApiMain::setContinuationManager: tried to set manager from ' .
135  'when a manager is already set from ' );
136 
137  list( $api, $manager ) = $args;
138  $api->setContinuationManager( $manager );
139  }
140 
141  public function testSetCacheModeUnrecognized() {
142  $api = new ApiMain();
143  $api->setCacheMode( 'unrecognized' );
144  $this->assertSame(
145  'private',
146  TestingAccessWrapper::newFromObject( $api )->mCacheMode,
147  'Unrecognized params must be silently ignored'
148  );
149  }
150 
151  public function testSetCacheModePrivateWiki() {
152  $this->setGroupPermissions( '*', 'read', false );
153 
154  $wrappedApi = TestingAccessWrapper::newFromObject( new ApiMain() );
155  $wrappedApi->setCacheMode( 'public' );
156  $this->assertSame( 'private', $wrappedApi->mCacheMode );
157  $wrappedApi->setCacheMode( 'anon-public-user-private' );
158  $this->assertSame( 'private', $wrappedApi->mCacheMode );
159  }
160 
162  $req = new FauxRequest( [
163  'action' => 'query',
164  'meta' => 'siteinfo',
165  'requestid' => '123456',
166  ] );
167  $api = new ApiMain( $req );
168  $api->execute();
169  $this->assertSame( '123456', $api->getResult()->getResultData()['requestid'] );
170  }
171 
173  $req = new FauxRequest( [
174  'action' => 'query',
175  'meta' => 'siteinfo',
176  'curtimestamp' => '',
177  ] );
178  $api = new ApiMain( $req );
179  $api->execute();
180  $timestamp = $api->getResult()->getResultData()['curtimestamp'];
181  $this->assertLessThanOrEqual( 1, abs( strtotime( $timestamp ) - time() ) );
182  }
183 
185  $req = new FauxRequest( [
186  'action' => 'query',
187  'meta' => 'siteinfo',
188  // errorlang is ignored if errorformat is not specified
189  'errorformat' => 'plaintext',
190  'uselang' => 'FR',
191  'errorlang' => 'ja',
192  'responselanginfo' => '',
193  ] );
194  $api = new ApiMain( $req );
195  $api->execute();
196  $data = $api->getResult()->getResultData();
197  $this->assertSame( 'fr', $data['uselang'] );
198  $this->assertSame( 'ja', $data['errorlang'] );
199  }
200 
201  public function testSetupModuleUnknown() {
202  $this->setExpectedException( ApiUsageException::class,
203  'Unrecognized value for parameter "action": unknownaction.' );
204 
205  $req = new FauxRequest( [ 'action' => 'unknownaction' ] );
206  $api = new ApiMain( $req );
207  $api->execute();
208  }
209 
210  public function testSetupModuleNoTokenProvided() {
211  $this->setExpectedException( ApiUsageException::class,
212  'The "token" parameter must be set.' );
213 
214  $req = new FauxRequest( [
215  'action' => 'edit',
216  'title' => 'New page',
217  'text' => 'Some text',
218  ] );
219  $api = new ApiMain( $req );
220  $api->execute();
221  }
222 
224  $this->setExpectedException( ApiUsageException::class, 'Invalid CSRF token.' );
225 
226  $req = new FauxRequest( [
227  'action' => 'edit',
228  'title' => 'New page',
229  'text' => 'Some text',
230  'token' => "This isn't a real token!",
231  ] );
232  $api = new ApiMain( $req );
233  $api->execute();
234  }
235 
236  public function testSetupModuleNeedsTokenTrue() {
237  $this->setExpectedException( MWException::class,
238  "Module 'testmodule' must be updated for the new token handling. " .
239  "See documentation for ApiBase::needsToken for details." );
240 
241  $mock = $this->createMock( ApiBase::class );
242  $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
243  $mock->method( 'needsToken' )->willReturn( true );
244 
245  $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
246  $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
247  function () use ( $mock ) {
248  return $mock;
249  }
250  );
251  $api->execute();
252  }
253 
255  $this->setExpectedException( MWException::class,
256  "Module 'testmodule' must require POST to use tokens." );
257 
258  $mock = $this->createMock( ApiBase::class );
259  $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
260  $mock->method( 'needsToken' )->willReturn( 'csrf' );
261  $mock->method( 'mustBePosted' )->willReturn( false );
262 
263  $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
264  $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
265  function () use ( $mock ) {
266  return $mock;
267  }
268  );
269  $api->execute();
270  }
271 
272  public function testCheckMaxLagFailed() {
273  // It's hard to mock the LoadBalancer properly, so instead we'll mock
274  // checkMaxLag (which is tested directly in other tests below).
275  $req = new FauxRequest( [
276  'action' => 'query',
277  'meta' => 'siteinfo',
278  ] );
279 
280  $mock = $this->getMockBuilder( ApiMain::class )
281  ->setConstructorArgs( [ $req ] )
282  ->setMethods( [ 'checkMaxLag' ] )
283  ->getMock();
284  $mock->method( 'checkMaxLag' )->willReturn( false );
285 
286  $mock->execute();
287 
288  $this->assertArrayNotHasKey( 'query', $mock->getResult()->getResultData() );
289  }
290 
292  // The detailed checking of all cases of checkConditionalRequestHeaders
293  // is below in testCheckConditionalRequestHeaders(), which calls the
294  // method directly. Here we just check that it will stop execution if
295  // it does fail.
296  $now = time();
297 
298  $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
299 
300  $mock = $this->createMock( ApiBase::class );
301  $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
302  $mock->method( 'getConditionalRequestData' )
303  ->willReturn( wfTimestamp( TS_MW, $now - 3600 ) );
304  $mock->expects( $this->exactly( 0 ) )->method( 'execute' );
305 
306  $req = new FauxRequest( [
307  'action' => 'testmodule',
308  ] );
309  $req->setHeader( 'If-Modified-Since', wfTimestamp( TS_RFC2822, $now - 3600 ) );
310  $req->setRequestURL( "http://localhost" );
311 
312  $api = new ApiMain( $req );
313  $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
314  function () use ( $mock ) {
315  return $mock;
316  }
317  );
318 
319  $wrapper = TestingAccessWrapper::newFromObject( $api );
320  $wrapper->mInternalMode = false;
321 
322  ob_start();
323  $api->execute();
324  ob_end_clean();
325  }
326 
327  private function doTestCheckMaxLag( $lag ) {
328  $mockLB = $this->getMockBuilder( LoadBalancer::class )
329  ->disableOriginalConstructor()
330  ->setMethods( [ 'getMaxLag', '__destruct' ] )
331  ->getMock();
332  $mockLB->method( 'getMaxLag' )->willReturn( [ 'somehost', $lag ] );
333  $this->setService( 'DBLoadBalancer', $mockLB );
334 
335  $req = new FauxRequest();
336 
337  $api = new ApiMain( $req );
338  $wrapper = TestingAccessWrapper::newFromObject( $api );
339 
340  $mockModule = $this->createMock( ApiBase::class );
341  $mockModule->method( 'shouldCheckMaxLag' )->willReturn( true );
342 
343  try {
344  $wrapper->checkMaxLag( $mockModule, [ 'maxlag' => 3 ] );
345  } finally {
346  if ( $lag > 3 ) {
347  $this->assertSame( '5', $req->response()->getHeader( 'Retry-After' ) );
348  $this->assertSame( (string)$lag, $req->response()->getHeader( 'X-Database-Lag' ) );
349  }
350  }
351  }
352 
353  public function testCheckMaxLagOkay() {
354  $this->doTestCheckMaxLag( 3 );
355 
356  // No exception, we're happy
357  $this->assertTrue( true );
358  }
359 
360  public function testCheckMaxLagExceeded() {
361  $this->setExpectedException( ApiUsageException::class,
362  'Waiting for a database server: 4 seconds lagged.' );
363 
364  $this->setMwGlobals( 'wgShowHostnames', false );
365 
366  $this->doTestCheckMaxLag( 4 );
367  }
368 
370  $this->setExpectedException( ApiUsageException::class,
371  'Waiting for somehost: 4 seconds lagged.' );
372 
373  $this->setMwGlobals( 'wgShowHostnames', true );
374 
375  $this->doTestCheckMaxLag( 4 );
376  }
377 
378  public static function provideAssert() {
379  return [
380  [ false, [], 'user', 'assertuserfailed' ],
381  [ true, [], 'user', false ],
382  [ true, [], 'bot', 'assertbotfailed' ],
383  [ true, [ 'bot' ], 'user', false ],
384  [ true, [ 'bot' ], 'bot', false ],
385  ];
386  }
387 
397  public function testAssert( $registered, $rights, $assert, $error ) {
398  if ( $registered ) {
399  $user = $this->getMutableTestUser()->getUser();
400  $user->load(); // load before setting mRights
401  } else {
402  $user = new User();
403  }
404  $user->mRights = $rights;
405  try {
406  $this->doApiRequest( [
407  'action' => 'query',
408  'assert' => $assert,
409  ], null, null, $user );
410  $this->assertFalse( $error ); // That no error was expected
411  } catch ( ApiUsageException $e ) {
412  $this->assertTrue( self::apiExceptionHasCode( $e, $error ),
413  "Error '{$e->getMessage()}' matched expected '$error'" );
414  }
415  }
416 
420  public function testAssertUser() {
421  $user = $this->getTestUser()->getUser();
422  $this->doApiRequest( [
423  'action' => 'query',
424  'assertuser' => $user->getName(),
425  ], null, null, $user );
426 
427  try {
428  $this->doApiRequest( [
429  'action' => 'query',
430  'assertuser' => $user->getName() . 'X',
431  ], null, null, $user );
432  $this->fail( 'Expected exception not thrown' );
433  } catch ( ApiUsageException $e ) {
434  $this->assertTrue( self::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
435  }
436  }
437 
441  public function testAssertBeforeModule() {
442  // Sanity check that the query without assert throws too-many-titles
443  try {
444  $this->doApiRequest( [
445  'action' => 'query',
446  'titles' => implode( '|', range( 1, ApiBase::LIMIT_SML1 + 1 ) ),
447  ], null, null, new User );
448  $this->fail( 'Expected exception not thrown' );
449  } catch ( ApiUsageException $e ) {
450  $this->assertTrue( self::apiExceptionHasCode( $e, 'too-many-titles' ), 'sanity check' );
451  }
452 
453  // Now test that the assert happens first
454  try {
455  $this->doApiRequest( [
456  'action' => 'query',
457  'titles' => implode( '|', range( 1, ApiBase::LIMIT_SML1 + 1 ) ),
458  'assert' => 'user',
459  ], null, null, new User );
460  $this->fail( 'Expected exception not thrown' );
461  } catch ( ApiUsageException $e ) {
462  $this->assertTrue( self::apiExceptionHasCode( $e, 'assertuserfailed' ),
463  "Error '{$e->getMessage()}' matched expected 'assertuserfailed'" );
464  }
465  }
466 
470  public function testClassNamesInModuleManager() {
471  $api = new ApiMain(
472  new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
473  );
474  $modules = $api->getModuleManager()->getNamesWithClasses();
475 
476  foreach ( $modules as $name => $class ) {
477  $this->assertTrue(
478  class_exists( $class ),
479  'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
480  );
481  }
482  }
483 
496  $headers, $conditions, $status, $options = []
497  ) {
498  $request = new FauxRequest(
499  [ 'action' => 'query', 'meta' => 'siteinfo' ],
500  !empty( $options['post'] )
501  );
502  $request->setHeaders( $headers );
503  $request->response()->statusHeader( 200 ); // Why doesn't it default?
504 
505  $context = $this->apiContext->newTestContext( $request, null );
506  $api = new ApiMain( $context );
507  $priv = TestingAccessWrapper::newFromObject( $api );
508  $priv->mInternalMode = false;
509 
510  if ( !empty( $options['cdn'] ) ) {
511  $this->setMwGlobals( 'wgUseSquid', true );
512  }
513 
514  // Can't do this in TestSetup.php because Setup.php will override it
515  $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
516 
517  $module = $this->getMockBuilder( ApiBase::class )
518  ->setConstructorArgs( [ $api, 'mock' ] )
519  ->setMethods( [ 'getConditionalRequestData' ] )
520  ->getMockForAbstractClass();
521  $module->expects( $this->any() )
522  ->method( 'getConditionalRequestData' )
523  ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
524  return $conditions[$condition] ?? null;
525  } ) );
526 
527  $ret = $priv->checkConditionalRequestHeaders( $module );
528 
529  $this->assertSame( $status, $request->response()->getStatusCode() );
530  $this->assertSame( $status === 200, $ret );
531  }
532 
533  public static function provideCheckConditionalRequestHeaders() {
534  global $wgSquidMaxage;
535  $now = time();
536 
537  return [
538  // Non-existing from module is ignored
539  'If-None-Match' => [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
540  'If-Modified-Since' =>
541  [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
542 
543  // No headers
544  'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
545 
546  // Basic If-None-Match
547  'If-None-Match with matching etag' =>
548  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
549  'If-None-Match with non-matching etag' =>
550  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
551  'Strong If-None-Match with weak matching etag' =>
552  [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
553  'Weak If-None-Match with strong matching etag' =>
554  [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
555  'Weak If-None-Match with weak matching etag' =>
556  [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
557 
558  // Pointless for GET, but supported
559  'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
560 
561  // Basic If-Modified-Since
562  'If-Modified-Since, modified one second earlier' =>
563  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
564  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
565  'If-Modified-Since, modified now' =>
566  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
567  [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
568  'If-Modified-Since, modified one second later' =>
569  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
570  [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
571 
572  // If-Modified-Since ignored when If-None-Match is given too
573  'Non-matching If-None-Match and matching If-Modified-Since' =>
574  [ [ 'If-None-Match' => '""',
575  'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
576  [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
577  'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
578  [
579  [
580  'If-None-Match' => '""',
581  'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now )
582  ],
583  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ],
584  304
585  ],
586 
587  // Ignored for POST
588  'Matching If-None-Match with POST' =>
589  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200,
590  [ 'post' => true ] ],
591  'Matching If-Modified-Since with POST' =>
592  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
593  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200,
594  [ 'post' => true ] ],
595 
596  // Other date formats allowed by the RFC
597  'If-Modified-Since with alternate date format 1' =>
598  [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
599  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
600  'If-Modified-Since with alternate date format 2' =>
601  [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
602  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
603 
604  // Old browser extension to HTTP/1.0
605  'If-Modified-Since with length' =>
606  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
607  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
608 
609  // Invalid date formats should be ignored
610  'If-Modified-Since with invalid date format' =>
611  [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
612  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
613  'If-Modified-Since with entirely unparseable date' =>
614  [ [ 'If-Modified-Since' => 'a potato' ],
615  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
616 
617  // Anything before $wgSquidMaxage seconds ago should be considered
618  // expired.
619  'If-Modified-Since with CDN post-expiry' =>
620  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now - $wgSquidMaxage * 2 ) ],
621  [ 'last-modified' => wfTimestamp( TS_MW, $now - $wgSquidMaxage * 3 ) ],
622  200, [ 'cdn' => true ] ],
623  'If-Modified-Since with CDN pre-expiry' =>
624  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now - $wgSquidMaxage / 2 ) ],
625  [ 'last-modified' => wfTimestamp( TS_MW, $now - $wgSquidMaxage * 3 ) ],
626  304, [ 'cdn' => true ] ],
627  ];
628  }
629 
639  $conditions, $headers, $isError = false, $post = false
640  ) {
641  $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
642  $response = $request->response();
643 
644  $api = new ApiMain( $request );
645  $priv = TestingAccessWrapper::newFromObject( $api );
646  $priv->mInternalMode = false;
647 
648  $module = $this->getMockBuilder( ApiBase::class )
649  ->setConstructorArgs( [ $api, 'mock' ] )
650  ->setMethods( [ 'getConditionalRequestData' ] )
651  ->getMockForAbstractClass();
652  $module->expects( $this->any() )
653  ->method( 'getConditionalRequestData' )
654  ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
655  return $conditions[$condition] ?? null;
656  } ) );
657  $priv->mModule = $module;
658 
659  $priv->sendCacheHeaders( $isError );
660 
661  foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
662  $this->assertEquals(
663  $headers[$header] ?? null,
664  $response->getHeader( $header ),
665  $header
666  );
667  }
668  }
669 
670  public static function provideConditionalRequestHeadersOutput() {
671  return [
672  [
673  [],
674  []
675  ],
676  [
677  [ 'etag' => '"foo"' ],
678  [ 'ETag' => '"foo"' ]
679  ],
680  [
681  [ 'last-modified' => '20150818000102' ],
682  [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
683  ],
684  [
685  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
686  [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
687  ],
688  [
689  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
690  [],
691  true,
692  ],
693  [
694  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
695  [],
696  false,
697  true,
698  ],
699  ];
700  }
701 
703  $this->setExpectedException( ApiUsageException::class,
704  'You need read permission to use this module.' );
705 
706  $this->setGroupPermissions( '*', 'read', false );
707 
708  $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
709  $main->execute();
710  }
711 
713  $this->setExpectedException( ApiUsageException::class,
714  'Editing of this wiki through the API is disabled. Make sure the ' .
715  '"$wgEnableWriteAPI=true;" statement is included in the wiki\'s ' .
716  '"LocalSettings.php" file.' );
717  $main = new ApiMain( new FauxRequest( [
718  'action' => 'edit',
719  'title' => 'Some page',
720  'text' => 'Some text',
721  'token' => '+\\',
722  ] ) );
723  $main->execute();
724  }
725 
727  $this->setExpectedException( ApiUsageException::class,
728  "You're not allowed to edit this wiki through the API." );
729  $this->setGroupPermissions( '*', 'writeapi', false );
730 
731  $main = new ApiMain( new FauxRequest( [
732  'action' => 'edit',
733  'title' => 'Some page',
734  'text' => 'Some text',
735  'token' => '+\\',
736  ] ), /* enableWrite = */ true );
737  $main->execute();
738  }
739 
741  $this->setExpectedException( ApiUsageException::class,
742  'The "Promise-Non-Write-API-Action" HTTP header cannot be sent ' .
743  'to write-mode API modules.' );
744 
745  $req = new FauxRequest( [
746  'action' => 'edit',
747  'title' => 'Some page',
748  'text' => 'Some text',
749  'token' => '+\\',
750  ] );
751  $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
752  $main = new ApiMain( $req, /* enableWrite = */ true );
753  $main->execute();
754  }
755 
757  $this->setExpectedException( ApiUsageException::class, 'Main Page' );
758 
759  $this->setTemporaryHook( 'ApiCheckCanExecute', function ( $unused1, $unused2, &$message ) {
760  $message = 'mainpage';
761  return false;
762  } );
763 
764  $main = new ApiMain( new FauxRequest( [
765  'action' => 'edit',
766  'title' => 'Some page',
767  'text' => 'Some text',
768  'token' => '+\\',
769  ] ), /* enableWrite = */ true );
770  $main->execute();
771  }
772 
773  public function testGetValUnsupportedArray() {
774  $main = new ApiMain( new FauxRequest( [
775  'action' => 'query',
776  'meta' => 'siteinfo',
777  'siprop' => [ 'general', 'namespaces' ],
778  ] ) );
779  $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
780  $main->execute();
781  $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
782  $main->getResult()->getResultData()['warnings']['main']['warnings'] );
783  }
784 
785  public function testReportUnusedParams() {
786  $main = new ApiMain( new FauxRequest( [
787  'action' => 'query',
788  'meta' => 'siteinfo',
789  'unusedparam' => 'unusedval',
790  'anotherunusedparam' => 'anotherval',
791  ] ) );
792  $main->execute();
793  $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
794  $main->getResult()->getResultData()['warnings']['main']['warnings'] );
795  }
796 
797  public function testLacksSameOriginSecurity() {
798  // Basic test
799  $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
800  $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
801 
802  // JSONp
803  $main = new ApiMain(
804  new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
805  );
806  $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
807 
808  // Header
809  $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
810  $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
811  $main = new ApiMain( $request );
812  $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
813 
814  // Hook
815  $this->mergeMwGlobalArrayValue( 'wgHooks', [
816  'RequestHasSameOriginSecurity' => [ function () {
817  return false;
818  } ]
819  ] );
820  $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
821  $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
822  }
823 
836  public function testApiErrorFormatterCreation( array $request, array $expect ) {
837  $context = new RequestContext();
838  $context->setRequest( new FauxRequest( $request ) );
839  $context->setLanguage( 'ru' );
840 
841  $main = new ApiMain( $context );
842  $formatter = $main->getErrorFormatter();
843  $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
844 
845  $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
846  $this->assertInstanceOf( $expect['class'], $formatter );
847  $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
848  $this->assertSame( $expect['format'], $wrappedFormatter->format );
849  $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
850  }
851 
852  public static function provideApiErrorFormatterCreation() {
853  return [
854  'Default (BC)' => [ [], [
855  'uselang' => 'ru',
857  'lang' => 'en',
858  'format' => 'none',
859  'usedb' => false,
860  ] ],
861  'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
862  'uselang' => 'ru',
864  'lang' => 'en',
865  'format' => 'none',
866  'usedb' => false,
867  ] ],
868  'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
869  'uselang' => 'ru',
871  'lang' => 'en',
872  'format' => 'none',
873  'usedb' => false,
874  ] ],
875  'Basic' => [ [ 'errorformat' => 'wikitext' ], [
876  'uselang' => 'ru',
877  'class' => ApiErrorFormatter::class,
878  'lang' => 'ru',
879  'format' => 'wikitext',
880  'usedb' => false,
881  ] ],
882  'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
883  'uselang' => 'fr',
884  'class' => ApiErrorFormatter::class,
885  'lang' => 'fr',
886  'format' => 'plaintext',
887  'usedb' => false,
888  ] ],
889  'Explicitly follows uselang' => [
890  [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
891  [
892  'uselang' => 'fr',
893  'class' => ApiErrorFormatter::class,
894  'lang' => 'fr',
895  'format' => 'plaintext',
896  'usedb' => false,
897  ]
898  ],
899  'uselang=content' => [
900  [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
901  [
902  'uselang' => 'en',
903  'class' => ApiErrorFormatter::class,
904  'lang' => 'en',
905  'format' => 'plaintext',
906  'usedb' => false,
907  ]
908  ],
909  'errorlang=content' => [
910  [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
911  [
912  'uselang' => 'ru',
913  'class' => ApiErrorFormatter::class,
914  'lang' => 'en',
915  'format' => 'plaintext',
916  'usedb' => false,
917  ]
918  ],
919  'Explicit parameters' => [
920  [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
921  [
922  'uselang' => 'ru',
923  'class' => ApiErrorFormatter::class,
924  'lang' => 'de',
925  'format' => 'html',
926  'usedb' => true,
927  ]
928  ],
929  'Explicit parameters override uselang' => [
930  [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
931  [
932  'uselang' => 'fr',
933  'class' => ApiErrorFormatter::class,
934  'lang' => 'de',
935  'format' => 'raw',
936  'usedb' => false,
937  ]
938  ],
939  'Bogus language doesn\'t explode' => [
940  [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
941  [
942  'uselang' => 'en',
943  'class' => ApiErrorFormatter::class,
944  'lang' => 'en',
945  'format' => 'none',
946  'usedb' => false,
947  ]
948  ],
949  'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
950  'uselang' => 'ru',
952  'lang' => 'en',
953  'format' => 'none',
954  'usedb' => false,
955  ] ],
956  ];
957  }
958 
965  public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
966  $context = new RequestContext();
967  $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
968  $context->setLanguage( 'en' );
969  $context->setConfig( new MultiConfig( [
970  new HashConfig( [
971  'ShowHostnames' => true, 'ShowExceptionDetails' => true,
972  ] ),
973  $context->getConfig()
974  ] ) );
975 
976  $main = new ApiMain( $context );
977  $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
978  $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
979 
980  $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
981  $this->assertSame( $expectReturn, $ret );
982 
983  // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
984  // so let's try ->assertEquals().
985  $this->assertEquals(
986  $expectResult,
987  $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
988  );
989  }
990 
991  // Not static so $this can be used
992  public function provideExceptionErrors() {
993  $reqId = WebRequest::getRequestId();
994  $doclink = wfExpandUrl( wfScript( 'api' ) );
995 
996  $ex = new InvalidArgumentException( 'Random exception' );
997  $trace = wfMessage( 'api-exception-trace',
998  get_class( $ex ),
999  $ex->getFile(),
1000  $ex->getLine(),
1002  )->inLanguage( 'en' )->useDatabase( false )->text();
1003 
1004  $dbex = new DBQueryError(
1005  $this->createMock( \Wikimedia\Rdbms\IDatabase::class ),
1006  'error', 1234, 'SELECT 1', __METHOD__ );
1007  $dbtrace = wfMessage( 'api-exception-trace',
1008  get_class( $dbex ),
1009  $dbex->getFile(),
1010  $dbex->getLine(),
1012  )->inLanguage( 'en' )->useDatabase( false )->text();
1013 
1014  // The specific exception doesn't matter, as long as it's namespaced.
1015  $nsex = new MediaWiki\ShellDisabledError();
1016  $nstrace = wfMessage( 'api-exception-trace',
1017  get_class( $nsex ),
1018  $nsex->getFile(),
1019  $nsex->getLine(),
1021  )->inLanguage( 'en' )->useDatabase( false )->text();
1022 
1023  $apiEx1 = new ApiUsageException( null,
1024  StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
1025  TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
1026  $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
1027  $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
1028  $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
1029 
1030  $badMsg = $this->getMockBuilder( ApiRawMessage::class )
1031  ->setConstructorArgs( [ 'An error', 'ignored' ] )
1032  ->setMethods( [ 'getApiCode' ] )
1033  ->getMock();
1034  $badMsg->method( 'getApiCode' )->willReturn( "bad\nvalue" );
1035  $apiEx2 = new ApiUsageException( null, StatusValue::newFatal( $badMsg ) );
1036 
1037  return [
1038  [
1039  $ex,
1040  [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1041  [
1042  'warnings' => [
1043  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1044  ],
1045  'errors' => [
1046  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1047  [
1048  'code' => 'internal_api_error_InvalidArgumentException',
1049  'text' => "[$reqId] Exception caught: Random exception",
1050  'data' => [
1051  'errorclass' => InvalidArgumentException::class,
1052  ],
1053  ]
1054  ],
1055  'trace' => $trace,
1056  'servedby' => wfHostname(),
1057  ]
1058  ],
1059  [
1060  $dbex,
1061  [ 'existing-error', 'internal_api_error_DBQueryError' ],
1062  [
1063  'warnings' => [
1064  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1065  ],
1066  'errors' => [
1067  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1068  [
1069  'code' => 'internal_api_error_DBQueryError',
1070  'text' => "[$reqId] Exception caught: A database query error has occurred. " .
1071  "This may indicate a bug in the software.",
1072  'data' => [
1073  'errorclass' => DBQueryError::class,
1074  ],
1075  ]
1076  ],
1077  'trace' => $dbtrace,
1078  'servedby' => wfHostname(),
1079  ]
1080  ],
1081  [
1082  $nsex,
1083  [ 'existing-error', 'internal_api_error_MediaWiki\ShellDisabledError' ],
1084  [
1085  'warnings' => [
1086  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1087  ],
1088  'errors' => [
1089  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1090  [
1091  'code' => 'internal_api_error_MediaWiki\ShellDisabledError',
1092  'text' => "[$reqId] Exception caught: " . $nsex->getMessage(),
1093  'data' => [
1094  'errorclass' => MediaWiki\ShellDisabledError::class,
1095  ],
1096  ]
1097  ],
1098  'trace' => $nstrace,
1099  'servedby' => wfHostname(),
1100  ]
1101  ],
1102  [
1103  $apiEx1,
1104  [ 'existing-error', 'sv-error1', 'sv-error2' ],
1105  [
1106  'warnings' => [
1107  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1108  [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1109  [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1110  ],
1111  'errors' => [
1112  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1113  [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1114  [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1115  ],
1116  'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1117  "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
1118  "for notice of API deprecations and breaking changes.",
1119  'servedby' => wfHostname(),
1120  ]
1121  ],
1122  [
1123  $apiEx2,
1124  [ 'existing-error', '<invalid-code>' ],
1125  [
1126  'warnings' => [
1127  [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1128  ],
1129  'errors' => [
1130  [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1131  [ 'code' => "bad\nvalue", 'text' => 'An error' ],
1132  ],
1133  'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1134  "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
1135  "for notice of API deprecations and breaking changes.",
1136  'servedby' => wfHostname(),
1137  ]
1138  ]
1139  ];
1140  }
1141 
1143  $api = $this->getNonInternalApiMain( [
1144  'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', 'formatversion' => 'bogus',
1145  ] );
1146 
1147  ob_start();
1148  $api->execute();
1149  $txt = ob_get_clean();
1150 
1151  // Test that the actual output is valid JSON, not just the format of the ApiResult.
1152  $data = FormatJson::decode( $txt, true );
1153  $this->assertInternalType( 'array', $data );
1154  $this->assertArrayHasKey( 'error', $data );
1155  $this->assertArrayHasKey( 'code', $data['error'] );
1156  $this->assertSame( 'unknown_formatversion', $data['error']['code'] );
1157  }
1158 }
ApiMainTest\testCheckMaxLagOkay
testCheckMaxLagOkay()
Definition: ApiMainTest.php:353
ApiMainTest\testSetupModuleUnknown
testSetupModuleUnknown()
Definition: ApiMainTest.php:201
$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. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header '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). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. '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:1266
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
$user
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1476
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:28
ApiMainTest\testSetContinuationManager
testSetContinuationManager()
Definition: ApiMainTest.php:121
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:2636
MediaWikiTestCase\mergeMwGlobalArrayValue
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
Definition: MediaWikiTestCase.php:904
MediaWikiTestCase\getTestUser
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
Definition: MediaWikiTestCase.php:180
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
ApiMainTest\testSetCacheModeUnrecognized
testSetCacheModeUnrecognized()
Definition: ApiMainTest.php:141
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1912
ApiMainTest\testApi
testApi()
Test that the API will accept a FauxRequest and execute.
Definition: ApiMainTest.php:18
ApiMainTest\testNonWhitelistedCorsWithCookies
testNonWhitelistedCorsWithCookies()
Definition: ApiMainTest.php:81
$req
this hook is for auditing only $req
Definition: hooks.txt:979
TestLogger
A logger that may be configured to either buffer logs or to print them to the output where PHPUnit wi...
Definition: TestLogger.php:33
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:638
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1352
ApiMainTest\testCheckMaxLagFailed
testCheckMaxLagFailed()
Definition: ApiMainTest.php:272
ApiMainTest\testAddRequestedFieldsResponseLangInfo
testAddRequestedFieldsResponseLangInfo()
Definition: ApiMainTest.php:184
ApiMainTest\testReportUnusedParams
testReportUnusedParams()
Definition: ApiMainTest.php:785
ApiMainTest\testSetupModuleNeedsTokenNeedntBePosted
testSetupModuleNeedsTokenNeedntBePosted()
Definition: ApiMainTest.php:254
User
User
Definition: All_system_messages.txt:425
ApiMainTest\testPrinterParameterValidationError
testPrinterParameterValidationError()
Definition: ApiMainTest.php:1142
ApiMainTest\testCheckExecutePermissionPromiseNonWrite
testCheckExecutePermissionPromiseNonWrite()
Definition: ApiMainTest.php:740
ApiMainTest\testCheckExecutePermissionHookAbort
testCheckExecutePermissionHookAbort()
Definition: ApiMainTest.php:756
ApiMainTest\testCheckConditionalRequestHeaders
testCheckConditionalRequestHeaders( $headers, $conditions, $status, $options=[])
Test HTTP precondition headers.
Definition: ApiMainTest.php:495
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
ApiMainTest\testAssertBeforeModule
testAssertBeforeModule()
Test that 'assert' is processed before module errors.
Definition: ApiMainTest.php:441
ApiRawMessage
Extension of RawMessage implementing IApiMessage.
Definition: ApiRawMessage.php:26
ApiMainTest\testCheckExecutePermissionWriteApiProhibited
testCheckExecutePermissionWriteApiProhibited()
Definition: ApiMainTest.php:726
ApiTestCase\doApiRequest
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:62
ApiMainTest\testCheckMaxLagExceeded
testCheckMaxLagExceeded()
Definition: ApiMainTest.php:360
ApiMainTest\provideCheckConditionalRequestHeaders
static provideCheckConditionalRequestHeaders()
Definition: ApiMainTest.php:533
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:174
ApiMainTest\testCheckExecutePermissionWriteDisabled
testCheckExecutePermissionWriteDisabled()
Definition: ApiMainTest.php:712
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2714
ApiMainTest\testCheckConditionalRequestHeadersFailed
testCheckConditionalRequestHeadersFailed()
Definition: ApiMainTest.php:291
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Definition: MediaWikiTestCase.php:709
MediaWikiTestCase\getNewTempFile
getNewTempFile()
Obtains a new temporary file name.
Definition: MediaWikiTestCase.php:474
ApiMainTest\testAssertUser
testAssertUser()
Tests the assertuser= functionality.
Definition: ApiMainTest.php:420
$wgLang
$wgLang
Definition: Setup.php:875
$modules
$modules
Definition: HTMLFormElement.php:12
ApiMainTest\testLacksSameOriginSecurity
testLacksSameOriginSecurity()
Definition: ApiMainTest.php:797
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
RequestContext
Group all the pieces relevant to the context of a request into one instance.
Definition: RequestContext.php:32
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
ApiMainTest
API Database medium.
Definition: ApiMainTest.php:13
$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:2636
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
ApiMainTest\testSetupModuleNeedsTokenTrue
testSetupModuleNeedsTokenTrue()
Definition: ApiMainTest.php:236
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
ApiMainTest\testCheckExecutePermissionsReadProhibited
testCheckExecutePermissionsReadProhibited()
Definition: ApiMainTest.php:702
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
ApiTestCase
Definition: ApiTestCase.php:5
$header
$header
Definition: updateCredits.php:41
MediaWikiTestCase\getMutableTestUser
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
Definition: MediaWikiTestCase.php:192
ApiMainTest\testSetCacheModePrivateWiki
testSetCacheModePrivateWiki()
Definition: ApiMainTest.php:151
MediaWiki\ShellDisabledError
Definition: ShellDisabledError.php:28
$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:1985
MediaWikiTestCase\setGroupPermissions
setGroupPermissions( $newPerms, $newKey=null, $newValue=null)
Alters $wgGroupPermissions for the duration of the test.
Definition: MediaWikiTestCase.php:1095
ApiMainTest\testSetContinuationManagerTwice
testSetContinuationManagerTwice( $args)
@depends testSetContinuationManager
Definition: ApiMainTest.php:132
ApiMainTest\doTestCheckMaxLag
doTestCheckMaxLag( $lag)
Definition: ApiMainTest.php:327
$response
this hook is for auditing only $response
Definition: hooks.txt:780
ApiMainTest\testSuppressedLogin
testSuppressedLogin()
Definition: ApiMainTest.php:102
ApiMainTest\testAddRequestedFieldsCurTimestamp
testAddRequestedFieldsCurTimestamp()
Definition: ApiMainTest.php:172
ApiMainTest\testExceptionErrors
testExceptionErrors( $error, $expectReturn, $expectResult)
provideExceptionErrors
Definition: ApiMainTest.php:965
$args
if( $line===false) $args
Definition: cdb.php:64
FauxResponse
Definition: FauxResponse.php:26
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1985
ApiMainTest\testAddRequestedFieldsRequestId
testAddRequestedFieldsRequestId()
Definition: ApiMainTest.php:161
MediaWikiTestCase\setLogger
setLogger( $channel, LoggerInterface $logger)
Sets the logger for a specified channel, for the duration of the test.
Definition: MediaWikiTestCase.php:1118
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:275
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
ApiMainTest\testApiNoParam
testApiNoParam()
Definition: ApiMainTest.php:28
Wikimedia
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
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:1985
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:378
ApiMainTest\testSetupModuleInvalidTokenProvided
testSetupModuleInvalidTokenProvided()
Definition: ApiMainTest.php:223
ApiMainTest\testCheckMaxLagExceededWithHostNames
testCheckMaxLagExceededWithHostNames()
Definition: ApiMainTest.php:369
MediaWikiTestCase\setTemporaryHook
setTemporaryHook( $hookName, $handler)
Create a temporary hook handler which will be reset by tearDown.
Definition: MediaWikiTestCase.php:2325
ApiMainTest\provideApiErrorFormatterCreation
static provideApiErrorFormatterCreation()
Definition: ApiMainTest.php:852
RawMessage
Variant of the Message class.
Definition: RawMessage.php:34
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 use $formDescriptor instead 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
ApiMainTest\testAssert
testAssert( $registered, $rights, $assert, $error)
Tests the assert={user|bot} functionality.
Definition: ApiMainTest.php:397
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:48
MediaWikiTestCase\setService
setService( $name, $object)
Sets a service, maintaining a stashed version of the previous service to be restored in tearDown.
Definition: MediaWikiTestCase.php:649
ApiMainTest\getNonInternalApiMain
getNonInternalApiMain(array $requestData, array $headers=[])
ApiMain behaves differently if passed a FauxRequest (mInternalMode set to true) or a proper WebReques...
Definition: ApiMainTest.php:48
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
Definition: MWExceptionHandler.php:381
ApiMainTest\testGetValUnsupportedArray
testGetValUnsupportedArray()
Definition: ApiMainTest.php:773
ApiMainTest\provideExceptionErrors
provideExceptionErrors()
Definition: ApiMainTest.php:992
$wgSquidMaxage
$wgSquidMaxage
Cache TTL for the CDN sent as s-maxage (without ESI) or Surrogate-Control (with ESI).
Definition: DefaultSettings.php:2751
ApiBase\LIMIT_SML1
const LIMIT_SML1
Slow query, standard limit.
Definition: ApiBase.php:256
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:515
ApiMainTest\provideConditionalRequestHeadersOutput
static provideConditionalRequestHeadersOutput()
Definition: ApiMainTest.php:670
ApiMainTest\testApiErrorFormatterCreation
testApiErrorFormatterCreation(array $request, array $expect)
Test proper creation of the ApiErrorFormatter.
Definition: ApiMainTest.php:836
ApiMainTest\testSetupModuleNoTokenProvided
testSetupModuleNoTokenProvided()
Definition: ApiMainTest.php:210
ApiMainTest\testUselang
testUselang()
Definition: ApiMainTest.php:65
ApiMainTest\testClassNamesInModuleManager
testClassNamesInModuleManager()
Test if all classes in the main module manager exists.
Definition: ApiMainTest.php:470