565e829f7976444407fa8c662ddf2bd0eea7aa6a
[lhc/web/wiklou.git] / includes / api / ApiMain.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 4, 2006
6 *
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 * @defgroup API API
26 */
27
28 use MediaWiki\Logger\LoggerFactory;
29
30 /**
31 * This is the main API class, used for both external and internal processing.
32 * When executed, it will create the requested formatter object,
33 * instantiate and execute an object associated with the needed action,
34 * and use formatter to print results.
35 * In case of an exception, an error message will be printed using the same formatter.
36 *
37 * To use API from another application, run it using FauxRequest object, in which
38 * case any internal exceptions will not be handled but passed up to the caller.
39 * After successful execution, use getResult() for the resulting data.
40 *
41 * @ingroup API
42 */
43 class ApiMain extends ApiBase {
44 /**
45 * When no format parameter is given, this format will be used
46 */
47 const API_DEFAULT_FORMAT = 'jsonfm';
48
49 /**
50 * List of available modules: action name => module class
51 */
52 private static $Modules = [
53 'login' => 'ApiLogin',
54 'clientlogin' => 'ApiClientLogin',
55 'logout' => 'ApiLogout',
56 'createaccount' => 'ApiAMCreateAccount',
57 'linkaccount' => 'ApiLinkAccount',
58 'unlinkaccount' => 'ApiRemoveAuthenticationData',
59 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
60 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
61 'resetpassword' => 'ApiResetPassword',
62 'query' => 'ApiQuery',
63 'expandtemplates' => 'ApiExpandTemplates',
64 'parse' => 'ApiParse',
65 'stashedit' => 'ApiStashEdit',
66 'opensearch' => 'ApiOpenSearch',
67 'feedcontributions' => 'ApiFeedContributions',
68 'feedrecentchanges' => 'ApiFeedRecentChanges',
69 'feedwatchlist' => 'ApiFeedWatchlist',
70 'help' => 'ApiHelp',
71 'paraminfo' => 'ApiParamInfo',
72 'rsd' => 'ApiRsd',
73 'compare' => 'ApiComparePages',
74 'tokens' => 'ApiTokens',
75 'checktoken' => 'ApiCheckToken',
76 'cspreport' => 'ApiCSPReport',
77
78 // Write modules
79 'purge' => 'ApiPurge',
80 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
81 'rollback' => 'ApiRollback',
82 'delete' => 'ApiDelete',
83 'undelete' => 'ApiUndelete',
84 'protect' => 'ApiProtect',
85 'block' => 'ApiBlock',
86 'unblock' => 'ApiUnblock',
87 'move' => 'ApiMove',
88 'edit' => 'ApiEditPage',
89 'upload' => 'ApiUpload',
90 'filerevert' => 'ApiFileRevert',
91 'emailuser' => 'ApiEmailUser',
92 'watch' => 'ApiWatch',
93 'patrol' => 'ApiPatrol',
94 'import' => 'ApiImport',
95 'clearhasmsg' => 'ApiClearHasMsg',
96 'userrights' => 'ApiUserrights',
97 'options' => 'ApiOptions',
98 'imagerotate' => 'ApiImageRotate',
99 'revisiondelete' => 'ApiRevisionDelete',
100 'managetags' => 'ApiManageTags',
101 'tag' => 'ApiTag',
102 'mergehistory' => 'ApiMergeHistory',
103 ];
104
105 /**
106 * List of available formats: format name => format class
107 */
108 private static $Formats = [
109 'json' => 'ApiFormatJson',
110 'jsonfm' => 'ApiFormatJson',
111 'php' => 'ApiFormatPhp',
112 'phpfm' => 'ApiFormatPhp',
113 'xml' => 'ApiFormatXml',
114 'xmlfm' => 'ApiFormatXml',
115 'rawfm' => 'ApiFormatJson',
116 'none' => 'ApiFormatNone',
117 ];
118
119 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
120 /**
121 * List of user roles that are specifically relevant to the API.
122 * [ 'right' => [ 'msg' => 'Some message with a $1',
123 * 'params' => [ $someVarToSubst ] ],
124 * ];
125 */
126 private static $mRights = [
127 'writeapi' => [
128 'msg' => 'right-writeapi',
129 'params' => []
130 ],
131 'apihighlimits' => [
132 'msg' => 'api-help-right-apihighlimits',
133 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ]
134 ]
135 ];
136 // @codingStandardsIgnoreEnd
137
138 /**
139 * @var ApiFormatBase
140 */
141 private $mPrinter;
142
143 private $mModuleMgr, $mResult, $mErrorFormatter;
144 /** @var ApiContinuationManager|null */
145 private $mContinuationManager;
146 private $mAction;
147 private $mEnableWrite;
148 private $mInternalMode, $mSquidMaxage;
149 /** @var ApiBase */
150 private $mModule;
151
152 private $mCacheMode = 'private';
153 private $mCacheControl = [];
154 private $mParamsUsed = [];
155
156 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
157 private $lacksSameOriginSecurity = null;
158
159 /**
160 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
161 *
162 * @param IContextSource|WebRequest $context If this is an instance of
163 * FauxRequest, errors are thrown and no printing occurs
164 * @param bool $enableWrite Should be set to true if the api may modify data
165 */
166 public function __construct( $context = null, $enableWrite = false ) {
167 if ( $context === null ) {
168 $context = RequestContext::getMain();
169 } elseif ( $context instanceof WebRequest ) {
170 // BC for pre-1.19
171 $request = $context;
172 $context = RequestContext::getMain();
173 }
174 // We set a derivative context so we can change stuff later
175 $this->setContext( new DerivativeContext( $context ) );
176
177 if ( isset( $request ) ) {
178 $this->getContext()->setRequest( $request );
179 } else {
180 $request = $this->getRequest();
181 }
182
183 $this->mInternalMode = ( $request instanceof FauxRequest );
184
185 // Special handling for the main module: $parent === $this
186 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
187
188 $config = $this->getConfig();
189
190 if ( !$this->mInternalMode ) {
191 // Log if a request with a non-whitelisted Origin header is seen
192 // with session cookies.
193 $originHeader = $request->getHeader( 'Origin' );
194 if ( $originHeader === false ) {
195 $origins = [];
196 } else {
197 $originHeader = trim( $originHeader );
198 $origins = preg_split( '/\s+/', $originHeader );
199 }
200 $sessionCookies = array_intersect(
201 array_keys( $_COOKIE ),
202 MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
203 );
204 if ( $origins && $sessionCookies && (
205 count( $origins ) !== 1 || !self::matchOrigin(
206 $origins[0],
207 $config->get( 'CrossSiteAJAXdomains' ),
208 $config->get( 'CrossSiteAJAXdomainExceptions' )
209 )
210 ) ) {
211 LoggerFactory::getInstance( 'cors' )->warning(
212 'Non-whitelisted CORS request with session cookies', [
213 'origin' => $originHeader,
214 'cookies' => $sessionCookies,
215 'ip' => $request->getIP(),
216 'userAgent' => $this->getUserAgent(),
217 'wiki' => wfWikiID(),
218 ]
219 );
220 }
221
222 // If we're in a mode that breaks the same-origin policy, strip
223 // user credentials for security.
224 if ( $this->lacksSameOriginSecurity() ) {
225 global $wgUser;
226 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
227 $wgUser = new User();
228 $this->getContext()->setUser( $wgUser );
229 }
230 }
231
232 $uselang = $this->getParameter( 'uselang' );
233 if ( $uselang === 'user' ) {
234 // Assume the parent context is going to return the user language
235 // for uselang=user (see T85635).
236 } else {
237 if ( $uselang === 'content' ) {
238 global $wgContLang;
239 $uselang = $wgContLang->getCode();
240 }
241 $code = RequestContext::sanitizeLangCode( $uselang );
242 $this->getContext()->setLanguage( $code );
243 if ( !$this->mInternalMode ) {
244 global $wgLang;
245 $wgLang = $this->getContext()->getLanguage();
246 RequestContext::getMain()->setLanguage( $wgLang );
247 }
248 }
249
250 $this->mModuleMgr = new ApiModuleManager( $this );
251 $this->mModuleMgr->addModules( self::$Modules, 'action' );
252 $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
253 $this->mModuleMgr->addModules( self::$Formats, 'format' );
254 $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
255
256 Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
257
258 $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
259 $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
260 $this->mResult->setErrorFormatter( $this->mErrorFormatter );
261 $this->mResult->setMainForContinuation( $this );
262 $this->mContinuationManager = null;
263 $this->mEnableWrite = $enableWrite;
264
265 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
266 $this->mCommit = false;
267 }
268
269 /**
270 * Return true if the API was started by other PHP code using FauxRequest
271 * @return bool
272 */
273 public function isInternalMode() {
274 return $this->mInternalMode;
275 }
276
277 /**
278 * Get the ApiResult object associated with current request
279 *
280 * @return ApiResult
281 */
282 public function getResult() {
283 return $this->mResult;
284 }
285
286 /**
287 * Get the security flag for the current request
288 * @return bool
289 */
290 public function lacksSameOriginSecurity() {
291 if ( $this->lacksSameOriginSecurity !== null ) {
292 return $this->lacksSameOriginSecurity;
293 }
294
295 $request = $this->getRequest();
296
297 // JSONP mode
298 if ( $request->getVal( 'callback' ) !== null ) {
299 $this->lacksSameOriginSecurity = true;
300 return true;
301 }
302
303 // Anonymous CORS
304 if ( $request->getVal( 'origin' ) === '*' ) {
305 $this->lacksSameOriginSecurity = true;
306 return true;
307 }
308
309 // Header to be used from XMLHTTPRequest when the request might
310 // otherwise be used for XSS.
311 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
312 $this->lacksSameOriginSecurity = true;
313 return true;
314 }
315
316 // Allow extensions to override.
317 $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
318 return $this->lacksSameOriginSecurity;
319 }
320
321 /**
322 * Get the ApiErrorFormatter object associated with current request
323 * @return ApiErrorFormatter
324 */
325 public function getErrorFormatter() {
326 return $this->mErrorFormatter;
327 }
328
329 /**
330 * Get the continuation manager
331 * @return ApiContinuationManager|null
332 */
333 public function getContinuationManager() {
334 return $this->mContinuationManager;
335 }
336
337 /**
338 * Set the continuation manager
339 * @param ApiContinuationManager|null
340 */
341 public function setContinuationManager( $manager ) {
342 if ( $manager !== null ) {
343 if ( !$manager instanceof ApiContinuationManager ) {
344 throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
345 is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
346 );
347 }
348 if ( $this->mContinuationManager !== null ) {
349 throw new UnexpectedValueException(
350 __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
351 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
352 );
353 }
354 }
355 $this->mContinuationManager = $manager;
356 }
357
358 /**
359 * Get the API module object. Only works after executeAction()
360 *
361 * @return ApiBase
362 */
363 public function getModule() {
364 return $this->mModule;
365 }
366
367 /**
368 * Get the result formatter object. Only works after setupExecuteAction()
369 *
370 * @return ApiFormatBase
371 */
372 public function getPrinter() {
373 return $this->mPrinter;
374 }
375
376 /**
377 * Set how long the response should be cached.
378 *
379 * @param int $maxage
380 */
381 public function setCacheMaxAge( $maxage ) {
382 $this->setCacheControl( [
383 'max-age' => $maxage,
384 's-maxage' => $maxage
385 ] );
386 }
387
388 /**
389 * Set the type of caching headers which will be sent.
390 *
391 * @param string $mode One of:
392 * - 'public': Cache this object in public caches, if the maxage or smaxage
393 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
394 * not provided by any of these means, the object will be private.
395 * - 'private': Cache this object only in private client-side caches.
396 * - 'anon-public-user-private': Make this object cacheable for logged-out
397 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
398 * set consistently for a given URL, it cannot be set differently depending on
399 * things like the contents of the database, or whether the user is logged in.
400 *
401 * If the wiki does not allow anonymous users to read it, the mode set here
402 * will be ignored, and private caching headers will always be sent. In other words,
403 * the "public" mode is equivalent to saying that the data sent is as public as a page
404 * view.
405 *
406 * For user-dependent data, the private mode should generally be used. The
407 * anon-public-user-private mode should only be used where there is a particularly
408 * good performance reason for caching the anonymous response, but where the
409 * response to logged-in users may differ, or may contain private data.
410 *
411 * If this function is never called, then the default will be the private mode.
412 */
413 public function setCacheMode( $mode ) {
414 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
415 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
416
417 // Ignore for forwards-compatibility
418 return;
419 }
420
421 if ( !User::isEveryoneAllowed( 'read' ) ) {
422 // Private wiki, only private headers
423 if ( $mode !== 'private' ) {
424 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
425
426 return;
427 }
428 }
429
430 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
431 // User language is used for i18n, so we don't want to publicly
432 // cache. Anons are ok, because if they have non-default language
433 // then there's an appropriate Vary header set by whatever set
434 // their non-default language.
435 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
436 "'anon-public-user-private' due to uselang=user\n" );
437 $mode = 'anon-public-user-private';
438 }
439
440 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
441 $this->mCacheMode = $mode;
442 }
443
444 /**
445 * Set directives (key/value pairs) for the Cache-Control header.
446 * Boolean values will be formatted as such, by including or omitting
447 * without an equals sign.
448 *
449 * Cache control values set here will only be used if the cache mode is not
450 * private, see setCacheMode().
451 *
452 * @param array $directives
453 */
454 public function setCacheControl( $directives ) {
455 $this->mCacheControl = $directives + $this->mCacheControl;
456 }
457
458 /**
459 * Create an instance of an output formatter by its name
460 *
461 * @param string $format
462 *
463 * @return ApiFormatBase
464 */
465 public function createPrinterByName( $format ) {
466 $printer = $this->mModuleMgr->getModule( $format, 'format' );
467 if ( $printer === null ) {
468 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
469 }
470
471 return $printer;
472 }
473
474 /**
475 * Execute api request. Any errors will be handled if the API was called by the remote client.
476 */
477 public function execute() {
478 if ( $this->mInternalMode ) {
479 $this->executeAction();
480 } else {
481 $this->executeActionWithErrorHandling();
482 }
483 }
484
485 /**
486 * Execute an action, and in case of an error, erase whatever partial results
487 * have been accumulated, and replace it with an error message and a help screen.
488 */
489 protected function executeActionWithErrorHandling() {
490 // Verify the CORS header before executing the action
491 if ( !$this->handleCORS() ) {
492 // handleCORS() has sent a 403, abort
493 return;
494 }
495
496 // Exit here if the request method was OPTIONS
497 // (assume there will be a followup GET or POST)
498 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
499 return;
500 }
501
502 // In case an error occurs during data output,
503 // clear the output buffer and print just the error information
504 $obLevel = ob_get_level();
505 ob_start();
506
507 $t = microtime( true );
508 $isError = false;
509 try {
510 $this->executeAction();
511 $runTime = microtime( true ) - $t;
512 $this->logRequest( $runTime );
513 if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
514 $this->getStats()->timing(
515 'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
516 );
517 }
518 } catch ( Exception $e ) {
519 $this->handleException( $e );
520 $this->logRequest( microtime( true ) - $t, $e );
521 $isError = true;
522 }
523
524 // Commit DBs and send any related cookies and headers
525 MediaWiki::preOutputCommit( $this->getContext() );
526
527 // Send cache headers after any code which might generate an error, to
528 // avoid sending public cache headers for errors.
529 $this->sendCacheHeaders( $isError );
530
531 // Executing the action might have already messed with the output
532 // buffers.
533 while ( ob_get_level() > $obLevel ) {
534 ob_end_flush();
535 }
536 }
537
538 /**
539 * Handle an exception as an API response
540 *
541 * @since 1.23
542 * @param Exception $e
543 */
544 protected function handleException( Exception $e ) {
545 // Bug 63145: Rollback any open database transactions
546 if ( !( $e instanceof UsageException ) ) {
547 // UsageExceptions are intentional, so don't rollback if that's the case
548 try {
549 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
550 } catch ( DBError $e2 ) {
551 // Rollback threw an exception too. Log it, but don't interrupt
552 // our regularly scheduled exception handling.
553 MWExceptionHandler::logException( $e2 );
554 }
555 }
556
557 // Allow extra cleanup and logging
558 Hooks::run( 'ApiMain::onException', [ $this, $e ] );
559
560 // Log it
561 if ( !( $e instanceof UsageException ) ) {
562 MWExceptionHandler::logException( $e );
563 }
564
565 // Handle any kind of exception by outputting properly formatted error message.
566 // If this fails, an unhandled exception should be thrown so that global error
567 // handler will process and log it.
568
569 $errCode = $this->substituteResultWithError( $e );
570
571 // Error results should not be cached
572 $this->setCacheMode( 'private' );
573
574 $response = $this->getRequest()->response();
575 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
576 if ( $e->getCode() === 0 ) {
577 $response->header( $headerStr );
578 } else {
579 $response->header( $headerStr, true, $e->getCode() );
580 }
581
582 // Reset and print just the error message
583 ob_clean();
584
585 // Printer may not be initialized if the extractRequestParams() fails for the main module
586 $this->createErrorPrinter();
587
588 try {
589 $this->printResult( true );
590 } catch ( UsageException $ex ) {
591 // The error printer itself is failing. Try suppressing its request
592 // parameters and redo.
593 $this->setWarning(
594 'Error printer failed (will retry without params): ' . $ex->getMessage()
595 );
596 $this->mPrinter = null;
597 $this->createErrorPrinter();
598 $this->mPrinter->forceDefaultParams();
599 $this->printResult( true );
600 }
601 }
602
603 /**
604 * Handle an exception from the ApiBeforeMain hook.
605 *
606 * This tries to print the exception as an API response, to be more
607 * friendly to clients. If it fails, it will rethrow the exception.
608 *
609 * @since 1.23
610 * @param Exception $e
611 * @throws Exception
612 */
613 public static function handleApiBeforeMainException( Exception $e ) {
614 ob_start();
615
616 try {
617 $main = new self( RequestContext::getMain(), false );
618 $main->handleException( $e );
619 $main->logRequest( 0, $e );
620 } catch ( Exception $e2 ) {
621 // Nope, even that didn't work. Punt.
622 throw $e;
623 }
624
625 // Reset cache headers
626 $main->sendCacheHeaders( true );
627
628 ob_end_flush();
629 }
630
631 /**
632 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
633 *
634 * If no origin parameter is present, nothing happens.
635 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
636 * is set and false is returned.
637 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
638 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
639 * headers are set.
640 * http://www.w3.org/TR/cors/#resource-requests
641 * http://www.w3.org/TR/cors/#resource-preflight-requests
642 *
643 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
644 */
645 protected function handleCORS() {
646 $originParam = $this->getParameter( 'origin' ); // defaults to null
647 if ( $originParam === null ) {
648 // No origin parameter, nothing to do
649 return true;
650 }
651
652 $request = $this->getRequest();
653 $response = $request->response();
654
655 $matchOrigin = false;
656 $allowTiming = false;
657 $varyOrigin = true;
658
659 if ( $originParam === '*' ) {
660 // Request for anonymous CORS
661 $matchOrigin = true;
662 $allowOrigin = '*';
663 $allowCredentials = 'false';
664 $varyOrigin = false; // No need to vary
665 } else {
666 // Non-anonymous CORS, check we allow the domain
667
668 // Origin: header is a space-separated list of origins, check all of them
669 $originHeader = $request->getHeader( 'Origin' );
670 if ( $originHeader === false ) {
671 $origins = [];
672 } else {
673 $originHeader = trim( $originHeader );
674 $origins = preg_split( '/\s+/', $originHeader );
675 }
676
677 if ( !in_array( $originParam, $origins ) ) {
678 // origin parameter set but incorrect
679 // Send a 403 response
680 $response->statusHeader( 403 );
681 $response->header( 'Cache-Control: no-cache' );
682 echo "'origin' parameter does not match Origin header\n";
683
684 return false;
685 }
686
687 $config = $this->getConfig();
688 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
689 $originParam,
690 $config->get( 'CrossSiteAJAXdomains' ),
691 $config->get( 'CrossSiteAJAXdomainExceptions' )
692 );
693
694 $allowOrigin = $originHeader;
695 $allowCredentials = 'true';
696 $allowTiming = $originHeader;
697 }
698
699 if ( $matchOrigin ) {
700 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
701 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
702 if ( $preflight ) {
703 // This is a CORS preflight request
704 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
705 // If method is not a case-sensitive match, do not set any additional headers and terminate.
706 return true;
707 }
708 // We allow the actual request to send the following headers
709 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
710 if ( $requestedHeaders !== false ) {
711 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
712 return true;
713 }
714 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
715 }
716
717 // We only allow the actual request to be GET or POST
718 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
719 }
720
721 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
722 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
723 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
724 if ( $allowTiming !== false ) {
725 $response->header( "Timing-Allow-Origin: $allowTiming" );
726 }
727
728 if ( !$preflight ) {
729 $response->header(
730 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
731 );
732 }
733 }
734
735 if ( $varyOrigin ) {
736 $this->getOutput()->addVaryHeader( 'Origin' );
737 }
738
739 return true;
740 }
741
742 /**
743 * Attempt to match an Origin header against a set of rules and a set of exceptions
744 * @param string $value Origin header
745 * @param array $rules Set of wildcard rules
746 * @param array $exceptions Set of wildcard rules
747 * @return bool True if $value matches a rule in $rules and doesn't match
748 * any rules in $exceptions, false otherwise
749 */
750 protected static function matchOrigin( $value, $rules, $exceptions ) {
751 foreach ( $rules as $rule ) {
752 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
753 // Rule matches, check exceptions
754 foreach ( $exceptions as $exc ) {
755 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
756 return false;
757 }
758 }
759
760 return true;
761 }
762 }
763
764 return false;
765 }
766
767 /**
768 * Attempt to validate the value of Access-Control-Request-Headers against a list
769 * of headers that we allow the follow up request to send.
770 *
771 * @param string $requestedHeaders Comma seperated list of HTTP headers
772 * @return bool True if all requested headers are in the list of allowed headers
773 */
774 protected static function matchRequestedHeaders( $requestedHeaders ) {
775 if ( trim( $requestedHeaders ) === '' ) {
776 return true;
777 }
778 $requestedHeaders = explode( ',', $requestedHeaders );
779 $allowedAuthorHeaders = array_flip( [
780 /* simple headers (see spec) */
781 'accept',
782 'accept-language',
783 'content-language',
784 'content-type',
785 /* non-authorable headers in XHR, which are however requested by some UAs */
786 'accept-encoding',
787 'dnt',
788 'origin',
789 /* MediaWiki whitelist */
790 'api-user-agent',
791 ] );
792 foreach ( $requestedHeaders as $rHeader ) {
793 $rHeader = strtolower( trim( $rHeader ) );
794 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
795 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
796 return false;
797 }
798 }
799 return true;
800 }
801
802 /**
803 * Helper function to convert wildcard string into a regex
804 * '*' => '.*?'
805 * '?' => '.'
806 *
807 * @param string $wildcard String with wildcards
808 * @return string Regular expression
809 */
810 protected static function wildcardToRegex( $wildcard ) {
811 $wildcard = preg_quote( $wildcard, '/' );
812 $wildcard = str_replace(
813 [ '\*', '\?' ],
814 [ '.*?', '.' ],
815 $wildcard
816 );
817
818 return "/^https?:\/\/$wildcard$/";
819 }
820
821 /**
822 * Send caching headers
823 * @param bool $isError Whether an error response is being output
824 * @since 1.26 added $isError parameter
825 */
826 protected function sendCacheHeaders( $isError ) {
827 $response = $this->getRequest()->response();
828 $out = $this->getOutput();
829
830 $out->addVaryHeader( 'Treat-as-Untrusted' );
831
832 $config = $this->getConfig();
833
834 if ( $config->get( 'VaryOnXFP' ) ) {
835 $out->addVaryHeader( 'X-Forwarded-Proto' );
836 }
837
838 if ( !$isError && $this->mModule &&
839 ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
840 ) {
841 $etag = $this->mModule->getConditionalRequestData( 'etag' );
842 if ( $etag !== null ) {
843 $response->header( "ETag: $etag" );
844 }
845 $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
846 if ( $lastMod !== null ) {
847 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
848 }
849 }
850
851 // The logic should be:
852 // $this->mCacheControl['max-age'] is set?
853 // Use it, the module knows better than our guess.
854 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
855 // Use 0 because we can guess caching is probably the wrong thing to do.
856 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
857 $maxage = 0;
858 if ( isset( $this->mCacheControl['max-age'] ) ) {
859 $maxage = $this->mCacheControl['max-age'];
860 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
861 $this->mCacheMode !== 'private'
862 ) {
863 $maxage = $this->getParameter( 'maxage' );
864 }
865 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
866
867 if ( $this->mCacheMode == 'private' ) {
868 $response->header( "Cache-Control: $privateCache" );
869 return;
870 }
871
872 $useKeyHeader = $config->get( 'UseKeyHeader' );
873 if ( $this->mCacheMode == 'anon-public-user-private' ) {
874 $out->addVaryHeader( 'Cookie' );
875 $response->header( $out->getVaryHeader() );
876 if ( $useKeyHeader ) {
877 $response->header( $out->getKeyHeader() );
878 if ( $out->haveCacheVaryCookies() ) {
879 // Logged in, mark this request private
880 $response->header( "Cache-Control: $privateCache" );
881 return;
882 }
883 // Logged out, send normal public headers below
884 } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
885 // Logged in or otherwise has session (e.g. anonymous users who have edited)
886 // Mark request private
887 $response->header( "Cache-Control: $privateCache" );
888
889 return;
890 } // else no Key and anonymous, send public headers below
891 }
892
893 // Send public headers
894 $response->header( $out->getVaryHeader() );
895 if ( $useKeyHeader ) {
896 $response->header( $out->getKeyHeader() );
897 }
898
899 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
900 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
901 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
902 }
903 if ( !isset( $this->mCacheControl['max-age'] ) ) {
904 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
905 }
906
907 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
908 // Public cache not requested
909 // Sending a Vary header in this case is harmless, and protects us
910 // against conditional calls of setCacheMaxAge().
911 $response->header( "Cache-Control: $privateCache" );
912
913 return;
914 }
915
916 $this->mCacheControl['public'] = true;
917
918 // Send an Expires header
919 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
920 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
921 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
922
923 // Construct the Cache-Control header
924 $ccHeader = '';
925 $separator = '';
926 foreach ( $this->mCacheControl as $name => $value ) {
927 if ( is_bool( $value ) ) {
928 if ( $value ) {
929 $ccHeader .= $separator . $name;
930 $separator = ', ';
931 }
932 } else {
933 $ccHeader .= $separator . "$name=$value";
934 $separator = ', ';
935 }
936 }
937
938 $response->header( "Cache-Control: $ccHeader" );
939 }
940
941 /**
942 * Create the printer for error output
943 */
944 private function createErrorPrinter() {
945 if ( !isset( $this->mPrinter ) ) {
946 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
947 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
948 $value = self::API_DEFAULT_FORMAT;
949 }
950 $this->mPrinter = $this->createPrinterByName( $value );
951 }
952
953 // Printer may not be able to handle errors. This is particularly
954 // likely if the module returns something for getCustomPrinter().
955 if ( !$this->mPrinter->canPrintErrors() ) {
956 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
957 }
958 }
959
960 /**
961 * Create an error message for the given exception.
962 *
963 * If the exception is a UsageException then
964 * UsageException::getMessageArray() will be called to create the message.
965 *
966 * @param Exception $e
967 * @return array ['code' => 'some string', 'info' => 'some other string']
968 * @since 1.27
969 */
970 protected function errorMessageFromException( $e ) {
971 if ( $e instanceof UsageException ) {
972 // User entered incorrect parameters - generate error response
973 $errMessage = $e->getMessageArray();
974 } else {
975 $config = $this->getConfig();
976 // Something is seriously wrong
977 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
978 $info = 'Database query error';
979 } else {
980 $info = "Exception Caught: {$e->getMessage()}";
981 }
982
983 $errMessage = [
984 'code' => 'internal_api_error_' . get_class( $e ),
985 'info' => '[' . WebRequest::getRequestId() . '] ' . $info,
986 ];
987 }
988 return $errMessage;
989 }
990
991 /**
992 * Replace the result data with the information about an exception.
993 * Returns the error code
994 * @param Exception $e
995 * @return string
996 */
997 protected function substituteResultWithError( $e ) {
998 $result = $this->getResult();
999 $config = $this->getConfig();
1000
1001 $errMessage = $this->errorMessageFromException( $e );
1002 if ( $e instanceof UsageException ) {
1003 // User entered incorrect parameters - generate error response
1004 $link = wfExpandUrl( wfScript( 'api' ) );
1005 ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
1006 } else {
1007 // Something is seriously wrong
1008 if ( $config->get( 'ShowExceptionDetails' ) ) {
1009 ApiResult::setContentValue(
1010 $errMessage,
1011 'trace',
1012 MWExceptionHandler::getRedactedTraceAsString( $e )
1013 );
1014 }
1015 }
1016
1017 // Remember all the warnings to re-add them later
1018 $warnings = $result->getResultData( [ 'warnings' ] );
1019
1020 $result->reset();
1021 // Re-add the id
1022 $requestid = $this->getParameter( 'requestid' );
1023 if ( !is_null( $requestid ) ) {
1024 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1025 }
1026 if ( $config->get( 'ShowHostnames' ) ) {
1027 // servedby is especially useful when debugging errors
1028 $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1029 }
1030 if ( $warnings !== null ) {
1031 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1032 }
1033
1034 $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
1035
1036 return $errMessage['code'];
1037 }
1038
1039 /**
1040 * Set up for the execution.
1041 * @return array
1042 */
1043 protected function setupExecuteAction() {
1044 // First add the id to the top element
1045 $result = $this->getResult();
1046 $requestid = $this->getParameter( 'requestid' );
1047 if ( !is_null( $requestid ) ) {
1048 $result->addValue( null, 'requestid', $requestid );
1049 }
1050
1051 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1052 $servedby = $this->getParameter( 'servedby' );
1053 if ( $servedby ) {
1054 $result->addValue( null, 'servedby', wfHostname() );
1055 }
1056 }
1057
1058 if ( $this->getParameter( 'curtimestamp' ) ) {
1059 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
1060 ApiResult::NO_SIZE_CHECK );
1061 }
1062
1063 $params = $this->extractRequestParams();
1064
1065 $this->mAction = $params['action'];
1066
1067 if ( !is_string( $this->mAction ) ) {
1068 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1069 }
1070
1071 return $params;
1072 }
1073
1074 /**
1075 * Set up the module for response
1076 * @return ApiBase The module that will handle this action
1077 * @throws MWException
1078 * @throws UsageException
1079 */
1080 protected function setupModule() {
1081 // Instantiate the module requested by the user
1082 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1083 if ( $module === null ) {
1084 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1085 }
1086 $moduleParams = $module->extractRequestParams();
1087
1088 // Check token, if necessary
1089 if ( $module->needsToken() === true ) {
1090 throw new MWException(
1091 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1092 'See documentation for ApiBase::needsToken for details.'
1093 );
1094 }
1095 if ( $module->needsToken() ) {
1096 if ( !$module->mustBePosted() ) {
1097 throw new MWException(
1098 "Module '{$module->getModuleName()}' must require POST to use tokens."
1099 );
1100 }
1101
1102 if ( !isset( $moduleParams['token'] ) ) {
1103 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1104 }
1105
1106 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1107 array_key_exists(
1108 $module->encodeParamName( 'token' ),
1109 $this->getRequest()->getQueryValues()
1110 )
1111 ) {
1112 $this->dieUsage(
1113 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1114 'found in the query string, but must be in the POST body',
1115 'mustposttoken'
1116 );
1117 }
1118
1119 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1120 $this->dieUsageMsg( 'sessionfailure' );
1121 }
1122 }
1123
1124 return $module;
1125 }
1126
1127 /**
1128 * Check the max lag if necessary
1129 * @param ApiBase $module Api module being used
1130 * @param array $params Array an array containing the request parameters.
1131 * @return bool True on success, false should exit immediately
1132 */
1133 protected function checkMaxLag( $module, $params ) {
1134 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1135 $maxLag = $params['maxlag'];
1136 list( $host, $lag ) = wfGetLB()->getMaxLag();
1137 if ( $lag > $maxLag ) {
1138 $response = $this->getRequest()->response();
1139
1140 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1141 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1142
1143 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1144 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1145 }
1146
1147 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1148 }
1149 }
1150
1151 return true;
1152 }
1153
1154 /**
1155 * Check selected RFC 7232 precondition headers
1156 *
1157 * RFC 7232 envisions a particular model where you send your request to "a
1158 * resource", and for write requests that you can read "the resource" by
1159 * changing the method to GET. When the API receives a GET request, it
1160 * works out even though "the resource" from RFC 7232's perspective might
1161 * be many resources from MediaWiki's perspective. But it totally fails for
1162 * a POST, since what HTTP sees as "the resource" is probably just
1163 * "/api.php" with all the interesting bits in the body.
1164 *
1165 * Therefore, we only support RFC 7232 precondition headers for GET (and
1166 * HEAD). That means we don't need to bother with If-Match and
1167 * If-Unmodified-Since since they only apply to modification requests.
1168 *
1169 * And since we don't support Range, If-Range is ignored too.
1170 *
1171 * @since 1.26
1172 * @param ApiBase $module Api module being used
1173 * @return bool True on success, false should exit immediately
1174 */
1175 protected function checkConditionalRequestHeaders( $module ) {
1176 if ( $this->mInternalMode ) {
1177 // No headers to check in internal mode
1178 return true;
1179 }
1180
1181 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1182 // Don't check POSTs
1183 return true;
1184 }
1185
1186 $return304 = false;
1187
1188 $ifNoneMatch = array_diff(
1189 $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1190 [ '' ]
1191 );
1192 if ( $ifNoneMatch ) {
1193 if ( $ifNoneMatch === [ '*' ] ) {
1194 // API responses always "exist"
1195 $etag = '*';
1196 } else {
1197 $etag = $module->getConditionalRequestData( 'etag' );
1198 }
1199 }
1200 if ( $ifNoneMatch && $etag !== null ) {
1201 $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1202 $match = array_map( function ( $s ) {
1203 return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1204 }, $ifNoneMatch );
1205 $return304 = in_array( $test, $match, true );
1206 } else {
1207 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1208
1209 // Some old browsers sends sizes after the date, like this:
1210 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1211 // Ignore that.
1212 $i = strpos( $value, ';' );
1213 if ( $i !== false ) {
1214 $value = trim( substr( $value, 0, $i ) );
1215 }
1216
1217 if ( $value !== '' ) {
1218 try {
1219 $ts = new MWTimestamp( $value );
1220 if (
1221 // RFC 7231 IMF-fixdate
1222 $ts->getTimestamp( TS_RFC2822 ) === $value ||
1223 // RFC 850
1224 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1225 // asctime (with and without space-padded day)
1226 $ts->format( 'D M j H:i:s Y' ) === $value ||
1227 $ts->format( 'D M j H:i:s Y' ) === $value
1228 ) {
1229 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1230 if ( $lastMod !== null ) {
1231 // Mix in some MediaWiki modification times
1232 $modifiedTimes = [
1233 'page' => $lastMod,
1234 'user' => $this->getUser()->getTouched(),
1235 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1236 ];
1237 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1238 // T46570: the core page itself may not change, but resources might
1239 $modifiedTimes['sepoch'] = wfTimestamp(
1240 TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1241 );
1242 }
1243 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1244 $lastMod = max( $modifiedTimes );
1245 $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1246 }
1247 }
1248 } catch ( TimestampException $e ) {
1249 // Invalid timestamp, ignore it
1250 }
1251 }
1252 }
1253
1254 if ( $return304 ) {
1255 $this->getRequest()->response()->statusHeader( 304 );
1256
1257 // Avoid outputting the compressed representation of a zero-length body
1258 MediaWiki\suppressWarnings();
1259 ini_set( 'zlib.output_compression', 0 );
1260 MediaWiki\restoreWarnings();
1261 wfClearOutputBuffers();
1262
1263 return false;
1264 }
1265
1266 return true;
1267 }
1268
1269 /**
1270 * Check for sufficient permissions to execute
1271 * @param ApiBase $module An Api module
1272 */
1273 protected function checkExecutePermissions( $module ) {
1274 $user = $this->getUser();
1275 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1276 !$user->isAllowed( 'read' )
1277 ) {
1278 $this->dieUsageMsg( 'readrequired' );
1279 }
1280
1281 if ( $module->isWriteMode() ) {
1282 if ( !$this->mEnableWrite ) {
1283 $this->dieUsageMsg( 'writedisabled' );
1284 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1285 $this->dieUsageMsg( 'writerequired' );
1286 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1287 $this->dieUsage(
1288 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1289 'promised-nonwrite-api'
1290 );
1291 }
1292
1293 $this->checkReadOnly( $module );
1294 }
1295
1296 // Allow extensions to stop execution for arbitrary reasons.
1297 $message = false;
1298 if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1299 $this->dieUsageMsg( $message );
1300 }
1301 }
1302
1303 /**
1304 * Check if the DB is read-only for this user
1305 * @param ApiBase $module An Api module
1306 */
1307 protected function checkReadOnly( $module ) {
1308 if ( wfReadOnly() ) {
1309 $this->dieReadOnly();
1310 }
1311
1312 if ( $module->isWriteMode()
1313 && in_array( 'bot', $this->getUser()->getGroups() )
1314 && wfGetLB()->getServerCount() > 1
1315 ) {
1316 $this->checkBotReadOnly();
1317 }
1318 }
1319
1320 /**
1321 * Check whether we are readonly for bots
1322 */
1323 private function checkBotReadOnly() {
1324 // Figure out how many servers have passed the lag threshold
1325 $numLagged = 0;
1326 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1327 $laggedServers = [];
1328 $loadBalancer = wfGetLB();
1329 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1330 if ( $lag > $lagLimit ) {
1331 ++$numLagged;
1332 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1333 }
1334 }
1335
1336 // If a majority of slaves are too lagged then disallow writes
1337 $slaveCount = wfGetLB()->getServerCount() - 1;
1338 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1339 $laggedServers = implode( ', ', $laggedServers );
1340 wfDebugLog(
1341 'api-readonly',
1342 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1343 );
1344
1345 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1346 $this->dieUsage(
1347 $parsed['info'],
1348 $parsed['code'],
1349 /* http error */
1350 0,
1351 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1352 );
1353 }
1354 }
1355
1356 /**
1357 * Check asserts of the user's rights
1358 * @param array $params
1359 */
1360 protected function checkAsserts( $params ) {
1361 if ( isset( $params['assert'] ) ) {
1362 $user = $this->getUser();
1363 switch ( $params['assert'] ) {
1364 case 'user':
1365 if ( $user->isAnon() ) {
1366 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1367 }
1368 break;
1369 case 'bot':
1370 if ( !$user->isAllowed( 'bot' ) ) {
1371 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1372 }
1373 break;
1374 }
1375 }
1376 }
1377
1378 /**
1379 * Check POST for external response and setup result printer
1380 * @param ApiBase $module An Api module
1381 * @param array $params An array with the request parameters
1382 */
1383 protected function setupExternalResponse( $module, $params ) {
1384 $request = $this->getRequest();
1385 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1386 // Module requires POST. GET request might still be allowed
1387 // if $wgDebugApi is true, otherwise fail.
1388 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction ] );
1389 }
1390
1391 // See if custom printer is used
1392 $this->mPrinter = $module->getCustomPrinter();
1393 if ( is_null( $this->mPrinter ) ) {
1394 // Create an appropriate printer
1395 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1396 }
1397
1398 if ( $request->getProtocol() === 'http' && (
1399 $request->getSession()->shouldForceHTTPS() ||
1400 ( $this->getUser()->isLoggedIn() &&
1401 $this->getUser()->requiresHTTPS() )
1402 ) ) {
1403 $this->logFeatureUsage( 'https-expected' );
1404 $this->setWarning( 'HTTP used when HTTPS was expected' );
1405 }
1406 }
1407
1408 /**
1409 * Execute the actual module, without any error handling
1410 */
1411 protected function executeAction() {
1412 $params = $this->setupExecuteAction();
1413 $module = $this->setupModule();
1414 $this->mModule = $module;
1415
1416 if ( !$this->mInternalMode ) {
1417 $this->setRequestExpectations( $module );
1418 }
1419
1420 $this->checkExecutePermissions( $module );
1421
1422 if ( !$this->checkMaxLag( $module, $params ) ) {
1423 return;
1424 }
1425
1426 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1427 return;
1428 }
1429
1430 if ( !$this->mInternalMode ) {
1431 $this->setupExternalResponse( $module, $params );
1432 }
1433
1434 $this->checkAsserts( $params );
1435
1436 // Execute
1437 $module->execute();
1438 Hooks::run( 'APIAfterExecute', [ &$module ] );
1439
1440 $this->reportUnusedParams();
1441
1442 if ( !$this->mInternalMode ) {
1443 // append Debug information
1444 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1445
1446 // Print result data
1447 $this->printResult( false );
1448 }
1449 }
1450
1451 /**
1452 * Set database connection, query, and write expectations given this module request
1453 * @param ApiBase $module
1454 */
1455 protected function setRequestExpectations( ApiBase $module ) {
1456 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1457 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1458 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1459 if ( $this->getRequest()->hasSafeMethod() ) {
1460 $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1461 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1462 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1463 $this->getRequest()->markAsSafeRequest();
1464 } else {
1465 $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1466 }
1467 }
1468
1469 /**
1470 * Log the preceding request
1471 * @param float $time Time in seconds
1472 * @param Exception $e Exception caught while processing the request
1473 */
1474 protected function logRequest( $time, $e = null ) {
1475 $request = $this->getRequest();
1476 $logCtx = [
1477 'ts' => time(),
1478 'ip' => $request->getIP(),
1479 'userAgent' => $this->getUserAgent(),
1480 'wiki' => wfWikiID(),
1481 'timeSpentBackend' => (int) round( $time * 1000 ),
1482 'hadError' => $e !== null,
1483 'errorCodes' => [],
1484 'params' => [],
1485 ];
1486
1487 if ( $e ) {
1488 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1489 }
1490
1491 // Construct space separated message for 'api' log channel
1492 $msg = "API {$request->getMethod()} " .
1493 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1494 " {$logCtx['ip']} " .
1495 "T={$logCtx['timeSpentBackend']}ms";
1496
1497 foreach ( $this->getParamsUsed() as $name ) {
1498 $value = $request->getVal( $name );
1499 if ( $value === null ) {
1500 continue;
1501 }
1502
1503 if ( strlen( $value ) > 256 ) {
1504 $value = substr( $value, 0, 256 );
1505 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1506 } else {
1507 $encValue = $this->encodeRequestLogValue( $value );
1508 }
1509
1510 $logCtx['params'][$name] = $value;
1511 $msg .= " {$name}={$encValue}";
1512 }
1513
1514 wfDebugLog( 'api', $msg, 'private' );
1515 // ApiAction channel is for structured data consumers
1516 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1517 }
1518
1519 /**
1520 * Encode a value in a format suitable for a space-separated log line.
1521 * @param string $s
1522 * @return string
1523 */
1524 protected function encodeRequestLogValue( $s ) {
1525 static $table;
1526 if ( !$table ) {
1527 $chars = ';@$!*(),/:';
1528 $numChars = strlen( $chars );
1529 for ( $i = 0; $i < $numChars; $i++ ) {
1530 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1531 }
1532 }
1533
1534 return strtr( rawurlencode( $s ), $table );
1535 }
1536
1537 /**
1538 * Get the request parameters used in the course of the preceding execute() request
1539 * @return array
1540 */
1541 protected function getParamsUsed() {
1542 return array_keys( $this->mParamsUsed );
1543 }
1544
1545 /**
1546 * Mark parameters as used
1547 * @param string|string[] $params
1548 */
1549 public function markParamsUsed( $params ) {
1550 $this->mParamsUsed += array_fill_keys( (array)$params, true );
1551 }
1552
1553 /**
1554 * Get a request value, and register the fact that it was used, for logging.
1555 * @param string $name
1556 * @param mixed $default
1557 * @return mixed
1558 */
1559 public function getVal( $name, $default = null ) {
1560 $this->mParamsUsed[$name] = true;
1561
1562 $ret = $this->getRequest()->getVal( $name );
1563 if ( $ret === null ) {
1564 if ( $this->getRequest()->getArray( $name ) !== null ) {
1565 // See bug 10262 for why we don't just implode( '|', ... ) the
1566 // array.
1567 $this->setWarning(
1568 "Parameter '$name' uses unsupported PHP array syntax"
1569 );
1570 }
1571 $ret = $default;
1572 }
1573 return $ret;
1574 }
1575
1576 /**
1577 * Get a boolean request value, and register the fact that the parameter
1578 * was used, for logging.
1579 * @param string $name
1580 * @return bool
1581 */
1582 public function getCheck( $name ) {
1583 return $this->getVal( $name, null ) !== null;
1584 }
1585
1586 /**
1587 * Get a request upload, and register the fact that it was used, for logging.
1588 *
1589 * @since 1.21
1590 * @param string $name Parameter name
1591 * @return WebRequestUpload
1592 */
1593 public function getUpload( $name ) {
1594 $this->mParamsUsed[$name] = true;
1595
1596 return $this->getRequest()->getUpload( $name );
1597 }
1598
1599 /**
1600 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1601 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1602 */
1603 protected function reportUnusedParams() {
1604 $paramsUsed = $this->getParamsUsed();
1605 $allParams = $this->getRequest()->getValueNames();
1606
1607 if ( !$this->mInternalMode ) {
1608 // Printer has not yet executed; don't warn that its parameters are unused
1609 $printerParams = array_map(
1610 [ $this->mPrinter, 'encodeParamName' ],
1611 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1612 );
1613 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1614 } else {
1615 $unusedParams = array_diff( $allParams, $paramsUsed );
1616 }
1617
1618 if ( count( $unusedParams ) ) {
1619 $s = count( $unusedParams ) > 1 ? 's' : '';
1620 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1621 }
1622 }
1623
1624 /**
1625 * Print results using the current printer
1626 *
1627 * @param bool $isError
1628 */
1629 protected function printResult( $isError ) {
1630 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1631 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1632 }
1633
1634 $printer = $this->mPrinter;
1635 $printer->initPrinter( false );
1636 $printer->execute();
1637 $printer->closePrinter();
1638 }
1639
1640 /**
1641 * @return bool
1642 */
1643 public function isReadMode() {
1644 return false;
1645 }
1646
1647 /**
1648 * See ApiBase for description.
1649 *
1650 * @return array
1651 */
1652 public function getAllowedParams() {
1653 return [
1654 'action' => [
1655 ApiBase::PARAM_DFLT => 'help',
1656 ApiBase::PARAM_TYPE => 'submodule',
1657 ],
1658 'format' => [
1659 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1660 ApiBase::PARAM_TYPE => 'submodule',
1661 ],
1662 'maxlag' => [
1663 ApiBase::PARAM_TYPE => 'integer'
1664 ],
1665 'smaxage' => [
1666 ApiBase::PARAM_TYPE => 'integer',
1667 ApiBase::PARAM_DFLT => 0
1668 ],
1669 'maxage' => [
1670 ApiBase::PARAM_TYPE => 'integer',
1671 ApiBase::PARAM_DFLT => 0
1672 ],
1673 'assert' => [
1674 ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1675 ],
1676 'requestid' => null,
1677 'servedby' => false,
1678 'curtimestamp' => false,
1679 'origin' => null,
1680 'uselang' => [
1681 ApiBase::PARAM_DFLT => 'user',
1682 ],
1683 ];
1684 }
1685
1686 /** @see ApiBase::getExamplesMessages() */
1687 protected function getExamplesMessages() {
1688 return [
1689 'action=help'
1690 => 'apihelp-help-example-main',
1691 'action=help&recursivesubmodules=1'
1692 => 'apihelp-help-example-recursive',
1693 ];
1694 }
1695
1696 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1697 // Wish PHP had an "array_insert_before". Instead, we have to manually
1698 // reindex the array to get 'permissions' in the right place.
1699 $oldHelp = $help;
1700 $help = [];
1701 foreach ( $oldHelp as $k => $v ) {
1702 if ( $k === 'submodules' ) {
1703 $help['permissions'] = '';
1704 }
1705 $help[$k] = $v;
1706 }
1707 $help['datatypes'] = '';
1708 $help['credits'] = '';
1709
1710 // Fill 'permissions'
1711 $help['permissions'] .= Html::openElement( 'div',
1712 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1713 $m = $this->msg( 'api-help-permissions' );
1714 if ( !$m->isDisabled() ) {
1715 $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1716 $m->numParams( count( self::$mRights ) )->parse()
1717 );
1718 }
1719 $help['permissions'] .= Html::openElement( 'dl' );
1720 foreach ( self::$mRights as $right => $rightMsg ) {
1721 $help['permissions'] .= Html::element( 'dt', null, $right );
1722
1723 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1724 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1725
1726 $groups = array_map( function ( $group ) {
1727 return $group == '*' ? 'all' : $group;
1728 }, User::getGroupsWithPermission( $right ) );
1729
1730 $help['permissions'] .= Html::rawElement( 'dd', null,
1731 $this->msg( 'api-help-permissions-granted-to' )
1732 ->numParams( count( $groups ) )
1733 ->params( $this->getLanguage()->commaList( $groups ) )
1734 ->parse()
1735 );
1736 }
1737 $help['permissions'] .= Html::closeElement( 'dl' );
1738 $help['permissions'] .= Html::closeElement( 'div' );
1739
1740 // Fill 'datatypes' and 'credits', if applicable
1741 if ( empty( $options['nolead'] ) ) {
1742 $level = $options['headerlevel'];
1743 $tocnumber = &$options['tocnumber'];
1744
1745 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1746
1747 // Add an additional span with sanitized ID
1748 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1749 $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1750 $header;
1751 }
1752 $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1753 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1754 $header
1755 );
1756 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1757 if ( !isset( $tocData['main/datatypes'] ) ) {
1758 $tocnumber[$level]++;
1759 $tocData['main/datatypes'] = [
1760 'toclevel' => count( $tocnumber ),
1761 'level' => $level,
1762 'anchor' => 'main/datatypes',
1763 'line' => $header,
1764 'number' => implode( '.', $tocnumber ),
1765 'index' => false,
1766 ];
1767 }
1768
1769 // Add an additional span with sanitized ID
1770 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1771 $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1772 $header;
1773 }
1774 $header = $this->msg( 'api-credits-header' )->parse();
1775 $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1776 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1777 $header
1778 );
1779 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1780 if ( !isset( $tocData['main/credits'] ) ) {
1781 $tocnumber[$level]++;
1782 $tocData['main/credits'] = [
1783 'toclevel' => count( $tocnumber ),
1784 'level' => $level,
1785 'anchor' => 'main/credits',
1786 'line' => $header,
1787 'number' => implode( '.', $tocnumber ),
1788 'index' => false,
1789 ];
1790 }
1791 }
1792 }
1793
1794 private $mCanApiHighLimits = null;
1795
1796 /**
1797 * Check whether the current user is allowed to use high limits
1798 * @return bool
1799 */
1800 public function canApiHighLimits() {
1801 if ( !isset( $this->mCanApiHighLimits ) ) {
1802 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1803 }
1804
1805 return $this->mCanApiHighLimits;
1806 }
1807
1808 /**
1809 * Overrides to return this instance's module manager.
1810 * @return ApiModuleManager
1811 */
1812 public function getModuleManager() {
1813 return $this->mModuleMgr;
1814 }
1815
1816 /**
1817 * Fetches the user agent used for this request
1818 *
1819 * The value will be the combination of the 'Api-User-Agent' header (if
1820 * any) and the standard User-Agent header (if any).
1821 *
1822 * @return string
1823 */
1824 public function getUserAgent() {
1825 return trim(
1826 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1827 $this->getRequest()->getHeader( 'User-agent' )
1828 );
1829 }
1830
1831 /************************************************************************//**
1832 * @name Deprecated
1833 * @{
1834 */
1835
1836 /**
1837 * Sets whether the pretty-printer should format *bold* and $italics$
1838 *
1839 * @deprecated since 1.25
1840 * @param bool $help
1841 */
1842 public function setHelp( $help = true ) {
1843 wfDeprecated( __METHOD__, '1.25' );
1844 $this->mPrinter->setHelp( $help );
1845 }
1846
1847 /**
1848 * Override the parent to generate help messages for all available modules.
1849 *
1850 * @deprecated since 1.25
1851 * @return string
1852 */
1853 public function makeHelpMsg() {
1854 wfDeprecated( __METHOD__, '1.25' );
1855
1856 $this->setHelp();
1857 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1858
1859 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1860 wfMemcKey(
1861 'apihelp',
1862 $this->getModuleName(),
1863 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
1864 ),
1865 $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
1866 [ $this, 'reallyMakeHelpMsg' ]
1867 );
1868 }
1869
1870 /**
1871 * @deprecated since 1.25
1872 * @return mixed|string
1873 */
1874 public function reallyMakeHelpMsg() {
1875 wfDeprecated( __METHOD__, '1.25' );
1876 $this->setHelp();
1877
1878 // Use parent to make default message for the main module
1879 $msg = parent::makeHelpMsg();
1880
1881 $asterisks = str_repeat( '*** ', 14 );
1882 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1883
1884 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1885 $module = $this->mModuleMgr->getModule( $name );
1886 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1887
1888 $msg2 = $module->makeHelpMsg();
1889 if ( $msg2 !== false ) {
1890 $msg .= $msg2;
1891 }
1892 $msg .= "\n";
1893 }
1894
1895 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1896 foreach ( self::$mRights as $right => $rightMsg ) {
1897 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1898 ->useDatabase( false )
1899 ->inLanguage( 'en' )
1900 ->text();
1901 $groups = User::getGroupsWithPermission( $right );
1902 $msg .= '* ' . $right . " *\n $rightsMsg" .
1903 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1904 }
1905
1906 $msg .= "\n$asterisks Formats $asterisks\n\n";
1907 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1908 $module = $this->mModuleMgr->getModule( $name );
1909 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1910 $msg2 = $module->makeHelpMsg();
1911 if ( $msg2 !== false ) {
1912 $msg .= $msg2;
1913 }
1914 $msg .= "\n";
1915 }
1916
1917 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1918 $credits = str_replace( "\n", "\n ", $credits );
1919 $msg .= "\n*** Credits: ***\n $credits\n";
1920
1921 return $msg;
1922 }
1923
1924 /**
1925 * @deprecated since 1.25
1926 * @param ApiBase $module
1927 * @param string $paramName What type of request is this? e.g. action,
1928 * query, list, prop, meta, format
1929 * @return string
1930 */
1931 public static function makeHelpMsgHeader( $module, $paramName ) {
1932 wfDeprecated( __METHOD__, '1.25' );
1933 $modulePrefix = $module->getModulePrefix();
1934 if ( strval( $modulePrefix ) !== '' ) {
1935 $modulePrefix = "($modulePrefix) ";
1936 }
1937
1938 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1939 }
1940
1941 /**@}*/
1942
1943 }
1944
1945 /**
1946 * This exception will be thrown when dieUsage is called to stop module execution.
1947 *
1948 * @ingroup API
1949 */
1950 class UsageException extends MWException {
1951
1952 private $mCodestr;
1953
1954 /**
1955 * @var null|array
1956 */
1957 private $mExtraData;
1958
1959 /**
1960 * @param string $message
1961 * @param string $codestr
1962 * @param int $code
1963 * @param array|null $extradata
1964 */
1965 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1966 parent::__construct( $message, $code );
1967 $this->mCodestr = $codestr;
1968 $this->mExtraData = $extradata;
1969
1970 // This should never happen, so throw an exception about it that will
1971 // hopefully get logged with a backtrace (T138585)
1972 if ( !is_string( $codestr ) || $codestr === '' ) {
1973 throw new InvalidArgumentException( 'Invalid $codestr, was ' .
1974 ( $codestr === '' ? 'empty string' : gettype( $codestr ) )
1975 );
1976 }
1977 }
1978
1979 /**
1980 * @return string
1981 */
1982 public function getCodeString() {
1983 return $this->mCodestr;
1984 }
1985
1986 /**
1987 * @return array
1988 */
1989 public function getMessageArray() {
1990 $result = [
1991 'code' => $this->mCodestr,
1992 'info' => $this->getMessage()
1993 ];
1994 if ( is_array( $this->mExtraData ) ) {
1995 $result = array_merge( $result, $this->mExtraData );
1996 }
1997
1998 return $result;
1999 }
2000
2001 /**
2002 * @return string
2003 */
2004 public function __toString() {
2005 return "{$this->getCodeString()}: {$this->getMessage()}";
2006 }
2007 }
2008
2009 /**
2010 * For really cool vim folding this needs to be at the end:
2011 * vim: foldmarker=@{,@} foldmethod=marker
2012 */