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