MediaWiki  REL1_31
ApiBaseTest.php
Go to the documentation of this file.
1 <?php
2 
3 use Wikimedia\TestingAccessWrapper;
4 
12 class ApiBaseTest extends ApiTestCase {
21  public function testStubMethods( $expected, $method, $args = [] ) {
22  // Some of these are protected
23  $mock = TestingAccessWrapper::newFromObject( new MockApi() );
24  $result = call_user_func_array( [ $mock, $method ], $args );
25  $this->assertSame( $expected, $result );
26  }
27 
28  public function provideStubMethods() {
29  return [
30  [ null, 'getModuleManager' ],
31  [ null, 'getCustomPrinter' ],
32  [ [], 'getHelpUrls' ],
33  // @todo This is actually overriden by MockApi
34  // [ [], 'getAllowedParams' ],
35  [ true, 'shouldCheckMaxLag' ],
36  [ true, 'isReadMode' ],
37  [ false, 'isWriteMode' ],
38  [ false, 'mustBePosted' ],
39  [ false, 'isDeprecated' ],
40  [ false, 'isInternal' ],
41  [ false, 'needsToken' ],
42  [ null, 'getWebUITokenSalt', [ [] ] ],
43  [ null, 'getConditionalRequestData', [ 'etag' ] ],
44  [ null, 'dynamicParameterDocumentation' ],
45  ];
46  }
47 
49  $mock = new MockApi();
50  $mock->requireOnlyOneParameter(
51  [ "filename" => "foo.txt", "enablechunks" => false ],
52  "filename", "enablechunks"
53  );
54  $this->assertTrue( true );
55  }
56 
60  public function testRequireOnlyOneParameterZero() {
61  $mock = new MockApi();
62  $mock->requireOnlyOneParameter(
63  [ "filename" => "foo.txt", "enablechunks" => 0 ],
64  "filename", "enablechunks"
65  );
66  }
67 
71  public function testRequireOnlyOneParameterTrue() {
72  $mock = new MockApi();
73  $mock->requireOnlyOneParameter(
74  [ "filename" => "foo.txt", "enablechunks" => true ],
75  "filename", "enablechunks"
76  );
77  }
78 
80  $this->setExpectedException( ApiUsageException::class,
81  'One of the parameters "foo" and "bar" is required.' );
82  $mock = new MockApi();
83  $mock->requireOnlyOneParameter(
84  [ "filename" => "foo.txt", "enablechunks" => false ],
85  "foo", "bar" );
86  }
87 
88  public function testRequireMaxOneParameterZero() {
89  $mock = new MockApi();
90  $mock->requireMaxOneParameter(
91  [ 'foo' => 'bar', 'baz' => 'quz' ],
92  'squirrel' );
93  $this->assertTrue( true );
94  }
95 
96  public function testRequireMaxOneParameterOne() {
97  $mock = new MockApi();
98  $mock->requireMaxOneParameter(
99  [ 'foo' => 'bar', 'baz' => 'quz' ],
100  'foo', 'squirrel' );
101  $this->assertTrue( true );
102  }
103 
104  public function testRequireMaxOneParameterTwo() {
105  $this->setExpectedException( ApiUsageException::class,
106  'The parameters "foo" and "baz" can not be used together.' );
107  $mock = new MockApi();
108  $mock->requireMaxOneParameter(
109  [ 'foo' => 'bar', 'baz' => 'quz' ],
110  'foo', 'baz' );
111  }
112 
114  $this->setExpectedException( ApiUsageException::class,
115  'At least one of the parameters "foo" and "bar" is required.' );
116  $mock = new MockApi();
117  $mock->requireAtLeastOneParameter(
118  [ 'a' => 'b', 'c' => 'd' ],
119  'foo', 'bar' );
120  }
121 
123  $mock = new MockApi();
124  $mock->requireAtLeastOneParameter(
125  [ 'a' => 'b', 'c' => 'd' ],
126  'foo', 'a' );
127  $this->assertTrue( true );
128  }
129 
131  $mock = new MockApi();
132  $mock->requireAtLeastOneParameter(
133  [ 'a' => 'b', 'c' => 'd' ],
134  'a', 'c' );
135  $this->assertTrue( true );
136  }
137 
138  public function testGetTitleOrPageIdBadParams() {
139  $this->setExpectedException( ApiUsageException::class,
140  'The parameters "title" and "pageid" can not be used together.' );
141  $mock = new MockApi();
142  $mock->getTitleOrPageId( [ 'title' => 'a', 'pageid' => 7 ] );
143  }
144 
145  public function testGetTitleOrPageIdTitle() {
146  $mock = new MockApi();
147  $result = $mock->getTitleOrPageId( [ 'title' => 'Foo' ] );
148  $this->assertInstanceOf( WikiPage::class, $result );
149  $this->assertSame( 'Foo', $result->getTitle()->getPrefixedText() );
150  }
151 
153  $this->setExpectedException( ApiUsageException::class,
154  'Bad title "|".' );
155  $mock = new MockApi();
156  $mock->getTitleOrPageId( [ 'title' => '|' ] );
157  }
158 
160  $this->setExpectedException( ApiUsageException::class,
161  "Namespace doesn't allow actual pages." );
162  $mock = new MockApi();
163  $mock->getTitleOrPageId( [ 'title' => 'Special:RandomPage' ] );
164  }
165 
166  public function testGetTitleOrPageIdPageId() {
167  $result = ( new MockApi() )->getTitleOrPageId(
168  [ 'pageid' => Title::newFromText( 'UTPage' )->getArticleId() ] );
169  $this->assertInstanceOf( WikiPage::class, $result );
170  $this->assertSame( 'UTPage', $result->getTitle()->getPrefixedText() );
171  }
172 
174  $this->setExpectedException( ApiUsageException::class,
175  'There is no page with ID 2147483648.' );
176  $mock = new MockApi();
177  $mock->getTitleOrPageId( [ 'pageid' => 2147483648 ] );
178  }
179 
181  $this->setExpectedException( ApiUsageException::class,
182  'The parameters "title" and "pageid" can not be used together.' );
183  $mock = new MockApi();
184  $mock->getTitleFromTitleOrPageId( [ 'title' => 'a', 'pageid' => 7 ] );
185  }
186 
188  $mock = new MockApi();
189  $result = $mock->getTitleFromTitleOrPageId( [ 'title' => 'Foo' ] );
190  $this->assertInstanceOf( Title::class, $result );
191  $this->assertSame( 'Foo', $result->getPrefixedText() );
192  }
193 
195  $this->setExpectedException( ApiUsageException::class,
196  'Bad title "|".' );
197  $mock = new MockApi();
198  $mock->getTitleFromTitleOrPageId( [ 'title' => '|' ] );
199  }
200 
202  $result = ( new MockApi() )->getTitleFromTitleOrPageId(
203  [ 'pageid' => Title::newFromText( 'UTPage' )->getArticleId() ] );
204  $this->assertInstanceOf( Title::class, $result );
205  $this->assertSame( 'UTPage', $result->getPrefixedText() );
206  }
207 
209  $this->setExpectedException( ApiUsageException::class,
210  'There is no page with ID 298401643.' );
211  $mock = new MockApi();
212  $mock->getTitleFromTitleOrPageId( [ 'pageid' => 298401643 ] );
213  }
214 
227  $input, $paramSettings, $expected, $warnings, $options = []
228  ) {
229  $mock = new MockApi();
230  $wrapper = TestingAccessWrapper::newFromObject( $mock );
231 
232  $context = new DerivativeContext( $mock );
233  $context->setRequest( new FauxRequest(
234  $input !== null ? [ 'myParam' => $input ] : [] ) );
235  $wrapper->mMainModule = new ApiMain( $context );
236 
237  $parseLimits = isset( $options['parseLimits'] ) ?
238  $options['parseLimits'] : true;
239 
240  if ( !empty( $options['apihighlimits'] ) ) {
241  $context->setUser( self::$users['sysop']->getUser() );
242  }
243 
244  if ( isset( $options['internalmode'] ) && !$options['internalmode'] ) {
245  $mainWrapper = TestingAccessWrapper::newFromObject( $wrapper->mMainModule );
246  $mainWrapper->mInternalMode = false;
247  }
248 
249  // If we're testing tags, set up some tags
250  if ( isset( $paramSettings[ApiBase::PARAM_TYPE] ) &&
251  $paramSettings[ApiBase::PARAM_TYPE] === 'tags'
252  ) {
253  ChangeTags::defineTag( 'tag1' );
254  ChangeTags::defineTag( 'tag2' );
255  }
256 
257  if ( $expected instanceof Exception ) {
258  try {
259  $wrapper->getParameterFromSettings( 'myParam', $paramSettings,
260  $parseLimits );
261  $this->fail( 'No exception thrown' );
262  } catch ( Exception $ex ) {
263  $this->assertEquals( $expected, $ex );
264  }
265  } else {
266  $result = $wrapper->getParameterFromSettings( 'myParam',
267  $paramSettings, $parseLimits );
268  if ( isset( $paramSettings[ApiBase::PARAM_TYPE] ) &&
269  $paramSettings[ApiBase::PARAM_TYPE] === 'timestamp' &&
270  $expected === 'now'
271  ) {
272  // Allow one second of fuzziness. Make sure the formats are
273  // correct!
274  $this->assertRegExp( '/^\d{14}$/', $result );
275  $this->assertLessThanOrEqual( 1,
276  abs( wfTimestamp( TS_UNIX, $result ) - time() ),
277  "Result $result differs from expected $expected by " .
278  'more than one second' );
279  } else {
280  $this->assertSame( $expected, $result );
281  }
282  $actualWarnings = array_map( function ( $warn ) {
283  return $warn instanceof Message
284  ? array_merge( [ $warn->getKey() ], $warn->getParams() )
285  : $warn;
286  }, $mock->warnings );
287  $this->assertSame( $warnings, $actualWarnings );
288  }
289 
290  if ( !empty( $paramSettings[ApiBase::PARAM_SENSITIVE] ) ||
291  ( isset( $paramSettings[ApiBase::PARAM_TYPE] ) &&
292  $paramSettings[ApiBase::PARAM_TYPE] === 'password' )
293  ) {
294  $mainWrapper = TestingAccessWrapper::newFromObject( $wrapper->getMain() );
295  $this->assertSame( [ 'myParam' ],
296  $mainWrapper->getSensitiveParams() );
297  }
298  }
299 
300  public static function provideGetParameterFromSettings() {
301  $warnings = [
302  [ 'apiwarn-badutf8', 'myParam' ],
303  ];
304 
305  $c0 = '';
306  $enc = '';
307  for ( $i = 0; $i < 32; $i++ ) {
308  $c0 .= chr( $i );
309  $enc .= ( $i === 9 || $i === 10 || $i === 13 )
310  ? chr( $i )
311  : '�';
312  }
313 
314  $returnArray = [
315  'Basic param' => [ 'bar', null, 'bar', [] ],
316  'Basic param, C0 controls' => [ $c0, null, $enc, $warnings ],
317  'String param' => [ 'bar', '', 'bar', [] ],
318  'String param, defaulted' => [ null, '', '', [] ],
319  'String param, empty' => [ '', 'default', '', [] ],
320  'String param, required, empty' => [
321  '',
322  [ ApiBase::PARAM_DFLT => 'default', ApiBase::PARAM_REQUIRED => true ],
324  [ 'apierror-missingparam', 'myParam' ] ),
325  []
326  ],
327  'Multi-valued parameter' => [
328  'a|b|c',
330  [ 'a', 'b', 'c' ],
331  []
332  ],
333  'Multi-valued parameter, alternative separator' => [
334  "\x1fa|b\x1fc|d",
336  [ 'a|b', 'c|d' ],
337  []
338  ],
339  'Multi-valued parameter, other C0 controls' => [
340  $c0,
342  [ $enc ],
343  $warnings
344  ],
345  'Multi-valued parameter, other C0 controls (2)' => [
346  "\x1f" . $c0,
348  [ substr( $enc, 0, -3 ), '' ],
349  $warnings
350  ],
351  'Multi-valued parameter with limits' => [
352  'a|b|c',
353  [
354  ApiBase::PARAM_ISMULTI => true,
356  ],
357  [ 'a', 'b', 'c' ],
358  [],
359  ],
360  'Multi-valued parameter with exceeded limits' => [
361  'a|b|c',
362  [
363  ApiBase::PARAM_ISMULTI => true,
365  ],
366  [ 'a', 'b' ],
367  [ [ 'apiwarn-toomanyvalues', 'myParam', 2 ] ],
368  ],
369  'Multi-valued parameter with exceeded limits for non-bot' => [
370  'a|b|c',
371  [
372  ApiBase::PARAM_ISMULTI => true,
375  ],
376  [ 'a', 'b' ],
377  [ [ 'apiwarn-toomanyvalues', 'myParam', 2 ] ],
378  ],
379  'Multi-valued parameter with non-exceeded limits for bot' => [
380  'a|b|c',
381  [
382  ApiBase::PARAM_ISMULTI => true,
385  ],
386  [ 'a', 'b', 'c' ],
387  [],
388  [ 'apihighlimits' => true ],
389  ],
390  'Multi-valued parameter with prohibited duplicates' => [
391  'a|b|a|c',
393  // Note that the keys are not sequential! This matches
394  // array_unique, but might be unexpected.
395  [ 0 => 'a', 1 => 'b', 3 => 'c' ],
396  [],
397  ],
398  'Multi-valued parameter with allowed duplicates' => [
399  'a|a',
400  [
401  ApiBase::PARAM_ISMULTI => true,
403  ],
404  [ 'a', 'a' ],
405  [],
406  ],
407  'Empty boolean param' => [
408  '',
409  [ ApiBase::PARAM_TYPE => 'boolean' ],
410  true,
411  [],
412  ],
413  'Boolean param 0' => [
414  '0',
415  [ ApiBase::PARAM_TYPE => 'boolean' ],
416  true,
417  [],
418  ],
419  'Boolean param false' => [
420  'false',
421  [ ApiBase::PARAM_TYPE => 'boolean' ],
422  true,
423  [],
424  ],
425  'Boolean multi-param' => [
426  'true|false',
427  [
428  ApiBase::PARAM_TYPE => 'boolean',
429  ApiBase::PARAM_ISMULTI => true,
430  ],
431  new MWException(
432  'Internal error in ApiBase::getParameterFromSettings: ' .
433  'Multi-values not supported for myParam'
434  ),
435  [],
436  ],
437  'Empty boolean param with non-false default' => [
438  '',
439  [
440  ApiBase::PARAM_TYPE => 'boolean',
441  ApiBase::PARAM_DFLT => true,
442  ],
443  new MWException(
444  'Internal error in ApiBase::getParameterFromSettings: ' .
445  "Boolean param myParam's default is set to '1'. " .
446  'Boolean parameters must default to false.' ),
447  [],
448  ],
449  'Deprecated parameter' => [
450  'foo',
452  'foo',
453  [ [ 'apiwarn-deprecation-parameter', 'myParam' ] ],
454  ],
455  'Deprecated parameter value' => [
456  'a',
457  [ ApiBase::PARAM_DEPRECATED_VALUES => [ 'a' => true ] ],
458  'a',
459  [ [ 'apiwarn-deprecation-parameter', 'myParam=a' ] ],
460  ],
461  'Multiple deprecated parameter values' => [
462  'a|b|c|d',
464  [ 'b' => true, 'd' => true ],
466  [ 'a', 'b', 'c', 'd' ],
467  [
468  [ 'apiwarn-deprecation-parameter', 'myParam=b' ],
469  [ 'apiwarn-deprecation-parameter', 'myParam=d' ],
470  ],
471  ],
472  'Deprecated parameter value with custom warning' => [
473  'a',
474  [ ApiBase::PARAM_DEPRECATED_VALUES => [ 'a' => 'my-msg' ] ],
475  'a',
476  [ 'my-msg' ],
477  ],
478  '"*" when wildcard not allowed' => [
479  '*',
480  [ ApiBase::PARAM_ISMULTI => true,
481  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ] ],
482  [],
483  [ [ 'apiwarn-unrecognizedvalues', 'myParam',
484  [ 'list' => [ '&#42;' ], 'type' => 'comma' ], 1 ] ],
485  ],
486  'Wildcard "*"' => [
487  '*',
488  [
489  ApiBase::PARAM_ISMULTI => true,
490  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ],
491  ApiBase::PARAM_ALL => true,
492  ],
493  [ 'a', 'b', 'c' ],
494  [],
495  ],
496  'Wildcard "*" with multiples not allowed' => [
497  '*',
498  [
499  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ],
500  ApiBase::PARAM_ALL => true,
501  ],
503  [ 'apierror-unrecognizedvalue', 'myParam', '&#42;' ],
504  'unknown_myParam' ),
505  [],
506  ],
507  'Wildcard "*" with unrestricted type' => [
508  '*',
509  [
510  ApiBase::PARAM_ISMULTI => true,
511  ApiBase::PARAM_ALL => true,
512  ],
513  [ '*' ],
514  [],
515  ],
516  'Wildcard "x"' => [
517  'x',
518  [
519  ApiBase::PARAM_ISMULTI => true,
520  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ],
521  ApiBase::PARAM_ALL => 'x',
522  ],
523  [ 'a', 'b', 'c' ],
524  [],
525  ],
526  'Wildcard conflicting with allowed value' => [
527  'a',
528  [
529  ApiBase::PARAM_ISMULTI => true,
530  ApiBase::PARAM_TYPE => [ 'a', 'b', 'c' ],
531  ApiBase::PARAM_ALL => 'a',
532  ],
533  new MWException(
534  'Internal error in ApiBase::getParameterFromSettings: ' .
535  'For param myParam, PARAM_ALL collides with a possible ' .
536  'value' ),
537  [],
538  ],
539  'Namespace with wildcard' => [
540  '*',
541  [
542  ApiBase::PARAM_ISMULTI => true,
543  ApiBase::PARAM_TYPE => 'namespace',
544  ],
546  [],
547  ],
548  // PARAM_ALL is ignored with namespace types.
549  'Namespace with wildcard suppressed' => [
550  '*',
551  [
552  ApiBase::PARAM_ISMULTI => true,
553  ApiBase::PARAM_TYPE => 'namespace',
554  ApiBase::PARAM_ALL => false,
555  ],
557  [],
558  ],
559  'Namespace with wildcard "x"' => [
560  'x',
561  [
562  ApiBase::PARAM_ISMULTI => true,
563  ApiBase::PARAM_TYPE => 'namespace',
564  ApiBase::PARAM_ALL => 'x',
565  ],
566  [],
567  [ [ 'apiwarn-unrecognizedvalues', 'myParam',
568  [ 'list' => [ 'x' ], 'type' => 'comma' ], 1 ] ],
569  ],
570  'Password' => [
571  'dDy+G?e?txnr.1:(@[Ru',
572  [ ApiBase::PARAM_TYPE => 'password' ],
573  'dDy+G?e?txnr.1:(@[Ru',
574  [],
575  ],
576  'Sensitive field' => [
577  'I am fond of pineapples',
579  'I am fond of pineapples',
580  [],
581  ],
582  'Upload with default' => [
583  '',
584  [
585  ApiBase::PARAM_TYPE => 'upload',
586  ApiBase::PARAM_DFLT => '',
587  ],
588  new MWException(
589  'Internal error in ApiBase::getParameterFromSettings: ' .
590  "File upload param myParam's default is set to ''. " .
591  'File upload parameters may not have a default.' ),
592  [],
593  ],
594  'Multiple upload' => [
595  '',
596  [
597  ApiBase::PARAM_TYPE => 'upload',
598  ApiBase::PARAM_ISMULTI => true,
599  ],
600  new MWException(
601  'Internal error in ApiBase::getParameterFromSettings: ' .
602  'Multi-values not supported for myParam' ),
603  [],
604  ],
605  // @todo Test actual upload
606  'Namespace -1' => [
607  '-1',
608  [ ApiBase::PARAM_TYPE => 'namespace' ],
610  [ 'apierror-unrecognizedvalue', 'myParam', '-1' ],
611  'unknown_myParam' ),
612  [],
613  ],
614  'Extra namespace -1' => [
615  '-1',
616  [
617  ApiBase::PARAM_TYPE => 'namespace',
619  ],
620  '-1',
621  [],
622  ],
623  // @todo Test with PARAM_SUBMODULE_MAP unset, need
624  // getModuleManager() to return something real
625  'Nonexistent module' => [
626  'not-a-module-name',
627  [
628  ApiBase::PARAM_TYPE => 'submodule',
630  [ 'foo' => 'foo', 'bar' => 'foo+bar' ],
631  ],
633  null,
634  [
635  'apierror-unrecognizedvalue',
636  'myParam',
637  'not-a-module-name',
638  ],
639  'unknown_myParam'
640  ),
641  [],
642  ],
643  '\\x1f with multiples not allowed' => [
644  "\x1f",
645  [],
647  'apierror-badvalue-notmultivalue',
648  'badvalue_notmultivalue' ),
649  [],
650  ],
651  'Integer with unenforced min' => [
652  '-2',
653  [
654  ApiBase::PARAM_TYPE => 'integer',
655  ApiBase::PARAM_MIN => -1,
656  ],
657  -1,
658  [ [ 'apierror-integeroutofrange-belowminimum', 'myParam', -1,
659  -2 ] ],
660  ],
661  'Integer with enforced min' => [
662  '-2',
663  [
664  ApiBase::PARAM_TYPE => 'integer',
665  ApiBase::PARAM_MIN => -1,
667  ],
669  [ 'apierror-integeroutofrange-belowminimum', 'myParam',
670  '-1', '-2' ], 'integeroutofrange',
671  [ 'min' => -1, 'max' => null, 'botMax' => null ] ),
672  [],
673  ],
674  'Integer with unenforced max (internal mode)' => [
675  '8',
676  [
677  ApiBase::PARAM_TYPE => 'integer',
678  ApiBase::PARAM_MAX => 7,
679  ],
680  8,
681  [],
682  ],
683  'Integer with enforced max (internal mode)' => [
684  '8',
685  [
686  ApiBase::PARAM_TYPE => 'integer',
687  ApiBase::PARAM_MAX => 7,
689  ],
690  8,
691  [],
692  ],
693  'Integer with unenforced max (non-internal mode)' => [
694  '8',
695  [
696  ApiBase::PARAM_TYPE => 'integer',
697  ApiBase::PARAM_MAX => 7,
698  ],
699  7,
700  [ [ 'apierror-integeroutofrange-abovemax', 'myParam', 7, 8 ] ],
701  [ 'internalmode' => false ],
702  ],
703  'Integer with enforced max (non-internal mode)' => [
704  '8',
705  [
706  ApiBase::PARAM_TYPE => 'integer',
707  ApiBase::PARAM_MAX => 7,
709  ],
711  null,
712  [ 'apierror-integeroutofrange-abovemax', 'myParam', '7', '8' ],
713  'integeroutofrange',
714  [ 'min' => null, 'max' => 7, 'botMax' => 7 ]
715  ),
716  [],
717  [ 'internalmode' => false ],
718  ],
719  'Array of integers' => [
720  '3|12|966|-1',
721  [
722  ApiBase::PARAM_ISMULTI => true,
723  ApiBase::PARAM_TYPE => 'integer',
724  ],
725  [ 3, 12, 966, -1 ],
726  [],
727  ],
728  'Array of integers with unenforced min/max (internal mode)' => [
729  '3|12|966|-1',
730  [
731  ApiBase::PARAM_ISMULTI => true,
732  ApiBase::PARAM_TYPE => 'integer',
733  ApiBase::PARAM_MIN => 0,
734  ApiBase::PARAM_MAX => 100,
735  ],
736  [ 3, 12, 966, 0 ],
737  [ [ 'apierror-integeroutofrange-belowminimum', 'myParam', 0, -1 ] ],
738  ],
739  'Array of integers with enforced min/max (internal mode)' => [
740  '3|12|966|-1',
741  [
742  ApiBase::PARAM_ISMULTI => true,
743  ApiBase::PARAM_TYPE => 'integer',
744  ApiBase::PARAM_MIN => 0,
745  ApiBase::PARAM_MAX => 100,
747  ],
749  null,
750  [ 'apierror-integeroutofrange-belowminimum', 'myParam', 0, -1 ],
751  'integeroutofrange',
752  [ 'min' => 0, 'max' => 100, 'botMax' => 100 ]
753  ),
754  [],
755  ],
756  'Array of integers with unenforced min/max (non-internal mode)' => [
757  '3|12|966|-1',
758  [
759  ApiBase::PARAM_ISMULTI => true,
760  ApiBase::PARAM_TYPE => 'integer',
761  ApiBase::PARAM_MIN => 0,
762  ApiBase::PARAM_MAX => 100,
763  ],
764  [ 3, 12, 100, 0 ],
765  [
766  [ 'apierror-integeroutofrange-abovemax', 'myParam', 100, 966 ],
767  [ 'apierror-integeroutofrange-belowminimum', 'myParam', 0, -1 ]
768  ],
769  [ 'internalmode' => false ],
770  ],
771  'Array of integers with enforced min/max (non-internal mode)' => [
772  '3|12|966|-1',
773  [
774  ApiBase::PARAM_ISMULTI => true,
775  ApiBase::PARAM_TYPE => 'integer',
776  ApiBase::PARAM_MIN => 0,
777  ApiBase::PARAM_MAX => 100,
779  ],
781  null,
782  [ 'apierror-integeroutofrange-abovemax', 'myParam', 100, 966 ],
783  'integeroutofrange',
784  [ 'min' => 0, 'max' => 100, 'botMax' => 100 ]
785  ),
786  [],
787  [ 'internalmode' => false ],
788  ],
789  'Limit with parseLimits false' => [
790  '100',
791  [ ApiBase::PARAM_TYPE => 'limit' ],
792  '100',
793  [],
794  [ 'parseLimits' => false ],
795  ],
796  'Limit with no max' => [
797  '100',
798  [
799  ApiBase::PARAM_TYPE => 'limit',
800  ApiBase::PARAM_MAX2 => 10,
801  ApiBase::PARAM_ISMULTI => true,
802  ],
803  new MWException(
804  'Internal error in ApiBase::getParameterFromSettings: ' .
805  'MAX1 or MAX2 are not defined for the limit myParam' ),
806  [],
807  ],
808  'Limit with no max2' => [
809  '100',
810  [
811  ApiBase::PARAM_TYPE => 'limit',
812  ApiBase::PARAM_MAX => 10,
813  ApiBase::PARAM_ISMULTI => true,
814  ],
815  new MWException(
816  'Internal error in ApiBase::getParameterFromSettings: ' .
817  'MAX1 or MAX2 are not defined for the limit myParam' ),
818  [],
819  ],
820  'Limit with multi-value' => [
821  '100',
822  [
823  ApiBase::PARAM_TYPE => 'limit',
824  ApiBase::PARAM_MAX => 10,
825  ApiBase::PARAM_MAX2 => 10,
826  ApiBase::PARAM_ISMULTI => true,
827  ],
828  new MWException(
829  'Internal error in ApiBase::getParameterFromSettings: ' .
830  'Multi-values not supported for myParam' ),
831  [],
832  ],
833  'Valid limit' => [
834  '100',
835  [
836  ApiBase::PARAM_TYPE => 'limit',
837  ApiBase::PARAM_MAX => 100,
838  ApiBase::PARAM_MAX2 => 100,
839  ],
840  100,
841  [],
842  ],
843  'Limit max' => [
844  'max',
845  [
846  ApiBase::PARAM_TYPE => 'limit',
847  ApiBase::PARAM_MAX => 100,
848  ApiBase::PARAM_MAX2 => 101,
849  ],
850  100,
851  [],
852  ],
853  'Limit max for apihighlimits' => [
854  'max',
855  [
856  ApiBase::PARAM_TYPE => 'limit',
857  ApiBase::PARAM_MAX => 100,
858  ApiBase::PARAM_MAX2 => 101,
859  ],
860  101,
861  [],
862  [ 'apihighlimits' => true ],
863  ],
864  'Limit too large (internal mode)' => [
865  '101',
866  [
867  ApiBase::PARAM_TYPE => 'limit',
868  ApiBase::PARAM_MAX => 100,
869  ApiBase::PARAM_MAX2 => 101,
870  ],
871  101,
872  [],
873  ],
874  'Limit okay for apihighlimits (internal mode)' => [
875  '101',
876  [
877  ApiBase::PARAM_TYPE => 'limit',
878  ApiBase::PARAM_MAX => 100,
879  ApiBase::PARAM_MAX2 => 101,
880  ],
881  101,
882  [],
883  [ 'apihighlimits' => true ],
884  ],
885  'Limit too large for apihighlimits (internal mode)' => [
886  '102',
887  [
888  ApiBase::PARAM_TYPE => 'limit',
889  ApiBase::PARAM_MAX => 100,
890  ApiBase::PARAM_MAX2 => 101,
891  ],
892  102,
893  [],
894  [ 'apihighlimits' => true ],
895  ],
896  'Limit too large (non-internal mode)' => [
897  '101',
898  [
899  ApiBase::PARAM_TYPE => 'limit',
900  ApiBase::PARAM_MAX => 100,
901  ApiBase::PARAM_MAX2 => 101,
902  ],
903  100,
904  [ [ 'apierror-integeroutofrange-abovemax', 'myParam', 100, 101 ] ],
905  [ 'internalmode' => false ],
906  ],
907  'Limit okay for apihighlimits (non-internal mode)' => [
908  '101',
909  [
910  ApiBase::PARAM_TYPE => 'limit',
911  ApiBase::PARAM_MAX => 100,
912  ApiBase::PARAM_MAX2 => 101,
913  ],
914  101,
915  [],
916  [ 'internalmode' => false, 'apihighlimits' => true ],
917  ],
918  'Limit too large for apihighlimits (non-internal mode)' => [
919  '102',
920  [
921  ApiBase::PARAM_TYPE => 'limit',
922  ApiBase::PARAM_MAX => 100,
923  ApiBase::PARAM_MAX2 => 101,
924  ],
925  101,
926  [ [ 'apierror-integeroutofrange-abovebotmax', 'myParam', 101, 102 ] ],
927  [ 'internalmode' => false, 'apihighlimits' => true ],
928  ],
929  'Limit too small' => [
930  '-2',
931  [
932  ApiBase::PARAM_TYPE => 'limit',
933  ApiBase::PARAM_MIN => -1,
934  ApiBase::PARAM_MAX => 100,
935  ApiBase::PARAM_MAX2 => 100,
936  ],
937  -1,
938  [ [ 'apierror-integeroutofrange-belowminimum', 'myParam', -1,
939  -2 ] ],
940  ],
941  'Timestamp' => [
942  wfTimestamp( TS_UNIX, '20211221122112' ),
943  [ ApiBase::PARAM_TYPE => 'timestamp' ],
944  '20211221122112',
945  [],
946  ],
947  'Timestamp 0' => [
948  '0',
949  [ ApiBase::PARAM_TYPE => 'timestamp' ],
950  // Magic keyword
951  'now',
952  [ [ 'apiwarn-unclearnowtimestamp', 'myParam', '0' ] ],
953  ],
954  'Timestamp empty' => [
955  '',
956  [ ApiBase::PARAM_TYPE => 'timestamp' ],
957  'now',
958  [ [ 'apiwarn-unclearnowtimestamp', 'myParam', '' ] ],
959  ],
960  // wfTimestamp() interprets this as Unix time
961  'Timestamp 00' => [
962  '00',
963  [ ApiBase::PARAM_TYPE => 'timestamp' ],
964  '19700101000000',
965  [],
966  ],
967  'Timestamp now' => [
968  'now',
969  [ ApiBase::PARAM_TYPE => 'timestamp' ],
970  'now',
971  [],
972  ],
973  'Invalid timestamp' => [
974  'a potato',
975  [ ApiBase::PARAM_TYPE => 'timestamp' ],
977  null,
978  [ 'apierror-badtimestamp', 'myParam', 'a potato' ],
979  'badtimestamp_myParam'
980  ),
981  [],
982  ],
983  'Timestamp array' => [
984  '100|101',
985  [
986  ApiBase::PARAM_TYPE => 'timestamp',
988  ],
989  [ wfTimestamp( TS_MW, 100 ), wfTimestamp( TS_MW, 101 ) ],
990  [],
991  ],
992  'User' => [
993  'foo_bar',
994  [ ApiBase::PARAM_TYPE => 'user' ],
995  'Foo bar',
996  [],
997  ],
998  'Invalid username "|"' => [
999  '|',
1000  [ ApiBase::PARAM_TYPE => 'user' ],
1002  [ 'apierror-baduser', 'myParam', '&#124;' ],
1003  'baduser_myParam' ),
1004  [],
1005  ],
1006  'Invalid username "300.300.300.300"' => [
1007  '300.300.300.300',
1008  [ ApiBase::PARAM_TYPE => 'user' ],
1010  [ 'apierror-baduser', 'myParam', '300.300.300.300' ],
1011  'baduser_myParam' ),
1012  [],
1013  ],
1014  'IP range as username' => [
1015  '10.0.0.0/8',
1016  [ ApiBase::PARAM_TYPE => 'user' ],
1017  '10.0.0.0/8',
1018  [],
1019  ],
1020  'IPv6 as username' => [
1021  '::1',
1022  [ ApiBase::PARAM_TYPE => 'user' ],
1023  '0:0:0:0:0:0:0:1',
1024  [],
1025  ],
1026  'Obsolete cloaked usemod IP address as username' => [
1027  '1.2.3.xxx',
1028  [ ApiBase::PARAM_TYPE => 'user' ],
1029  '1.2.3.xxx',
1030  [],
1031  ],
1032  'Invalid username containing IP address' => [
1033  'This is [not] valid 1.2.3.xxx, ha!',
1034  [ ApiBase::PARAM_TYPE => 'user' ],
1036  null,
1037  [ 'apierror-baduser', 'myParam', 'This is &#91;not&#93; valid 1.2.3.xxx, ha!' ],
1038  'baduser_myParam'
1039  ),
1040  [],
1041  ],
1042  'External username' => [
1043  'M>Foo bar',
1044  [ ApiBase::PARAM_TYPE => 'user' ],
1045  'M>Foo bar',
1046  [],
1047  ],
1048  'Array of usernames' => [
1049  'foo|bar',
1050  [
1051  ApiBase::PARAM_TYPE => 'user',
1052  ApiBase::PARAM_ISMULTI => true,
1053  ],
1054  [ 'Foo', 'Bar' ],
1055  [],
1056  ],
1057  'tag' => [
1058  'tag1',
1059  [ ApiBase::PARAM_TYPE => 'tags' ],
1060  [ 'tag1' ],
1061  [],
1062  ],
1063  'Array of one tag' => [
1064  'tag1',
1065  [
1066  ApiBase::PARAM_TYPE => 'tags',
1067  ApiBase::PARAM_ISMULTI => true,
1068  ],
1069  [ 'tag1' ],
1070  [],
1071  ],
1072  'Array of tags' => [
1073  'tag1|tag2',
1074  [
1075  ApiBase::PARAM_TYPE => 'tags',
1076  ApiBase::PARAM_ISMULTI => true,
1077  ],
1078  [ 'tag1', 'tag2' ],
1079  [],
1080  ],
1081  'Invalid tag' => [
1082  'invalid tag',
1083  [ ApiBase::PARAM_TYPE => 'tags' ],
1084  new ApiUsageException( null,
1085  Status::newFatal( 'tags-apply-not-allowed-one',
1086  'invalid tag', 1 ) ),
1087  [],
1088  ],
1089  'Unrecognized type' => [
1090  'foo',
1091  [ ApiBase::PARAM_TYPE => 'nonexistenttype' ],
1092  new MWException(
1093  'Internal error in ApiBase::getParameterFromSettings: ' .
1094  "Param myParam's type is unknown - nonexistenttype" ),
1095  [],
1096  ],
1097  'Too many bytes' => [
1098  '1',
1099  [
1102  ],
1104  [ 'apierror-maxbytes', 'myParam', 0 ] ),
1105  [],
1106  ],
1107  'Too many chars' => [
1108  '§§',
1109  [
1112  ],
1114  [ 'apierror-maxchars', 'myParam', 1 ] ),
1115  [],
1116  ],
1117  'Omitted required param' => [
1118  null,
1121  [ 'apierror-missingparam', 'myParam' ] ),
1122  [],
1123  ],
1124  'Empty multi-value' => [
1125  '',
1127  [],
1128  [],
1129  ],
1130  'Multi-value \x1f' => [
1131  "\x1f",
1133  [],
1134  [],
1135  ],
1136  'Allowed non-multi-value with "|"' => [
1137  'a|b',
1138  [ ApiBase::PARAM_TYPE => [ 'a|b' ] ],
1139  'a|b',
1140  [],
1141  ],
1142  'Prohibited multi-value' => [
1143  'a|b',
1144  [ ApiBase::PARAM_TYPE => [ 'a', 'b' ] ],
1146  [
1147  'apierror-multival-only-one-of',
1148  'myParam',
1149  Message::listParam( [ '<kbd>a</kbd>', '<kbd>b</kbd>' ] ),
1150  2
1151  ],
1152  'multival_myParam'
1153  ),
1154  [],
1155  ],
1156  ];
1157 
1158  // The following really just test PHP's string-to-int conversion.
1159  $integerTests = [
1160  [ '+1', 1 ],
1161  [ '-1', -1 ],
1162  [ '1.5', 1 ],
1163  [ '-1.5', -1 ],
1164  [ '1abc', 1 ],
1165  [ ' 1', 1 ],
1166  [ "\t1", 1, '\t1' ],
1167  [ "\r1", 1, '\r1' ],
1168  [ "\f1", 0, '\f1', 'badutf-8' ],
1169  [ "\n1", 1, '\n1' ],
1170  [ "\v1", 0, '\v1', 'badutf-8' ],
1171  [ "\e1", 0, '\e1', 'badutf-8' ],
1172  [ "\x001", 0, '\x001', 'badutf-8' ],
1173  ];
1174 
1175  foreach ( $integerTests as $test ) {
1176  $desc = isset( $test[2] ) ? $test[2] : $test[0];
1177  $warnings = isset( $test[3] ) ?
1178  [ [ 'apiwarn-badutf8', 'myParam' ] ] : [];
1179  $returnArray["\"$desc\" as integer"] = [
1180  $test[0],
1181  [ ApiBase::PARAM_TYPE => 'integer' ],
1182  $test[1],
1183  $warnings,
1184  ];
1185  }
1186 
1187  return $returnArray;
1188  }
1189 
1190  public function testErrorArrayToStatus() {
1191  $mock = new MockApi();
1192 
1193  // Sanity check empty array
1194  $expect = Status::newGood();
1195  $this->assertEquals( $expect, $mock->errorArrayToStatus( [] ) );
1196 
1197  // No blocked $user, so no special block handling
1198  $expect = Status::newGood();
1199  $expect->fatal( 'blockedtext' );
1200  $expect->fatal( 'autoblockedtext' );
1201  $expect->fatal( 'systemblockedtext' );
1202  $expect->fatal( 'mainpage' );
1203  $expect->fatal( 'parentheses', 'foobar' );
1204  $this->assertEquals( $expect, $mock->errorArrayToStatus( [
1205  [ 'blockedtext' ],
1206  [ 'autoblockedtext' ],
1207  [ 'systemblockedtext' ],
1208  'mainpage',
1209  [ 'parentheses', 'foobar' ],
1210  ] ) );
1211 
1212  // Has a blocked $user, so special block handling
1213  $user = $this->getMutableTestUser()->getUser();
1214  $block = new \Block( [
1215  'address' => $user->getName(),
1216  'user' => $user->getID(),
1217  'by' => $this->getTestSysop()->getUser()->getId(),
1218  'reason' => __METHOD__,
1219  'expiry' => time() + 100500,
1220  ] );
1221  $block->insert();
1222  $blockinfo = [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ];
1223 
1224  $expect = Status::newGood();
1225  $expect->fatal( ApiMessage::create( 'apierror-blocked', 'blocked', $blockinfo ) );
1226  $expect->fatal( ApiMessage::create( 'apierror-autoblocked', 'autoblocked', $blockinfo ) );
1227  $expect->fatal( ApiMessage::create( 'apierror-systemblocked', 'blocked', $blockinfo ) );
1228  $expect->fatal( 'mainpage' );
1229  $expect->fatal( 'parentheses', 'foobar' );
1230  $this->assertEquals( $expect, $mock->errorArrayToStatus( [
1231  [ 'blockedtext' ],
1232  [ 'autoblockedtext' ],
1233  [ 'systemblockedtext' ],
1234  'mainpage',
1235  [ 'parentheses', 'foobar' ],
1236  ], $user ) );
1237  }
1238 
1239  public function testDieStatus() {
1240  $mock = new MockApi();
1241 
1243  $status->error( 'foo' );
1244  $status->warning( 'bar' );
1245  try {
1246  $mock->dieStatus( $status );
1247  $this->fail( 'Expected exception not thrown' );
1248  } catch ( ApiUsageException $ex ) {
1249  $this->assertTrue( ApiTestCase::apiExceptionHasCode( $ex, 'foo' ), 'Exception has "foo"' );
1250  $this->assertFalse( ApiTestCase::apiExceptionHasCode( $ex, 'bar' ), 'Exception has "bar"' );
1251  }
1252 
1254  $status->warning( 'foo' );
1255  $status->warning( 'bar' );
1256  try {
1257  $mock->dieStatus( $status );
1258  $this->fail( 'Expected exception not thrown' );
1259  } catch ( ApiUsageException $ex ) {
1260  $this->assertTrue( ApiTestCase::apiExceptionHasCode( $ex, 'foo' ), 'Exception has "foo"' );
1261  $this->assertTrue( ApiTestCase::apiExceptionHasCode( $ex, 'bar' ), 'Exception has "bar"' );
1262  }
1263 
1265  $status->setOk( false );
1266  try {
1267  $mock->dieStatus( $status );
1268  $this->fail( 'Expected exception not thrown' );
1269  } catch ( ApiUsageException $ex ) {
1270  $this->assertTrue( ApiTestCase::apiExceptionHasCode( $ex, 'unknownerror-nocode' ),
1271  'Exception has "unknownerror-nocode"' );
1272  }
1273  }
1274 
1275 }
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:247
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:43
ApiBase\PARAM_SUBMODULE_MAP
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is 'submodule', map parameter values to submodule paths.
Definition: ApiBase.php:165
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:273
ApiBaseTest\testGetTitleOrPageIdBadParams
testGetTitleOrPageIdBadParams()
Definition: ApiBaseTest.php:138
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:103
ApiBaseTest\testGetTitleFromTitleOrPageIdInvalidTitle
testGetTitleFromTitleOrPageIdInvalidTitle()
Definition: ApiBaseTest.php:194
ApiBaseTest\testRequireOnlyOneParameterZero
testRequireOnlyOneParameterZero()
ApiUsageException.
Definition: ApiBaseTest.php:60
MWNamespace\getValidNamespaces
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
Definition: MWNamespace.php:290
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:111
MockApi
Definition: MockApi.php:3
ApiBase\PARAM_ALL
const PARAM_ALL
(boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,...
Definition: ApiBase.php:180
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1980
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:87
ApiBaseTest\testGetTitleFromTitleOrPageIdPageId
testGetTitleFromTitleOrPageIdPageId()
Definition: ApiBaseTest.php:201
ApiBaseTest\testRequireAtLeastOneParameterTwo
testRequireAtLeastOneParameterTwo()
Definition: ApiBaseTest.php:130
StatusValue\newFatal
static newFatal( $message)
Factory function for fatal errors.
Definition: StatusValue.php:68
ApiBaseTest\testGetTitleOrPageIdTitle
testGetTitleOrPageIdTitle()
Definition: ApiBaseTest.php:145
ApiBaseTest\testRequireOnlyOneParameterDefault
testRequireOnlyOneParameterDefault()
Definition: ApiBaseTest.php:48
ApiBase\PARAM_ISMULTI_LIMIT1
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
Definition: ApiBase.php:208
ApiBase\PARAM_ALLOW_DUPLICATES
const PARAM_ALLOW_DUPLICATES
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
Definition: ApiBase.php:102
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links: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! 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:1993
ApiBase\PARAM_DEPRECATED_VALUES
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
Definition: ApiBase.php:202
ApiUsageException\newWithMessage
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
Definition: ApiUsageException.php:143
Message\listParam
static listParam(array $list, $type='text')
Definition: Message.php:1105
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:2006
ApiBaseTest\testGetTitleOrPageIdPageId
testGetTitleOrPageIdPageId()
Definition: ApiBaseTest.php:166
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:37
ApiBase\PARAM_SENSITIVE
const PARAM_SENSITIVE
(boolean) Is the parameter sensitive? Note 'password'-type fields are always sensitive regardless of ...
Definition: ApiBase.php:193
ApiBase\PARAM_ISMULTI_LIMIT2
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
Definition: ApiBase.php:215
ApiBaseTest\testRequireMaxOneParameterZero
testRequireMaxOneParameterZero()
Definition: ApiBaseTest.php:88
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:105
ApiBase\PARAM_MIN
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:99
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:30
ApiBaseTest\testRequireAtLeastOneParameterOne
testRequireAtLeastOneParameterOne()
Definition: ApiBaseTest.php:122
MWException
MediaWiki exception.
Definition: MWException.php:26
ApiBaseTest\testRequireOnlyOneParameterTrue
testRequireOnlyOneParameterTrue()
ApiUsageException.
Definition: ApiBaseTest.php:71
ApiBaseTest\testDieStatus
testDieStatus()
Definition: ApiBaseTest.php:1239
$input
if(is_array( $mode)) switch( $mode) $input
Definition: postprocess-phan.php:145
ApiBaseTest
API Database medium.
Definition: ApiBaseTest.php:12
ApiBase\PARAM_MAX
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:90
ApiBaseTest\testRequireMaxOneParameterOne
testRequireMaxOneParameterOne()
Definition: ApiBaseTest.php:96
ApiBaseTest\provideStubMethods
provideStubMethods()
Definition: ApiBaseTest.php:28
ApiBaseTest\testStubMethods
testStubMethods( $expected, $method, $args=[])
This covers a variety of stub methods that return a fixed value.
Definition: ApiBaseTest.php:21
ChangeTags\defineTag
static defineTag( $tag)
Defines a tag in the valid_tag table, without checking that the tag name is valid.
Definition: ChangeTags.php:825
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:219
ApiBase\PARAM_EXTRA_NAMESPACES
const PARAM_EXTRA_NAMESPACES
(int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
Definition: ApiBase.php:186
ApiBaseTest\testRequireOnlyOneParameterMissing
testRequireOnlyOneParameterMissing()
Definition: ApiBaseTest.php:79
$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:2001
ApiBaseTest\testRequireAtLeastOneParameterZero
testRequireAtLeastOneParameterZero()
Definition: ApiBaseTest.php:113
ApiTestCase
Definition: ApiTestCase.php:5
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
MediaWikiTestCase\getMutableTestUser
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
Definition: MediaWikiTestCase.php:165
ApiBaseTest\testGetTitleFromTitleOrPageIdInvalidPageId
testGetTitleFromTitleOrPageIdInvalidPageId()
Definition: ApiBaseTest.php:208
ApiBaseTest\testGetTitleOrPageIdInvalidPageId
testGetTitleOrPageIdInvalidPageId()
Definition: ApiBaseTest.php:173
$status
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). '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:1255
ApiBase\PARAM_RANGE_ENFORCE
const PARAM_RANGE_ENFORCE
(boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
Definition: ApiBase.php:117
$args
if( $line===false) $args
Definition: cdb.php:64
ApiBaseTest\testGetTitleFromTitleOrPageIdBadParams
testGetTitleFromTitleOrPageIdBadParams()
Definition: ApiBaseTest.php:180
ApiBaseTest\provideGetParameterFromSettings
static provideGetParameterFromSettings()
Definition: ApiBaseTest.php:300
ApiTestCase\apiExceptionHasCode
static apiExceptionHasCode(ApiUsageException $ex, $code)
Definition: ApiTestCase.php:225
ApiBaseTest\testErrorArrayToStatus
testErrorArrayToStatus()
Definition: ApiBaseTest.php:1190
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:48
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:22
ApiBaseTest\testRequireMaxOneParameterTwo
testRequireMaxOneParameterTwo()
Definition: ApiBaseTest.php:104
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:51
Message
The Message class provides methods which fulfil two basic services:
Definition: Message.php:159
ApiBaseTest\testGetParameterFromSettings
testGetParameterFromSettings( $input, $paramSettings, $expected, $warnings, $options=[])
provideGetParameterFromSettings
Definition: ApiBaseTest.php:226
ApiBase\PARAM_MAX2
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right,...
Definition: ApiBase.php:96
ApiBase\PARAM_MAX_CHARS
const PARAM_MAX_CHARS
(integer) Maximum length of a string in characters (unicode codepoints).
Definition: ApiBase.php:227
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:56
ApiBaseTest\testGetTitleOrPageIdSpecialTitle
testGetTitleOrPageIdSpecialTitle()
Definition: ApiBaseTest.php:159
ApiBase\PARAM_MAX_BYTES
const PARAM_MAX_BYTES
(integer) Maximum length of a string in bytes (in UTF-8 encoding).
Definition: ApiBase.php:221
ApiBaseTest\testGetTitleOrPageIdInvalidTitle
testGetTitleOrPageIdInvalidTitle()
Definition: ApiBaseTest.php:152
$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:2811
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
ApiBaseTest\testGetTitleFromTitleOrPageIdTitle
testGetTitleFromTitleOrPageIdTitle()
Definition: ApiBaseTest.php:187
ApiQueryUserInfo\getBlockInfo
static getBlockInfo(Block $block)
Get basic info about a given block.
Definition: ApiQueryUserInfo.php:65