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