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