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