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