Merge "Cleanup Special:PrefixIndex::showPrefixChunk()"
[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->getModuleName() . '.executeTiming', 1000 * $runTime );
475 }
476 } catch ( Exception $e ) {
477 $this->handleException( $e );
478 $this->logRequest( microtime( true ) - $t, $e );
479 $isError = true;
480 }
481
482 // Commit DBs and send any related cookies and headers
483 MediaWiki::preOutputCommit( $this->getContext() );
484
485 // Send cache headers after any code which might generate an error, to
486 // avoid sending public cache headers for errors.
487 $this->sendCacheHeaders( $isError );
488
489 // Executing the action might have already messed with the output
490 // buffers.
491 while ( ob_get_level() > $obLevel ) {
492 ob_end_flush();
493 }
494 }
495
496 /**
497 * Handle an exception as an API response
498 *
499 * @since 1.23
500 * @param Exception $e
501 */
502 protected function handleException( Exception $e ) {
503 // Bug 63145: Rollback any open database transactions
504 if ( !( $e instanceof UsageException ) ) {
505 // UsageExceptions are intentional, so don't rollback if that's the case
506 try {
507 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
508 } catch ( DBError $e2 ) {
509 // Rollback threw an exception too. Log it, but don't interrupt
510 // our regularly scheduled exception handling.
511 MWExceptionHandler::logException( $e2 );
512 }
513 }
514
515 // Allow extra cleanup and logging
516 Hooks::run( 'ApiMain::onException', [ $this, $e ] );
517
518 // Log it
519 if ( !( $e instanceof UsageException ) ) {
520 MWExceptionHandler::logException( $e );
521 }
522
523 // Handle any kind of exception by outputting properly formatted error message.
524 // If this fails, an unhandled exception should be thrown so that global error
525 // handler will process and log it.
526
527 $errCode = $this->substituteResultWithError( $e );
528
529 // Error results should not be cached
530 $this->setCacheMode( 'private' );
531
532 $response = $this->getRequest()->response();
533 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
534 if ( $e->getCode() === 0 ) {
535 $response->header( $headerStr );
536 } else {
537 $response->header( $headerStr, true, $e->getCode() );
538 }
539
540 // Reset and print just the error message
541 ob_clean();
542
543 // Printer may not be initialized if the extractRequestParams() fails for the main module
544 $this->createErrorPrinter();
545
546 try {
547 $this->printResult( true );
548 } catch ( UsageException $ex ) {
549 // The error printer itself is failing. Try suppressing its request
550 // parameters and redo.
551 $this->setWarning(
552 'Error printer failed (will retry without params): ' . $ex->getMessage()
553 );
554 $this->mPrinter = null;
555 $this->createErrorPrinter();
556 $this->mPrinter->forceDefaultParams();
557 $this->printResult( true );
558 }
559 }
560
561 /**
562 * Handle an exception from the ApiBeforeMain hook.
563 *
564 * This tries to print the exception as an API response, to be more
565 * friendly to clients. If it fails, it will rethrow the exception.
566 *
567 * @since 1.23
568 * @param Exception $e
569 * @throws Exception
570 */
571 public static function handleApiBeforeMainException( Exception $e ) {
572 ob_start();
573
574 try {
575 $main = new self( RequestContext::getMain(), false );
576 $main->handleException( $e );
577 $main->logRequest( 0, $e );
578 } catch ( Exception $e2 ) {
579 // Nope, even that didn't work. Punt.
580 throw $e;
581 }
582
583 // Reset cache headers
584 $main->sendCacheHeaders( true );
585
586 ob_end_flush();
587 }
588
589 /**
590 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
591 *
592 * If no origin parameter is present, nothing happens.
593 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
594 * is set and false is returned.
595 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
596 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
597 * headers are set.
598 * http://www.w3.org/TR/cors/#resource-requests
599 * http://www.w3.org/TR/cors/#resource-preflight-requests
600 *
601 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
602 */
603 protected function handleCORS() {
604 $originParam = $this->getParameter( 'origin' ); // defaults to null
605 if ( $originParam === null ) {
606 // No origin parameter, nothing to do
607 return true;
608 }
609
610 $request = $this->getRequest();
611 $response = $request->response();
612
613 // Origin: header is a space-separated list of origins, check all of them
614 $originHeader = $request->getHeader( 'Origin' );
615 if ( $originHeader === false ) {
616 $origins = [];
617 } else {
618 $originHeader = trim( $originHeader );
619 $origins = preg_split( '/\s+/', $originHeader );
620 }
621
622 if ( !in_array( $originParam, $origins ) ) {
623 // origin parameter set but incorrect
624 // Send a 403 response
625 $response->statusHeader( 403 );
626 $response->header( 'Cache-Control: no-cache' );
627 echo "'origin' parameter does not match Origin header\n";
628
629 return false;
630 }
631
632 $config = $this->getConfig();
633 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
634 $originParam,
635 $config->get( 'CrossSiteAJAXdomains' ),
636 $config->get( 'CrossSiteAJAXdomainExceptions' )
637 );
638
639 if ( $matchOrigin ) {
640 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
641 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
642 if ( $preflight ) {
643 // This is a CORS preflight request
644 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
645 // If method is not a case-sensitive match, do not set any additional headers and terminate.
646 return true;
647 }
648 // We allow the actual request to send the following headers
649 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
650 if ( $requestedHeaders !== false ) {
651 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
652 return true;
653 }
654 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
655 }
656
657 // We only allow the actual request to be GET or POST
658 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
659 }
660
661 $response->header( "Access-Control-Allow-Origin: $originHeader" );
662 $response->header( 'Access-Control-Allow-Credentials: true' );
663 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
664 $response->header( "Timing-Allow-Origin: $originHeader" );
665
666 if ( !$preflight ) {
667 $response->header(
668 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
669 );
670 }
671 }
672
673 $this->getOutput()->addVaryHeader( 'Origin' );
674 return true;
675 }
676
677 /**
678 * Attempt to match an Origin header against a set of rules and a set of exceptions
679 * @param string $value Origin header
680 * @param array $rules Set of wildcard rules
681 * @param array $exceptions Set of wildcard rules
682 * @return bool True if $value matches a rule in $rules and doesn't match
683 * any rules in $exceptions, false otherwise
684 */
685 protected static function matchOrigin( $value, $rules, $exceptions ) {
686 foreach ( $rules as $rule ) {
687 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
688 // Rule matches, check exceptions
689 foreach ( $exceptions as $exc ) {
690 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
691 return false;
692 }
693 }
694
695 return true;
696 }
697 }
698
699 return false;
700 }
701
702 /**
703 * Attempt to validate the value of Access-Control-Request-Headers against a list
704 * of headers that we allow the follow up request to send.
705 *
706 * @param string $requestedHeaders Comma seperated list of HTTP headers
707 * @return bool True if all requested headers are in the list of allowed headers
708 */
709 protected static function matchRequestedHeaders( $requestedHeaders ) {
710 if ( trim( $requestedHeaders ) === '' ) {
711 return true;
712 }
713 $requestedHeaders = explode( ',', $requestedHeaders );
714 $allowedAuthorHeaders = array_flip( [
715 /* simple headers (see spec) */
716 'accept',
717 'accept-language',
718 'content-language',
719 'content-type',
720 /* non-authorable headers in XHR, which are however requested by some UAs */
721 'accept-encoding',
722 'dnt',
723 'origin',
724 /* MediaWiki whitelist */
725 'api-user-agent',
726 ] );
727 foreach ( $requestedHeaders as $rHeader ) {
728 $rHeader = strtolower( trim( $rHeader ) );
729 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
730 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
731 return false;
732 }
733 }
734 return true;
735 }
736
737 /**
738 * Helper function to convert wildcard string into a regex
739 * '*' => '.*?'
740 * '?' => '.'
741 *
742 * @param string $wildcard String with wildcards
743 * @return string Regular expression
744 */
745 protected static function wildcardToRegex( $wildcard ) {
746 $wildcard = preg_quote( $wildcard, '/' );
747 $wildcard = str_replace(
748 [ '\*', '\?' ],
749 [ '.*?', '.' ],
750 $wildcard
751 );
752
753 return "/^https?:\/\/$wildcard$/";
754 }
755
756 /**
757 * Send caching headers
758 * @param bool $isError Whether an error response is being output
759 * @since 1.26 added $isError parameter
760 */
761 protected function sendCacheHeaders( $isError ) {
762 $response = $this->getRequest()->response();
763 $out = $this->getOutput();
764
765 $out->addVaryHeader( 'Treat-as-Untrusted' );
766
767 $config = $this->getConfig();
768
769 if ( $config->get( 'VaryOnXFP' ) ) {
770 $out->addVaryHeader( 'X-Forwarded-Proto' );
771 }
772
773 if ( !$isError && $this->mModule &&
774 ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
775 ) {
776 $etag = $this->mModule->getConditionalRequestData( 'etag' );
777 if ( $etag !== null ) {
778 $response->header( "ETag: $etag" );
779 }
780 $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
781 if ( $lastMod !== null ) {
782 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
783 }
784 }
785
786 // The logic should be:
787 // $this->mCacheControl['max-age'] is set?
788 // Use it, the module knows better than our guess.
789 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
790 // Use 0 because we can guess caching is probably the wrong thing to do.
791 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
792 $maxage = 0;
793 if ( isset( $this->mCacheControl['max-age'] ) ) {
794 $maxage = $this->mCacheControl['max-age'];
795 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
796 $this->mCacheMode !== 'private'
797 ) {
798 $maxage = $this->getParameter( 'maxage' );
799 }
800 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
801
802 if ( $this->mCacheMode == 'private' ) {
803 $response->header( "Cache-Control: $privateCache" );
804 return;
805 }
806
807 $useKeyHeader = $config->get( 'UseKeyHeader' );
808 if ( $this->mCacheMode == 'anon-public-user-private' ) {
809 $out->addVaryHeader( 'Cookie' );
810 $response->header( $out->getVaryHeader() );
811 if ( $useKeyHeader ) {
812 $response->header( $out->getKeyHeader() );
813 if ( $out->haveCacheVaryCookies() ) {
814 // Logged in, mark this request private
815 $response->header( "Cache-Control: $privateCache" );
816 return;
817 }
818 // Logged out, send normal public headers below
819 } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
820 // Logged in or otherwise has session (e.g. anonymous users who have edited)
821 // Mark request private
822 $response->header( "Cache-Control: $privateCache" );
823
824 return;
825 } // else no Key and anonymous, send public headers below
826 }
827
828 // Send public headers
829 $response->header( $out->getVaryHeader() );
830 if ( $useKeyHeader ) {
831 $response->header( $out->getKeyHeader() );
832 }
833
834 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
835 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
836 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
837 }
838 if ( !isset( $this->mCacheControl['max-age'] ) ) {
839 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
840 }
841
842 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
843 // Public cache not requested
844 // Sending a Vary header in this case is harmless, and protects us
845 // against conditional calls of setCacheMaxAge().
846 $response->header( "Cache-Control: $privateCache" );
847
848 return;
849 }
850
851 $this->mCacheControl['public'] = true;
852
853 // Send an Expires header
854 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
855 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
856 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
857
858 // Construct the Cache-Control header
859 $ccHeader = '';
860 $separator = '';
861 foreach ( $this->mCacheControl as $name => $value ) {
862 if ( is_bool( $value ) ) {
863 if ( $value ) {
864 $ccHeader .= $separator . $name;
865 $separator = ', ';
866 }
867 } else {
868 $ccHeader .= $separator . "$name=$value";
869 $separator = ', ';
870 }
871 }
872
873 $response->header( "Cache-Control: $ccHeader" );
874 }
875
876 /**
877 * Create the printer for error output
878 */
879 private function createErrorPrinter() {
880 if ( !isset( $this->mPrinter ) ) {
881 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
882 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
883 $value = self::API_DEFAULT_FORMAT;
884 }
885 $this->mPrinter = $this->createPrinterByName( $value );
886 }
887
888 // Printer may not be able to handle errors. This is particularly
889 // likely if the module returns something for getCustomPrinter().
890 if ( !$this->mPrinter->canPrintErrors() ) {
891 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
892 }
893 }
894
895 /**
896 * Create an error message for the given exception.
897 *
898 * If the exception is a UsageException then
899 * UsageException::getMessageArray() will be called to create the message.
900 *
901 * @param Exception $e
902 * @return array ['code' => 'some string', 'info' => 'some other string']
903 * @since 1.27
904 */
905 protected function errorMessageFromException( $e ) {
906 if ( $e instanceof UsageException ) {
907 // User entered incorrect parameters - generate error response
908 $errMessage = $e->getMessageArray();
909 } else {
910 $config = $this->getConfig();
911 // Something is seriously wrong
912 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
913 $info = 'Database query error';
914 } else {
915 $info = "Exception Caught: {$e->getMessage()}";
916 }
917
918 $errMessage = [
919 'code' => 'internal_api_error_' . get_class( $e ),
920 'info' => '[' . WebRequest::getRequestId() . '] ' . $info,
921 ];
922 }
923 return $errMessage;
924 }
925
926 /**
927 * Replace the result data with the information about an exception.
928 * Returns the error code
929 * @param Exception $e
930 * @return string
931 */
932 protected function substituteResultWithError( $e ) {
933 $result = $this->getResult();
934 $config = $this->getConfig();
935
936 $errMessage = $this->errorMessageFromException( $e );
937 if ( $e instanceof UsageException ) {
938 // User entered incorrect parameters - generate error response
939 $link = wfExpandUrl( wfScript( 'api' ) );
940 ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
941 } else {
942 // Something is seriously wrong
943 if ( $config->get( 'ShowExceptionDetails' ) ) {
944 ApiResult::setContentValue(
945 $errMessage,
946 'trace',
947 MWExceptionHandler::getRedactedTraceAsString( $e )
948 );
949 }
950 }
951
952 // Remember all the warnings to re-add them later
953 $warnings = $result->getResultData( [ 'warnings' ] );
954
955 $result->reset();
956 // Re-add the id
957 $requestid = $this->getParameter( 'requestid' );
958 if ( !is_null( $requestid ) ) {
959 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
960 }
961 if ( $config->get( 'ShowHostnames' ) ) {
962 // servedby is especially useful when debugging errors
963 $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
964 }
965 if ( $warnings !== null ) {
966 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
967 }
968
969 $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
970
971 return $errMessage['code'];
972 }
973
974 /**
975 * Set up for the execution.
976 * @return array
977 */
978 protected function setupExecuteAction() {
979 // First add the id to the top element
980 $result = $this->getResult();
981 $requestid = $this->getParameter( 'requestid' );
982 if ( !is_null( $requestid ) ) {
983 $result->addValue( null, 'requestid', $requestid );
984 }
985
986 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
987 $servedby = $this->getParameter( 'servedby' );
988 if ( $servedby ) {
989 $result->addValue( null, 'servedby', wfHostname() );
990 }
991 }
992
993 if ( $this->getParameter( 'curtimestamp' ) ) {
994 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
995 ApiResult::NO_SIZE_CHECK );
996 }
997
998 $params = $this->extractRequestParams();
999
1000 $this->mAction = $params['action'];
1001
1002 if ( !is_string( $this->mAction ) ) {
1003 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1004 }
1005
1006 return $params;
1007 }
1008
1009 /**
1010 * Set up the module for response
1011 * @return ApiBase The module that will handle this action
1012 * @throws MWException
1013 * @throws UsageException
1014 */
1015 protected function setupModule() {
1016 // Instantiate the module requested by the user
1017 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1018 if ( $module === null ) {
1019 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1020 }
1021 $moduleParams = $module->extractRequestParams();
1022
1023 // Check token, if necessary
1024 if ( $module->needsToken() === true ) {
1025 throw new MWException(
1026 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1027 'See documentation for ApiBase::needsToken for details.'
1028 );
1029 }
1030 if ( $module->needsToken() ) {
1031 if ( !$module->mustBePosted() ) {
1032 throw new MWException(
1033 "Module '{$module->getModuleName()}' must require POST to use tokens."
1034 );
1035 }
1036
1037 if ( !isset( $moduleParams['token'] ) ) {
1038 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1039 }
1040
1041 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1042 array_key_exists(
1043 $module->encodeParamName( 'token' ),
1044 $this->getRequest()->getQueryValues()
1045 )
1046 ) {
1047 $this->dieUsage(
1048 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1049 'found in the query string, but must be in the POST body',
1050 'mustposttoken'
1051 );
1052 }
1053
1054 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1055 $this->dieUsageMsg( 'sessionfailure' );
1056 }
1057 }
1058
1059 return $module;
1060 }
1061
1062 /**
1063 * Check the max lag if necessary
1064 * @param ApiBase $module Api module being used
1065 * @param array $params Array an array containing the request parameters.
1066 * @return bool True on success, false should exit immediately
1067 */
1068 protected function checkMaxLag( $module, $params ) {
1069 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1070 $maxLag = $params['maxlag'];
1071 list( $host, $lag ) = wfGetLB()->getMaxLag();
1072 if ( $lag > $maxLag ) {
1073 $response = $this->getRequest()->response();
1074
1075 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1076 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1077
1078 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1079 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1080 }
1081
1082 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1083 }
1084 }
1085
1086 return true;
1087 }
1088
1089 /**
1090 * Check selected RFC 7232 precondition headers
1091 *
1092 * RFC 7232 envisions a particular model where you send your request to "a
1093 * resource", and for write requests that you can read "the resource" by
1094 * changing the method to GET. When the API receives a GET request, it
1095 * works out even though "the resource" from RFC 7232's perspective might
1096 * be many resources from MediaWiki's perspective. But it totally fails for
1097 * a POST, since what HTTP sees as "the resource" is probably just
1098 * "/api.php" with all the interesting bits in the body.
1099 *
1100 * Therefore, we only support RFC 7232 precondition headers for GET (and
1101 * HEAD). That means we don't need to bother with If-Match and
1102 * If-Unmodified-Since since they only apply to modification requests.
1103 *
1104 * And since we don't support Range, If-Range is ignored too.
1105 *
1106 * @since 1.26
1107 * @param ApiBase $module Api module being used
1108 * @return bool True on success, false should exit immediately
1109 */
1110 protected function checkConditionalRequestHeaders( $module ) {
1111 if ( $this->mInternalMode ) {
1112 // No headers to check in internal mode
1113 return true;
1114 }
1115
1116 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1117 // Don't check POSTs
1118 return true;
1119 }
1120
1121 $return304 = false;
1122
1123 $ifNoneMatch = array_diff(
1124 $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1125 [ '' ]
1126 );
1127 if ( $ifNoneMatch ) {
1128 if ( $ifNoneMatch === [ '*' ] ) {
1129 // API responses always "exist"
1130 $etag = '*';
1131 } else {
1132 $etag = $module->getConditionalRequestData( 'etag' );
1133 }
1134 }
1135 if ( $ifNoneMatch && $etag !== null ) {
1136 $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1137 $match = array_map( function ( $s ) {
1138 return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1139 }, $ifNoneMatch );
1140 $return304 = in_array( $test, $match, true );
1141 } else {
1142 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1143
1144 // Some old browsers sends sizes after the date, like this:
1145 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1146 // Ignore that.
1147 $i = strpos( $value, ';' );
1148 if ( $i !== false ) {
1149 $value = trim( substr( $value, 0, $i ) );
1150 }
1151
1152 if ( $value !== '' ) {
1153 try {
1154 $ts = new MWTimestamp( $value );
1155 if (
1156 // RFC 7231 IMF-fixdate
1157 $ts->getTimestamp( TS_RFC2822 ) === $value ||
1158 // RFC 850
1159 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1160 // asctime (with and without space-padded day)
1161 $ts->format( 'D M j H:i:s Y' ) === $value ||
1162 $ts->format( 'D M j H:i:s Y' ) === $value
1163 ) {
1164 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1165 if ( $lastMod !== null ) {
1166 // Mix in some MediaWiki modification times
1167 $modifiedTimes = [
1168 'page' => $lastMod,
1169 'user' => $this->getUser()->getTouched(),
1170 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1171 ];
1172 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1173 // T46570: the core page itself may not change, but resources might
1174 $modifiedTimes['sepoch'] = wfTimestamp(
1175 TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1176 );
1177 }
1178 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1179 $lastMod = max( $modifiedTimes );
1180 $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1181 }
1182 }
1183 } catch ( TimestampException $e ) {
1184 // Invalid timestamp, ignore it
1185 }
1186 }
1187 }
1188
1189 if ( $return304 ) {
1190 $this->getRequest()->response()->statusHeader( 304 );
1191
1192 // Avoid outputting the compressed representation of a zero-length body
1193 MediaWiki\suppressWarnings();
1194 ini_set( 'zlib.output_compression', 0 );
1195 MediaWiki\restoreWarnings();
1196 wfClearOutputBuffers();
1197
1198 return false;
1199 }
1200
1201 return true;
1202 }
1203
1204 /**
1205 * Check for sufficient permissions to execute
1206 * @param ApiBase $module An Api module
1207 */
1208 protected function checkExecutePermissions( $module ) {
1209 $user = $this->getUser();
1210 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1211 !$user->isAllowed( 'read' )
1212 ) {
1213 $this->dieUsageMsg( 'readrequired' );
1214 }
1215
1216 if ( $module->isWriteMode() ) {
1217 if ( !$this->mEnableWrite ) {
1218 $this->dieUsageMsg( 'writedisabled' );
1219 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1220 $this->dieUsageMsg( 'writerequired' );
1221 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1222 $this->dieUsage(
1223 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1224 'promised-nonwrite-api'
1225 );
1226 }
1227
1228 $this->checkReadOnly( $module );
1229 }
1230
1231 // Allow extensions to stop execution for arbitrary reasons.
1232 $message = false;
1233 if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1234 $this->dieUsageMsg( $message );
1235 }
1236 }
1237
1238 /**
1239 * Check if the DB is read-only for this user
1240 * @param ApiBase $module An Api module
1241 */
1242 protected function checkReadOnly( $module ) {
1243 if ( wfReadOnly() ) {
1244 $this->dieReadOnly();
1245 }
1246
1247 if ( $module->isWriteMode()
1248 && in_array( 'bot', $this->getUser()->getGroups() )
1249 && wfGetLB()->getServerCount() > 1
1250 ) {
1251 $this->checkBotReadOnly();
1252 }
1253 }
1254
1255 /**
1256 * Check whether we are readonly for bots
1257 */
1258 private function checkBotReadOnly() {
1259 // Figure out how many servers have passed the lag threshold
1260 $numLagged = 0;
1261 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1262 $laggedServers = [];
1263 $loadBalancer = wfGetLB();
1264 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1265 if ( $lag > $lagLimit ) {
1266 ++$numLagged;
1267 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1268 }
1269 }
1270
1271 // If a majority of slaves are too lagged then disallow writes
1272 $slaveCount = wfGetLB()->getServerCount() - 1;
1273 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1274 $laggedServers = implode( ', ', $laggedServers );
1275 wfDebugLog(
1276 'api-readonly',
1277 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1278 );
1279
1280 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1281 $this->dieUsage(
1282 $parsed['info'],
1283 $parsed['code'],
1284 /* http error */
1285 0,
1286 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1287 );
1288 }
1289 }
1290
1291 /**
1292 * Check asserts of the user's rights
1293 * @param array $params
1294 */
1295 protected function checkAsserts( $params ) {
1296 if ( isset( $params['assert'] ) ) {
1297 $user = $this->getUser();
1298 switch ( $params['assert'] ) {
1299 case 'user':
1300 if ( $user->isAnon() ) {
1301 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1302 }
1303 break;
1304 case 'bot':
1305 if ( !$user->isAllowed( 'bot' ) ) {
1306 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1307 }
1308 break;
1309 }
1310 }
1311 }
1312
1313 /**
1314 * Check POST for external response and setup result printer
1315 * @param ApiBase $module An Api module
1316 * @param array $params An array with the request parameters
1317 */
1318 protected function setupExternalResponse( $module, $params ) {
1319 $request = $this->getRequest();
1320 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1321 // Module requires POST. GET request might still be allowed
1322 // if $wgDebugApi is true, otherwise fail.
1323 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction ] );
1324 }
1325
1326 // See if custom printer is used
1327 $this->mPrinter = $module->getCustomPrinter();
1328 if ( is_null( $this->mPrinter ) ) {
1329 // Create an appropriate printer
1330 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1331 }
1332
1333 if ( $request->getProtocol() === 'http' && (
1334 $request->getSession()->shouldForceHTTPS() ||
1335 ( $this->getUser()->isLoggedIn() &&
1336 $this->getUser()->requiresHTTPS() )
1337 ) ) {
1338 $this->logFeatureUsage( 'https-expected' );
1339 $this->setWarning( 'HTTP used when HTTPS was expected' );
1340 }
1341 }
1342
1343 /**
1344 * Execute the actual module, without any error handling
1345 */
1346 protected function executeAction() {
1347 $params = $this->setupExecuteAction();
1348 $module = $this->setupModule();
1349 $this->mModule = $module;
1350
1351 if ( !$this->mInternalMode ) {
1352 $this->setRequestExpectations( $module );
1353 }
1354
1355 $this->checkExecutePermissions( $module );
1356
1357 if ( !$this->checkMaxLag( $module, $params ) ) {
1358 return;
1359 }
1360
1361 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1362 return;
1363 }
1364
1365 if ( !$this->mInternalMode ) {
1366 $this->setupExternalResponse( $module, $params );
1367 }
1368
1369 $this->checkAsserts( $params );
1370
1371 // Execute
1372 $module->execute();
1373 Hooks::run( 'APIAfterExecute', [ &$module ] );
1374
1375 $this->reportUnusedParams();
1376
1377 if ( !$this->mInternalMode ) {
1378 // append Debug information
1379 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1380
1381 // Print result data
1382 $this->printResult( false );
1383 }
1384 }
1385
1386 /**
1387 * Set database connection, query, and write expectations given this module request
1388 * @param ApiBase $module
1389 */
1390 protected function setRequestExpectations( ApiBase $module ) {
1391 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1392 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1393 if ( $this->getRequest()->wasPosted() ) {
1394 if ( $module->isWriteMode() ) {
1395 $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1396 } else {
1397 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1398 $this->getRequest()->markAsSafeRequest();
1399 }
1400 } else {
1401 $trxProfiler->setExpectations( $limits['GET'], __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
1907 /**
1908 * @return string
1909 */
1910 public function getCodeString() {
1911 return $this->mCodestr;
1912 }
1913
1914 /**
1915 * @return array
1916 */
1917 public function getMessageArray() {
1918 $result = [
1919 'code' => $this->mCodestr,
1920 'info' => $this->getMessage()
1921 ];
1922 if ( is_array( $this->mExtraData ) ) {
1923 $result = array_merge( $result, $this->mExtraData );
1924 }
1925
1926 return $result;
1927 }
1928
1929 /**
1930 * @return string
1931 */
1932 public function __toString() {
1933 return "{$this->getCodeString()}: {$this->getMessage()}";
1934 }
1935 }
1936
1937 /**
1938 * For really cool vim folding this needs to be at the end:
1939 * vim: foldmarker=@{,@} foldmethod=marker
1940 */