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