MediaWiki  master
ApiBaseTest.php
Go to the documentation of this file.
1 <?php
2 
6 
14 class ApiBaseTest extends ApiTestCase {
23  public function testStubMethods( $expected, $method, $args = [] ) {
24  // Some of these are protected
25  $mock = TestingAccessWrapper::newFromObject( new MockApi() );
26  $result = call_user_func_array( [ $mock, $method ], $args );
27  $this->assertSame( $expected, $result );
28  }
29 
30  public function provideStubMethods() {
31  return [
32  [ null, 'getModuleManager' ],
33  [ null, 'getCustomPrinter' ],
34  [ [], 'getHelpUrls' ],
35  // @todo This is actually overriden by MockApi
36  // [ [], 'getAllowedParams' ],
37  [ true, 'shouldCheckMaxLag' ],
38  [ true, 'isReadMode' ],
39  [ false, 'isWriteMode' ],
40  [ false, 'mustBePosted' ],
41  [ false, 'isDeprecated' ],
42  [ false, 'isInternal' ],
43  [ false, 'needsToken' ],
44  [ null, 'getWebUITokenSalt', [ [] ] ],
45  [ null, 'getConditionalRequestData', [ 'etag' ] ],
46  [ null, 'dynamicParameterDocumentation' ],
47  ];
48  }
49 
51  $mock = new MockApi();
52  $mock->requireOnlyOneParameter(
53  [ "filename" => "foo.txt", "enablechunks" => false ],
54  "filename", "enablechunks"
55  );
56  $this->assertTrue( true );
57  }
58 
62  public function testRequireOnlyOneParameterZero() {
63  $mock = new MockApi();
64  $mock->requireOnlyOneParameter(
65  [ "filename" => "foo.txt", "enablechunks" => 0 ],
66  "filename", "enablechunks"
67  );
68  }
69 
73  public function testRequireOnlyOneParameterTrue() {
74  $mock = new MockApi();
75  $mock->requireOnlyOneParameter(
76  [ "filename" => "foo.txt", "enablechunks" => true ],
77  "filename", "enablechunks"
78  );
79  }
80 
82  $this->setExpectedException( ApiUsageException::class,
83  'One of the parameters "foo" and "bar" is required.' );
84  $mock = new MockApi();
85  $mock->requireOnlyOneParameter(
86  [ "filename" => "foo.txt", "enablechunks" => false ],
87  "foo", "bar" );
88  }
89 
90  public function testRequireMaxOneParameterZero() {
91  $mock = new MockApi();
92  $mock->requireMaxOneParameter(
93  [ 'foo' => 'bar', 'baz' => 'quz' ],
94  'squirrel' );
95  $this->assertTrue( true );
96  }
97 
98  public function testRequireMaxOneParameterOne() {
99  $mock = new MockApi();
100  $mock->requireMaxOneParameter(
101  [ 'foo' => 'bar', 'baz' => 'quz' ],
102  'foo', 'squirrel' );
103  $this->assertTrue( true );
104  }
105 
106  public function testRequireMaxOneParameterTwo() {
107  $this->setExpectedException( ApiUsageException::class,
108  'The parameters "foo" and "baz" can not be used together.' );
109  $mock = new MockApi();
110  $mock->requireMaxOneParameter(
111  [ 'foo' => 'bar', 'baz' => 'quz' ],
112  'foo', 'baz' );
113  }
114 
116  $this->setExpectedException( ApiUsageException::class,
117  'At least one of the parameters "foo" and "bar" is required.' );
118  $mock = new MockApi();
119  $mock->requireAtLeastOneParameter(
120  [ 'a' => 'b', 'c' => 'd' ],
121  'foo', 'bar' );
122  }
123 
125  $mock = new MockApi();
126  $mock->requireAtLeastOneParameter(
127  [ 'a' => 'b', 'c' => 'd' ],
128  'foo', 'a' );
129  $this->assertTrue( true );
130  }
131 
133  $mock = new MockApi();
134  $mock->requireAtLeastOneParameter(
135  [ 'a' => 'b', 'c' => 'd' ],
136  'a', 'c' );
137  $this->assertTrue( true );
138  }
139 
140  public function testGetTitleOrPageIdBadParams() {
141  $this->setExpectedException( ApiUsageException::class,
142  'The parameters "title" and "pageid" can not be used together.' );
143  $mock = new MockApi();
144  $mock->getTitleOrPageId( [ 'title' => 'a', 'pageid' => 7 ] );
145  }
146 
147  public function testGetTitleOrPageIdTitle() {
148  $mock = new MockApi();
149  $result = $mock->getTitleOrPageId( [ 'title' => 'Foo' ] );
150  $this->assertInstanceOf( WikiPage::class, $result );
151  $this->assertSame( 'Foo', $result->getTitle()->getPrefixedText() );
152  }
153 
155  $this->setExpectedException( ApiUsageException::class,
156  'Bad title "|".' );
157  $mock = new MockApi();
158  $mock->getTitleOrPageId( [ 'title' => '|' ] );
159  }
160 
162  $this->setExpectedException( ApiUsageException::class,
163  "Namespace doesn't allow actual pages." );
164  $mock = new MockApi();
165  $mock->getTitleOrPageId( [ 'title' => 'Special:RandomPage' ] );
166  }
167 
168  public function testGetTitleOrPageIdPageId() {
169  $page = $this->getExistingTestPage();
170  $result = ( new MockApi() )->getTitleOrPageId(
171  [ 'pageid' => $page->getId() ] );
172  $this->assertInstanceOf( WikiPage::class, $result );
173  $this->assertSame(
174  $page->getTitle()->getPrefixedText(),
175  $result->getTitle()->getPrefixedText()
176  );
177  }
178 
180  // FIXME: fails under postgres
181  $this->markTestSkippedIfDbType( 'postgres' );
182 
183  $this->setExpectedException( ApiUsageException::class,
184  'There is no page with ID 2147483648.' );
185  $mock = new MockApi();
186  $mock->getTitleOrPageId( [ 'pageid' => 2147483648 ] );
187  }
188 
190  $this->setExpectedException( ApiUsageException::class,
191  'The parameters "title" and "pageid" can not be used together.' );
192  $mock = new MockApi();
193  $mock->getTitleFromTitleOrPageId( [ 'title' => 'a', 'pageid' => 7 ] );
194  }
195 
197  $mock = new MockApi();
198  $result = $mock->getTitleFromTitleOrPageId( [ 'title' => 'Foo' ] );
199  $this->assertInstanceOf( Title::class, $result );
200  $this->assertSame( 'Foo', $result->getPrefixedText() );
201  }
202 
204  $this->setExpectedException( ApiUsageException::class,
205  'Bad title "|".' );
206  $mock = new MockApi();
207  $mock->getTitleFromTitleOrPageId( [ 'title' => '|' ] );
208  }
209 
211  $page = $this->getExistingTestPage();
212  $result = ( new MockApi() )->getTitleFromTitleOrPageId(
213  [ 'pageid' => $page->getId() ] );
214  $this->assertInstanceOf( Title::class, $result );
215  $this->assertSame( $page->getTitle()->getPrefixedText(), $result->getPrefixedText() );
216  }
217 
219  $this->setExpectedException( ApiUsageException::class,
220  'There is no page with ID 298401643.' );
221  $mock = new MockApi();
222  $mock->getTitleFromTitleOrPageId( [ 'pageid' => 298401643 ] );
223  }
224 
225  public function testGetParameter() {
226  $mock = $this->getMockBuilder( MockApi::class )
227  ->setMethods( [ 'getAllowedParams' ] )
228  ->getMock();
229  $mock->method( 'getAllowedParams' )->willReturn( [
230  'foo' => [
231  ApiBase::PARAM_TYPE => [ 'value' ],
232  ],
233  'bar' => [
234  ApiBase::PARAM_TYPE => [ 'value' ],
235  ],
236  ] );
237  $wrapper = TestingAccessWrapper::newFromObject( $mock );
238 
239  $context = new DerivativeContext( $mock );
240  $context->setRequest( new FauxRequest( [ 'foo' => 'bad', 'bar' => 'value' ] ) );
241  $wrapper->mMainModule = new ApiMain( $context );
242 
243  // Even though 'foo' is bad, getParameter( 'bar' ) must not fail
244  $this->assertSame( 'value', $wrapper->getParameter( 'bar' ) );
245 
246  // But getParameter( 'foo' ) must throw.
247  try {
248  $wrapper->getParameter( 'foo' );
249  $this->fail( 'Expected exception not thrown' );
250  } catch ( ApiUsageException $ex ) {
251  $this->assertTrue( $this->apiExceptionHasCode( $ex, 'unknown_foo' ) );
252  }
253 
254  // And extractRequestParams() must throw too.
255  try {
256  $mock->extractRequestParams();
257  $this->fail( 'Expected exception not thrown' );
258  } catch ( ApiUsageException $ex ) {
259  $this->assertTrue( $this->apiExceptionHasCode( $ex, 'unknown_foo' ) );
260  }
261  }
262 
274  private function doGetParameterFromSettings(
275  $input, $paramSettings, $expected, $warnings, $options = []
276  ) {
277  $mock = new MockApi();
278  $wrapper = TestingAccessWrapper::newFromObject( $mock );
279  if ( $options['prefix'] ) {
280  $wrapper->mModulePrefix = 'my';
281  $paramName = 'Param';
282  } else {
283  $paramName = 'myParam';
284  }
285 
286  $context = new DerivativeContext( $mock );
287  $context->setRequest( new FauxRequest(
288  $input !== null ? [ 'myParam' => $input ] : [] ) );
289  $wrapper->mMainModule = new ApiMain( $context );
290 
291  $parseLimits = $options['parseLimits'] ?? true;
292 
293  if ( !empty( $options['apihighlimits'] ) ) {
294  $context->setUser( self::$users['sysop']->getUser() );
295  }
296 
297  if ( isset( $options['internalmode'] ) && !$options['internalmode'] ) {
298  $mainWrapper = TestingAccessWrapper::newFromObject( $wrapper->mMainModule );
299  $mainWrapper->mInternalMode = false;
300  }
301 
302  // If we're testing tags, set up some tags
303  if ( isset( $paramSettings[ApiBase::PARAM_TYPE] ) &&
304  $paramSettings[ApiBase::PARAM_TYPE] === 'tags'
305  ) {
306  ChangeTags::defineTag( 'tag1' );
307  ChangeTags::defineTag( 'tag2' );
308  }
309 
310  if ( $expected instanceof Exception ) {
311  try {
312  $wrapper->getParameterFromSettings( $paramName, $paramSettings,
313  $parseLimits );
314  $this->fail( 'No exception thrown' );
315  } catch ( Exception $ex ) {
316  $this->assertEquals( $expected, $ex );
317  }
318  } else {
319  $result = $wrapper->getParameterFromSettings( $paramName,
320  $paramSettings, $parseLimits );
321  if ( isset( $paramSettings[ApiBase::PARAM_TYPE] ) &&
322  $paramSettings[ApiBase::PARAM_TYPE] === 'timestamp' &&
323  $expected === 'now'
324  ) {
325  // Allow one second of fuzziness. Make sure the formats are
326  // correct!
327  $this->assertRegExp( '/^\d{14}$/', $result );
328  $this->assertLessThanOrEqual( 1,
329  abs( wfTimestamp( TS_UNIX, $result ) - time() ),
330  "Result $result differs from expected $expected by " .
331  'more than one second' );
332  } else {
333  $this->assertSame( $expected, $result );
334  }
335  $actualWarnings = array_map( function ( $warn ) {
336  return $warn instanceof Message
337  ? array_merge( [ $warn->getKey() ], $warn->getParams() )
338  : $warn;
339  }, $mock->warnings );
340  $this->assertSame( $warnings, $actualWarnings );
341  }
342 
343  if ( !empty( $paramSettings[ApiBase::PARAM_SENSITIVE] ) ||
344  ( isset( $paramSettings[ApiBase::PARAM_TYPE] ) &&
345  $paramSettings[ApiBase::PARAM_TYPE] === 'password' )
346  ) {
347  $mainWrapper = TestingAccessWrapper::newFromObject( $wrapper->getMain() );
348  $this->assertSame( [ 'myParam' ],
349  $mainWrapper->getSensitiveParams() );
350  }
351  }
352 
358  $input, $paramSettings, $expected, $warnings, $options = []
359  ) {
360  $options['prefix'] = false;
361  $this->doGetParameterFromSettings( $input, $paramSettings, $expected, $warnings, $options );
362  }
363 
369  $input, $paramSettings, $expected, $warnings, $options = []
370  ) {
371  $options['prefix'] = true;
372  $this->doGetParameterFromSettings( $input, $paramSettings, $expected, $warnings, $options );
373  }
374 
375  public static function provideGetParameterFromSettings() {
376  $warnings = [
377  [ 'apiwarn-badutf8', 'myParam' ],
378  ];
379 
380  $c0 = '';
381  $enc = '';
382  for ( $i = 0; $i < 32; $i++ ) {
383  $c0 .= chr( $i );
384  $enc .= ( $i === 9 || $i === 10 || $i === 13 )
385  ? chr( $i )
386  : '�';
387  }
388 
389  $returnArray = [
390  'Basic param' => [ 'bar', null, 'bar', [] ],
391  'Basic param, C0 controls' => [ $c0, null, $enc, $warnings ],
392  'String param' => [ 'bar', '', 'bar', [] ],
393  'String param, defaulted' => [ null, '', '', [] ],
394  'String param, empty' => [ '', 'default', '', [] ],
395  'String param, required, empty' => [
396  '',
397  [ ApiBase::PARAM_DFLT => 'default', ApiBase::PARAM_REQUIRED => true ],
399  [ 'apierror-missingparam', 'myParam' ] ),
400  []
401  ],
402  'Multi-valued parameter' => [
403  'a|b|c',
405  [ 'a', 'b', 'c' ],
406  []
407  ],
408  'Multi-valued parameter, alternative separator' => [
409  "\x1fa|b\x1fc|d",
411  [ 'a|b', 'c|d' ],
412  []
413  ],
414  'Multi-valued parameter, other C0 controls' => [
415  $c0,
417  [ $enc ],
418  $warnings
419  ],
420  'Multi-valued parameter, other C0 controls (2)' => [
421  "\x1f" . $c0,
422  [ ApiBase::PARAM_ISMULTI => true ],
423  [ substr( $enc, 0, -3 ), '' ],
424  $warnings
425  ],
426  'Multi-valued parameter with limits' => [
427  'a|b|c',
428  [
429  ApiBase::PARAM_ISMULTI => true,
431  ],
432  [ 'a', 'b', 'c' ],
433  [],
434  ],
435  'Multi-valued parameter with exceeded limits' => [
436  'a|b|c',
437  [
438  ApiBase::PARAM_ISMULTI => true,
440  ],
442  null, [ 'apierror-toomanyvalues', 'myParam', 2 ], 'too-many-myParam'
443  ),
444  []
445  ],
446  'Multi-valued parameter with exceeded limits for non-bot' => [
447  'a|b|c',
448  [
449  ApiBase::PARAM_ISMULTI => true,
452  ],
454  null, [ 'apierror-toomanyvalues', 'myParam', 2 ], 'too-many-myParam'
455  ),
456  []
457  ],
458  'Multi-valued parameter with non-exceeded limits for bot' => [
459  'a|b|c',
460  [
461  ApiBase::PARAM_ISMULTI => true,
464  ],
465  [ 'a', 'b', 'c' ],
466  [],
467  [ 'apihighlimits' => true ],
468  ],
469  'Multi-valued parameter with prohibited duplicates' => [
470  'a|b|a|c',
471  [ ApiBase::PARAM_ISMULTI => true ],
472  // Note that the keys are not sequential! This matches
473  // array_unique, but might be unexpected.
474  [ 0 => 'a', 1 => 'b', 3 => 'c' ],
475  [],
476  ],
477  'Multi-valued parameter with allowed duplicates' => [
478  'a|a',
479  [
480  ApiBase::PARAM_ISMULTI => true,
482  ],
483  [ 'a', 'a' ],
484  [],
485  ],
486  'Empty boolean param' => [
487  '',
488  [ ApiBase::PARAM_TYPE => 'boolean' ],
489  true,
490  [],
491  ],
492  'Boolean param 0' => [
493  '0',
494  [ ApiBase::PARAM_TYPE => 'boolean' ],
495  true,
496  [],
497  ],
498  'Boolean param false' => [
499  'false',
500  [ ApiBase::PARAM_TYPE => 'boolean' ],
501  true,
502  [],
503  ],
504  'Boolean multi-param' => [
505  'true|false',
506  [
507  ApiBase::PARAM_TYPE => 'boolean',
508  ApiBase::PARAM_ISMULTI => true,
509  ],
510  new MWException(
511  'Internal error in ApiBase::getParameterFromSettings: ' .
512  'Multi-values not supported for myParam'
513  ),
514  [],
515  ],
516  'Empty boolean param with non-false default' => [
517  '',
518  [
519  ApiBase::PARAM_TYPE => 'boolean',
520  ApiBase::PARAM_DFLT => true,
521  ],
522  new MWException(
523  'Internal error in ApiBase::getParameterFromSettings: ' .
524  "Boolean param myParam's default is set to '1'. " .
525  'Boolean parameters must default to false.' ),
526  [],
527  ],
528  'Deprecated parameter' => [
529  'foo',
531  'foo',
532  [ [ 'apiwarn-deprecation-parameter', 'myParam' ] ],
533  ],
534  'Deprecated parameter with default, unspecified' => [
535  null,
536  [ ApiBase::PARAM_DEPRECATED => true, ApiBase::PARAM_DFLT => 'foo' ],
537  'foo',
538  [],
539  ],
540  'Deprecated parameter with default, specified' => [
541  'foo',
542  [ ApiBase::PARAM_DEPRECATED => true, ApiBase::PARAM_DFLT => 'foo' ],
543  'foo',
544  [ [ 'apiwarn-deprecation-parameter', 'myParam' ] ],
545  ],
546  'Deprecated parameter value' => [
547  'a',
548  [ ApiBase::PARAM_DEPRECATED_VALUES => [ 'a' => true ] ],
549  'a',
550  [ [ 'apiwarn-deprecation-parameter', 'myParam=a' ] ],
551  ],
552  'Deprecated parameter value as default, unspecified' => [
553  null,
555  'a',
556  [],
557  ],
558  'Deprecated parameter value as default, specified' => [
559  'a',
560  [ ApiBase::PARAM_DEPRECATED_VALUES => [ 'a' => true ], ApiBase::PARAM_DFLT => 'a' ],
561  'a',
562  [ [ 'apiwarn-deprecation-parameter', 'myParam=a' ] ],
563  ],
564  'Multiple deprecated parameter values' => [
565  'a|b|c|d',
566  [ ApiBase::PARAM_DEPRECATED_VALUES =>
567  [ 'b' => true, 'd' => true ],
568  ApiBase::PARAM_ISMULTI => true ],
569  [ 'a', 'b', 'c', 'd' ],
570  [
571  [ 'apiwarn-deprecation-parameter', 'myParam=b' ],
572  [ 'apiwarn-deprecation-parameter', 'myParam=d' ],
573  ],
574  ],
575  'Deprecated parameter value with custom warning' => [
576  'a',
577  [ ApiBase::PARAM_DEPRECATED_VALUES => [ 'a' => 'my-msg' ] ],
578  'a',
579  [ 'my-msg' ],
580  ],
581  '"*" when wildcard not allowed' => [
582  '*',
583  [ ApiBase::PARAM_ISMULTI => true,
584  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ] ],
585  [],
586  [ [ 'apiwarn-unrecognizedvalues', 'myParam',
587  [ 'list' => [ '&#42;' ], 'type' => 'comma' ], 1 ] ],
588  ],
589  'Wildcard "*"' => [
590  '*',
591  [
592  ApiBase::PARAM_ISMULTI => true,
593  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ],
594  ApiBase::PARAM_ALL => true,
595  ],
596  [ 'a', 'b', 'c' ],
597  [],
598  ],
599  'Wildcard "*" with multiples not allowed' => [
600  '*',
601  [
602  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ],
603  ApiBase::PARAM_ALL => true,
604  ],
606  [ 'apierror-unrecognizedvalue', 'myParam', '&#42;' ],
607  'unknown_myParam' ),
608  [],
609  ],
610  'Wildcard "*" with unrestricted type' => [
611  '*',
612  [
613  ApiBase::PARAM_ISMULTI => true,
614  ApiBase::PARAM_ALL => true,
615  ],
616  [ '*' ],
617  [],
618  ],
619  'Wildcard "x"' => [
620  'x',
621  [
622  ApiBase::PARAM_ISMULTI => true,
623  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ],
624  ApiBase::PARAM_ALL => 'x',
625  ],
626  [ 'a', 'b', 'c' ],
627  [],
628  ],
629  'Wildcard conflicting with allowed value' => [
630  'a',
631  [
632  ApiBase::PARAM_ISMULTI => true,
633  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ],
634  ApiBase::PARAM_ALL => 'a',
635  ],
636  new MWException(
637  'Internal error in ApiBase::getParameterFromSettings: ' .
638  'For param myParam, PARAM_ALL collides with a possible ' .
639  'value' ),
640  [],
641  ],
642  'Namespace with wildcard' => [
643  '*',
644  [
645  ApiBase::PARAM_ISMULTI => true,
646  ApiBase::PARAM_TYPE => 'namespace',
647  ],
648  MediaWikiServices::getInstance()->getNamespaceInfo()->getValidNamespaces(),
649  [],
650  ],
651  // PARAM_ALL is ignored with namespace types.
652  'Namespace with wildcard suppressed' => [
653  '*',
654  [
655  ApiBase::PARAM_ISMULTI => true,
656  ApiBase::PARAM_TYPE => 'namespace',
657  ApiBase::PARAM_ALL => false,
658  ],
659  MediaWikiServices::getInstance()->getNamespaceInfo()->getValidNamespaces(),
660  [],
661  ],
662  'Namespace with wildcard "x"' => [
663  'x',
664  [
665  ApiBase::PARAM_ISMULTI => true,
666  ApiBase::PARAM_TYPE => 'namespace',
667  ApiBase::PARAM_ALL => 'x',
668  ],
669  [],
670  [ [ 'apiwarn-unrecognizedvalues', 'myParam',
671  [ 'list' => [ 'x' ], 'type' => 'comma' ], 1 ] ],
672  ],
673  'Password' => [
674  'dDy+G?e?txnr.1:(@[Ru',
675  [ ApiBase::PARAM_TYPE => 'password' ],
676  'dDy+G?e?txnr.1:(@[Ru',
677  [],
678  ],
679  'Sensitive field' => [
680  'I am fond of pineapples',
682  'I am fond of pineapples',
683  [],
684  ],
685  'Upload with default' => [
686  '',
687  [
688  ApiBase::PARAM_TYPE => 'upload',
689  ApiBase::PARAM_DFLT => '',
690  ],
691  new MWException(
692  'Internal error in ApiBase::getParameterFromSettings: ' .
693  "File upload param myParam's default is set to ''. " .
694  'File upload parameters may not have a default.' ),
695  [],
696  ],
697  'Multiple upload' => [
698  '',
699  [
700  ApiBase::PARAM_TYPE => 'upload',
701  ApiBase::PARAM_ISMULTI => true,
702  ],
703  new MWException(
704  'Internal error in ApiBase::getParameterFromSettings: ' .
705  'Multi-values not supported for myParam' ),
706  [],
707  ],
708  // @todo Test actual upload
709  'Namespace -1' => [
710  '-1',
711  [ ApiBase::PARAM_TYPE => 'namespace' ],
713  [ 'apierror-unrecognizedvalue', 'myParam', '-1' ],
714  'unknown_myParam' ),
715  [],
716  ],
717  'Extra namespace -1' => [
718  '-1',
719  [
720  ApiBase::PARAM_TYPE => 'namespace',
722  ],
723  '-1',
724  [],
725  ],
726  // @todo Test with PARAM_SUBMODULE_MAP unset, need
727  // getModuleManager() to return something real
728  'Nonexistent module' => [
729  'not-a-module-name',
730  [
731  ApiBase::PARAM_TYPE => 'submodule',
733  [ 'foo' => 'foo', 'bar' => 'foo+bar' ],
734  ],
736  null,
737  [
738  'apierror-unrecognizedvalue',
739  'myParam',
740  'not-a-module-name',
741  ],
742  'unknown_myParam'
743  ),
744  [],
745  ],
746  '\\x1f with multiples not allowed' => [
747  "\x1f",
748  [],
750  'apierror-badvalue-notmultivalue',
751  'badvalue_notmultivalue' ),
752  [],
753  ],
754  'Integer with unenforced min' => [
755  '-2',
756  [
757  ApiBase::PARAM_TYPE => 'integer',
758  ApiBase::PARAM_MIN => -1,
759  ],
760  -1,
761  [ [ 'apierror-integeroutofrange-belowminimum', 'myParam', -1,
762  -2 ] ],
763  ],
764  'Integer with enforced min' => [
765  '-2',
766  [
767  ApiBase::PARAM_TYPE => 'integer',
768  ApiBase::PARAM_MIN => -1,
770  ],
772  [ 'apierror-integeroutofrange-belowminimum', 'myParam',
773  '-1', '-2' ], 'integeroutofrange',
774  [ 'min' => -1, 'max' => null, 'botMax' => null ] ),
775  [],
776  ],
777  'Integer with unenforced max (internal mode)' => [
778  '8',
779  [
780  ApiBase::PARAM_TYPE => 'integer',
781  ApiBase::PARAM_MAX => 7,
782  ],
783  8,
784  [],
785  ],
786  'Integer with enforced max (internal mode)' => [
787  '8',
788  [
789  ApiBase::PARAM_TYPE => 'integer',
790  ApiBase::PARAM_MAX => 7,
792  ],
793  8,
794  [],
795  ],
796  'Integer with unenforced max (non-internal mode)' => [
797  '8',
798  [
799  ApiBase::PARAM_TYPE => 'integer',
800  ApiBase::PARAM_MAX => 7,
801  ],
802  7,
803  [ [ 'apierror-integeroutofrange-abovemax', 'myParam', 7, 8 ] ],
804  [ 'internalmode' => false ],
805  ],
806  'Integer with enforced max (non-internal mode)' => [
807  '8',
808  [
809  ApiBase::PARAM_TYPE => 'integer',
810  ApiBase::PARAM_MAX => 7,
812  ],
814  null,
815  [ 'apierror-integeroutofrange-abovemax', 'myParam', '7', '8' ],
816  'integeroutofrange',
817  [ 'min' => null, 'max' => 7, 'botMax' => 7 ]
818  ),
819  [],
820  [ 'internalmode' => false ],
821  ],
822  'Array of integers' => [
823  '3|12|966|-1',
824  [
825  ApiBase::PARAM_ISMULTI => true,
826  ApiBase::PARAM_TYPE => 'integer',
827  ],
828  [ 3, 12, 966, -1 ],
829  [],
830  ],
831  'Array of integers with unenforced min/max (internal mode)' => [
832  '3|12|966|-1',
833  [
834  ApiBase::PARAM_ISMULTI => true,
835  ApiBase::PARAM_TYPE => 'integer',
836  ApiBase::PARAM_MIN => 0,
837  ApiBase::PARAM_MAX => 100,
838  ],
839  [ 3, 12, 966, 0 ],
840  [ [ 'apierror-integeroutofrange-belowminimum', 'myParam', 0, -1 ] ],
841  ],
842  'Array of integers with enforced min/max (internal mode)' => [
843  '3|12|966|-1',
844  [
845  ApiBase::PARAM_ISMULTI => true,
846  ApiBase::PARAM_TYPE => 'integer',
847  ApiBase::PARAM_MIN => 0,
848  ApiBase::PARAM_MAX => 100,
850  ],
852  null,
853  [ 'apierror-integeroutofrange-belowminimum', 'myParam', 0, -1 ],
854  'integeroutofrange',
855  [ 'min' => 0, 'max' => 100, 'botMax' => 100 ]
856  ),
857  [],
858  ],
859  'Array of integers with unenforced min/max (non-internal mode)' => [
860  '3|12|966|-1',
861  [
862  ApiBase::PARAM_ISMULTI => true,
863  ApiBase::PARAM_TYPE => 'integer',
864  ApiBase::PARAM_MIN => 0,
865  ApiBase::PARAM_MAX => 100,
866  ],
867  [ 3, 12, 100, 0 ],
868  [
869  [ 'apierror-integeroutofrange-abovemax', 'myParam', 100, 966 ],
870  [ 'apierror-integeroutofrange-belowminimum', 'myParam', 0, -1 ]
871  ],
872  [ 'internalmode' => false ],
873  ],
874  'Array of integers with enforced min/max (non-internal mode)' => [
875  '3|12|966|-1',
876  [
877  ApiBase::PARAM_ISMULTI => true,
878  ApiBase::PARAM_TYPE => 'integer',
879  ApiBase::PARAM_MIN => 0,
880  ApiBase::PARAM_MAX => 100,
882  ],
884  null,
885  [ 'apierror-integeroutofrange-abovemax', 'myParam', 100, 966 ],
886  'integeroutofrange',
887  [ 'min' => 0, 'max' => 100, 'botMax' => 100 ]
888  ),
889  [],
890  [ 'internalmode' => false ],
891  ],
892  'Limit with parseLimits false' => [
893  '100',
894  [ ApiBase::PARAM_TYPE => 'limit' ],
895  '100',
896  [],
897  [ 'parseLimits' => false ],
898  ],
899  'Limit with no max' => [
900  '100',
901  [
902  ApiBase::PARAM_TYPE => 'limit',
903  ApiBase::PARAM_MAX2 => 10,
904  ApiBase::PARAM_ISMULTI => true,
905  ],
906  new MWException(
907  'Internal error in ApiBase::getParameterFromSettings: ' .
908  'MAX1 or MAX2 are not defined for the limit myParam' ),
909  [],
910  ],
911  'Limit with no max2' => [
912  '100',
913  [
914  ApiBase::PARAM_TYPE => 'limit',
915  ApiBase::PARAM_MAX => 10,
916  ApiBase::PARAM_ISMULTI => true,
917  ],
918  new MWException(
919  'Internal error in ApiBase::getParameterFromSettings: ' .
920  'MAX1 or MAX2 are not defined for the limit myParam' ),
921  [],
922  ],
923  'Limit with multi-value' => [
924  '100',
925  [
926  ApiBase::PARAM_TYPE => 'limit',
927  ApiBase::PARAM_MAX => 10,
928  ApiBase::PARAM_MAX2 => 10,
929  ApiBase::PARAM_ISMULTI => true,
930  ],
931  new MWException(
932  'Internal error in ApiBase::getParameterFromSettings: ' .
933  'Multi-values not supported for myParam' ),
934  [],
935  ],
936  'Valid limit' => [
937  '100',
938  [
939  ApiBase::PARAM_TYPE => 'limit',
940  ApiBase::PARAM_MAX => 100,
941  ApiBase::PARAM_MAX2 => 100,
942  ],
943  100,
944  [],
945  ],
946  'Limit max' => [
947  'max',
948  [
949  ApiBase::PARAM_TYPE => 'limit',
950  ApiBase::PARAM_MAX => 100,
951  ApiBase::PARAM_MAX2 => 101,
952  ],
953  100,
954  [],
955  ],
956  'Limit max for apihighlimits' => [
957  'max',
958  [
959  ApiBase::PARAM_TYPE => 'limit',
960  ApiBase::PARAM_MAX => 100,
961  ApiBase::PARAM_MAX2 => 101,
962  ],
963  101,
964  [],
965  [ 'apihighlimits' => true ],
966  ],
967  'Limit too large (internal mode)' => [
968  '101',
969  [
970  ApiBase::PARAM_TYPE => 'limit',
971  ApiBase::PARAM_MAX => 100,
972  ApiBase::PARAM_MAX2 => 101,
973  ],
974  101,
975  [],
976  ],
977  'Limit okay for apihighlimits (internal mode)' => [
978  '101',
979  [
980  ApiBase::PARAM_TYPE => 'limit',
981  ApiBase::PARAM_MAX => 100,
982  ApiBase::PARAM_MAX2 => 101,
983  ],
984  101,
985  [],
986  [ 'apihighlimits' => true ],
987  ],
988  'Limit too large for apihighlimits (internal mode)' => [
989  '102',
990  [
991  ApiBase::PARAM_TYPE => 'limit',
992  ApiBase::PARAM_MAX => 100,
993  ApiBase::PARAM_MAX2 => 101,
994  ],
995  102,
996  [],
997  [ 'apihighlimits' => true ],
998  ],
999  'Limit too large (non-internal mode)' => [
1000  '101',
1001  [
1002  ApiBase::PARAM_TYPE => 'limit',
1003  ApiBase::PARAM_MAX => 100,
1004  ApiBase::PARAM_MAX2 => 101,
1005  ],
1006  100,
1007  [ [ 'apierror-integeroutofrange-abovemax', 'myParam', 100, 101 ] ],
1008  [ 'internalmode' => false ],
1009  ],
1010  'Limit okay for apihighlimits (non-internal mode)' => [
1011  '101',
1012  [
1013  ApiBase::PARAM_TYPE => 'limit',
1014  ApiBase::PARAM_MAX => 100,
1015  ApiBase::PARAM_MAX2 => 101,
1016  ],
1017  101,
1018  [],
1019  [ 'internalmode' => false, 'apihighlimits' => true ],
1020  ],
1021  'Limit too large for apihighlimits (non-internal mode)' => [
1022  '102',
1023  [
1024  ApiBase::PARAM_TYPE => 'limit',
1025  ApiBase::PARAM_MAX => 100,
1026  ApiBase::PARAM_MAX2 => 101,
1027  ],
1028  101,
1029  [ [ 'apierror-integeroutofrange-abovebotmax', 'myParam', 101, 102 ] ],
1030  [ 'internalmode' => false, 'apihighlimits' => true ],
1031  ],
1032  'Limit too small' => [
1033  '-2',
1034  [
1035  ApiBase::PARAM_TYPE => 'limit',
1036  ApiBase::PARAM_MIN => -1,
1037  ApiBase::PARAM_MAX => 100,
1038  ApiBase::PARAM_MAX2 => 100,
1039  ],
1040  -1,
1041  [ [ 'apierror-integeroutofrange-belowminimum', 'myParam', -1,
1042  -2 ] ],
1043  ],
1044  'Timestamp' => [
1045  wfTimestamp( TS_UNIX, '20211221122112' ),
1046  [ ApiBase::PARAM_TYPE => 'timestamp' ],
1047  '20211221122112',
1048  [],
1049  ],
1050  'Timestamp 0' => [
1051  '0',
1052  [ ApiBase::PARAM_TYPE => 'timestamp' ],
1053  // Magic keyword
1054  'now',
1055  [ [ 'apiwarn-unclearnowtimestamp', 'myParam', '0' ] ],
1056  ],
1057  'Timestamp empty' => [
1058  '',
1059  [ ApiBase::PARAM_TYPE => 'timestamp' ],
1060  'now',
1061  [ [ 'apiwarn-unclearnowtimestamp', 'myParam', '' ] ],
1062  ],
1063  // wfTimestamp() interprets this as Unix time
1064  'Timestamp 00' => [
1065  '00',
1066  [ ApiBase::PARAM_TYPE => 'timestamp' ],
1067  '19700101000000',
1068  [],
1069  ],
1070  'Timestamp now' => [
1071  'now',
1072  [ ApiBase::PARAM_TYPE => 'timestamp' ],
1073  'now',
1074  [],
1075  ],
1076  'Invalid timestamp' => [
1077  'a potato',
1078  [ ApiBase::PARAM_TYPE => 'timestamp' ],
1080  null,
1081  [ 'apierror-badtimestamp', 'myParam', 'a potato' ],
1082  'badtimestamp_myParam'
1083  ),
1084  [],
1085  ],
1086  'Timestamp array' => [
1087  '100|101',
1088  [
1089  ApiBase::PARAM_TYPE => 'timestamp',
1090  ApiBase::PARAM_ISMULTI => 1,
1091  ],
1092  [ wfTimestamp( TS_MW, 100 ), wfTimestamp( TS_MW, 101 ) ],
1093  [],
1094  ],
1095  'User' => [
1096  'foo_bar',
1097  [ ApiBase::PARAM_TYPE => 'user' ],
1098  'Foo bar',
1099  [],
1100  ],
1101  'User prefixed with "User:"' => [
1102  'User:foo_bar',
1103  [ ApiBase::PARAM_TYPE => 'user' ],
1104  'Foo bar',
1105  [],
1106  ],
1107  'Invalid username "|"' => [
1108  '|',
1109  [ ApiBase::PARAM_TYPE => 'user' ],
1111  [ 'apierror-baduser', 'myParam', '&#124;' ],
1112  'baduser_myParam' ),
1113  [],
1114  ],
1115  'Invalid username "300.300.300.300"' => [
1116  '300.300.300.300',
1117  [ ApiBase::PARAM_TYPE => 'user' ],
1119  [ 'apierror-baduser', 'myParam', '300.300.300.300' ],
1120  'baduser_myParam' ),
1121  [],
1122  ],
1123  'IP range as username' => [
1124  '10.0.0.0/8',
1125  [ ApiBase::PARAM_TYPE => 'user' ],
1126  '10.0.0.0/8',
1127  [],
1128  ],
1129  'IPv6 as username' => [
1130  '::1',
1131  [ ApiBase::PARAM_TYPE => 'user' ],
1132  '0:0:0:0:0:0:0:1',
1133  [],
1134  ],
1135  'Obsolete cloaked usemod IP address as username' => [
1136  '1.2.3.xxx',
1137  [ ApiBase::PARAM_TYPE => 'user' ],
1138  '1.2.3.xxx',
1139  [],
1140  ],
1141  'Invalid username containing IP address' => [
1142  'This is [not] valid 1.2.3.xxx, ha!',
1143  [ ApiBase::PARAM_TYPE => 'user' ],
1145  null,
1146  [ 'apierror-baduser', 'myParam', 'This is &#91;not&#93; valid 1.2.3.xxx, ha!' ],
1147  'baduser_myParam'
1148  ),
1149  [],
1150  ],
1151  'External username' => [
1152  'M>Foo bar',
1153  [ ApiBase::PARAM_TYPE => 'user' ],
1154  'M>Foo bar',
1155  [],
1156  ],
1157  'Array of usernames' => [
1158  'foo|bar',
1159  [
1160  ApiBase::PARAM_TYPE => 'user',
1161  ApiBase::PARAM_ISMULTI => true,
1162  ],
1163  [ 'Foo', 'Bar' ],
1164  [],
1165  ],
1166  'tag' => [
1167  'tag1',
1168  [ ApiBase::PARAM_TYPE => 'tags' ],
1169  [ 'tag1' ],
1170  [],
1171  ],
1172  'Array of one tag' => [
1173  'tag1',
1174  [
1175  ApiBase::PARAM_TYPE => 'tags',
1176  ApiBase::PARAM_ISMULTI => true,
1177  ],
1178  [ 'tag1' ],
1179  [],
1180  ],
1181  'Array of tags' => [
1182  'tag1|tag2',
1183  [
1184  ApiBase::PARAM_TYPE => 'tags',
1185  ApiBase::PARAM_ISMULTI => true,
1186  ],
1187  [ 'tag1', 'tag2' ],
1188  [],
1189  ],
1190  'Invalid tag' => [
1191  'invalid tag',
1192  [ ApiBase::PARAM_TYPE => 'tags' ],
1193  new ApiUsageException( null,
1194  Status::newFatal( 'tags-apply-not-allowed-one',
1195  'invalid tag', 1 ) ),
1196  [],
1197  ],
1198  'Unrecognized type' => [
1199  'foo',
1200  [ ApiBase::PARAM_TYPE => 'nonexistenttype' ],
1201  new MWException(
1202  'Internal error in ApiBase::getParameterFromSettings: ' .
1203  "Param myParam's type is unknown - nonexistenttype" ),
1204  [],
1205  ],
1206  'Too many bytes' => [
1207  '1',
1208  [
1211  ],
1213  [ 'apierror-maxbytes', 'myParam', 0 ] ),
1214  [],
1215  ],
1216  'Too many chars' => [
1217  '§§',
1218  [
1221  ],
1223  [ 'apierror-maxchars', 'myParam', 1 ] ),
1224  [],
1225  ],
1226  'Omitted required param' => [
1227  null,
1230  [ 'apierror-missingparam', 'myParam' ] ),
1231  [],
1232  ],
1233  'Empty multi-value' => [
1234  '',
1235  [ ApiBase::PARAM_ISMULTI => true ],
1236  [],
1237  [],
1238  ],
1239  'Multi-value \x1f' => [
1240  "\x1f",
1241  [ ApiBase::PARAM_ISMULTI => true ],
1242  [],
1243  [],
1244  ],
1245  'Allowed non-multi-value with "|"' => [
1246  'a|b',
1247  [ ApiBase::PARAM_TYPE => [ 'a|b' ] ],
1248  'a|b',
1249  [],
1250  ],
1251  'Prohibited multi-value' => [
1252  'a|b',
1253  [ ApiBase::PARAM_TYPE => [ 'a', 'b' ] ],
1255  [
1256  'apierror-multival-only-one-of',
1257  'myParam',
1258  Message::listParam( [ '<kbd>a</kbd>', '<kbd>b</kbd>' ] ),
1259  2
1260  ],
1261  'multival_myParam'
1262  ),
1263  [],
1264  ],
1265  ];
1266 
1267  // The following really just test PHP's string-to-int conversion.
1268  $integerTests = [
1269  [ '+1', 1 ],
1270  [ '-1', -1 ],
1271  [ '1.5', 1 ],
1272  [ '-1.5', -1 ],
1273  [ '1abc', 1 ],
1274  [ ' 1', 1 ],
1275  [ "\t1", 1, '\t1' ],
1276  [ "\r1", 1, '\r1' ],
1277  [ "\f1", 0, '\f1', 'badutf-8' ],
1278  [ "\n1", 1, '\n1' ],
1279  [ "\v1", 0, '\v1', 'badutf-8' ],
1280  [ "\e1", 0, '\e1', 'badutf-8' ],
1281  [ "\x001", 0, '\x001', 'badutf-8' ],
1282  ];
1283 
1284  foreach ( $integerTests as $test ) {
1285  $desc = $test[2] ?? $test[0];
1286  $warnings = isset( $test[3] ) ?
1287  [ [ 'apiwarn-badutf8', 'myParam' ] ] : [];
1288  $returnArray["\"$desc\" as integer"] = [
1289  $test[0],
1290  [ ApiBase::PARAM_TYPE => 'integer' ],
1291  $test[1],
1292  $warnings,
1293  ];
1294  }
1295 
1296  return $returnArray;
1297  }
1298 
1299  public function testErrorArrayToStatus() {
1300  $mock = new MockApi();
1301 
1302  $msg = new Message( 'mainpage' );
1303 
1304  // Sanity check empty array
1305  $expect = Status::newGood();
1306  $this->assertEquals( $expect, $mock->errorArrayToStatus( [] ) );
1307 
1308  // No blocked $user, so no special block handling
1309  $expect = Status::newGood();
1310  $expect->fatal( 'blockedtext' );
1311  $expect->fatal( 'autoblockedtext' );
1312  $expect->fatal( 'systemblockedtext' );
1313  $expect->fatal( 'mainpage' );
1314  $expect->fatal( $msg );
1315  $expect->fatal( $msg, 'foobar' );
1316  $expect->fatal( 'parentheses', 'foobar' );
1317  $this->assertEquals( $expect, $mock->errorArrayToStatus( [
1318  [ 'blockedtext' ],
1319  [ 'autoblockedtext' ],
1320  [ 'systemblockedtext' ],
1321  'mainpage',
1322  $msg,
1323  [ $msg, 'foobar' ],
1324  [ 'parentheses', 'foobar' ],
1325  ] ) );
1326 
1327  // Has a blocked $user, so special block handling
1328  $user = $this->getMutableTestUser()->getUser();
1329  $block = new DatabaseBlock( [
1330  'address' => $user->getName(),
1331  'user' => $user->getID(),
1332  'by' => $this->getTestSysop()->getUser()->getId(),
1333  'reason' => __METHOD__,
1334  'expiry' => time() + 100500,
1335  ] );
1336  $block->insert();
1337  $userInfoTrait = TestingAccessWrapper::newFromObject(
1338  $this->getMockForTrait( ApiBlockInfoTrait::class )
1339  );
1340  $blockinfo = [ 'blockinfo' => $userInfoTrait->getBlockDetails( $block ) ];
1341 
1342  $expect = Status::newGood();
1343  $expect->fatal( ApiMessage::create( 'apierror-blocked', 'blocked', $blockinfo ) );
1344  $expect->fatal( ApiMessage::create( 'apierror-autoblocked', 'autoblocked', $blockinfo ) );
1345  $expect->fatal( ApiMessage::create( 'apierror-systemblocked', 'blocked', $blockinfo ) );
1346  $expect->fatal( 'mainpage' );
1347  $expect->fatal( $msg );
1348  $expect->fatal( $msg, 'foobar' );
1349  $expect->fatal( 'parentheses', 'foobar' );
1350  $this->assertEquals( $expect, $mock->errorArrayToStatus( [
1351  [ 'blockedtext' ],
1352  [ 'autoblockedtext' ],
1353  [ 'systemblockedtext' ],
1354  'mainpage',
1355  $msg,
1356  [ $msg, 'foobar' ],
1357  [ 'parentheses', 'foobar' ],
1358  ], $user ) );
1359  }
1360 
1361  public function testAddBlockInfoToStatus() {
1362  $mock = new MockApi();
1363 
1364  $msg = new Message( 'mainpage' );
1365 
1366  // Sanity check empty array
1367  $expect = Status::newGood();
1368  $test = Status::newGood();
1369  $mock->addBlockInfoToStatus( $test );
1370  $this->assertEquals( $expect, $test );
1371 
1372  // No blocked $user, so no special block handling
1373  $expect = Status::newGood();
1374  $expect->fatal( 'blockedtext' );
1375  $expect->fatal( 'autoblockedtext' );
1376  $expect->fatal( 'systemblockedtext' );
1377  $expect->fatal( 'mainpage' );
1378  $expect->fatal( $msg );
1379  $expect->fatal( $msg, 'foobar' );
1380  $expect->fatal( 'parentheses', 'foobar' );
1381  $test = clone $expect;
1382  $mock->addBlockInfoToStatus( $test );
1383  $this->assertEquals( $expect, $test );
1384 
1385  // Has a blocked $user, so special block handling
1386  $user = $this->getMutableTestUser()->getUser();
1387  $block = new DatabaseBlock( [
1388  'address' => $user->getName(),
1389  'user' => $user->getID(),
1390  'by' => $this->getTestSysop()->getUser()->getId(),
1391  'reason' => __METHOD__,
1392  'expiry' => time() + 100500,
1393  ] );
1394  $block->insert();
1395  $userInfoTrait = TestingAccessWrapper::newFromObject(
1396  $this->getObjectForTrait( ApiBlockInfoTrait::class )
1397  );
1398  $blockinfo = [ 'blockinfo' => $userInfoTrait->getBlockDetails( $block ) ];
1399 
1400  $expect = Status::newGood();
1401  $expect->fatal( ApiMessage::create( 'apierror-blocked', 'blocked', $blockinfo ) );
1402  $expect->fatal( ApiMessage::create( 'apierror-autoblocked', 'autoblocked', $blockinfo ) );
1403  $expect->fatal( ApiMessage::create( 'apierror-systemblocked', 'blocked', $blockinfo ) );
1404  $expect->fatal( 'mainpage' );
1405  $expect->fatal( $msg );
1406  $expect->fatal( $msg, 'foobar' );
1407  $expect->fatal( 'parentheses', 'foobar' );
1408  $test = Status::newGood();
1409  $test->fatal( 'blockedtext' );
1410  $test->fatal( 'autoblockedtext' );
1411  $test->fatal( 'systemblockedtext' );
1412  $test->fatal( 'mainpage' );
1413  $test->fatal( $msg );
1414  $test->fatal( $msg, 'foobar' );
1415  $test->fatal( 'parentheses', 'foobar' );
1416  $mock->addBlockInfoToStatus( $test, $user );
1417  $this->assertEquals( $expect, $test );
1418  }
1419 
1420  public function testDieStatus() {
1421  $mock = new MockApi();
1422 
1424  $status->error( 'foo' );
1425  $status->warning( 'bar' );
1426  try {
1427  $mock->dieStatus( $status );
1428  $this->fail( 'Expected exception not thrown' );
1429  } catch ( ApiUsageException $ex ) {
1430  $this->assertTrue( ApiTestCase::apiExceptionHasCode( $ex, 'foo' ), 'Exception has "foo"' );
1431  $this->assertFalse( ApiTestCase::apiExceptionHasCode( $ex, 'bar' ), 'Exception has "bar"' );
1432  }
1433 
1435  $status->warning( 'foo' );
1436  $status->warning( 'bar' );
1437  try {
1438  $mock->dieStatus( $status );
1439  $this->fail( 'Expected exception not thrown' );
1440  } catch ( ApiUsageException $ex ) {
1441  $this->assertTrue( ApiTestCase::apiExceptionHasCode( $ex, 'foo' ), 'Exception has "foo"' );
1442  $this->assertTrue( ApiTestCase::apiExceptionHasCode( $ex, 'bar' ), 'Exception has "bar"' );
1443  }
1444 
1446  $status->setOk( false );
1447  try {
1448  $mock->dieStatus( $status );
1449  $this->fail( 'Expected exception not thrown' );
1450  } catch ( ApiUsageException $ex ) {
1451  $this->assertTrue( ApiTestCase::apiExceptionHasCode( $ex, 'unknownerror-nocode' ),
1452  'Exception has "unknownerror-nocode"' );
1453  }
1454  }
1455 
1459  public function testExtractRequestParams() {
1460  $request = new FauxRequest( [
1461  'xxexists' => 'exists!',
1462  'xxmulti' => 'a|b|c|d|{bad}',
1463  'xxempty' => '',
1464  'xxtemplate-a' => 'A!',
1465  'xxtemplate-b' => 'B1|B2|B3',
1466  'xxtemplate-c' => '',
1467  'xxrecursivetemplate-b-B1' => 'X',
1468  'xxrecursivetemplate-b-B3' => 'Y',
1469  'xxrecursivetemplate-b-B4' => '?',
1470  'xxemptytemplate-' => 'nope',
1471  'foo' => 'a|b|c',
1472  'xxfoo' => 'a|b|c',
1473  'errorformat' => 'raw',
1474  ] );
1476  $context->setRequest( $request );
1477  $main = new ApiMain( $context );
1478 
1479  $mock = $this->getMockBuilder( ApiBase::class )
1480  ->setConstructorArgs( [ $main, 'test', 'xx' ] )
1481  ->setMethods( [ 'getAllowedParams' ] )
1482  ->getMockForAbstractClass();
1483  $mock->method( 'getAllowedParams' )->willReturn( [
1484  'notexists' => null,
1485  'exists' => null,
1486  'multi' => [
1487  ApiBase::PARAM_ISMULTI => true,
1488  ],
1489  'empty' => [
1490  ApiBase::PARAM_ISMULTI => true,
1491  ],
1492  'template-{m}' => [
1493  ApiBase::PARAM_ISMULTI => true,
1494  ApiBase::PARAM_TEMPLATE_VARS => [ 'm' => 'multi' ],
1495  ],
1496  'recursivetemplate-{m}-{t}' => [
1497  ApiBase::PARAM_TEMPLATE_VARS => [ 't' => 'template-{m}', 'm' => 'multi' ],
1498  ],
1499  'emptytemplate-{m}' => [
1500  ApiBase::PARAM_ISMULTI => true,
1501  ApiBase::PARAM_TEMPLATE_VARS => [ 'm' => 'empty' ],
1502  ],
1503  'badtemplate-{e}' => [
1504  ApiBase::PARAM_TEMPLATE_VARS => [ 'e' => 'exists' ],
1505  ],
1506  'badtemplate2-{e}' => [
1507  ApiBase::PARAM_TEMPLATE_VARS => [ 'e' => 'badtemplate2-{e}' ],
1508  ],
1509  'badtemplate3-{x}' => [
1510  ApiBase::PARAM_TEMPLATE_VARS => [ 'x' => 'foo' ],
1511  ],
1512  ] );
1513 
1514  $this->assertEquals( [
1515  'notexists' => null,
1516  'exists' => 'exists!',
1517  'multi' => [ 'a', 'b', 'c', 'd', '{bad}' ],
1518  'empty' => [],
1519  'template-a' => [ 'A!' ],
1520  'template-b' => [ 'B1', 'B2', 'B3' ],
1521  'template-c' => [],
1522  'template-d' => null,
1523  'recursivetemplate-a-A!' => null,
1524  'recursivetemplate-b-B1' => 'X',
1525  'recursivetemplate-b-B2' => null,
1526  'recursivetemplate-b-B3' => 'Y',
1527  ], $mock->extractRequestParams() );
1528 
1529  $used = TestingAccessWrapper::newFromObject( $main )->getParamsUsed();
1530  sort( $used );
1531  $this->assertEquals( [
1532  'xxempty',
1533  'xxexists',
1534  'xxmulti',
1535  'xxnotexists',
1536  'xxrecursivetemplate-a-A!',
1537  'xxrecursivetemplate-b-B1',
1538  'xxrecursivetemplate-b-B2',
1539  'xxrecursivetemplate-b-B3',
1540  'xxtemplate-a',
1541  'xxtemplate-b',
1542  'xxtemplate-c',
1543  'xxtemplate-d',
1544  ], $used );
1545 
1546  $warnings = $mock->getResult()->getResultData( 'warnings', [ 'Strip' => 'all' ] );
1547  $this->assertCount( 1, $warnings );
1548  $this->assertSame( 'ignoring-invalid-templated-value', $warnings[0]['code'] );
1549  }
1550 
1551 }
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
const PARAM_MAX_BYTES
(integer) Maximum length of a string in bytes (in UTF-8 encoding).
Definition: ApiBase.php:228
testGetTitleOrPageIdSpecialTitle()
testGetTitleOrPageIdTitle()
if(is_array( $mode)) switch( $mode) $input
testExtractRequestParams()
ApiBase::extractRequestParams.
testGetTitleOrPageIdBadParams()
testGetTitleFromTitleOrPageIdTitle()
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
testRequireOnlyOneParameterZero()
ApiUsageException.
Definition: ApiBaseTest.php:62
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
testGetTitleFromTitleOrPageIdPageId()
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
testGetTitleOrPageIdPageId()
Exception used to abort API execution with an error.
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:97
An IContextSource implementation which will inherit context from another source but allow individual ...
testRequireOnlyOneParameterDefault()
Definition: ApiBaseTest.php:50
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:118
markTestSkippedIfDbType( $type)
Skip the test if using the specified database type.
testRequireMaxOneParameterZero()
Definition: ApiBaseTest.php:90
testGetTitleFromTitleOrPageIdInvalidTitle()
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 MediaWikiServices
Definition: injection.txt:23
testRequireAtLeastOneParameterTwo()
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
const PARAM_ALL
(boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true...
Definition: ApiBase.php:187
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
Definition: ApiBase.php:215
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
if( $line===false) $args
Definition: cdb.php:64
const PARAM_MAX_CHARS
(integer) Maximum length of a string in characters (unicode codepoints).
Definition: ApiBase.php:234
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:1982
insert( $dbw=null)
Insert a block into the block table.
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
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 '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:1263
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static getTestSysop()
Convenience method for getting an immutable admin test user.
static getMain()
Get the RequestContext object associated with the main request.
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
Definition: ApiBase.php:222
doGetParameterFromSettings( $input, $paramSettings, $expected, $warnings, $options=[])
testRequireAtLeastOneParameterOne()
provideStubMethods()
Definition: ApiBaseTest.php:30
testRequireOnlyOneParameterTrue()
ApiUsageException.
Definition: ApiBaseTest.php:73
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
const PARAM_RANGE_ENFORCE
(boolean) For PARAM_TYPE &#39;integer&#39;, enforce PARAM_MIN and PARAM_MAX?
Definition: ApiBase.php:124
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is &#39;submodule&#39;, map parameter values to submodule paths.
Definition: ApiBase.php:172
testGetParameterFromSettings_prefix( $input, $paramSettings, $expected, $warnings, $options=[])
provideGetParameterFromSettings
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
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:1982
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE &#39;limit&#39;.
Definition: ApiBase.php:103
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
testGetTitleFromTitleOrPageIdBadParams()
testGetTitleFromTitleOrPageIdInvalidPageId()
testGetTitleOrPageIdInvalidPageId()
testRequireMaxOneParameterOne()
Definition: ApiBaseTest.php:98
testErrorArrayToStatus()
testRequireAtLeastOneParameterZero()
const PARAM_SENSITIVE
(boolean) Is the parameter sensitive? Note &#39;password&#39;-type fields are always sensitive regardless of ...
Definition: ApiBase.php:200
const PARAM_TEMPLATE_VARS
(array) Indicate that this is a templated parameter, and specify replacements.
Definition: ApiBase.php:252
testStubMethods( $expected, $method, $args=[])
This covers a variety of stub methods that return a fixed value.
Definition: ApiBaseTest.php:23
testRequireMaxOneParameterTwo()
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
testAddBlockInfoToStatus()
testRequireOnlyOneParameterMissing()
Definition: ApiBaseTest.php:81
static defineTag( $tag)
Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
Definition: ChangeTags.php:881
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
testGetParameterFromSettings_noprefix( $input, $paramSettings, $expected, $warnings, $options=[])
provideGetParameterFromSettings
API Database medium.
Definition: ApiBaseTest.php:14
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
Definition: ApiBase.php:209
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
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:2633
static provideGetParameterFromSettings()
const PARAM_EXTRA_NAMESPACES
(int[]) When PARAM_TYPE is &#39;namespace&#39;, include these as additional possible values.
Definition: ApiBase.php:193
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:112
testGetTitleOrPageIdInvalidTitle()
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:106
getExistingTestPage( $title=null)
Returns a WikiPage representing an existing page.
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:2633
static apiExceptionHasCode(ApiUsageException $ex, $code)
const PARAM_ALLOW_DUPLICATES
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
Definition: ApiBase.php:109
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
static listParam(array $list, $type='text')
Definition: Message.php:1126
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40