3use Wikimedia\TestingAccessWrapper;
19 new FauxRequest( [
'action' =>
'query',
'meta' =>
'siteinfo' ] )
22 $data = $api->getResult()->getResultData();
23 $this->assertInternalType(
'array', $data );
24 $this->assertArrayHasKey(
'query', $data );
30 $data = $api->getResult()->getResultData();
31 $this->assertInternalType(
'array', $data );
48 $req = $this->getMockBuilder( WebRequest::class )
49 ->setMethods( [
'response',
'getRawIP' ] )
53 $req->method(
'getRawIP' )->willReturn(
'127.0.0.1' );
55 $wrapper = TestingAccessWrapper::newFromObject(
$req );
56 $wrapper->data = $requestData;
58 $wrapper->headers = $headers;
77 $this->assertSame(
'fr',
$wgLang->getCode() );
93 ], [
'ORIGIN' =>
'https://www.example.com https://www.com.example' ] );
96 [ [ Psr\Log\LogLevel::WARNING,
'Non-whitelisted CORS request with session cookies' ] ],
107 'meta' =>
'siteinfo',
115 $this->assertNotSame( $origUser, $wgUser );
116 $this->assertSame(
'true', $api->getContext()->getRequest()->response()
117 ->getHeader(
'MediaWiki-Login-Suppressed' ) );
122 $manager = $this->createMock( ApiContinuationManager::class );
123 $api->setContinuationManager( $manager );
124 $this->assertTrue(
true,
'No exception' );
125 return [ $api, $manager ];
132 $this->setExpectedException( UnexpectedValueException::class,
133 'ApiMain::setContinuationManager: tried to set manager from ' .
134 'when a manager is already set from ' );
137 $api->setContinuationManager( $manager );
142 $api->setCacheMode(
'unrecognized' );
145 TestingAccessWrapper::newFromObject( $api )->mCacheMode,
146 'Unrecognized params must be silently ignored'
153 $wrappedApi = TestingAccessWrapper::newFromObject(
new ApiMain() );
154 $wrappedApi->setCacheMode(
'public' );
155 $this->assertSame(
'private', $wrappedApi->mCacheMode );
156 $wrappedApi->setCacheMode(
'anon-public-user-private' );
157 $this->assertSame(
'private', $wrappedApi->mCacheMode );
163 'meta' =>
'siteinfo',
164 'requestid' =>
'123456',
168 $this->assertSame(
'123456', $api->getResult()->getResultData()[
'requestid'] );
174 'meta' =>
'siteinfo',
175 'curtimestamp' =>
'',
179 $timestamp = $api->getResult()->getResultData()[
'curtimestamp'];
180 $this->assertLessThanOrEqual( 1, abs( strtotime( $timestamp ) - time() ) );
186 'meta' =>
'siteinfo',
188 'errorformat' =>
'plaintext',
191 'responselanginfo' =>
'',
195 $data = $api->getResult()->getResultData();
196 $this->assertSame(
'fr', $data[
'uselang'] );
197 $this->assertSame(
'ja', $data[
'errorlang'] );
201 $this->setExpectedException( ApiUsageException::class,
202 'Unrecognized value for parameter "action": unknownaction.' );
210 $this->setExpectedException( ApiUsageException::class,
211 'The "token" parameter must be set.' );
215 'title' =>
'New page',
216 'text' =>
'Some text',
223 $this->setExpectedException( ApiUsageException::class,
'Invalid CSRF token.' );
227 'title' =>
'New page',
228 'text' =>
'Some text',
229 'token' =>
"This isn't a real token!",
236 $this->setExpectedException( MWException::class,
237 "Module 'testmodule' must be updated for the new token handling. " .
238 "See documentation for ApiBase::needsToken for details." );
240 $mock = $this->createMock( ApiBase::class );
241 $mock->method(
'getModuleName' )->willReturn(
'testmodule' );
242 $mock->method(
'needsToken' )->willReturn(
true );
245 $api->getModuleManager()->addModule(
'testmodule',
'action', get_class( $mock ),
246 function ()
use ( $mock ) {
254 $this->setExpectedException( MWException::class,
255 "Module 'testmodule' must require POST to use tokens." );
257 $mock = $this->createMock( ApiBase::class );
258 $mock->method(
'getModuleName' )->willReturn(
'testmodule' );
259 $mock->method(
'needsToken' )->willReturn(
'csrf' );
260 $mock->method(
'mustBePosted' )->willReturn(
false );
263 $api->getModuleManager()->addModule(
'testmodule',
'action', get_class( $mock ),
264 function ()
use ( $mock ) {
276 'meta' =>
'siteinfo',
279 $mock = $this->getMockBuilder( ApiMain::class )
280 ->setConstructorArgs( [
$req ] )
281 ->setMethods( [
'checkMaxLag' ] )
283 $mock->method(
'checkMaxLag' )->willReturn(
false );
287 $this->assertArrayNotHasKey(
'query', $mock->getResult()->getResultData() );
297 $this->
setMwGlobals(
'wgCacheEpoch',
'20030516000000' );
299 $mock = $this->createMock( ApiBase::class );
300 $mock->method(
'getModuleName' )->willReturn(
'testmodule' );
301 $mock->method(
'getConditionalRequestData' )
303 $mock->expects( $this->exactly( 0 ) )->method(
'execute' );
306 'action' =>
'testmodule',
308 $req->setHeader(
'If-Modified-Since',
wfTimestamp( TS_RFC2822, $now - 3600 ) );
309 $req->setRequestURL(
"http://localhost" );
312 $api->getModuleManager()->addModule(
'testmodule',
'action', get_class( $mock ),
313 function ()
use ( $mock ) {
318 $wrapper = TestingAccessWrapper::newFromObject( $api );
319 $wrapper->mInternalMode =
false;
327 $mockLB = $this->getMockBuilder( LoadBalancer::class )
328 ->disableOriginalConstructor()
329 ->setMethods( [
'getMaxLag',
'__destruct' ] )
331 $mockLB->method(
'getMaxLag' )->willReturn( [
'somehost', $lag ] );
332 $this->
setService(
'DBLoadBalancer', $mockLB );
337 $wrapper = TestingAccessWrapper::newFromObject( $api );
339 $mockModule = $this->createMock( ApiBase::class );
340 $mockModule->method(
'shouldCheckMaxLag' )->willReturn(
true );
343 $wrapper->checkMaxLag( $mockModule, [
'maxlag' => 3 ] );
346 $this->assertSame(
'5',
$req->response()->getHeader(
'Retry-After' ) );
347 $this->assertSame( (
string)$lag,
$req->response()->getHeader(
'X-Database-Lag' ) );
356 $this->assertTrue(
true );
360 $this->setExpectedException( ApiUsageException::class,
361 'Waiting for a database server: 4 seconds lagged.' );
369 $this->setExpectedException( ApiUsageException::class,
370 'Waiting for somehost: 4 seconds lagged.' );
379 [
false, [],
'user',
'assertuserfailed' ],
380 [
true, [],
'user',
false ],
381 [
true, [],
'bot',
'assertbotfailed' ],
382 [
true, [
'bot' ],
'user',
false ],
383 [
true, [
'bot' ],
'bot',
false ],
396 public function testAssert( $registered, $rights, $assert, $error ) {
403 $user->mRights = $rights;
408 ],
null,
null,
$user );
409 $this->assertFalse( $error );
411 $this->assertTrue( self::apiExceptionHasCode(
$e, $error ),
412 "Error '{$e->getMessage()}' matched expected '$error'" );
423 'assertuser' =>
$user->getName(),
424 ],
null,
null,
$user );
429 'assertuser' =>
$user->getName() .
'X',
430 ],
null,
null,
$user );
431 $this->fail(
'Expected exception not thrown' );
433 $this->assertTrue( self::apiExceptionHasCode(
$e,
'assertnameduserfailed' ) );
446 ],
null,
null,
new User );
447 $this->fail(
'Expected exception not thrown' );
449 $this->assertTrue( self::apiExceptionHasCode(
$e,
'too-many-titles' ),
'sanity check' );
458 ],
null,
null,
new User );
459 $this->fail(
'Expected exception not thrown' );
461 $this->assertTrue( self::apiExceptionHasCode(
$e,
'assertuserfailed' ),
462 "Error '{$e->getMessage()}' matched expected 'assertuserfailed'" );
471 new FauxRequest( [
'action' =>
'query',
'meta' =>
'siteinfo' ] )
473 $modules = $api->getModuleManager()->getNamesWithClasses();
477 class_exists( $class ),
478 'Class ' . $class .
' for api module ' .
$name .
' does not exist (with exact case)'
498 [
'action' =>
'query',
'meta' =>
'siteinfo' ],
502 $request->response()->statusHeader( 200 );
506 $priv = TestingAccessWrapper::newFromObject( $api );
507 $priv->mInternalMode =
false;
514 $this->
setMwGlobals(
'wgCacheEpoch',
'20030516000000' );
516 $module = $this->getMockBuilder( ApiBase::class )
517 ->setConstructorArgs( [ $api,
'mock' ] )
518 ->setMethods( [
'getConditionalRequestData' ] )
519 ->getMockForAbstractClass();
520 $module->expects( $this->any() )
521 ->method(
'getConditionalRequestData' )
522 ->will( $this->returnCallback(
function ( $condition )
use ( $conditions ) {
523 return $conditions[$condition] ??
null;
526 $ret = $priv->checkConditionalRequestHeaders( $module );
538 'If-None-Match' => [ [
'If-None-Match' =>
'"foo", "bar"' ], [], 200 ],
539 'If-Modified-Since' =>
540 [ [
'If-Modified-Since' =>
'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
543 'No headers' => [ [], [
'etag' =>
'""',
'last-modified' =>
'20150815000000', ], 200 ],
546 'If-None-Match with matching etag' =>
547 [ [
'If-None-Match' =>
'"foo", "bar"' ], [
'etag' =>
'"bar"' ], 304 ],
548 'If-None-Match with non-matching etag' =>
549 [ [
'If-None-Match' =>
'"foo", "bar"' ], [
'etag' =>
'"baz"' ], 200 ],
550 'Strong If-None-Match with weak matching etag' =>
551 [ [
'If-None-Match' =>
'"foo"' ], [
'etag' =>
'W/"foo"' ], 304 ],
552 'Weak If-None-Match with strong matching etag' =>
553 [ [
'If-None-Match' =>
'W/"foo"' ], [
'etag' =>
'"foo"' ], 304 ],
554 'Weak If-None-Match with weak matching etag' =>
555 [ [
'If-None-Match' =>
'W/"foo"' ], [
'etag' =>
'W/"foo"' ], 304 ],
558 'If-None-Match: *' => [ [
'If-None-Match' =>
'*' ], [], 304 ],
561 'If-Modified-Since, modified one second earlier' =>
562 [ [
'If-Modified-Since' =>
wfTimestamp( TS_RFC2822, $now ) ],
563 [
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
564 'If-Modified-Since, modified now' =>
565 [ [
'If-Modified-Since' =>
wfTimestamp( TS_RFC2822, $now ) ],
566 [
'last-modified' =>
wfTimestamp( TS_MW, $now ) ], 304 ],
567 'If-Modified-Since, modified one second later' =>
568 [ [
'If-Modified-Since' =>
wfTimestamp( TS_RFC2822, $now ) ],
569 [
'last-modified' =>
wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
572 'Non-matching If-None-Match and matching If-Modified-Since' =>
573 [ [
'If-None-Match' =>
'""',
574 'If-Modified-Since' =>
wfTimestamp( TS_RFC2822, $now ) ],
575 [
'etag' =>
'"x"',
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
576 'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
579 'If-None-Match' =>
'""',
580 'If-Modified-Since' =>
wfTimestamp( TS_RFC2822, $now )
582 [
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ],
587 'Matching If-None-Match with POST' =>
588 [ [
'If-None-Match' =>
'"foo", "bar"' ], [
'etag' =>
'"bar"' ], 200,
589 [
'post' =>
true ] ],
590 'Matching If-Modified-Since with POST' =>
591 [ [
'If-Modified-Since' =>
wfTimestamp( TS_RFC2822, $now ) ],
592 [
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ], 200,
593 [
'post' =>
true ] ],
596 'If-Modified-Since with alternate date format 1' =>
597 [ [
'If-Modified-Since' => gmdate(
'l, d-M-y H:i:s', $now ) .
' GMT' ],
598 [
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
599 'If-Modified-Since with alternate date format 2' =>
600 [ [
'If-Modified-Since' => gmdate(
'D M j H:i:s Y', $now ) ],
601 [
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
604 'If-Modified-Since with length' =>
605 [ [
'If-Modified-Since' =>
wfTimestamp( TS_RFC2822, $now ) .
'; length=123' ],
606 [
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
609 'If-Modified-Since with invalid date format' =>
610 [ [
'If-Modified-Since' => gmdate(
'Y-m-d H:i:s', $now ) .
' GMT' ],
611 [
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
612 'If-Modified-Since with entirely unparseable date' =>
613 [ [
'If-Modified-Since' =>
'a potato' ],
614 [
'last-modified' =>
wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
618 'If-Modified-Since with CDN post-expiry' =>
621 200, [
'cdn' =>
true ] ],
622 'If-Modified-Since with CDN pre-expiry' =>
625 304, [
'cdn' =>
true ] ],
638 $conditions, $headers, $isError =
false, $post =
false
644 $priv = TestingAccessWrapper::newFromObject( $api );
645 $priv->mInternalMode =
false;
647 $module = $this->getMockBuilder( ApiBase::class )
648 ->setConstructorArgs( [ $api,
'mock' ] )
649 ->setMethods( [
'getConditionalRequestData' ] )
650 ->getMockForAbstractClass();
651 $module->expects( $this->any() )
652 ->method(
'getConditionalRequestData' )
653 ->will( $this->returnCallback(
function ( $condition )
use ( $conditions ) {
654 return $conditions[$condition] ??
null;
656 $priv->mModule = $module;
658 $priv->sendCacheHeaders( $isError );
660 foreach ( [
'Last-Modified',
'ETag' ]
as $header ) {
676 [
'etag' =>
'"foo"' ],
677 [
'ETag' =>
'"foo"' ]
680 [
'last-modified' =>
'20150818000102' ],
681 [
'Last-Modified' =>
'Tue, 18 Aug 2015 00:01:02 GMT' ]
684 [
'etag' =>
'"foo"',
'last-modified' =>
'20150818000102' ],
685 [
'ETag' =>
'"foo"',
'Last-Modified' =>
'Tue, 18 Aug 2015 00:01:02 GMT' ]
688 [
'etag' =>
'"foo"',
'last-modified' =>
'20150818000102' ],
693 [
'etag' =>
'"foo"',
'last-modified' =>
'20150818000102' ],
702 $this->setExpectedException( ApiUsageException::class,
703 'You need read permission to use this module.' );
707 $main =
new ApiMain(
new FauxRequest( [
'action' =>
'query',
'meta' =>
'siteinfo' ] ) );
712 $this->setExpectedException( ApiUsageException::class,
713 'Editing of this wiki through the API is disabled. Make sure the ' .
714 '"$wgEnableWriteAPI=true;" statement is included in the wiki\'s ' .
715 '"LocalSettings.php" file.' );
718 'title' =>
'Some page',
719 'text' =>
'Some text',
726 $this->setExpectedException( ApiUsageException::class,
727 "You're not allowed to edit this wiki through the API." );
732 'title' =>
'Some page',
733 'text' =>
'Some text',
740 $this->setExpectedException( ApiUsageException::class,
741 'The "Promise-Non-Write-API-Action" HTTP header cannot be sent ' .
742 'to write-mode API modules.' );
746 'title' =>
'Some page',
747 'text' =>
'Some text',
750 $req->setHeaders( [
'Promise-Non-Write-API-Action' =>
'1' ] );
756 $this->setExpectedException( ApiUsageException::class,
'Main Page' );
758 $this->
setTemporaryHook(
'ApiCheckCanExecute',
function ( $unused1, $unused2, &$message ) {
759 $message =
'mainpage';
765 'title' =>
'Some page',
766 'text' =>
'Some text',
775 'meta' =>
'siteinfo',
776 'siprop' => [
'general',
'namespaces' ],
778 $this->assertSame(
'myDefault', $main->getVal(
'siprop',
'myDefault' ) );
780 $this->assertSame(
'Parameter "siprop" uses unsupported PHP array syntax.',
781 $main->getResult()->getResultData()[
'warnings'][
'main'][
'warnings'] );
787 'meta' =>
'siteinfo',
788 'unusedparam' =>
'unusedval',
789 'anotherunusedparam' =>
'anotherval',
792 $this->assertSame(
'Unrecognized parameters: unusedparam, anotherunusedparam.',
793 $main->getResult()->getResultData()[
'warnings'][
'main'][
'warnings'] );
798 $main =
new ApiMain(
new FauxRequest( [
'action' =>
'query',
'meta' =>
'siteinfo' ] ) );
799 $this->assertFalse( $main->lacksSameOriginSecurity(),
'Basic test, should have security' );
803 new FauxRequest( [
'action' =>
'query',
'format' =>
'xml',
'callback' =>
'foo' ] )
805 $this->assertTrue( $main->lacksSameOriginSecurity(),
'JSONp, should lack security' );
809 $request->setHeader(
'TrEaT-As-UnTrUsTeD',
'' );
811 $this->assertTrue( $main->lacksSameOriginSecurity(),
'Header supplied, should lack security' );
815 'RequestHasSameOriginSecurity' => [
function () {
819 $main =
new ApiMain(
new FauxRequest( [
'action' =>
'query',
'meta' =>
'siteinfo' ] ) );
820 $this->assertTrue( $main->lacksSameOriginSecurity(),
'Hook, should lack security' );
841 $formatter = $main->getErrorFormatter();
842 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
844 $this->assertSame( $expect[
'uselang'], $main->getLanguage()->getCode() );
845 $this->assertInstanceOf( $expect[
'class'], $formatter );
846 $this->assertSame( $expect[
'lang'], $formatter->getLanguage()->getCode() );
847 $this->assertSame( $expect[
'format'], $wrappedFormatter->format );
848 $this->assertSame( $expect[
'usedb'], $wrappedFormatter->useDB );
853 'Default (BC)' => [ [], [
855 'class' => ApiErrorFormatter_BackCompat::class,
860 'BC ignores fields' => [ [
'errorlang' =>
'de',
'errorsuselocal' => 1 ], [
862 'class' => ApiErrorFormatter_BackCompat::class,
867 'Explicit BC' => [ [
'errorformat' =>
'bc' ], [
869 'class' => ApiErrorFormatter_BackCompat::class,
874 'Basic' => [ [
'errorformat' =>
'wikitext' ], [
876 'class' => ApiErrorFormatter::class,
878 'format' =>
'wikitext',
881 'Follows uselang' => [ [
'uselang' =>
'fr',
'errorformat' =>
'plaintext' ], [
883 'class' => ApiErrorFormatter::class,
885 'format' =>
'plaintext',
888 'Explicitly follows uselang' => [
889 [
'uselang' =>
'fr',
'errorlang' =>
'uselang',
'errorformat' =>
'plaintext' ],
892 'class' => ApiErrorFormatter::class,
894 'format' =>
'plaintext',
898 'uselang=content' => [
899 [
'uselang' =>
'content',
'errorformat' =>
'plaintext' ],
902 'class' => ApiErrorFormatter::class,
904 'format' =>
'plaintext',
908 'errorlang=content' => [
909 [
'errorlang' =>
'content',
'errorformat' =>
'plaintext' ],
912 'class' => ApiErrorFormatter::class,
914 'format' =>
'plaintext',
918 'Explicit parameters' => [
919 [
'errorlang' =>
'de',
'errorformat' =>
'html',
'errorsuselocal' => 1 ],
922 'class' => ApiErrorFormatter::class,
928 'Explicit parameters override uselang' => [
929 [
'errorlang' =>
'de',
'uselang' =>
'fr',
'errorformat' =>
'raw' ],
932 'class' => ApiErrorFormatter::class,
938 'Bogus language doesn\'t explode' => [
939 [
'errorlang' =>
'<bogus1>',
'uselang' =>
'<bogus2>',
'errorformat' =>
'none' ],
942 'class' => ApiErrorFormatter::class,
948 'Bogus format doesn\'t explode' => [ [
'errorformat' =>
'bogus' ], [
950 'class' => ApiErrorFormatter_BackCompat::class,
970 'ShowHostnames' =>
true,
'ShowExceptionDetails' =>
true,
976 $main->addWarning(
new RawMessage(
'existing warning' ),
'existing-warning' );
977 $main->addError(
new RawMessage(
'existing error' ),
'existing-error' );
979 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
980 $this->assertSame( $expectReturn,
$ret );
986 $main->getResult()->getResultData( [], [
'Strip' =>
'all' ] )
992 $reqId = WebRequest::getRequestId();
995 $ex =
new InvalidArgumentException(
'Random exception' );
996 $trace =
wfMessage(
'api-exception-trace',
1000 MWExceptionHandler::getRedactedTraceAsString( $ex )
1001 )->inLanguage(
'en' )->useDatabase(
false )->text();
1003 $dbex =
new DBQueryError(
1004 $this->createMock( \
Wikimedia\Rdbms\IDatabase::class ),
1005 'error', 1234,
'SELECT 1', __METHOD__ );
1006 $dbtrace =
wfMessage(
'api-exception-trace',
1010 MWExceptionHandler::getRedactedTraceAsString( $dbex )
1011 )->inLanguage(
'en' )->useDatabase(
false )->text();
1014 StatusValue::newFatal(
new ApiRawMessage(
'An error',
'sv-error1' ) ) );
1015 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath =
'foo+bar';
1016 $apiEx1->getStatusValue()->warning(
new ApiRawMessage(
'A warning',
'sv-warn1' ) );
1017 $apiEx1->getStatusValue()->warning(
new ApiRawMessage(
'Another warning',
'sv-warn2' ) );
1018 $apiEx1->getStatusValue()->fatal(
new ApiRawMessage(
'Another error',
'sv-error2' ) );
1023 [
'existing-error',
'internal_api_error_InvalidArgumentException' ],
1026 [
'code' =>
'existing-warning',
'text' =>
'existing warning',
'module' =>
'main' ],
1029 [
'code' =>
'existing-error',
'text' =>
'existing error',
'module' =>
'main' ],
1031 'code' =>
'internal_api_error_InvalidArgumentException',
1032 'text' =>
"[$reqId] Exception caught: Random exception",
1041 [
'existing-error',
'internal_api_error_DBQueryError' ],
1044 [
'code' =>
'existing-warning',
'text' =>
'existing warning',
'module' =>
'main' ],
1047 [
'code' =>
'existing-error',
'text' =>
'existing error',
'module' =>
'main' ],
1049 'code' =>
'internal_api_error_DBQueryError',
1050 'text' =>
"[$reqId] Exception caught: A database query error has occurred. " .
1051 "This may indicate a bug in the software.",
1054 'trace' => $dbtrace,
1060 [
'existing-error',
'sv-error1',
'sv-error2' ],
1063 [
'code' =>
'existing-warning',
'text' =>
'existing warning',
'module' =>
'main' ],
1064 [
'code' =>
'sv-warn1',
'text' =>
'A warning',
'module' =>
'foo+bar' ],
1065 [
'code' =>
'sv-warn2',
'text' =>
'Another warning',
'module' =>
'foo+bar' ],
1068 [
'code' =>
'existing-error',
'text' =>
'existing error',
'module' =>
'main' ],
1069 [
'code' =>
'sv-error1',
'text' =>
'An error',
'module' =>
'foo+bar' ],
1070 [
'code' =>
'sv-error2',
'text' =>
'Another error',
'module' =>
'foo+bar' ],
1072 'docref' =>
"See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1073 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
1074 "for notice of API deprecations and breaking changes.",
1083 'action' =>
'query',
'meta' =>
'siteinfo',
'format' =>
'json',
'formatversion' =>
'bogus',
1088 $txt = ob_get_clean();
1091 $data = FormatJson::decode( $txt,
true );
1092 $this->assertInternalType(
'array', $data );
1093 $this->assertArrayHasKey(
'error', $data );
1094 $this->assertArrayHasKey(
'code', $data[
'error'] );
1095 $this->assertSame(
'unknown_formatversion', $data[
'error'][
'code'] );
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgSquidMaxage
Cache TTL for the CDN sent as s-maxage (without ESI) or Surrogate-Control (with ESI).
wfHostname()
Fetch server name for use in error reporting etc.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const LIMIT_SML1
Slow query, standard limit.
testLacksSameOriginSecurity()
testCheckConditionalRequestHeadersFailed()
testGetValUnsupportedArray()
testSetupModuleNeedsTokenNeedntBePosted()
testClassNamesInModuleManager()
Test if all classes in the main module manager exists.
testApi()
Test that the API will accept a FauxRequest and execute.
testConditionalRequestHeadersOutput( $conditions, $headers, $isError=false, $post=false)
Test conditional headers output provideConditionalRequestHeadersOutput.
getNonInternalApiMain(array $requestData, array $headers=[])
ApiMain behaves differently if passed a FauxRequest (mInternalMode set to true) or a proper WebReques...
testCheckMaxLagExceeded()
static provideApiErrorFormatterCreation()
testCheckExecutePermissionHookAbort()
testCheckMaxLagExceededWithHostNames()
testCheckExecutePermissionPromiseNonWrite()
static provideConditionalRequestHeadersOutput()
testApiErrorFormatterCreation(array $request, array $expect)
Test proper creation of the ApiErrorFormatter.
testSetCacheModeUnrecognized()
testAddRequestedFieldsResponseLangInfo()
testSetContinuationManager()
testAddRequestedFieldsRequestId()
testNonWhitelistedCorsWithCookies()
testCheckExecutePermissionsReadProhibited()
testCheckExecutePermissionWriteDisabled()
testAssert( $registered, $rights, $assert, $error)
Tests the assert={user|bot} functionality.
testSetupModuleNeedsTokenTrue()
testCheckExecutePermissionWriteApiProhibited()
testPrinterParameterValidationError()
testSetCacheModePrivateWiki()
testAddRequestedFieldsCurTimestamp()
testSetContinuationManagerTwice( $args)
@depends testSetContinuationManager
testSetupModuleInvalidTokenProvided()
testCheckConditionalRequestHeaders( $headers, $conditions, $status, $options=[])
Test HTTP precondition headers.
testAssertUser()
Tests the assertuser= functionality.
testSetupModuleNoTokenProvided()
testAssertBeforeModule()
Test that 'assert' is processed before module errors.
static provideCheckConditionalRequestHeaders()
testExceptionErrors( $error, $expectReturn, $expectResult)
provideExceptionErrors
This is the main API class, used for both external and internal processing.
Extension of RawMessage implementing IApiMessage.
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Exception used to abort API execution with an error.
WebRequest clone which takes values from a provided array.
A Config instance which stores all settings as a member variable.
Provides a fallback sequence for Config objects.
Variant of the Message class.
Group all the pieces relevant to the context of a request into one instance.
A logger that may be configured to either buffer logs or to print them to the output where PHPUnit wi...
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
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
this hook is for auditing only $req
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
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
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
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
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
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
Allows to change the fields on the form that will be generated $name
this hook is for auditing only $response
processing should stop and the error should be shown to the user * false
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
returning false will NOT prevent logging $e
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
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))