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