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